copied mono-api-diff.cs from mono-2-2 branch so new patch can be applied and history...
[mono.git] / mcs / class / System.ServiceModel.Web / System.ServiceModel.Syndication / Rss20FeedFormatter.cs
1 //
2 // Rss20FeedFormatter.cs
3 //
4 // Author:
5 //      Atsushi Enomoto  <atsushi@ximian.com>
6 //
7 // Copyright (C) 2007 Novell, Inc (http://www.novell.com)
8 //
9 // Permission is hereby granted, free of charge, to any person obtaining
10 // a copy of this software and associated documentation files (the
11 // "Software"), to deal in the Software without restriction, including
12 // without limitation the rights to use, copy, modify, merge, publish,
13 // distribute, sublicense, and/or sell copies of the Software, and to
14 // permit persons to whom the Software is furnished to do so, subject to
15 // the following conditions:
16 // 
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
19 // 
20 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27 //
28 using System;
29 using System.Collections.Generic;
30 using System.Collections.ObjectModel;
31 using System.Globalization;
32 using System.IO;
33 using System.Runtime.Serialization;
34 using System.Text;
35 using System.Xml;
36 using System.Xml.Schema;
37 using System.Xml.Serialization;
38
39 namespace System.ServiceModel.Syndication
40 {
41         [XmlRoot ("rss", Namespace = "")]
42         public class Rss20FeedFormatter : SyndicationFeedFormatter, IXmlSerializable
43         {
44                 const string AtomNamespace ="http://www.w3.org/2005/Atom";
45
46                 bool ext_atom_serialization, preserve_att_ext = true, preserve_elem_ext = true;
47                 Type feed_type;
48
49                 public Rss20FeedFormatter ()
50                 {
51                         ext_atom_serialization = true;
52                 }
53
54                 public Rss20FeedFormatter (SyndicationFeed feedToWrite)
55                         : this (feedToWrite, true)
56                 {
57                 }
58
59                 public Rss20FeedFormatter (SyndicationFeed feedToWrite, bool serializeExtensionsAsAtom)
60                         : base (feedToWrite)
61                 {
62                         ext_atom_serialization = serializeExtensionsAsAtom;
63                 }
64
65                 public Rss20FeedFormatter (Type feedTypeToCreate)
66                 {
67                         if (feedTypeToCreate == null)
68                                 throw new ArgumentNullException ("feedTypeToCreate");
69                         feed_type = feedTypeToCreate;
70                 }
71
72                 public bool SerializeExtensionsAsAtom {
73                         get { return ext_atom_serialization; }
74                         set { ext_atom_serialization = value; }
75                 }
76
77                 protected Type FeedType {
78                         get { return feed_type; }
79                 }
80
81                 public bool PreserveAttributeExtensions {
82                         get { return preserve_att_ext; }
83                         set { preserve_att_ext = value; }
84                 }
85
86                 public bool PreserveElementExtensions {
87                         get { return preserve_elem_ext; }
88                         set { preserve_elem_ext = value; }
89                 }
90
91                 public override string Version {
92                         get { return "Rss20"; }
93                 }
94
95                 protected override SyndicationFeed CreateFeedInstance ()
96                 {
97                         return new SyndicationFeed ();
98                 }
99
100                 // hmm, why is it overriden? probably failed API cleanup.
101                 protected internal override void SetFeed (SyndicationFeed feed)
102                 {
103                         base.SetFeed (feed);
104                 }
105
106                 public override bool CanRead (XmlReader reader)
107                 {
108                         if (reader == null)
109                                 throw new ArgumentNullException ("reader");
110                         reader.MoveToContent ();
111                         return reader.IsStartElement ("rss", String.Empty);
112                 }
113
114                 public override void ReadFrom (XmlReader reader)
115                 {
116                         if (!CanRead (reader))
117                                 throw new XmlException (String.Format ("Element '{0}' in namespace '{1}' is not accepted by this syndication formatter", reader.LocalName, reader.NamespaceURI));
118                         ReadXml (reader, true);
119                 }
120
121                 protected virtual SyndicationItem ReadItem (XmlReader reader, SyndicationFeed feed)
122                 {
123                         Rss20ItemFormatter formatter = new Rss20ItemFormatter();
124                         formatter.ReadFrom (reader);
125                         return formatter.Item;
126                 }
127
128                 protected virtual IEnumerable<SyndicationItem> ReadItems (XmlReader reader, SyndicationFeed feed, out bool areAllItemsRead)
129                 {
130                         Collection<SyndicationItem> c = new Collection<SyndicationItem> ();
131                         for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ())
132                                 if (reader.LocalName == "item" && reader.NamespaceURI == String.Empty)
133                                         c.Add (ReadItem (reader, feed));
134                         areAllItemsRead = (reader.NodeType == XmlNodeType.EndElement);
135                         return c;
136                 }
137
138                 protected virtual void WriteItem (XmlWriter writer, SyndicationItem item, Uri feedBaseUri)
139                 {
140                         item.SaveAsRss20 (writer);
141                 }
142
143                 protected virtual void WriteItems (XmlWriter writer, IEnumerable<SyndicationItem> items, Uri feedBaseUri)
144                 {
145                         if (items == null)
146                                 throw new ArgumentNullException ("items");
147                         foreach (SyndicationItem item in items)
148                                 WriteItem (writer, item, feedBaseUri);
149                 }
150
151                 public override void WriteTo (XmlWriter writer)
152                 {
153                         WriteXml (writer, true);
154                 }
155
156                 void IXmlSerializable.ReadXml (XmlReader reader)
157                 {
158                         ReadXml (reader, false);
159                 }
160
161                 void IXmlSerializable.WriteXml (XmlWriter writer)
162                 {
163                         WriteXml (writer, false);
164                 }
165
166                 XmlSchema IXmlSerializable.GetSchema ()
167                 {
168                         return null;
169                 }
170
171                 // read
172
173                 void ReadXml (XmlReader reader, bool fromSerializable)
174                 {
175                         if (reader == null)
176                                 throw new ArgumentNullException ("reader");
177                         SetFeed (CreateFeedInstance ());
178
179                         reader.MoveToContent ();
180
181                         string ver = reader.GetAttribute ("version");
182                         if (ver != "2.0")
183                                 throw new NotSupportedException (String.Format ("RSS Version '{0}' is not supported", ver));
184
185                         if (PreserveAttributeExtensions && reader.MoveToFirstAttribute ()) {
186                                 do {
187                                         if (reader.NamespaceURI == "http://www.w3.org/2000/xmlns/")
188                                                 continue;
189                                         if (reader.NamespaceURI == String.Empty && reader.LocalName == "version")
190                                                 continue;
191                                         if (!TryParseAttribute (reader.LocalName, reader.NamespaceURI, reader.Value, Feed, Version))
192                                                 Feed.AttributeExtensions.Add (new XmlQualifiedName (reader.LocalName, reader.NamespaceURI), reader.Value);
193                                 } while (reader.MoveToNextAttribute ());
194                         }
195
196                         reader.ReadStartElement (); // <rss> => <channel>
197                         reader.MoveToContent ();
198                         reader.ReadStartElement ("channel", String.Empty); // <channel> => *
199
200                         Collection<SyndicationItem> items = null;
201
202                         for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
203                                 if (reader.NodeType != XmlNodeType.Element)
204                                         throw new XmlException ("Only element node is expected under 'channel' element");
205                                 if (reader.NamespaceURI == String.Empty)
206                                         switch (reader.LocalName) {
207                                         case "title":
208                                                 Feed.Title = ReadTextSyndicationContent (reader);
209                                                 continue;
210                                         case "link":
211                                                 SyndicationLink l = Feed.CreateLink ();
212                                                 ReadLink (reader, l);
213                                                 Feed.Links.Add (l);
214                                                 continue;
215                                         case "description":
216                                                 Feed.Description = ReadTextSyndicationContent (reader);
217                                                 continue;
218                                         case "language":
219                                                 Feed.Language = reader.ReadElementContentAsString ();
220                                                 continue;
221                                         case "copyright":
222                                                 Feed.Copyright = ReadTextSyndicationContent (reader);
223                                                 continue;
224                                         case "managingEditor":
225                                                 SyndicationPerson p = Feed.CreatePerson ();
226                                                 ReadPerson (reader, p);
227                                                 Feed.Authors.Add (p);
228                                                 continue;
229                                         case "pubDate":
230                                                 // FIXME: somehow DateTimeOffset causes the runtime crash.
231                                                 reader.ReadElementContentAsString ();
232                                                 // Feed.PublishDate = FromRFC822DateString (reader.ReadElementContentAsString ());
233                                                 continue;
234                                         case "lastBuildDate":
235                                                 // FIXME: somehow DateTimeOffset causes the runtime crash.
236                                                 reader.ReadElementContentAsString ();
237                                                 // Feed.LastUpdatedTime = FromRFC822DateString (reader.ReadElementContentAsString ());
238                                                 continue;
239                                         case "category":
240                                                 SyndicationCategory c = Feed.CreateCategory ();
241                                                 ReadCategory (reader, c);
242                                                 Feed.Categories.Add (c);
243                                                 continue;
244                                         case "generator":
245                                                 Feed.Generator = reader.ReadElementContentAsString ();
246                                                 continue;
247                                         //  "webMaster" "docs" "cloud" "ttl" "image" "rating" "textInput" "skipHours" "skipDays" are not handled.
248                                         case "item":
249                                                 if (items == null) {
250                                                         items = new Collection<SyndicationItem> ();
251                                                         Feed.Items = items;
252                                                 }
253                                                 items.Add (ReadItem (reader, Feed));
254                                                 continue;
255                                         }
256                                 if (!TryParseElement (reader, Feed, Version)) {
257                                         if (PreserveElementExtensions)
258                                                 // FIXME: what to specify for maxExtensionSize
259                                                 LoadElementExtensions (reader, Feed, int.MaxValue);
260                                         else
261                                                 reader.Skip ();
262                                 }
263                         }
264
265                         reader.ReadEndElement (); // </channel>
266                         reader.ReadEndElement (); // </rss>
267                 }
268
269                 TextSyndicationContent ReadTextSyndicationContent (XmlReader reader)
270                 {
271                         TextSyndicationContentKind kind = TextSyndicationContentKind.Plaintext;
272                         switch (reader.GetAttribute ("type")) {
273                         case "html":
274                                 kind = TextSyndicationContentKind.Html;
275                                 break;
276                         case "xhtml":
277                                 kind = TextSyndicationContentKind.XHtml;
278                                 break;
279                         }
280                         string text = reader.ReadElementContentAsString ();
281                         TextSyndicationContent t = new TextSyndicationContent (text, kind);
282                         return t;
283                 }
284
285                 void ReadCategory (XmlReader reader, SyndicationCategory category)
286                 {
287                         if (reader.MoveToFirstAttribute ()) {
288                                 do {
289                                         if (reader.NamespaceURI == "http://www.w3.org/2000/xmlns/")
290                                                 continue;
291                                         if (reader.NamespaceURI == String.Empty) {
292                                                 switch (reader.LocalName) {
293                                                 case "domain":
294                                                         category.Scheme = reader.Value;
295                                                         continue;
296                                                 }
297                                         }
298                                         if (PreserveAttributeExtensions)
299                                                 if (!TryParseAttribute (reader.LocalName, reader.NamespaceURI, reader.Value, category, Version))
300                                                         category.AttributeExtensions.Add (new XmlQualifiedName (reader.LocalName, reader.NamespaceURI), reader.Value);
301                                 } while (reader.MoveToNextAttribute ());
302                                 reader.MoveToElement ();
303                         }
304
305                         if (!reader.IsEmptyElement) {
306                                 reader.Read ();
307                                 for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
308                                         if (reader.IsTextNode ())
309                                                 category.Name += reader.Value;
310                                         else if (!TryParseElement (reader, category, Version)) {
311                                                 if (PreserveElementExtensions)
312                                                         // FIXME: what should be used for maxExtenswionSize
313                                                         LoadElementExtensions (reader, category, int.MaxValue);
314                                                 else
315                                                         reader.Skip ();
316                                         }
317                                         reader.Read ();
318                                 }
319                         }
320                         reader.Read (); // </category> or <category ... />
321                 }
322
323                 void ReadLink (XmlReader reader, SyndicationLink link)
324                 {
325                         if (PreserveAttributeExtensions && reader.MoveToFirstAttribute ()) {
326                                 do {
327                                         if (reader.NamespaceURI == "http://www.w3.org/2000/xmlns/")
328                                                 continue;
329                                         if (!TryParseAttribute (reader.LocalName, reader.NamespaceURI, reader.Value, link, Version))
330                                                 link.AttributeExtensions.Add (new XmlQualifiedName (reader.LocalName, reader.NamespaceURI), reader.Value);
331                                 } while (reader.MoveToNextAttribute ());
332                                 reader.MoveToElement ();
333                         }
334
335                         if (!reader.IsEmptyElement) {
336                                 string url = null;
337                                 reader.Read ();
338                                 for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
339                                         if (reader.IsTextNode ())
340                                                 url += reader.Value;
341                                         else if (!TryParseElement (reader, link, Version)) {
342                                                 if (PreserveElementExtensions)
343                                                         // FIXME: what should be used for maxExtenswionSize
344                                                         LoadElementExtensions (reader, link, int.MaxValue);
345                                                 else
346                                                         reader.Skip ();
347                                         }
348                                         reader.Read ();
349                                 }
350                                 link.Uri = CreateUri (url);
351                         }
352                         reader.Read (); // </link> or <link ... />
353                 }
354
355                 void ReadPerson (XmlReader reader, SyndicationPerson person)
356                 {
357                         if (PreserveAttributeExtensions && reader.MoveToFirstAttribute ()) {
358                                 do {
359                                         if (reader.NamespaceURI == "http://www.w3.org/2000/xmlns/")
360                                                 continue;
361                                         if (!TryParseAttribute (reader.LocalName, reader.NamespaceURI, reader.Value, person, Version))
362                                                 person.AttributeExtensions.Add (new XmlQualifiedName (reader.LocalName, reader.NamespaceURI), reader.Value);
363                                 } while (reader.MoveToNextAttribute ());
364                                 reader.MoveToElement ();
365                         }
366
367                         if (!reader.IsEmptyElement) {
368                                 reader.Read ();
369                                 for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
370                                         if (reader.IsTextNode ())
371                                                 person.Email += reader.Value;
372                                         else if (!TryParseElement (reader, person, Version)) {
373                                                 if (PreserveElementExtensions)
374                                                         // FIXME: what should be used for maxExtenswionSize
375                                                         LoadElementExtensions (reader, person, int.MaxValue);
376                                                 else
377                                                         reader.Skip ();
378                                         }
379                                         reader.Read ();
380                                 }
381                         }
382                         reader.Read (); // end element or empty element
383                 }
384
385                 Uri CreateUri (string uri)
386                 {
387                         return new Uri (uri, UriKind.RelativeOrAbsolute);
388                 }
389
390                 // write
391
392                 void WriteXml (XmlWriter writer, bool writeRoot)
393                 {
394                         if (writer == null)
395                                 throw new ArgumentNullException ("writer");
396                         if (Feed == null)
397                                 throw new InvalidOperationException ("Syndication feed must be set before writing");
398
399                         if (writeRoot)
400                                 writer.WriteStartElement ("rss");
401
402                         if (SerializeExtensionsAsAtom)
403                                 writer.WriteAttributeString ("xmlns", "a10", "http://www.w3.org/2000/xmlns/", AtomNamespace);
404                         writer.WriteAttributeString ("version", "2.0");
405
406                         writer.WriteStartElement ("channel");
407
408                         if (Feed.BaseUri != null)
409                                 writer.WriteAttributeString ("xml:base", Feed.BaseUri.ToString ());
410
411                         writer.WriteElementString ("title", String.Empty, Feed.Title != null ? Feed.Title.Text : String.Empty);
412
413                         writer.WriteElementString ("description", String.Empty, Feed.Description != null ? Feed.Description.Text : String.Empty);
414
415                         if (Feed.Copyright != null)
416                                 writer.WriteElementString ("copyright", String.Empty, Feed.Copyright.Text);
417
418                         if (!Feed.LastUpdatedTime.Equals (default (DateTimeOffset))) {
419                                 writer.WriteStartElement ("lastBuildDate");
420                                 writer.WriteString (ToRFC822DateString (Feed.LastUpdatedTime));
421                                 writer.WriteEndElement ();
422                         }
423
424                         if (Feed.Generator != null)
425                                 writer.WriteElementString ("generator", String.Empty, Feed.Generator);
426                         if (Feed.ImageUrl != null) {
427                                 writer.WriteStartElement ("image");
428                                 writer.WriteElementString ("url", String.Empty, Feed.ImageUrl.ToString ());
429                                 // FIXME: are they really empty?
430                                 writer.WriteElementString ("title", String.Empty, String.Empty);
431                                 writer.WriteElementString ("link", String.Empty, String.Empty);
432                                 writer.WriteEndElement ();
433                         }
434                         if (Feed.Language != null)
435                                 writer.WriteElementString ("language", String.Empty, Feed.Language);
436
437                         foreach (SyndicationPerson author in Feed.Authors)
438                                 if (author != null) {
439                                         writer.WriteStartElement ("managingEditor");
440                                         WriteAttributeExtensions (writer, author, Version);
441                                         writer.WriteString (author.Email);
442                                         WriteElementExtensions (writer, author, Version);
443                                         writer.WriteEndElement ();
444                                 }
445                         foreach (SyndicationCategory category in Feed.Categories)
446                                 if (category != null) {
447                                         writer.WriteStartElement ("category");
448                                         if (category.Scheme != null)
449                                                 writer.WriteAttributeString ("domain", category.Scheme);
450                                         WriteAttributeExtensions (writer, category, Version);
451                                         writer.WriteString (category.Name);
452                                         WriteElementExtensions (writer, category, Version);
453                                         writer.WriteEndElement ();
454                                 }
455
456                         foreach (SyndicationLink link in Feed.Links)
457                                 if (link != null) {
458                                         writer.WriteStartElement ("link");
459                                         WriteAttributeExtensions (writer, link, Version);
460                                         writer.WriteString (link.Uri != null ? link.Uri.ToString () : String.Empty);
461                                         WriteElementExtensions (writer, link, Version);
462                                         writer.WriteEndElement ();
463                                 }
464
465                         WriteItems (writer, Feed.Items, Feed.BaseUri);
466
467                         if (SerializeExtensionsAsAtom) {
468
469                                 if (Feed.Id != null) {
470                                         writer.WriteStartElement ("a10", "id", AtomNamespace);
471                                         writer.WriteString (Feed.Id);
472                                         writer.WriteEndElement ();
473                                 }
474
475                                 foreach (SyndicationPerson contributor in Feed.Contributors) {
476                                         if (contributor != null) {
477                                                 writer.WriteStartElement ("a10", "contributor", AtomNamespace);
478                                                 WriteAttributeExtensions (writer, contributor, Version);
479                                                 writer.WriteElementString ("a10", "name", AtomNamespace, contributor.Name);
480                                                 writer.WriteElementString ("a10", "uri", AtomNamespace, contributor.Uri);
481                                                 writer.WriteElementString ("a10", "email", AtomNamespace, contributor.Email);
482                                                 WriteElementExtensions (writer, contributor, Version);
483                                                 writer.WriteEndElement ();
484                                         }
485                                 }
486                         }
487
488                         writer.WriteEndElement (); // </channel>
489
490                         if (writeRoot)
491                                 writer.WriteEndElement (); // </rss>
492                 }
493
494                 // FIXME: DateTimeOffset.ToString() needs another overload.
495                 // When it is implemented, just remove ".DateTime" parts below.
496                 string ToRFC822DateString (DateTimeOffset date)
497                 {
498                         switch (date.DateTime.Kind) {
499                         case DateTimeKind.Utc:
500                                 return date.DateTime.ToString ("ddd, dd MMM yyyy HH:mm:ss 'Z'", DateTimeFormatInfo.InvariantInfo);
501                         case DateTimeKind.Local:
502                                 StringBuilder sb = new StringBuilder (date.DateTime.ToString ("ddd, dd MMM yyyy HH:mm:ss zzz", DateTimeFormatInfo.InvariantInfo));
503                                 sb.Remove (sb.Length - 3, 1);
504                                 return sb.ToString (); // remove ':' from +hh:mm
505                         default:
506                                 return date.DateTime.ToString ("ddd, dd MMM yyyy HH:mm:ss", DateTimeFormatInfo.InvariantInfo);
507                         }
508                 }
509         }
510 }