home *** CD-ROM | disk | FTP | other *** search
/ Computer Shopper 233 / Computer Shopper 233 / ComputerShopperDVD233.iso / Toolkit / Internet / Firefox / Firefox Setup 2.0.0.3.exe / nonlocalized / components / FeedProcessor.js < prev    next >
Encoding:
JavaScript  |  2007-03-10  |  59.0 KB  |  1,800 lines

  1. /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* ***** BEGIN LICENSE BLOCK *****
  3.  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  4.  *
  5.  * The contents of this file are subject to the Mozilla Public License Version
  6.  * 1.1 (the "License"); you may not use this file except in compliance with
  7.  * the License. You may obtain a copy of the License at
  8.  * http://www.mozilla.org/MPL/
  9.  *
  10.  * Software distributed under the License is distributed on an "AS IS" basis,
  11.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  12.  * for the specific language governing rights and limitations under the
  13.  * License.
  14.  *
  15.  * The Original Code is mozilla.org code.
  16.  *
  17.  * The Initial Developer of the Original Code is Robert Sayre.
  18.  * Portions created by the Initial Developer are Copyright (C) 2006
  19.  * the Initial Developer. All Rights Reserved.
  20.  *
  21.  * Contributor(s):
  22.  *   Ben Goodger <beng@google.com>
  23.  *   Myk Melez <myk@mozilla.org>
  24.  *
  25.  * Alternatively, the contents of this file may be used under the terms of
  26.  * either the GNU General Public License Version 2 or later (the "GPL"), or
  27.  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  28.  * in which case the provisions of the GPL or the LGPL are applicable instead
  29.  * of those above. If you wish to allow use of your version of this file only
  30.  * under the terms of either the GPL or the LGPL, and not to allow others to
  31.  * use your version of this file under the terms of the MPL, indicate your
  32.  * decision by deleting the provisions above and replace them with the notice
  33.  * and other provisions required by the GPL or the LGPL. If you do not delete
  34.  * the provisions above, a recipient may use your version of this file under
  35.  * the terms of any one of the MPL, the GPL or the LGPL.
  36.  *
  37.  * ***** END LICENSE BLOCK ***** */
  38.  
  39. function LOG(str) {
  40.   dump("*** " + str + "\n");
  41. }
  42.  
  43. const Ci = Components.interfaces;
  44. const Cc = Components.classes;
  45. const Cr = Components.results;
  46.  
  47. const IO_CONTRACTID = "@mozilla.org/network/io-service;1"
  48. const BAG_CONTRACTID = "@mozilla.org/hash-property-bag;1"
  49. const ARRAY_CONTRACTID = "@mozilla.org/array;1";
  50. const SAX_CONTRACTID = "@mozilla.org/saxparser/xmlreader;1";
  51. const UNESCAPE_CONTRACTID = "@mozilla.org/feed-unescapehtml;1";
  52.  
  53. var gIoService = Cc[IO_CONTRACTID].getService(Ci.nsIIOService);
  54. var gUnescapeHTML = Cc[UNESCAPE_CONTRACTID].
  55.                     getService(Ci.nsIScriptableUnescapeHTML);
  56.  
  57. const XMLNS = "http://www.w3.org/XML/1998/namespace";
  58. const RSS090NS = "http://my.netscape.com/rdf/simple/0.9/";
  59.  
  60. /***** Some general utils *****/
  61. function strToURI(link, base) {
  62.   var base = base || null;
  63.   try {
  64.     return gIoService.newURI(link, null, base);
  65.   }
  66.   catch(e) {
  67.     return null;
  68.   }
  69. }
  70.  
  71. function isArray(a) {
  72.   return isObject(a) && a.constructor == Array;
  73. }
  74.  
  75. function isObject(a) {
  76.   return (a && typeof a == "object") || isFunction(a);
  77. }
  78.  
  79. function isFunction(a) {
  80.   return typeof a == "function";
  81. }
  82.  
  83. function isIID(a, iid) {
  84.   var rv = false;
  85.   try {
  86.     a.QueryInterface(iid);
  87.     rv = true;
  88.   }
  89.   catch(e) {
  90.   }
  91.   return rv;
  92. }
  93.  
  94. function isIArray(a) {
  95.   return isIID(a, Ci.nsIArray);
  96. }
  97.  
  98. function isIFeedContainer(a) {
  99.   return isIID(a, Ci.nsIFeedContainer);
  100. }
  101.  
  102. function stripTags(someHTML) {
  103.   return someHTML.replace(/<[^>]+>/g,"");
  104. }
  105.  
  106. /**
  107.  * Searches through an array of links and returns a JS array 
  108.  * of matching property bags.
  109.  */
  110. const IANA_URI = "http://www.iana.org/assignments/relation/";
  111. function findAtomLinks(rel, links) {
  112.   var rvLinks = [];
  113.   for (var i = 0; i < links.length; ++i) {
  114.     var linkElement = links.queryElementAt(i, Ci.nsIPropertyBag2);
  115.     // atom:link MUST have @href
  116.     if (bagHasKey(linkElement, "href")) {
  117.       var relAttribute = null;
  118.       if (bagHasKey(linkElement, "rel"))
  119.         relAttribute = linkElement.getPropertyAsAString("rel")
  120.       if ((!relAttribute && rel == "alternate") || relAttribute == rel) {
  121.         rvLinks.push(linkElement);
  122.         continue;
  123.       }
  124.       // catch relations specified by IANA URI 
  125.       if (relAttribute == IANA_URI + rel) {
  126.         rvLinks.push(linkElement);
  127.       }
  128.     }
  129.   }
  130.   return rvLinks;
  131. }
  132.  
  133. function xmlEscape(s) {
  134.   s = s.replace(/&/g, "&");
  135.   s = s.replace(/>/g, ">");
  136.   s = s.replace(/</g, "<");
  137.   s = s.replace(/"/g, """);
  138.   s = s.replace(/'/g, "'");
  139.   return s;
  140. }
  141.  
  142. function arrayContains(array, element) {
  143.   for (var i = 0; i < array.length; ++i) {
  144.     if (array[i] == element) {
  145.       return true;
  146.     }
  147.   }
  148.   return false;
  149. }
  150.  
  151. // XXX add hasKey to nsIPropertyBag
  152. function bagHasKey(bag, key) {
  153.   try {
  154.     bag.getProperty(key);
  155.     return true;
  156.   }
  157.   catch (e) {
  158.     return false;
  159.   }
  160. }
  161.  
  162. function makePropGetter(key) {
  163.   return function FeedPropGetter(bag) {
  164.     try {
  165.       return value = bag.getProperty(key);
  166.     }
  167.     catch(e) {
  168.     }
  169.     return null;
  170.   }
  171. }
  172.  
  173.  
  174.  
  175. /**
  176.  * XXX Thunderbird's W3C-DTF function
  177.  *
  178.  * Converts a W3C-DTF (subset of ISO 8601) date string to an IETF date
  179.  * string.  W3C-DTF is described in this note:
  180.  * http://www.w3.org/TR/NOTE-datetime IETF is obtained via the Date
  181.  * object's toUTCString() method.  The object's toString() method is
  182.  * insufficient because it spells out timezones on Win32
  183.  * (f.e. "Pacific Standard Time" instead of "PST"), which Mail doesn't
  184.  * grok.  For info, see
  185.  * http://lxr.mozilla.org/mozilla/source/js/src/jsdate.c#1526.
  186.  */
  187. const HOURS_TO_MINUTES = 60;
  188. const MINUTES_TO_SECONDS = 60;
  189. const SECONDS_TO_MILLISECONDS = 1000;
  190. const MINUTES_TO_MILLISECONDS = MINUTES_TO_SECONDS * SECONDS_TO_MILLISECONDS;
  191. const HOURS_TO_MILLISECONDS = HOURS_TO_MINUTES * MINUTES_TO_MILLISECONDS;
  192. function W3CToIETFDate(dateString) {
  193.  
  194.   var parts = dateString.match(/(\d\d\d\d)(-(\d\d))?(-(\d\d))?(T(\d\d):(\d\d)(:(\d\d)(\.(\d+))?)?(Z|([+-])(\d\d):(\d\d))?)?/);
  195.  
  196.   // Here's an example of a W3C-DTF date string and what .match returns for it.
  197.   // 
  198.   // date: 2003-05-30T11:18:50.345-08:00
  199.   // date.match returns array values:
  200.   //
  201.   //   0: 2003-05-30T11:18:50-08:00,
  202.   //   1: 2003,
  203.   //   2: -05,
  204.   //   3: 05,
  205.   //   4: -30,
  206.   //   5: 30,
  207.   //   6: T11:18:50-08:00,
  208.   //   7: 11,
  209.   //   8: 18,
  210.   //   9: :50,
  211.   //   10: 50,
  212.   //   11: .345,
  213.   //   12: 345,
  214.   //   13: -08:00,
  215.   //   14: -,
  216.   //   15: 08,
  217.   //   16: 00
  218.  
  219.   // Create a Date object from the date parts.  Note that the Date
  220.   // object apparently can't deal with empty string parameters in lieu
  221.   // of numbers, so optional values (like hours, minutes, seconds, and
  222.   // milliseconds) must be forced to be numbers.
  223.   var date = new Date(parts[1], parts[3] - 1, parts[5], parts[7] || 0,
  224.                       parts[8] || 0, parts[10] || 0, parts[12] || 0);
  225.  
  226.   // We now have a value that the Date object thinks is in the local
  227.   // timezone but which actually represents the date/time in the
  228.   // remote timezone (f.e. the value was "10:00 EST", and we have
  229.   // converted it to "10:00 PST" instead of "07:00 PST").  We need to
  230.   // correct that.  To do so, we're going to add the offset between
  231.   // the remote timezone and UTC (to convert the value to UTC), then
  232.   // add the offset between UTC and the local timezone //(to convert
  233.   // the value to the local timezone).
  234.  
  235.   // Ironically, W3C-DTF gives us the offset between UTC and the
  236.   // remote timezone rather than the other way around, while the
  237.   // getTimezoneOffset() method of a Date object gives us the offset
  238.   // between the local timezone and UTC rather than the other way
  239.   // around.  Both of these are the additive inverse (i.e. -x for x)
  240.   // of what we want, so we have to invert them to use them by
  241.   // multipying by -1 (f.e. if "the offset between UTC and the remote
  242.   // timezone" is -5 hours, then "the offset between the remote
  243.   // timezone and UTC" is -5*-1 = 5 hours).
  244.  
  245.   // Note that if the timezone portion of the date/time string is
  246.   // absent (which violates W3C-DTF, although ISO 8601 allows it), we
  247.   // assume the value to be in UTC.
  248.  
  249.   // The offset between the remote timezone and UTC in milliseconds.
  250.   var remoteToUTCOffset = 0;
  251.   if (parts[13] && parts[13] != "Z") {
  252.     var direction = (parts[14] == "+" ? 1 : -1);
  253.     if (parts[15])
  254.       remoteToUTCOffset += direction * parts[15] * HOURS_TO_MILLISECONDS;
  255.     if (parts[16])
  256.       remoteToUTCOffset += direction * parts[16] * MINUTES_TO_MILLISECONDS;
  257.   }
  258.   remoteToUTCOffset = remoteToUTCOffset * -1; // invert it
  259.  
  260.   // The offset between UTC and the local timezone in milliseconds.
  261.   var UTCToLocalOffset = date.getTimezoneOffset() * MINUTES_TO_MILLISECONDS;
  262.   UTCToLocalOffset = UTCToLocalOffset * -1; // invert it
  263.   date.setTime(date.getTime() + remoteToUTCOffset + UTCToLocalOffset);
  264.  
  265.   return date.toUTCString();
  266. }
  267.  
  268. const RDF_NS = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
  269. // namespace map
  270. var gNamespaces = {
  271.   "http://webns.net/mvcb/":"admin",
  272.   "http://backend.userland.com/rss":"",
  273.   "http://blogs.law.harvard.edu/tech/rss":"",
  274.   "http://www.w3.org/2005/Atom":"atom",
  275.   "http://purl.org/atom/ns#":"atom03",
  276.   "http://purl.org/rss/1.0/modules/content/":"content",
  277.   "http://purl.org/dc/elements/1.1/":"dc",
  278.   "http://purl.org/dc/terms/":"dcterms",
  279.   "http://www.w3.org/1999/02/22-rdf-syntax-ns#":"rdf",
  280.   "http://purl.org/rss/1.0/":"rss1",
  281.   "http://my.netscape.com/rdf/simple/0.9/":"rss1",
  282.   "http://wellformedweb.org/CommentAPI/":"wfw",                              
  283.   "http://purl.org/rss/1.0/modules/wiki/":"wiki", 
  284.   "http://www.w3.org/XML/1998/namespace":"xml"
  285. }
  286.  
  287.  
  288. function FeedResult() {}
  289. FeedResult.prototype = {
  290.   bozo: false,
  291.   doc: null,
  292.   version: null,
  293.   headers: null,
  294.   uri: null,
  295.   stylesheet: null,
  296.  
  297.   registerExtensionPrefix: function FR_registerExtensionPrefix(ns, prefix) {
  298.     throw Cr.NS_ERROR_NOT_IMPLEMENTED;
  299.   },
  300.  
  301.   QueryInterface: function FR_QI(iid) {
  302.     if (iid.equals(Ci.nsIFeedResult) ||
  303.         iid.equals(Ci.nsISupports))
  304.       return this;
  305.  
  306.     throw Cr.NS_ERROR_NOINTERFACE;
  307.   },
  308. }  
  309.  
  310. function Feed() {
  311.   this.subtitle = null;
  312.   this.title = null;
  313.   this.items = Cc[ARRAY_CONTRACTID].createInstance(Ci.nsIMutableArray);
  314.   this.link = null;
  315.   this.id = null;
  316.   this.generator = null;
  317.   this.authors = Cc[ARRAY_CONTRACTID].createInstance(Ci.nsIMutableArray);
  318.   this.contributors = Cc[ARRAY_CONTRACTID].createInstance(Ci.nsIMutableArray);
  319.   this.baseURI = null;
  320. }
  321.  
  322. Feed.prototype = {
  323.   searchLists: {
  324.     subtitle: ["description","dc:description","rss1:description",
  325.                "atom03:tagline","atom:subtitle"],
  326.     items: ["items","atom03_entries","entries"],
  327.     id: ["atom:id","rdf:about"],
  328.     generator: ["generator"],
  329.     authors : ["authors"],
  330.     contributors: ["contributors"],
  331.     title: ["title","rss1:title", "atom03:title","atom:title"],
  332.     link:  [["link",strToURI],["rss1:link",strToURI]],
  333.     categories: ["categories", "dc:subject"],
  334.     rights: ["atom03:rights","atom:rights"],
  335.     cloud: ["cloud"],
  336.     image: ["image", "rss1:image"],
  337.     textInput: ["textInput", "rss1:textinput"],
  338.     skipDays: ["skipDays"],
  339.     skipHours: ["skipHours"],
  340.     updated: ["pubDate", "lastBuildDate", "atom03:modified", "dc:date",
  341.               "dcterms:modified", "atom:updated"]
  342.   },
  343.  
  344.   normalize: function Feed_normalize() {
  345.     fieldsToObj(this, this.searchLists);
  346.     if (this.skipDays)
  347.       this.skipDays = this.skipDays.getProperty("days");
  348.     if (this.skipHours)
  349.       this.skipHours = this.skipHours.getProperty("hours");
  350.  
  351.     if (this.updated)
  352.       this.updated = dateParse(this.updated);
  353.  
  354.     // Assign Atom link if needed
  355.     if (bagHasKey(this.fields, "links"))
  356.       this._atomLinksToURI();
  357.  
  358.     this._resetBagMembersToRawText([this.searchLists.subtitle, 
  359.                                     this.searchLists.title]);
  360.   },
  361.  
  362.   _atomLinksToURI: function Feed_linkToURI() {
  363.     var links = this.fields.getPropertyAsInterface("links", Ci.nsIArray);
  364.     var alternates = findAtomLinks("alternate", links);
  365.     if (alternates.length > 0) {
  366.       try {
  367.         var href = alternates[0].getPropertyAsAString("href");
  368.         var base;
  369.         if (bagHasKey(alternates[0], "xml:base"))
  370.           base = strToURI(alternates[0].getPropertyAsAString("xml:base"),
  371.                           this.baseURI);
  372.         else
  373.           base = this.baseURI;
  374.         this.link = strToURI(alternates[0].getPropertyAsAString("href"), base);
  375.       }
  376.       catch(e) {
  377.         LOG(e);
  378.       }
  379.     }
  380.   },
  381.  
  382.   // reset the bag to raw contents, not text constructs
  383.   _resetBagMembersToRawText: function Feed_resetBagMembers(fieldLists) {
  384.     for (var i=0; i<fieldLists.length; i++) {      
  385.       for (var j=0; j<fieldLists[i].length; j++) {
  386.         if (bagHasKey(this.fields, fieldLists[i][j])) {
  387.           var textConstruct = this.fields.getProperty(fieldLists[i][j]);
  388.           this.fields.setPropertyAsAString(fieldLists[i][j],
  389.                                            textConstruct.text);
  390.         }
  391.       }
  392.     }
  393.   },
  394.    
  395.   QueryInterface: function Feed_QI(iid) {
  396.     if (iid.equals(Ci.nsIFeed) ||
  397.         iid.equals(Ci.nsIFeedContainer) ||
  398.         iid.equals(Ci.nsISupports))
  399.     return this;
  400.     throw Cr.NS_ERROR_NOINTERFACE;
  401.   }
  402. }
  403.  
  404. function Entry() {
  405.   this.summary = null;
  406.   this.content = null;
  407.   this.title = null;
  408.   this.fields = Cc["@mozilla.org/hash-property-bag;1"].
  409.     createInstance(Ci.nsIWritablePropertyBag2);
  410.   this.link = null;
  411.   this.id = null;
  412.   this.baseURI = null;
  413.   this.updated = null;
  414.   this.published = null;
  415.   this.authors = Cc[ARRAY_CONTRACTID].createInstance(Ci.nsIMutableArray);
  416.   this.contributors = Cc[ARRAY_CONTRACTID].createInstance(Ci.nsIMutableArray);
  417. }
  418.   
  419. Entry.prototype = {
  420.   fields: null,
  421.   enclosures: null,
  422.   mediaContent: null,
  423.   
  424.   searchLists: {
  425.     title: ["title", "rss1:title", "atom03:title", "atom:title"],
  426.     link: [["link",strToURI],["rss1:link",strToURI]],
  427.     id: [["guid", makePropGetter("guid")], "rdf:about",
  428.          "atom03:id", "atom:id"],
  429.     authors : ["authors"],
  430.     contributors: ["contributors"],
  431.     summary: ["description", "rss1:description", "dc:description",
  432.               "atom03:summary", "atom:summary"],
  433.     content: ["content:encoded","atom03:content","atom:content"],
  434.     rights: ["atom03:rights","atom:rights"],
  435.     published: ["atom03:issued", "dcterms:issued", "atom:published"],
  436.     updated: ["pubDate", "atom03:modified", "dc:date", "dcterms:modified",
  437.               "atom:updated"]
  438.   },
  439.   
  440.   normalize: function Entry_normalize() {
  441.     fieldsToObj(this, this.searchLists);
  442.  
  443.     // Assign Atom link if needed
  444.     if (bagHasKey(this.fields, "links"))
  445.       this._atomLinksToURI();
  446.  
  447.     // The link might be a guid w/ permalink=true
  448.     if (!this.link && bagHasKey(this.fields, "guid")) {
  449.       var guid = this.fields.getProperty("guid");
  450.       var isPermaLink = true;
  451.       
  452.       if (bagHasKey(guid, "isPermaLink"))
  453.         isPermaLink = new Boolean(guid.getProperty("isPermaLink"));
  454.       
  455.       if (guid && isPermaLink)
  456.         this.link = strToURI(guid.getProperty("guid"));
  457.     }
  458.  
  459.     if (this.updated)
  460.       this.updated = dateParse(this.updated);
  461.     if (this.published)
  462.       this.published = dateParse(this.published);
  463.  
  464.     this._resetBagMembersToRawText([this.searchLists.content, 
  465.                                     this.searchLists.summary, 
  466.                                     this.searchLists.title]);
  467.   },
  468.   
  469.   QueryInterface: function(iid) {
  470.     if (iid.equals(Ci.nsIFeedEntry) ||
  471.         iid.equals(Ci.nsIFeedContainer) ||
  472.         iid.equals(Ci.nsISupports))
  473.     return this;
  474.  
  475.     throw Cr.NS_ERROR_NOINTERFACE;
  476.   }
  477. }
  478.  
  479. Entry.prototype._atomLinksToURI = Feed.prototype._atomLinksToURI;
  480. Entry.prototype._resetBagMembersToRawText = 
  481.    Feed.prototype._resetBagMembersToRawText;
  482.  
  483. // TextConstruct represents and element that could contain (X)HTML
  484. function TextConstruct() {
  485.   this.lang = null;
  486.   this.base = null;
  487.   this.type = "text";
  488.   this.text = null;
  489. }
  490.  
  491. TextConstruct.prototype = {
  492.   plainText: function TC_plainText() {
  493.     if (this.type != "text") {
  494.       return gUnescapeHTML.unescape(stripTags(this.text));
  495.     }
  496.     return this.text;
  497.   },
  498.  
  499.   createDocumentFragment: function TC_createDocumentFragment(element) {
  500.     if (this.type == "text") {
  501.       var doc = element.ownerDocument;
  502.       var docFragment = doc.createDocumentFragment();
  503.       var node = doc.createTextNode(this.text);
  504.       docFragment.appendChild(node);
  505.       return docFragment;
  506.     }
  507.     var isXML;
  508.     if (this.type == "xhtml")
  509.       isXML = true
  510.     else if (this.type == "html")
  511.       isXML = false;
  512.     else
  513.       return null;
  514.  
  515.     return gUnescapeHTML.parseFragment(this.text, isXML, this.base, element);
  516.   },
  517.  
  518.   QueryInterface: function(iid) {
  519.     if (iid.equals(Ci.nsIFeedTextConstruct) ||
  520.         iid.equals(Ci.nsISupports))
  521.     return this;
  522.  
  523.     throw Cr.NS_ERROR_NOINTERFACE;
  524.   }
  525. }
  526.  
  527. // Generator represents the software that produced the feed
  528. function Generator() {
  529.   this.lang = null;
  530.   this.agent = null;
  531.   this.version = null;
  532.   this.uri = null;
  533.  
  534.   // nsIFeedElementBase
  535.   this._attributes = null;
  536.   this.baseURI = null;
  537. }
  538.  
  539. Generator.prototype = {
  540.  
  541.   get attributes() {
  542.     return this._attributes;
  543.   },
  544.  
  545.   set attributes(value) {
  546.     this._attributes = value;
  547.     this.version = this._attributes.getValueFromName("","version");
  548.     var uriAttribute = this._attributes.getValueFromName("","uri") ||
  549.                        this._attributes.getValueFromName("","url");
  550.     this.uri = strToURI(uriAttribute, this.baseURI);
  551.  
  552.     // RSS1
  553.     uriAttribute = this._attributes.getValueFromName(RDF_NS,"resource");
  554.     if (uriAttribute) {
  555.       this.agent = uriAttribute;
  556.       this.uri = strToURI(uriAttribute, this.baseURI);
  557.     }
  558.   },
  559.  
  560.   QueryInterface: function(iid) {
  561.     if (iid.equals(Ci.nsIFeedGenerator) ||
  562.         iid.equals(Ci.nsIFeedElementBase) ||
  563.         iid.equals(Ci.nsISupports))
  564.     return this;
  565.  
  566.     throw Cr.NS_ERROR_NOINTERFACE;
  567.   }
  568. }
  569.  
  570. function Person() {
  571.   this.name = null;
  572.   this.uri = null;
  573.   this.email = null;
  574.  
  575.   // nsIFeedElementBase
  576.   this.attributes = null;
  577.   this.baseURI = null;
  578. }
  579.  
  580. Person.prototype = {
  581.   QueryInterface: function(iid) {
  582.     if (iid.equals(Ci.nsIFeedPerson) ||
  583.         iid.equals(Ci.nsIFeedElementBase) ||
  584.         iid.equals(Ci.nsISupports))
  585.     return this;
  586.  
  587.     throw Cr.NS_ERROR_NOINTERFACE;
  588.   }
  589. }
  590.  
  591. /** 
  592.  * Map a list of fields into properties on a container.
  593.  *
  594.  * @param container An nsIFeedContainer
  595.  * @param fields A list of fields to search for. List members can
  596.  *               be a list, in which case the second member is 
  597.  *               transformation function (like parseInt).
  598.  */
  599. function fieldsToObj(container, fields) {
  600.   var props,prop,field,searchList;
  601.   for (var key in fields) {
  602.     searchList = fields[key];
  603.     for (var i=0; i < searchList.length; ++i) {
  604.       props = searchList[i];
  605.       prop = null;
  606.       field = isArray(props) ? props[0] : props;
  607.       try {
  608.         prop = container.fields.getProperty(field);
  609.       } 
  610.       catch(e) { 
  611.       }
  612.       if (prop) {
  613.         prop = isArray(props) ? props[1](prop) : prop;
  614.         container[key] = prop;
  615.       }
  616.     }
  617.   }
  618. }
  619.  
  620. /**
  621.  * Lower cases an element's localName property
  622.  * @param   element A DOM element.
  623.  *
  624.  * @returns The lower case localName property of the specified element
  625.  */
  626. function LC(element) {
  627.   return element.localName.toLowerCase();
  628. }
  629.  
  630. // TODO move these post-processor functions
  631. // create a generator element
  632. function atomGenerator(s, generator) {
  633.   generator.QueryInterface(Ci.nsIFeedGenerator);
  634.   generator.agent = trimString(s);
  635.   return generator;
  636.  
  637. // post-process an RSS category, map it to the Atom fields.
  638. function rssCatTerm(s, cat) {
  639.   // add slash handling?
  640.   cat.setPropertyAsAString("term", trimString(s));
  641.   return cat;
  642.  
  643. // post-process a GUID 
  644. function rssGuid(s, guid) {
  645.   guid.setPropertyAsAString("guid", trimString(s));
  646.   return guid;
  647. }
  648.  
  649. // post-process an RSS author element
  650. //
  651. // It can contain a field like this:
  652. // 
  653. //  <author>lawyer@boyer.net (Lawyer Boyer)</author>
  654. //
  655. // or, delightfully, a field like this:
  656. //
  657. //  <dc:creator>Simon St.Laurent (mailto:simonstl@simonstl.com)</dc:creator>
  658. //
  659. // We want to split this up and assign it to corresponding Atom
  660. // fields.
  661. //
  662. function rssAuthor(s,author) {
  663.   author.QueryInterface(Ci.nsIFeedPerson);
  664.   // check for RSS2 string format
  665.   var chars = trimString(s);
  666.   var matches = chars.match(/(.*)\((.*)\)/);
  667.   var emailCheck = 
  668.     /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  669.   if (matches) {
  670.     var match1 = trimString(matches[1]);
  671.     var match2 = trimString(matches[2]);
  672.     if (match2.indexOf("mailto:") == 0)
  673.       match2 = match2.substring(7);
  674.     if (emailCheck.test(match1)) {
  675.       author.email = match1;
  676.       author.name = match2;
  677.     }
  678.     else if (emailCheck.test(match2)) {
  679.       author.email = match2;
  680.       author.name = match1;
  681.     }
  682.     else {
  683.       // put it back together
  684.       author.name = match1 + " (" + match2 + ")";
  685.     }
  686.   }
  687.   else {
  688.     author.name = chars;
  689.     if (chars.indexOf('@'))
  690.       author.email = chars;
  691.   }
  692.   return author;
  693. }
  694.  
  695. //
  696. // skipHours and skipDays map to arrays, so we need to change the
  697. // string to an nsISupports in order to stick it in there.
  698. //
  699. function rssArrayElement(s) {
  700.   var str = Cc["@mozilla.org/supports-string;1"].
  701.               createInstance(Ci.nsISupportsString);
  702.   str.data = s;
  703.   str.QueryInterface(Ci.nsISupportsString);
  704.   return str;
  705. }
  706.  
  707. /***** Some feed utils from TBird *****/
  708.  
  709. /**
  710.  * Tests a RFC822 date against a regex.
  711.  * @param aDateStr A string to test as an RFC822 date.
  712.  *
  713.  * @returns A boolean indicating whether the string is a valid RFC822 date.
  714.  */
  715. function isValidRFC822Date(aDateStr) {
  716.   var regex = new RegExp(RFC822_RE);
  717.   return regex.test(aDateStr);
  718. }
  719.  
  720. /**
  721.  * Removes leading and trailing whitespace from a string.
  722.  * @param s The string to trim.
  723.  *
  724.  * @returns A new string with whitespace stripped.
  725.  */
  726. function trimString(s) {
  727.   return(s.replace(/^\s+/, "").replace(/\s+$/, ""));
  728. }
  729.  
  730. // Regular expression matching RFC822 dates 
  731. const RFC822_RE = "^(((Mon)|(Tue)|(Wed)|(Thu)|(Fri)|(Sat)|(Sun)), *)?\\d\\d?"
  732. + " +((Jan)|(Feb)|(Mar)|(Apr)|(May)|(Jun)|(Jul)|(Aug)|(Sep)|(Oct)|(Nov)|(Dec))"
  733. + " +\\d\\d(\\d\\d)? +\\d\\d:\\d\\d(:\\d\\d)? +(([+-]?\\d\\d\\d\\d)|(UT)|(GMT)"
  734. + "|(EST)|(EDT)|(CST)|(CDT)|(MST)|(MDT)|(PST)|(PDT)|\\w)$";
  735.  
  736. /**
  737.  * XXX -- need to decide what this should return. 
  738.  * XXX -- Is there a Date class usable from C++?
  739.  *
  740.  * Tries tries parsing various date formats.
  741.  * @param dateString
  742.  *        A string that is supposedly an RFC822 or RFC3339 date.
  743.  * @returns A Date.toString XXX--fixme
  744.  */
  745. function dateParse(dateString) {
  746.   var date = trimString(dateString);
  747.  
  748.   if (date.search(/^\d\d\d\d/) != -1) //Could be a ISO8601/W3C date
  749.     return W3CToIETFDate(dateString);
  750.  
  751.   if (isValidRFC822Date(date))
  752.     return date; 
  753.   
  754.   if (!isNaN(parseInt(date, 10))) { 
  755.     //It's an integer, so maybe it's a timestamp
  756.     var d = new Date(parseInt(date, 10) * 1000);
  757.     var now = new Date();
  758.     var yeardiff = now.getFullYear() - d.getFullYear();
  759.     if ((yeardiff >= 0) && (yeardiff < 3)) {
  760.       // it's quite likely the correct date. 3 years is an arbitrary cutoff,
  761.       // but this is an invalid date format, and there's no way to verify
  762.       // its correctness.
  763.       return d.toString();
  764.     }
  765.   }
  766.   // Can't help.
  767.   return null;
  768.  
  769.  
  770. const XHTML_NS = "http://www.w3.org/1999/xhtml";
  771.  
  772. // The XHTMLHandler handles inline XHTML found in things like atom:summary
  773. function XHTMLHandler(processor, isAtom) {
  774.   this._buf = "";
  775.   this._processor = processor;
  776.   this._depth = 0;
  777.   this._isAtom = isAtom;
  778. }
  779.  
  780. // The fidelity can be improved here, to allow handling of stuff like
  781. // SVG and MathML. XXX
  782. XHTMLHandler.prototype = {
  783.   startDocument: function XH_startDocument() {
  784.   },
  785.   endDocument: function XH_endDocument() {
  786.   },
  787.   startElement: function XH_startElement(uri, localName, qName, attributes) {
  788.     ++this._depth;
  789.  
  790.     // RFC4287 requires XHTML to be wrapped in a div that is *not* part of 
  791.     // the content. This prevents people from screwing up namespaces, but
  792.     // we need to skip it here.
  793.     if (this._isAtom && this._depth == 1 && localName == "div")
  794.       return;
  795.  
  796.     // If it's an XHTML element, record it. Otherwise, it's ignored.
  797.     if (uri == XHTML_NS) {
  798.       this._buf += "<" + localName;
  799.       for (var i=0; i < attributes.length; ++i) {
  800.         // XHTML attributes aren't in a namespace
  801.         if (attributes.getURI(i) == "") { 
  802.           this._buf += (" " + attributes.getLocalName(i) + "='" +
  803.                         xmlEscape(attributes.getValue(i)) + "'");
  804.         }
  805.       }
  806.       this._buf += ">";
  807.     }
  808.   },
  809.   endElement: function XH_endElement(uri, localName, qName) {
  810.     --this._depth;
  811.     
  812.     // We need to skip outer divs in Atom. See comment in startElement.
  813.     if (this._isAtom && this._depth == 0 && localName == "div")
  814.       return;
  815.  
  816.     // When we peek too far, go back to the main processor
  817.     if (this._depth < 0) {
  818.       this._processor.returnFromXHTMLHandler(trimString(this._buf),
  819.                                              uri, localName, qName);
  820.       return;
  821.     }
  822.     // If it's an XHTML element, record it. Otherwise, it's ignored.
  823.     if (uri == XHTML_NS) {
  824.       this._buf += "</" + localName + ">";
  825.     }
  826.   },
  827.   characters: function XH_characters(data) {
  828.     this._buf += xmlEscape(data);
  829.   },
  830.   startPrefixMapping: function XH_startPrefixMapping() {
  831.   },
  832.   endPrefixMapping: function XH_endPrefixMapping() {
  833.   },
  834.   processingInstruction: function XH_processingInstruction() {
  835.   }, 
  836. }
  837.  
  838. /**
  839.  * The ExtensionHandler deals with elements we haven't explicitly
  840.  * added to our transition table in the FeedProcessor.
  841.  */
  842. function ExtensionHandler(processor) {
  843.   this._buf = "";
  844.   this._depth = 0;
  845.   this._hasChildElements = false;
  846.  
  847.   // The FeedProcessor
  848.   this._processor = processor;
  849.  
  850.   // Fields of the outermost extension element.
  851.   this._localName = null;
  852.   this._uri = null;
  853.   this._qName = null;
  854.   this._attrs = null;
  855. }
  856.  
  857. ExtensionHandler.prototype = {
  858.   startDocument: function EH_startDocument() {
  859.   },
  860.   endDocument: function EH_endDocument() {
  861.   },
  862.   startElement: function EH_startElement(uri, localName, qName, attrs) {
  863.     ++this._depth;
  864.     var prefix = gNamespaces[uri] ? gNamespaces[uri] + ":" : "";
  865.     var key =  prefix + localName;
  866.     
  867.     if (this._depth == 1) {
  868.       this._uri = uri;
  869.       this._localName = localName;
  870.       this._qName = qName;
  871.       this._attrs = attrs;
  872.     }
  873.     
  874.     // if we descend into another element, we won't send text
  875.     this._hasChildElements = (this._depth > 1);
  876.     
  877.   },
  878.   endElement: function EH_endElement(uri, localName, qName) {
  879.     --this._depth;
  880.     if (this._depth == 0) {
  881.       var text = this._hasChildElements ? null : trimString(this._buf);
  882.       this._processor.returnFromExtHandler(this._uri, this._localName, 
  883.                                            text, this._attrs);
  884.     }
  885.   },
  886.   characters: function EH_characters(data) {
  887.     if (!this._hasChildElements)
  888.       this._buf += data;
  889.   },
  890.   startPrefixMapping: function EH_startPrefixMapping() {
  891.   },
  892.   endPrefixMapping: function EH_endPrefixMapping() {
  893.   },
  894.   processingInstruction: function EH_processingInstruction() {
  895.   }, 
  896. };
  897.  
  898.  
  899. /**
  900.  * ElementInfo is a simple container object that describes
  901.  * some characteristics of a feed element. For example, it
  902.  * says whether an element can be expected to appear more
  903.  * than once inside a given entry or feed.
  904.  */ 
  905. function ElementInfo(fieldName, containerClass, closeFunc, isArray) {
  906.   this.fieldName = fieldName;
  907.   this.containerClass = containerClass;
  908.   this.closeFunc = closeFunc;
  909.   this.isArray = isArray;
  910.   this.isWrapper = false;
  911. }
  912.  
  913. /**
  914.  * FeedElementInfo represents a feed element, usually the root.
  915.  */
  916. function FeedElementInfo(fieldName, feedVersion) {
  917.   this.isWrapper = false;
  918.   this.fieldName = fieldName;
  919.   this.feedVersion = feedVersion;
  920. }
  921.  
  922. /**
  923.  * Some feed formats include vestigial wrapper elements that we don't
  924.  * want to include in our object model, but we do need to keep track
  925.  * of during parsing.
  926.  */
  927. function WrapperElementInfo(fieldName) {
  928.   this.isWrapper = true;
  929.   this.fieldName = fieldName;
  930. }
  931.  
  932. /***** The Processor *****/
  933. function FeedProcessor() {
  934.   this._reader = Cc[SAX_CONTRACTID].createInstance(Ci.nsISAXXMLReader);
  935.   this._buf =  "";
  936.   this._feed = Cc[BAG_CONTRACTID].createInstance(Ci.nsIWritablePropertyBag2);
  937.   this._handlerStack = [];
  938.   this._xmlBaseStack = []; // sparse array keyed to nesting depth
  939.   this._depth = 0;
  940.   this._state = "START";
  941.   this._result = null;
  942.   this._extensionHandler = null;
  943.   this._xhtmlHandler = null;
  944.  
  945.   // The nsIFeedResultListener waiting for the parse results
  946.   this.listener = null;
  947.  
  948.   // These elements can contain (X)HTML or plain text.
  949.   // We keep a table here that contains their default treatment
  950.   this._textConstructs = {"atom:title":"text",
  951.                           "atom:summary":"text",
  952.                           "atom:rights":"text",
  953.                           "atom:content":"text",
  954.                           "atom:subtitle":"text",
  955.                           "description":"html",
  956.                           "rss1:description":"html",
  957.                           "dc:description":"html",
  958.                           "content:encoded":"html",
  959.                           "title":"text",
  960.                           "rss1:title":"text",
  961.                           "atom03:title":"text",
  962.                           "atom03:tagline":"text",
  963.                           "atom03:summary":"text",
  964.                           "atom03:content":"text"};
  965.   this._stack = [];
  966.  
  967.   this._trans = {   
  968.     "START": {
  969.       //If we hit a root RSS element, treat as RSS2.
  970.       "rss": new FeedElementInfo("RSS2", "rss2"),
  971.  
  972.       // If we hit an RDF element, if could be RSS1, but we can't
  973.       // verify that until we hit a rss1:channel element.
  974.       "rdf:RDF": new WrapperElementInfo("RDF"),
  975.  
  976.       // If we hit a Atom 1.0 element, treat as Atom 1.0.
  977.       "atom:feed": new FeedElementInfo("Atom", "atom"),
  978.  
  979.       // Treat as Atom 0.3
  980.       "atom03:feed": new FeedElementInfo("Atom03", "atom03"),
  981.     },
  982.     
  983.     /********* RSS2 **********/
  984.     "IN_RSS2": {
  985.       "channel": new WrapperElementInfo("channel")
  986.     },
  987.  
  988.     "IN_CHANNEL": {
  989.       "item": new ElementInfo("items", Cc[ENTRY_CONTRACTID], null, true),
  990.       "managingEditor": new ElementInfo("authors", Cc[PERSON_CONTRACTID],
  991.                                         rssAuthor, true),
  992.       "dc:creator": new ElementInfo("authors", Cc[PERSON_CONTRACTID],
  993.                                     rssAuthor, true),
  994.       "dc:author": new ElementInfo("authors", Cc[PERSON_CONTRACTID],
  995.                                    rssAuthor, true),
  996.       "dc:contributor": new ElementInfo("contributors", Cc[PERSON_CONTRACTID],
  997.                                          rssAuthor, true),
  998.       "category": new ElementInfo("categories", null, rssCatTerm, true),
  999.       "cloud": new ElementInfo("cloud", null, null, false),
  1000.       "image": new ElementInfo("image", null, null, false),
  1001.       "textInput": new ElementInfo("textInput", null, null, false),
  1002.       "skipDays": new ElementInfo("skipDays", null, null, false),
  1003.       "skipHours": new ElementInfo("skipHours", null, null, false),
  1004.       "generator": new ElementInfo("generator", Cc[GENERATOR_CONTRACTID],
  1005.                                    atomGenerator, false),
  1006.     },
  1007.  
  1008.     "IN_ITEMS": {
  1009.       "author": new ElementInfo("authors", Cc[PERSON_CONTRACTID],
  1010.                                 rssAuthor, true),
  1011.       "dc:creator": new ElementInfo("authors", Cc[PERSON_CONTRACTID],
  1012.                                     rssAuthor, true),
  1013.       "dc:author": new ElementInfo("authors", Cc[PERSON_CONTRACTID],
  1014.                                    rssAuthor, true),
  1015.       "dc:contributor": new ElementInfo("contributors", Cc[PERSON_CONTRACTID],
  1016.                                          rssAuthor, true),
  1017.       "category": new ElementInfo("categories", null, rssCatTerm, true),
  1018.       "enclosure": new ElementInfo("enclosure", null, null, true),
  1019.       "guid": new ElementInfo("guid", null, rssGuid, false)
  1020.     },
  1021.  
  1022.     "IN_SKIPDAYS": {
  1023.       "day": new ElementInfo("days", null, rssArrayElement, true)
  1024.     },
  1025.  
  1026.     "IN_SKIPHOURS":{
  1027.       "hour": new ElementInfo("hours", null, rssArrayElement, true)
  1028.     },
  1029.  
  1030.     /********* RSS1 **********/
  1031.     "IN_RDF": {
  1032.       // If we hit a rss1:channel, we can verify that we have RSS1
  1033.       "rss1:channel": new FeedElementInfo("rdf_channel", "rss1"),
  1034.       "rss1:image": new ElementInfo("image", null, null, false),
  1035.       "rss1:textinput": new ElementInfo("textInput", null, null, false),
  1036.       "rss1:item": new ElementInfo("items", Cc[ENTRY_CONTRACTID], null, true),
  1037.     },
  1038.  
  1039.     "IN_RDF_CHANNEL": {
  1040.       "admin:generatorAgent": new ElementInfo("generator",
  1041.                                               Cc[GENERATOR_CONTRACTID],
  1042.                                               null, false),
  1043.       "dc:creator": new ElementInfo("authors", Cc[PERSON_CONTRACTID],
  1044.                                     rssAuthor, true),
  1045.       "dc:author": new ElementInfo("authors", Cc[PERSON_CONTRACTID],
  1046.                                    rssAuthor, true),
  1047.       "dc:contributor": new ElementInfo("contributors", Cc[PERSON_CONTRACTID],
  1048.                                          rssAuthor, true),
  1049.     },
  1050.  
  1051.     /********* ATOM 1.0 **********/
  1052.     "IN_ATOM": {
  1053.       "atom:author": new ElementInfo("authors", Cc[PERSON_CONTRACTID],
  1054.                                      null, true),
  1055.       "atom:generator": new ElementInfo("generator", Cc[GENERATOR_CONTRACTID],
  1056.                                         atomGenerator, false),
  1057.       "atom:contributor": new ElementInfo("contributors",  Cc[PERSON_CONTRACTID],
  1058.                                           null, true),
  1059.       "atom:link": new ElementInfo("links", null, null, true),
  1060.       "atom:entry": new ElementInfo("entries", Cc[ENTRY_CONTRACTID],
  1061.                                     null, true)
  1062.     },
  1063.  
  1064.     "IN_ENTRIES": {
  1065.       "atom:author": new ElementInfo("authors", Cc[PERSON_CONTRACTID],
  1066.                                      null, true),
  1067.       "atom:contributor": new ElementInfo("contributors", Cc[PERSON_CONTRACTID],
  1068.                                           null, true),
  1069.       "atom:link": new ElementInfo("links", null, null, true),
  1070.     },
  1071.  
  1072.     /********* ATOM 0.3 **********/
  1073.     "IN_ATOM03": {
  1074.       "atom03:author": new ElementInfo("authors", Cc[PERSON_CONTRACTID],
  1075.                                        null, true),
  1076.       "atom03:contributor": new ElementInfo("contributors",
  1077.                                             Cc[PERSON_CONTRACTID],
  1078.                                             null, true),
  1079.       "atom03:link": new ElementInfo("links", null, null, true),
  1080.       "atom03:entry": new ElementInfo("atom03_entries", Cc[ENTRY_CONTRACTID],
  1081.                                       null, true),
  1082.       "atom03:generator": new ElementInfo("generator", Cc[GENERATOR_CONTRACTID],
  1083.                                           atomGenerator, false),
  1084.     },
  1085.  
  1086.     "IN_ATOM03_ENTRIES": {
  1087.       "atom03:author": new ElementInfo("authors", Cc[PERSON_CONTRACTID],
  1088.                                        null, true),
  1089.       "atom03:contributor": new ElementInfo("contributors",
  1090.                                             Cc[PERSON_CONTRACTID],
  1091.                                             null, true),
  1092.       "atom03:link": new ElementInfo("links", null, null, true),
  1093.       "atom03:entry": new ElementInfo("atom03_entries", Cc[ENTRY_CONTRACTID],
  1094.                                       null, true)
  1095.     }
  1096.   }
  1097. }
  1098.  
  1099. // See startElement for a long description of how feeds are processed.
  1100. FeedProcessor.prototype = { 
  1101.   
  1102.   // Set ourselves as the SAX handler, and set the base URI
  1103.   _init: function FP_init(uri) {
  1104.     this._reader.contentHandler = this;
  1105.     this._reader.errorHandler = this;
  1106.     this._result = Cc[FR_CONTRACTID].createInstance(Ci.nsIFeedResult);
  1107.     if (uri) {
  1108.       this._result.uri = uri;
  1109.       this._reader.baseURI = uri;
  1110.       this._xmlBaseStack[0] = uri;
  1111.     }
  1112.   },
  1113.  
  1114.   // This function is called once we figure out what type of feed
  1115.   // we're dealing with. Some feed types require digging a bit further
  1116.   // than the root.
  1117.   _docVerified: function FP_docVerified(version) {
  1118.     this._result.doc = Cc[FEED_CONTRACTID].createInstance(Ci.nsIFeed);
  1119.     this._result.doc.baseURI = 
  1120.       this._xmlBaseStack[this._xmlBaseStack.length - 1];
  1121.     this._result.doc.fields = this._feed;
  1122.     this._result.version = version;
  1123.   },
  1124.  
  1125.   // When we're done with the feed, let the listener know what
  1126.   // happened.
  1127.   _sendResult: function FP_sendResult() {
  1128.     try {
  1129.       // Can be null when a non-feed is fed to us
  1130.       if (this._result.doc)
  1131.         this._result.doc.normalize();
  1132.     }
  1133.     catch (e) {
  1134.       LOG("FIXME: " + e);
  1135.     }
  1136.  
  1137.     try {
  1138.       if (this.listener != null)
  1139.         this.listener.handleResult(this._result);
  1140.     }
  1141.     finally {
  1142.       this._result = null;
  1143.       this._reader = null;
  1144.     }
  1145.   },
  1146.  
  1147.   // Parsing functions
  1148.   parseFromStream: function FP_parseFromStream(stream, uri) {
  1149.     this._init(uri);
  1150.     this._reader.parseFromStream(stream, null, stream.available(), 
  1151.                                  "application/xml");
  1152.     this._reader = null;
  1153.   },
  1154.  
  1155.   parseFromString: function FP_parseFromString(inputString, uri) {
  1156.     this._init(uri);
  1157.     this._reader.parseFromString(inputString, "application/xml");
  1158.     this._reader = null;
  1159.   },
  1160.  
  1161.   parseAsync: function FP_parseAsync(requestObserver, uri) {
  1162.     this._init(uri);
  1163.     this._reader.parseAsync(requestObserver);
  1164.   },
  1165.  
  1166.   // nsIStreamListener 
  1167.  
  1168.   // The XMLReader will throw sensible exceptions if these get called
  1169.   // out of order.
  1170.   onStartRequest: function FP_onStartRequest(request, context) {
  1171.     this._reader.onStartRequest(request, context);
  1172.   },
  1173.  
  1174.   onStopRequest: function FP_onStopRequest(request, context, statusCode) {
  1175.     this._reader.onStopRequest(request, context, statusCode);
  1176.   },
  1177.  
  1178.   onDataAvailable:
  1179.   function FP_onDataAvailable(request, context, inputStream, offset, count) {
  1180.     this._reader.onDataAvailable(request, context, inputStream, offset, count);
  1181.   },
  1182.  
  1183.   // nsISAXErrorHandler
  1184.  
  1185.   // We only care about fatal errors. When this happens, we may have
  1186.   // parsed through the feed metadata and some number of entries. The
  1187.   // listener can still show some of that data if it wants, and we'll
  1188.   // set the bozo bit to indicate we were unable to parse all the way
  1189.   // through.
  1190.   fatalError: function FP_reportError() {
  1191.     this._result.bozo = true;
  1192.     //XXX need to QI to FeedProgressListener
  1193.     this._sendResult();
  1194.   },
  1195.  
  1196.   // nsISAXContentHandler
  1197.  
  1198.   startDocument: function FP_startDocument() {
  1199.     //LOG("----------");
  1200.   },
  1201.  
  1202.   endDocument: function FP_endDocument() {
  1203.     this._sendResult();
  1204.   },
  1205.  
  1206.   // The transitions defined above identify elements that contain more
  1207.   // than just text. For example RSS items contain many fields, and so
  1208.   // do Atom authors. The only commonly used elements that contain
  1209.   // mixed content are Atom Text Constructs of type="xhtml", which we
  1210.   // delegate to another handler for cleaning. That leaves a couple
  1211.   // different types of elements to deal with: those that should occur
  1212.   // only once, such as title elements, and those that can occur
  1213.   // multiple times, such as the RSS category element and the Atom
  1214.   // link element. Most of the RSS1/DC elements can occur multiple
  1215.   // times in theory, but in practice, the only ones that do have
  1216.   // analogues in Atom. 
  1217.   //
  1218.   // Some elements are also groups of attributes or sub-elements,
  1219.   // while others are simple text fields. For the most part, we don't
  1220.   // have to pay explicit attention to the simple text elements,
  1221.   // unless we want to post-process the resulting string to transform
  1222.   // it into some richer object like a Date or URI.
  1223.   //
  1224.   // Elements that have more sophisticated content models still end up
  1225.   // being dictionaries, whether they are based on attributes like RSS
  1226.   // cloud, sub-elements like Atom author, or even items and
  1227.   // entries. These elements are treated as "containers". It's
  1228.   // theoretically possible for a container to have an attribute with 
  1229.   // the same universal name as a sub-element, but none of the feed
  1230.   // formats allow this by default, and I don't of any extension that
  1231.   // works this way.
  1232.   //
  1233.   startElement: function FP_startElement(uri, localName, qName, attributes) {
  1234.     this._buf = "";
  1235.     ++this._depth;
  1236.     var elementInfo;
  1237.  
  1238.     //LOG("<" + localName + ">");
  1239.  
  1240.     // Check for xml:base
  1241.     var base = attributes.getValueFromName(XMLNS, "base");
  1242.     if (base) {
  1243.       this._xmlBaseStack[this._depth] =
  1244.         strToURI(base, this._xmlBaseStack[this._xmlBaseStack.length - 1]);
  1245.     }
  1246.  
  1247.     // To identify the element we're dealing with, we look up the
  1248.     // namespace URI in our gNamespaces dictionary, which will give us
  1249.     // a "canonical" prefix for a namespace URI. For example, this
  1250.     // allows Dublin Core "creator" elements to be consistently mapped
  1251.     // to "dc:creator", for easy field access by consumer code. This
  1252.     // strategy also happens to shorten up our state table.
  1253.     var key =  this._prefixForNS(uri) + localName;
  1254.  
  1255.     // Check to see if we need to hand this off to our XHTML handler.
  1256.     // The elements we're dealing with will look like this:
  1257.     // 
  1258.     // <title type="xhtml">
  1259.     //   <div xmlns="http://www.w3.org/1999/xhtml">
  1260.     //     A title with <b>bold</b> and <i>italics</i>.
  1261.     //   </div>
  1262.     // </title>
  1263.     //
  1264.     // When it returns in returnFromXHTMLHandler, the handler should
  1265.     // give us back a string like this: 
  1266.     // 
  1267.     //    "A title with <b>bold</b> and <i>italics</i>."
  1268.     //
  1269.     // The Atom spec explicitly says the div is not part of the content,
  1270.     // and explicitly allows whitespace collapsing.
  1271.     // 
  1272.     if ((this._result.version == "atom" || this._result.version == "atom03") &&
  1273.         this._textConstructs[key] != null) {
  1274.       var type = attributes.getValueFromName("","type");
  1275.       if (type != null && type.indexOf("xhtml") >= 0) {
  1276.         this._xhtmlHandler = 
  1277.           new XHTMLHandler(this, (this._result.version == "atom"));
  1278.         this._reader.contentHandler = this._xhtmlHandler;
  1279.         return;
  1280.       }
  1281.     }
  1282.  
  1283.     // Check our current state, and see if that state has a defined
  1284.     // transition. For example, this._trans["atom:entry"]["atom:author"]
  1285.     // will have one, and it tells us to add an item to our authors array.
  1286.     if (this._trans[this._state] && this._trans[this._state][key]) {
  1287.       elementInfo = this._trans[this._state][key];
  1288.     }
  1289.     else {
  1290.       // If we don't have a transition, hand off to extension handler
  1291.       this._extensionHandler = new ExtensionHandler(this);
  1292.       this._reader.contentHandler = this._extensionHandler;
  1293.       this._extensionHandler.startElement(uri, localName, qName, attributes);
  1294.       return;
  1295.     }
  1296.       
  1297.     // This distinguishes wrappers like 'channel' from elements
  1298.     // we'd actually like to do something with (which will test true).
  1299.     this._handlerStack[this._depth] = elementInfo; 
  1300.     if (elementInfo.isWrapper) {
  1301.       this._state = "IN_" + elementInfo.fieldName.toUpperCase();
  1302.       this._stack.push([this._feed, this._state]);
  1303.     } 
  1304.     else if (elementInfo.feedVersion) {
  1305.       this._state = "IN_" + elementInfo.fieldName.toUpperCase();
  1306.  
  1307.       // Check for the older RSS2 variants
  1308.       if (elementInfo.feedVersion == "rss2")
  1309.         elementInfo.feedVersion = this._findRSSVersion(attributes);
  1310.       else if (uri == RSS090NS)
  1311.         elementInfo.feedVersion = "rss090";
  1312.  
  1313.       this._docVerified(elementInfo.feedVersion);
  1314.       this._stack.push([this._feed, this._state]);
  1315.       this._mapAttributes(this._feed, attributes);
  1316.     }
  1317.     else {
  1318.       this._state = this._processComplexElement(elementInfo, attributes);
  1319.     }
  1320.   },
  1321.  
  1322.   // In the endElement handler, we decrement the stack and look
  1323.   // for cleanup/transition functions to execute. The second part
  1324.   // of the state transition works as above in startElement, but
  1325.   // the state we're looking for is prefixed with an underscore
  1326.   // to distinguish endElement events from startElement events.
  1327.   endElement:  function FP_endElement(uri, localName, qName) {
  1328.     var elementInfo = this._handlerStack[this._depth];
  1329.     //LOG("</" + localName + ">");
  1330.     if (elementInfo && !elementInfo.isWrapper)
  1331.       this._closeComplexElement(elementInfo);
  1332.   
  1333.     // cut down xml:base context
  1334.     if (this._xmlBaseStack.length == this._depth + 1)
  1335.       this._xmlBaseStack = this._xmlBaseStack.slice(0, this._depth);
  1336.  
  1337.     // our new state is whatever is at the top of the stack now
  1338.     if (this._stack.length > 0)
  1339.       this._state = this._stack[this._stack.length - 1][1];
  1340.     this._handlerStack = this._handlerStack.slice(0, this._depth);
  1341.     --this._depth;
  1342.   },
  1343.  
  1344.   // Buffer up character data. The buffer is cleared with every
  1345.   // opening element.
  1346.   characters: function FP_characters(data) {
  1347.     this._buf += data;
  1348.   },
  1349.  
  1350.   // TODO: It would be nice to check new prefixes here, and if they
  1351.   // don't conflict with the ones we've defined, throw them in a 
  1352.   // dictionary to check.
  1353.   startPrefixMapping: function FP_startPrefixMapping() {
  1354.   },
  1355.   endPrefixMapping: function FP_endPrefixMapping() {
  1356.   },
  1357.   processingInstruction: function FP_processingInstruction(target, data) {
  1358.     if (target == "xml-stylesheet") {
  1359.       var hrefAttribute = data.match(/href=[\"\'](.*?)[\"\']/);
  1360.       if (hrefAttribute && hrefAttribute.length == 2) 
  1361.         this._result.stylesheet = gIoService.newURI(hrefAttribute[1], null,
  1362.                                                     this._result.uri);
  1363.     }
  1364.   },
  1365.  
  1366.   // end of nsISAXContentHandler
  1367.  
  1368.   // Handle our more complicated elements--those that contain
  1369.   // attributes and child elements.
  1370.   _processComplexElement:
  1371.   function FP__processComplexElement(elementInfo, attributes) {
  1372.     var obj, key, prefix;
  1373.  
  1374.     // If the container is an entry/item, it'll need to have its 
  1375.     // more esoteric properties put in the 'fields' property bag.
  1376.     if (elementInfo.containerClass == Cc[ENTRY_CONTRACTID]) {
  1377.       obj = elementInfo.containerClass.createInstance(Ci.nsIFeedEntry);
  1378.       obj.baseURI = this._xmlBaseStack[this._xmlBaseStack.length - 1];
  1379.       this._mapAttributes(obj.fields, attributes);
  1380.     }
  1381.     else if (elementInfo.containerClass) {
  1382.       obj = elementInfo.containerClass.createInstance(Ci.nsIFeedElementBase);
  1383.       obj.baseURI = this._xmlBaseStack[this._xmlBaseStack.length - 1];
  1384.       obj.attributes = attributes; // just set the SAX attributes
  1385.     }
  1386.     else {
  1387.       obj = Cc[BAG_CONTRACTID].createInstance(Ci.nsIWritablePropertyBag2);
  1388.       this._mapAttributes(obj, attributes);
  1389.     }
  1390.  
  1391.     // We should have a container/propertyBag that's had its
  1392.     // attributes processed. Now we need to attach it to its
  1393.     // container.
  1394.     var newProp;
  1395.  
  1396.     // First we'll see what's on top of the stack.
  1397.     var container = this._stack[this._stack.length - 1][0];
  1398.  
  1399.     // Check to see if it has the property
  1400.     var prop;
  1401.     try {
  1402.       prop = container.getProperty(elementInfo.fieldName);
  1403.     }
  1404.     catch(e) {
  1405.     }
  1406.     
  1407.     if (elementInfo.isArray) {
  1408.       if (!prop) {
  1409.         container.setPropertyAsInterface(elementInfo.fieldName,
  1410.                                          Cc[ARRAY_CONTRACTID].
  1411.                                          createInstance(Ci.nsIMutableArray));
  1412.       }
  1413.  
  1414.       newProp = container.getProperty(elementInfo.fieldName);
  1415.       // XXX This QI should not be necessary, but XPConnect seems to fly
  1416.       // off the handle in the browser, and loses track of the interface
  1417.       // on large files. Bug 335638.
  1418.       newProp.QueryInterface(Ci.nsIMutableArray);
  1419.       newProp.appendElement(obj,false);
  1420.       
  1421.       // If new object is an nsIFeedContainer, we want to deal with
  1422.       // its member nsIPropertyBag instead.
  1423.       if (isIFeedContainer(obj))
  1424.         newProp = obj.fields; 
  1425.  
  1426.     }
  1427.     else {
  1428.       // If it doesn't, set it.
  1429.       if (!prop) {
  1430.         container.setPropertyAsInterface(elementInfo.fieldName,obj);
  1431.       }
  1432.       newProp = container.getProperty(elementInfo.fieldName);
  1433.     }
  1434.     
  1435.     // make our new state name, and push the property onto the stack
  1436.     var newState = "IN_" + elementInfo.fieldName.toUpperCase();
  1437.     this._stack.push([newProp, newState, obj]);
  1438.     return newState;
  1439.   },
  1440.  
  1441.   // Sometimes we need reconcile the element content with the object
  1442.   // model for a given feed. We use helper functions to do the
  1443.   // munging, but we need to identify array types here, so the munging
  1444.   // happens only to the last element of an array.
  1445.   _closeComplexElement: function FP__closeComplexElement(elementInfo) {
  1446.     var stateTuple = this._stack.pop();
  1447.     var container = stateTuple[0];
  1448.     var containerParent = stateTuple[2];
  1449.     var element = null;
  1450.     var isArray = isIArray(container);
  1451.  
  1452.     // If it's an array and we have to post-process,
  1453.     // grab the last element
  1454.     if (isArray)
  1455.       element = container.queryElementAt(container.length - 1, Ci.nsISupports);
  1456.     else
  1457.       element = container;
  1458.  
  1459.     // Run the post-processing function if there is one.
  1460.     if (elementInfo.closeFunc)
  1461.       element = elementInfo.closeFunc(this._buf, element);
  1462.  
  1463.     // If an nsIFeedContainer was on top of the stack,
  1464.     // we need to normalize it
  1465.     if (elementInfo.containerClass == Cc[ENTRY_CONTRACTID])
  1466.       containerParent.normalize();
  1467.  
  1468.     // If it's an array, re-set the last element
  1469.     if (isArray)
  1470.       container.replaceElementAt(element, container.length - 1, false);
  1471.   },
  1472.   
  1473.   _prefixForNS: function FP_prefixForNS(uri) {
  1474.     if (!uri)
  1475.       return "";
  1476.     var prefix = gNamespaces[uri];
  1477.     if (prefix)
  1478.       return prefix + ":";
  1479.     if (uri.toLowerCase().indexOf("http://backend.userland.com") == 0)
  1480.       return "";
  1481.     else
  1482.       return null;
  1483.   },
  1484.  
  1485.   _mapAttributes: function FP__mapAttributes(bag, attributes) {
  1486.     // Cycle through the attributes, and set our properties using the
  1487.     // prefix:localNames we find in our namespace dictionary.
  1488.     for (var i = 0; i < attributes.length; ++i) {
  1489.       var key = this._prefixForNS(attributes.getURI(i)) + attributes.getLocalName(i);
  1490.       var val = attributes.getValue(i);
  1491.       bag.setPropertyAsAString(key, val);
  1492.     }
  1493.   },
  1494.  
  1495.   // Only for RSS2esque formats
  1496.   _findRSSVersion: function FP__findRSSVersion(attributes) {
  1497.     var versionAttr = trimString(attributes.getValueFromName("", "version"));
  1498.     var versions = { "0.91":"rss091",
  1499.                      "0.92":"rss092",
  1500.                      "0.93":"rss093",
  1501.                      "0.94":"rss094" }
  1502.     if (versions[versionAttr])
  1503.       return versions[versionAttr];
  1504.     if (versionAttr.substr(0,2) != "2.")
  1505.       return "rssUnknown";
  1506.     return "rss2";
  1507.   },
  1508.  
  1509.   // unknown element values are returned here. See startElement above
  1510.   // for how this works.
  1511.   returnFromExtHandler:
  1512.   function FP_returnExt(uri, localName, chars, attributes) {
  1513.     --this._depth;
  1514.  
  1515.     // take control of the SAX events
  1516.     this._reader.contentHandler = this;
  1517.     if (localName == null && chars == null)
  1518.       return;
  1519.  
  1520.     // we don't take random elements inside rdf:RDF
  1521.     if (this._state == "IN_RDF")
  1522.       return;
  1523.     
  1524.     // Grab the top of the stack
  1525.     var top = this._stack[this._stack.length - 1];
  1526.     if (!top) 
  1527.       return;
  1528.  
  1529.     var container = top[0];
  1530.     // Grab the last element if it's an array
  1531.     if (isIArray(container)) {
  1532.       var contract = this._handlerStack[this._depth].containerClass;
  1533.       // check if it's something specific, but not an entry
  1534.       if (contract && contract != Cc[ENTRY_CONTRACTID]) {
  1535.         var el = container.queryElementAt(container.length - 1, 
  1536.                                           Ci.nsIFeedElementBase);
  1537.         // XXX there must be a way to flatten these interfaces
  1538.         if (contract == Cc[PERSON_CONTRACTID]) 
  1539.           el.QueryInterface(Ci.nsIFeedPerson);
  1540.         else
  1541.           return; // don't know about this interface
  1542.  
  1543.         var propName = localName;
  1544.         var prefix = gNamespaces[uri];
  1545.  
  1546.         // synonyms
  1547.         if ((uri == "" || 
  1548.              prefix &&
  1549.              ((prefix.indexOf("atom") > -1) ||
  1550.               (prefix.indexOf("rss") > -1))) && 
  1551.             (propName == "url" || propName == "href"))
  1552.           propName = "uri";
  1553.         
  1554.         try {
  1555.           if (el[propName] !== "undefined") {
  1556.             var propValue = chars;
  1557.             // convert URI-bearing values to an nsIURI
  1558.             if (propName == "uri") {
  1559.               var base = this._xmlBaseStack[this._xmlBaseStack.length - 1];
  1560.               propValue = strToURI(chars, base);
  1561.             }
  1562.             el[propName] = propValue;
  1563.           }
  1564.         }
  1565.         catch(e) {
  1566.           // ignore XPConnect errors
  1567.         }
  1568.         // the rest of the function deals with entry- and feed-level stuff
  1569.         return; 
  1570.       } 
  1571.       else {
  1572.         container = container.queryElementAt(container.length - 1, 
  1573.                                              Ci.nsIWritablePropertyBag2);
  1574.       }
  1575.     }
  1576.     
  1577.     // Make the buffer our new property
  1578.     var propName = this._prefixForNS(uri) + localName;
  1579.  
  1580.     // But, it could be something containing HTML. If so,
  1581.     // we need to know about that.
  1582.     if (this._textConstructs[propName] != null &&
  1583.         this._handlerStack[this._depth].containerClass !== null) {
  1584.       var newProp = Cc[TEXTCONSTRUCT_CONTRACTID].
  1585.                     createInstance(Ci.nsIFeedTextConstruct);
  1586.       newProp.text = chars;
  1587.       // Look up the default type in our table
  1588.       var type = this._textConstructs[propName];
  1589.       var typeAttribute = attributes.getValueFromName("","type");
  1590.       if (this._result.version == "atom" && typeAttribute != null) {
  1591.         type = typeAttribute;
  1592.       }
  1593.       else if (this._result.version == "atom03" && typeAttribute != null) {
  1594.         if (typeAttribute.toLowerCase().indexOf("xhtml") >= 0) {
  1595.           type = "xhtml";
  1596.         }
  1597.         else if (typeAttribute.toLowerCase().indexOf("html") >= 0) {
  1598.           type = "html";
  1599.         }
  1600.         else if (typeAttribute.toLowerCase().indexOf("text") >= 0) {
  1601.           type = "text";
  1602.         }
  1603.       }
  1604.       
  1605.       // If it's rss feed-level description, it's not supposed to have html
  1606.       if (this._result.version.indexOf("rss") >= 0 &&
  1607.           this._handlerStack[this._depth].containerClass != ENTRY_CONTRACTID) {
  1608.         type = "text";
  1609.       }
  1610.  
  1611.       newProp.type = type;
  1612.       newProp.base = this._xmlBaseStack[this._xmlBaseStack.length - 1];
  1613.       container.setPropertyAsInterface(propName, newProp);
  1614.     }
  1615.     else {
  1616.       container.setPropertyAsAString(propName, chars);
  1617.     }
  1618.     
  1619.   },
  1620.  
  1621.   // Sometimes, we'll hand off SAX handling duties to an XHTMLHandler
  1622.   // (see above) that will scrape out non-XHTML stuff, normalize
  1623.   // namespaces, and remove the wrapper div from Atom 1.0. When the
  1624.   // XHTMLHandler is done, it'll callback here.
  1625.   returnFromXHTMLHandler:
  1626.   function FP_returnFromXHTMLHandler(chars, uri, localName, qName) {
  1627.     // retake control of the SAX content events
  1628.     this._reader.contentHandler = this;
  1629.  
  1630.     // Grab the top of the stack
  1631.     var top = this._stack[this._stack.length - 1];
  1632.     if (!top) 
  1633.       return;
  1634.     var container = top[0];
  1635.  
  1636.     // Assign the property
  1637.     var newProp =  newProp = Cc[TEXTCONSTRUCT_CONTRACTID].
  1638.                    createInstance(Ci.nsIFeedTextConstruct);
  1639.     newProp.text = chars;
  1640.     newProp.type = "xhtml";
  1641.     newProp.base = this._xmlBaseStack[this._xmlBaseStack.length - 1];
  1642.     container.setPropertyAsInterface(this._prefixForNS(uri) + localName,
  1643.                                      newProp);
  1644.     
  1645.     // XHTML will cause us to peek too far. The XHTML handler will
  1646.     // send us an end element to call. RFC4287-valid feeds allow a
  1647.     // more graceful way to handle this. Unfortunately, we can't count
  1648.     // on compliance at this point.
  1649.     this.endElement(uri, localName, qName);
  1650.   },
  1651.  
  1652.   // nsISupports
  1653.   QueryInterface: function FP_QueryInterface(iid) {
  1654.     if (iid.equals(Ci.nsIFeedProcessor) ||
  1655.         iid.equals(Ci.nsISAXContentHandler) ||
  1656.         iid.equals(Ci.nsISAXErrorHandler) ||
  1657.         iid.equals(Ci.nsIStreamListener) ||
  1658.         iid.equals(Ci.nsIRequestObserver) ||
  1659.         iid.equals(Ci.nsISupports))
  1660.       return this;
  1661.  
  1662.     throw Cr.NS_ERROR_NOINTERFACE;
  1663.   },
  1664. }
  1665.  
  1666. const FP_CONTRACTID = "@mozilla.org/feed-processor;1";
  1667. const FP_CLASSID = Components.ID("{26acb1f0-28fc-43bc-867a-a46aabc85dd4}");
  1668. const FP_CLASSNAME = "Feed Processor";
  1669. const FR_CONTRACTID = "@mozilla.org/feed-result;1";
  1670. const FR_CLASSID = Components.ID("{072a5c3d-30c6-4f07-b87f-9f63d51403f2}");
  1671. const FR_CLASSNAME = "Feed Result";
  1672. const FEED_CONTRACTID = "@mozilla.org/feed;1";
  1673. const FEED_CLASSID = Components.ID("{5d0cfa97-69dd-4e5e-ac84-f253162e8f9a}");
  1674. const FEED_CLASSNAME = "Feed";
  1675. const ENTRY_CONTRACTID = "@mozilla.org/feed-entry;1";
  1676. const ENTRY_CLASSID = Components.ID("{8e4444ff-8e99-4bdd-aa7f-fb3c1c77319f}");
  1677. const ENTRY_CLASSNAME = "Feed Entry";
  1678. const TEXTCONSTRUCT_CONTRACTID = "@mozilla.org/feed-textconstruct;1";
  1679. const TEXTCONSTRUCT_CLASSID =
  1680.   Components.ID("{b992ddcd-3899-4320-9909-924b3e72c922}");
  1681. const TEXTCONSTRUCT_CLASSNAME = "Feed Text Construct";
  1682. const GENERATOR_CONTRACTID = "@mozilla.org/feed-generator;1";
  1683. const GENERATOR_CLASSID =
  1684.   Components.ID("{414af362-9ad8-4296-898e-62247f25a20e}");
  1685. const GENERATOR_CLASSNAME = "Feed Generator";
  1686. const PERSON_CONTRACTID = "@mozilla.org/feed-person;1";
  1687. const PERSON_CLASSID = Components.ID("{95c963b7-20b2-11db-92f6-001422106990}");
  1688. const PERSON_CLASSNAME = "Feed Person";
  1689.  
  1690. function GenericComponentFactory(ctor) {
  1691.   this._ctor = ctor;
  1692. }
  1693.  
  1694. GenericComponentFactory.prototype = {
  1695.  
  1696.   _ctor: null,
  1697.  
  1698.   // nsIFactory
  1699.   createInstance: function(outer, iid) {
  1700.     if (outer != null)
  1701.       throw Cr.NS_ERROR_NO_AGGREGATION;
  1702.     return (new this._ctor()).QueryInterface(iid);
  1703.   },
  1704.  
  1705.   // nsISupports
  1706.   QueryInterface: function(iid) {
  1707.     if (iid.equals(Ci.nsIFactory) ||
  1708.         iid.equals(Ci.nsISupports))
  1709.       return this;
  1710.     throw Cr.NS_ERROR_NO_INTERFACE;
  1711.   },
  1712.  
  1713. };
  1714.  
  1715. var Module = {
  1716.   QueryInterface: function(iid) {
  1717.     if (iid.equals(Ci.nsIModule) || 
  1718.         iid.equals(Ci.nsISupports))
  1719.       return this;
  1720.  
  1721.     throw Cr.NS_ERROR_NO_INTERFACE;
  1722.   },
  1723.  
  1724.   getClassObject: function(cm, cid, iid) {
  1725.     if (!iid.equals(Ci.nsIFactory))
  1726.       throw Cr.NS_ERROR_NOT_IMPLEMENTED;
  1727.  
  1728.     if (cid.equals(FP_CLASSID))
  1729.       return new GenericComponentFactory(FeedProcessor);
  1730.     if (cid.equals(FR_CLASSID))
  1731.       return new GenericComponentFactory(FeedResult);
  1732.     if (cid.equals(FEED_CLASSID))
  1733.       return new GenericComponentFactory(Feed);
  1734.     if (cid.equals(ENTRY_CLASSID))
  1735.       return new GenericComponentFactory(Entry);
  1736.     if (cid.equals(TEXTCONSTRUCT_CLASSID))
  1737.       return new GenericComponentFactory(TextConstruct);
  1738.     if (cid.equals(GENERATOR_CLASSID))
  1739.       return new GenericComponentFactory(Generator);
  1740.     if (cid.equals(PERSON_CLASSID))
  1741.       return new GenericComponentFactory(Person);
  1742.  
  1743.     throw Cr.NS_ERROR_NO_INTERFACE;
  1744.   },
  1745.  
  1746.   registerSelf: function(cm, file, location, type) {
  1747.     var cr = cm.QueryInterface(Ci.nsIComponentRegistrar);
  1748.     // Feed Processor
  1749.     cr.registerFactoryLocation(FP_CLASSID, FP_CLASSNAME,
  1750.       FP_CONTRACTID, file, location, type);
  1751.     // Feed Result
  1752.     cr.registerFactoryLocation(FR_CLASSID, FR_CLASSNAME,
  1753.       FR_CONTRACTID, file, location, type);
  1754.     // Feed
  1755.     cr.registerFactoryLocation(FEED_CLASSID, FEED_CLASSNAME,
  1756.       FEED_CONTRACTID, file, location, type);
  1757.     // Entry
  1758.     cr.registerFactoryLocation(ENTRY_CLASSID, ENTRY_CLASSNAME,
  1759.       ENTRY_CONTRACTID, file, location, type);
  1760.     // Text Construct
  1761.     cr.registerFactoryLocation(TEXTCONSTRUCT_CLASSID, TEXTCONSTRUCT_CLASSNAME,
  1762.       TEXTCONSTRUCT_CONTRACTID, file, location, type);
  1763.     // Generator
  1764.     cr.registerFactoryLocation(GENERATOR_CLASSID, GENERATOR_CLASSNAME,
  1765.       GENERATOR_CONTRACTID, file, location, type);
  1766.     // Person
  1767.     cr.registerFactoryLocation(PERSON_CLASSID, PERSON_CLASSNAME,
  1768.       PERSON_CONTRACTID, file, location, type);
  1769.   },
  1770.  
  1771.   unregisterSelf: function(cm, location, type) {
  1772.     var cr = cm.QueryInterface(Ci.nsIComponentRegistrar);
  1773.     // Feed Processor
  1774.     cr.unregisterFactoryLocation(FP_CLASSID, location);
  1775.     // Feed Result
  1776.     cr.unregisterFactoryLocation(FR_CLASSID, location);
  1777.     // Feed
  1778.     cr.unregisterFactoryLocation(FEED_CLASSID, location);
  1779.     // Entry
  1780.     cr.unregisterFactoryLocation(ENTRY_CLASSID, location);
  1781.     // Text Construct
  1782.     cr.unregisterFactoryLocation(TEXTCONSTRUCT_CLASSID, location);
  1783.     // Generator
  1784.     cr.unregisterFactoryLocation(GENERATOR_CLASSID, location);
  1785.     // Person
  1786.     cr.unregisterFactoryLocation(PERSON_CLASSID, location);
  1787.   },
  1788.  
  1789.   canUnload: function(cm) {
  1790.     return true;
  1791.   },
  1792. };
  1793.  
  1794. function NSGetModule(cm, file) {
  1795.   return Module;
  1796. }
  1797.