2
0

Rss20FeedFormatter.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. //
  2. // Rss20FeedFormatter.cs
  3. //
  4. // Author:
  5. // Atsushi Enomoto <[email protected]>
  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. namespace System.ServiceModel.Syndication
  39. {
  40. [XmlRoot ("rss", Namespace = "")]
  41. public class Rss20FeedFormatter : SyndicationFeedFormatter, IXmlSerializable
  42. {
  43. const string AtomNamespace ="http://www.w3.org/2005/Atom";
  44. bool ext_atom_serialization, preserve_att_ext = true, preserve_elem_ext = true;
  45. Type feed_type;
  46. public Rss20FeedFormatter ()
  47. {
  48. ext_atom_serialization = true;
  49. }
  50. public Rss20FeedFormatter (SyndicationFeed feedToWrite)
  51. : this (feedToWrite, true)
  52. {
  53. }
  54. public Rss20FeedFormatter (SyndicationFeed feedToWrite, bool serializeExtensionsAsAtom)
  55. : base (feedToWrite)
  56. {
  57. ext_atom_serialization = serializeExtensionsAsAtom;
  58. }
  59. public Rss20FeedFormatter (Type feedTypeToCreate)
  60. {
  61. if (feedTypeToCreate == null)
  62. throw new ArgumentNullException ("feedTypeToCreate");
  63. feed_type = feedTypeToCreate;
  64. }
  65. public bool SerializeExtensionsAsAtom {
  66. get { return ext_atom_serialization; }
  67. set { ext_atom_serialization = value; }
  68. }
  69. protected Type FeedType {
  70. get { return feed_type; }
  71. }
  72. public bool PreserveAttributeExtensions {
  73. get { return preserve_att_ext; }
  74. set { preserve_att_ext = value; }
  75. }
  76. public bool PreserveElementExtensions {
  77. get { return preserve_elem_ext; }
  78. set { preserve_elem_ext = value; }
  79. }
  80. public override string Version {
  81. get { return "Rss20"; }
  82. }
  83. protected override SyndicationFeed CreateFeedInstance ()
  84. {
  85. return new SyndicationFeed ();
  86. }
  87. // hmm, why is it overriden? probably failed API cleanup.
  88. protected internal override void SetFeed (SyndicationFeed feed)
  89. {
  90. base.SetFeed (feed);
  91. }
  92. public override bool CanRead (XmlReader reader)
  93. {
  94. if (reader == null)
  95. throw new ArgumentNullException ("reader");
  96. reader.MoveToContent ();
  97. return reader.IsStartElement ("rss", String.Empty);
  98. }
  99. public override void ReadFrom (XmlReader reader)
  100. {
  101. if (!CanRead (reader))
  102. throw new XmlException (String.Format ("Element '{0}' in namespace '{1}' is not accepted by this syndication formatter", reader.LocalName, reader.NamespaceURI));
  103. ReadXml (reader, true);
  104. }
  105. protected virtual SyndicationItem ReadItem (XmlReader reader, SyndicationFeed feed)
  106. {
  107. Rss20ItemFormatter formatter = new Rss20ItemFormatter();
  108. formatter.ReadFrom (reader);
  109. return formatter.Item;
  110. }
  111. protected virtual IEnumerable<SyndicationItem> ReadItems (XmlReader reader, SyndicationFeed feed, out bool areAllItemsRead)
  112. {
  113. Collection<SyndicationItem> c = new Collection<SyndicationItem> ();
  114. for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ())
  115. if (reader.LocalName == "item" && reader.NamespaceURI == String.Empty)
  116. c.Add (ReadItem (reader, feed));
  117. areAllItemsRead = (reader.NodeType == XmlNodeType.EndElement);
  118. return c;
  119. }
  120. [MonoTODO ("Find out how feedBaseUri is used")]
  121. protected virtual void WriteItem (XmlWriter writer, SyndicationItem item, Uri feedBaseUri)
  122. {
  123. item.SaveAsRss20 (writer);
  124. }
  125. protected virtual void WriteItems (XmlWriter writer, IEnumerable<SyndicationItem> items, Uri feedBaseUri)
  126. {
  127. if (items == null)
  128. throw new ArgumentNullException ("items");
  129. foreach (SyndicationItem item in items)
  130. WriteItem (writer, item, feedBaseUri);
  131. }
  132. public override void WriteTo (XmlWriter writer)
  133. {
  134. WriteXml (writer, true);
  135. }
  136. void IXmlSerializable.ReadXml (XmlReader reader)
  137. {
  138. ReadXml (reader, false);
  139. }
  140. void IXmlSerializable.WriteXml (XmlWriter writer)
  141. {
  142. WriteXml (writer, false);
  143. }
  144. XmlSchema IXmlSerializable.GetSchema ()
  145. {
  146. return null;
  147. }
  148. // read
  149. void ReadXml (XmlReader reader, bool fromSerializable)
  150. {
  151. if (reader == null)
  152. throw new ArgumentNullException ("reader");
  153. SetFeed (CreateFeedInstance ());
  154. reader.MoveToContent ();
  155. string ver = reader.GetAttribute ("version");
  156. if (ver != "2.0")
  157. throw new NotSupportedException (String.Format ("RSS Version '{0}' is not supported", ver));
  158. if (PreserveAttributeExtensions && reader.MoveToFirstAttribute ()) {
  159. do {
  160. if (reader.NamespaceURI == "http://www.w3.org/2000/xmlns/")
  161. continue;
  162. if (reader.NamespaceURI == String.Empty && reader.LocalName == "version")
  163. continue;
  164. if (!TryParseAttribute (reader.LocalName, reader.NamespaceURI, reader.Value, Feed, Version))
  165. Feed.AttributeExtensions.Add (new XmlQualifiedName (reader.LocalName, reader.NamespaceURI), reader.Value);
  166. } while (reader.MoveToNextAttribute ());
  167. }
  168. reader.ReadStartElement (); // <rss> => <channel>
  169. reader.MoveToContent ();
  170. reader.ReadStartElement ("channel", String.Empty); // <channel> => *
  171. Collection<SyndicationItem> items = null;
  172. for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
  173. if (reader.NodeType != XmlNodeType.Element)
  174. throw new XmlException ("Only element node is expected under 'channel' element");
  175. if (reader.NamespaceURI == String.Empty)
  176. switch (reader.LocalName) {
  177. case "title":
  178. Feed.Title = ReadTextSyndicationContent (reader);
  179. continue;
  180. case "link":
  181. SyndicationLink l = Feed.CreateLink ();
  182. ReadLink (reader, l);
  183. Feed.Links.Add (l);
  184. continue;
  185. case "description":
  186. Feed.Description = ReadTextSyndicationContent (reader);
  187. continue;
  188. case "language":
  189. Feed.Language = reader.ReadElementContentAsString ();
  190. continue;
  191. case "copyright":
  192. Feed.Copyright = ReadTextSyndicationContent (reader);
  193. continue;
  194. case "managingEditor":
  195. SyndicationPerson p = Feed.CreatePerson ();
  196. ReadPerson (reader, p);
  197. Feed.Authors.Add (p);
  198. continue;
  199. case "pubDate":
  200. // FIXME: somehow DateTimeOffset causes the runtime crash.
  201. reader.ReadElementContentAsString ();
  202. // Feed.PublishDate = FromRFC822DateString (reader.ReadElementContentAsString ());
  203. continue;
  204. case "lastBuildDate":
  205. // FIXME: somehow DateTimeOffset causes the runtime crash.
  206. reader.ReadElementContentAsString ();
  207. // Feed.LastUpdatedTime = FromRFC822DateString (reader.ReadElementContentAsString ());
  208. continue;
  209. case "category":
  210. SyndicationCategory c = Feed.CreateCategory ();
  211. ReadCategory (reader, c);
  212. Feed.Categories.Add (c);
  213. continue;
  214. case "generator":
  215. Feed.Generator = reader.ReadElementContentAsString ();
  216. continue;
  217. // "webMaster" "docs" "cloud" "ttl" "image" "rating" "textInput" "skipHours" "skipDays" are not handled.
  218. case "item":
  219. if (items == null) {
  220. items = new Collection<SyndicationItem> ();
  221. Feed.Items = items;
  222. }
  223. items.Add (ReadItem (reader, Feed));
  224. continue;
  225. }
  226. if (!TryParseElement (reader, Feed, Version)) {
  227. if (PreserveElementExtensions)
  228. // FIXME: what to specify for maxExtensionSize
  229. LoadElementExtensions (reader, Feed, int.MaxValue);
  230. else
  231. reader.Skip ();
  232. }
  233. }
  234. reader.ReadEndElement (); // </channel>
  235. reader.ReadEndElement (); // </rss>
  236. }
  237. TextSyndicationContent ReadTextSyndicationContent (XmlReader reader)
  238. {
  239. TextSyndicationContentKind kind = TextSyndicationContentKind.Plaintext;
  240. switch (reader.GetAttribute ("type")) {
  241. case "html":
  242. kind = TextSyndicationContentKind.Html;
  243. break;
  244. case "xhtml":
  245. kind = TextSyndicationContentKind.XHtml;
  246. break;
  247. }
  248. string text = reader.ReadElementContentAsString ();
  249. TextSyndicationContent t = new TextSyndicationContent (text, kind);
  250. return t;
  251. }
  252. void ReadCategory (XmlReader reader, SyndicationCategory category)
  253. {
  254. if (reader.MoveToFirstAttribute ()) {
  255. do {
  256. if (reader.NamespaceURI == "http://www.w3.org/2000/xmlns/")
  257. continue;
  258. if (reader.NamespaceURI == String.Empty) {
  259. switch (reader.LocalName) {
  260. case "domain":
  261. category.Scheme = reader.Value;
  262. continue;
  263. }
  264. }
  265. if (PreserveAttributeExtensions)
  266. if (!TryParseAttribute (reader.LocalName, reader.NamespaceURI, reader.Value, category, Version))
  267. category.AttributeExtensions.Add (new XmlQualifiedName (reader.LocalName, reader.NamespaceURI), reader.Value);
  268. } while (reader.MoveToNextAttribute ());
  269. reader.MoveToElement ();
  270. }
  271. if (!reader.IsEmptyElement) {
  272. reader.Read ();
  273. for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
  274. if (reader.NodeType == XmlNodeType.Text)
  275. category.Name += reader.Value;
  276. else if (!TryParseElement (reader, category, Version)) {
  277. if (PreserveElementExtensions)
  278. // FIXME: what should be used for maxExtenswionSize
  279. LoadElementExtensions (reader, category, int.MaxValue);
  280. else
  281. reader.Skip ();
  282. }
  283. reader.Read ();
  284. }
  285. }
  286. reader.Read (); // </category> or <category ... />
  287. }
  288. void ReadLink (XmlReader reader, SyndicationLink link)
  289. {
  290. if (PreserveAttributeExtensions && reader.MoveToFirstAttribute ()) {
  291. do {
  292. if (reader.NamespaceURI == "http://www.w3.org/2000/xmlns/")
  293. continue;
  294. if (!TryParseAttribute (reader.LocalName, reader.NamespaceURI, reader.Value, link, Version))
  295. link.AttributeExtensions.Add (new XmlQualifiedName (reader.LocalName, reader.NamespaceURI), reader.Value);
  296. } while (reader.MoveToNextAttribute ());
  297. reader.MoveToElement ();
  298. }
  299. if (!reader.IsEmptyElement) {
  300. string url = null;
  301. reader.Read ();
  302. for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
  303. if (reader.NodeType == XmlNodeType.Text)
  304. url += reader.Value;
  305. else if (!TryParseElement (reader, link, Version)) {
  306. if (PreserveElementExtensions)
  307. // FIXME: what should be used for maxExtenswionSize
  308. LoadElementExtensions (reader, link, int.MaxValue);
  309. else
  310. reader.Skip ();
  311. }
  312. reader.Read ();
  313. }
  314. link.Uri = CreateUri (url);
  315. }
  316. reader.Read (); // </link> or <link ... />
  317. }
  318. void ReadPerson (XmlReader reader, SyndicationPerson person)
  319. {
  320. if (PreserveAttributeExtensions && reader.MoveToFirstAttribute ()) {
  321. do {
  322. if (reader.NamespaceURI == "http://www.w3.org/2000/xmlns/")
  323. continue;
  324. if (!TryParseAttribute (reader.LocalName, reader.NamespaceURI, reader.Value, person, Version))
  325. person.AttributeExtensions.Add (new XmlQualifiedName (reader.LocalName, reader.NamespaceURI), reader.Value);
  326. } while (reader.MoveToNextAttribute ());
  327. reader.MoveToElement ();
  328. }
  329. if (!reader.IsEmptyElement) {
  330. reader.Read ();
  331. for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
  332. if (reader.NodeType == XmlNodeType.Text)
  333. person.Email += reader.Value;
  334. else if (!TryParseElement (reader, person, Version)) {
  335. if (PreserveElementExtensions)
  336. // FIXME: what should be used for maxExtenswionSize
  337. LoadElementExtensions (reader, person, int.MaxValue);
  338. else
  339. reader.Skip ();
  340. }
  341. reader.Read ();
  342. }
  343. }
  344. reader.Read (); // end element or empty element
  345. }
  346. Uri CreateUri (string uri)
  347. {
  348. return new Uri (uri, UriKind.RelativeOrAbsolute);
  349. }
  350. // write
  351. void WriteXml (XmlWriter writer, bool writeRoot)
  352. {
  353. if (writer == null)
  354. throw new ArgumentNullException ("writer");
  355. if (Feed == null)
  356. throw new InvalidOperationException ("Syndication feed must be set before writing");
  357. if (writeRoot)
  358. writer.WriteStartElement ("rss");
  359. if (SerializeExtensionsAsAtom)
  360. writer.WriteAttributeString ("xmlns", "a10", "http://www.w3.org/2000/xmlns/", AtomNamespace);
  361. writer.WriteAttributeString ("version", "2.0");
  362. writer.WriteStartElement ("channel");
  363. if (Feed.BaseUri != null)
  364. writer.WriteAttributeString ("xml:base", Feed.BaseUri.ToString ());
  365. writer.WriteElementString ("title", String.Empty, Feed.Title != null ? Feed.Title.Text : String.Empty);
  366. writer.WriteElementString ("description", String.Empty, Feed.Description != null ? Feed.Description.Text : String.Empty);
  367. if (Feed.Copyright != null)
  368. writer.WriteElementString ("copyright", String.Empty, Feed.Copyright.Text);
  369. if (!Feed.LastUpdatedTime.Equals (default (DateTimeOffset))) {
  370. writer.WriteStartElement ("lastBuildDate");
  371. writer.WriteString (ToRFC822DateString (Feed.LastUpdatedTime));
  372. writer.WriteEndElement ();
  373. }
  374. if (Feed.Generator != null)
  375. writer.WriteElementString ("generator", String.Empty, Feed.Generator);
  376. if (Feed.ImageUrl != null) {
  377. writer.WriteStartElement ("image");
  378. writer.WriteElementString ("url", String.Empty, Feed.ImageUrl.ToString ());
  379. // FIXME: are they really empty?
  380. writer.WriteElementString ("title", String.Empty, String.Empty);
  381. writer.WriteElementString ("link", String.Empty, String.Empty);
  382. writer.WriteEndElement ();
  383. }
  384. if (Feed.Language != null)
  385. writer.WriteElementString ("language", String.Empty, Feed.Language);
  386. foreach (SyndicationPerson author in Feed.Authors)
  387. if (author != null) {
  388. writer.WriteStartElement ("managingEditor");
  389. WriteAttributeExtensions (writer, author, Version);
  390. writer.WriteString (author.Email);
  391. WriteElementExtensions (writer, author, Version);
  392. writer.WriteEndElement ();
  393. }
  394. foreach (SyndicationCategory category in Feed.Categories)
  395. if (category != null) {
  396. writer.WriteStartElement ("category");
  397. if (category.Scheme != null)
  398. writer.WriteAttributeString ("domain", category.Scheme);
  399. WriteAttributeExtensions (writer, category, Version);
  400. writer.WriteString (category.Name);
  401. WriteElementExtensions (writer, category, Version);
  402. writer.WriteEndElement ();
  403. }
  404. foreach (SyndicationLink link in Feed.Links)
  405. if (link != null) {
  406. writer.WriteStartElement ("link");
  407. WriteAttributeExtensions (writer, link, Version);
  408. writer.WriteString (link.Uri != null ? link.Uri.ToString () : String.Empty);
  409. WriteElementExtensions (writer, link, Version);
  410. writer.WriteEndElement ();
  411. }
  412. WriteItems (writer, Feed.Items, Feed.BaseUri);
  413. if (SerializeExtensionsAsAtom) {
  414. if (Feed.Id != null) {
  415. writer.WriteStartElement ("a10", "id", AtomNamespace);
  416. writer.WriteString (Feed.Id);
  417. writer.WriteEndElement ();
  418. }
  419. foreach (SyndicationPerson contributor in Feed.Contributors) {
  420. if (contributor != null) {
  421. writer.WriteStartElement ("a10", "contributor", AtomNamespace);
  422. WriteAttributeExtensions (writer, contributor, Version);
  423. writer.WriteElementString ("a10", "name", AtomNamespace, contributor.Name);
  424. writer.WriteElementString ("a10", "uri", AtomNamespace, contributor.Uri);
  425. writer.WriteElementString ("a10", "email", AtomNamespace, contributor.Email);
  426. WriteElementExtensions (writer, contributor, Version);
  427. writer.WriteEndElement ();
  428. }
  429. }
  430. }
  431. writer.WriteEndElement (); // </channel>
  432. if (writeRoot)
  433. writer.WriteEndElement (); // </rss>
  434. }
  435. // FIXME: DateTimeOffset.ToString() needs another overload.
  436. // When it is implemented, just remove ".DateTime" parts below.
  437. string ToRFC822DateString (DateTimeOffset date)
  438. {
  439. switch (date.DateTime.Kind) {
  440. case DateTimeKind.Utc:
  441. return date.DateTime.ToString ("ddd, dd MMM yyyy HH:mm:ss 'Z'", DateTimeFormatInfo.InvariantInfo);
  442. case DateTimeKind.Local:
  443. StringBuilder sb = new StringBuilder (date.DateTime.ToString ("ddd, dd MMM yyyy HH:mm:ss zzz", DateTimeFormatInfo.InvariantInfo));
  444. sb.Remove (sb.Length - 3, 1);
  445. return sb.ToString (); // remove ':' from +hh:mm
  446. default:
  447. return date.DateTime.ToString ("ddd, dd MMM yyyy HH:mm:ss", DateTimeFormatInfo.InvariantInfo);
  448. }
  449. }
  450. }
  451. }