forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 2
/
FeedProcessor.js
1924 lines (1681 loc) · 63.9 KB
/
FeedProcessor.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Robert Sayre.
* Portions created by the Initial Developer are Copyright (C) 2006
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Ben Goodger <beng@google.com>
* Myk Melez <myk@mozilla.org>
* Michael Ventnor <m.ventnor@gmail.com>
* Will Guaraldi <will.guaraldi@pculture.org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
function LOG(str) {
dump("*** " + str + "\n");
}
const Ci = Components.interfaces;
const Cc = Components.classes;
const Cr = Components.results;
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
Components.utils.import("resource://gre/modules/ISO8601DateUtils.jsm");
const FP_CONTRACTID = "@mozilla.org/feed-processor;1";
const FP_CLASSID = Components.ID("{26acb1f0-28fc-43bc-867a-a46aabc85dd4}");
const FP_CLASSNAME = "Feed Processor";
const FR_CONTRACTID = "@mozilla.org/feed-result;1";
const FR_CLASSID = Components.ID("{072a5c3d-30c6-4f07-b87f-9f63d51403f2}");
const FR_CLASSNAME = "Feed Result";
const FEED_CONTRACTID = "@mozilla.org/feed;1";
const FEED_CLASSID = Components.ID("{5d0cfa97-69dd-4e5e-ac84-f253162e8f9a}");
const FEED_CLASSNAME = "Feed";
const ENTRY_CONTRACTID = "@mozilla.org/feed-entry;1";
const ENTRY_CLASSID = Components.ID("{8e4444ff-8e99-4bdd-aa7f-fb3c1c77319f}");
const ENTRY_CLASSNAME = "Feed Entry";
const TEXTCONSTRUCT_CONTRACTID = "@mozilla.org/feed-textconstruct;1";
const TEXTCONSTRUCT_CLASSID =
Components.ID("{b992ddcd-3899-4320-9909-924b3e72c922}");
const TEXTCONSTRUCT_CLASSNAME = "Feed Text Construct";
const GENERATOR_CONTRACTID = "@mozilla.org/feed-generator;1";
const GENERATOR_CLASSID =
Components.ID("{414af362-9ad8-4296-898e-62247f25a20e}");
const GENERATOR_CLASSNAME = "Feed Generator";
const PERSON_CONTRACTID = "@mozilla.org/feed-person;1";
const PERSON_CLASSID = Components.ID("{95c963b7-20b2-11db-92f6-001422106990}");
const PERSON_CLASSNAME = "Feed Person";
const IO_CONTRACTID = "@mozilla.org/network/io-service;1"
const BAG_CONTRACTID = "@mozilla.org/hash-property-bag;1"
const ARRAY_CONTRACTID = "@mozilla.org/array;1";
const SAX_CONTRACTID = "@mozilla.org/saxparser/xmlreader;1";
const UNESCAPE_CONTRACTID = "@mozilla.org/feed-unescapehtml;1";
var gIoService = null;
const XMLNS = "http://www.w3.org/XML/1998/namespace";
const RSS090NS = "http://my.netscape.com/rdf/simple/0.9/";
const WAIROLE_NS = "http://www.w3.org/2005/01/wai-rdf/GUIRoleTaxonomy#";
/***** Some general utils *****/
function strToURI(link, base) {
var base = base || null;
if (!gIoService)
gIoService = Cc[IO_CONTRACTID].getService(Ci.nsIIOService);
try {
return gIoService.newURI(link, null, base);
}
catch(e) {
return null;
}
}
function isArray(a) {
return isObject(a) && a.constructor == Array;
}
function isObject(a) {
return (a && typeof a == "object") || isFunction(a);
}
function isFunction(a) {
return typeof a == "function";
}
function isIID(a, iid) {
var rv = false;
try {
a.QueryInterface(iid);
rv = true;
}
catch(e) {
}
return rv;
}
function isIArray(a) {
return isIID(a, Ci.nsIArray);
}
function isIFeedContainer(a) {
return isIID(a, Ci.nsIFeedContainer);
}
function stripTags(someHTML) {
return someHTML.replace(/<[^>]+>/g,"");
}
/**
* Searches through an array of links and returns a JS array
* of matching property bags.
*/
const IANA_URI = "http://www.iana.org/assignments/relation/";
function findAtomLinks(rel, links) {
var rvLinks = [];
for (var i = 0; i < links.length; ++i) {
var linkElement = links.queryElementAt(i, Ci.nsIPropertyBag2);
// atom:link MUST have @href
if (bagHasKey(linkElement, "href")) {
var relAttribute = null;
if (bagHasKey(linkElement, "rel"))
relAttribute = linkElement.getPropertyAsAString("rel")
if ((!relAttribute && rel == "alternate") || relAttribute == rel) {
rvLinks.push(linkElement);
continue;
}
// catch relations specified by IANA URI
if (relAttribute == IANA_URI + rel) {
rvLinks.push(linkElement);
}
}
}
return rvLinks;
}
function xmlEscape(s) {
s = s.replace(/&/g, "&");
s = s.replace(/>/g, ">");
s = s.replace(/</g, "<");
s = s.replace(/"/g, """);
s = s.replace(/'/g, "'");
return s;
}
function arrayContains(array, element) {
for (var i = 0; i < array.length; ++i) {
if (array[i] == element) {
return true;
}
}
return false;
}
// XXX add hasKey to nsIPropertyBag
function bagHasKey(bag, key) {
try {
bag.getProperty(key);
return true;
}
catch (e) {
return false;
}
}
function makePropGetter(key) {
return function FeedPropGetter(bag) {
try {
return value = bag.getProperty(key);
}
catch(e) {
}
return null;
}
}
function W3CToIETFDate(dateString) {
var date = ISO8601DateUtils.parse(dateString);
return date.toUTCString();
}
const RDF_NS = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
// namespace map
var gNamespaces = {
"http://webns.net/mvcb/":"admin",
"http://backend.userland.com/rss":"",
"http://blogs.law.harvard.edu/tech/rss":"",
"http://www.w3.org/2005/Atom":"atom",
"http://purl.org/atom/ns#":"atom03",
"http://purl.org/rss/1.0/modules/content/":"content",
"http://purl.org/dc/elements/1.1/":"dc",
"http://purl.org/dc/terms/":"dcterms",
"http://www.w3.org/1999/02/22-rdf-syntax-ns#":"rdf",
"http://purl.org/rss/1.0/":"rss1",
"http://my.netscape.com/rdf/simple/0.9/":"rss1",
"http://wellformedweb.org/CommentAPI/":"wfw",
"http://purl.org/rss/1.0/modules/wiki/":"wiki",
"http://www.w3.org/XML/1998/namespace":"xml",
"http://search.yahoo.com/mrss/":"media",
"http://search.yahoo.com/mrss":"media"
}
// We allow a very small set of namespaces in XHTML content,
// for attributes only
var gAllowedXHTMLNamespaces = {
"http://www.w3.org/XML/1998/namespace":"xml",
"http://www.w3.org/TR/xhtml2":"xhtml2",
"http://www.w3.org/2005/07/aaa":"aaa",
// if someone ns qualifies XHTML, we have to prefix it to avoid an
// attribute collision.
"http://www.w3.org/1999/xhtml":"xhtml"
}
function FeedResult() {}
FeedResult.prototype = {
bozo: false,
doc: null,
version: null,
headers: null,
uri: null,
stylesheet: null,
registerExtensionPrefix: function FR_registerExtensionPrefix(ns, prefix) {
throw Cr.NS_ERROR_NOT_IMPLEMENTED;
},
// XPCOM stuff
classID: FR_CLASSID,
QueryInterface: XPCOMUtils.generateQI([Ci.nsIFeedResult])
}
function Feed() {
this.subtitle = null;
this.title = null;
this.items = Cc[ARRAY_CONTRACTID].createInstance(Ci.nsIMutableArray);
this.link = null;
this.id = null;
this.generator = null;
this.authors = Cc[ARRAY_CONTRACTID].createInstance(Ci.nsIMutableArray);
this.contributors = Cc[ARRAY_CONTRACTID].createInstance(Ci.nsIMutableArray);
this.baseURI = null;
this.enclosureCount = 0;
this.type = Ci.nsIFeed.TYPE_FEED;
}
Feed.prototype = {
searchLists: {
title: ["title", "rss1:title", "atom03:title", "atom:title"],
subtitle: ["description","dc:description","rss1:description",
"atom03:tagline","atom:subtitle"],
items: ["items","atom03_entries","entries"],
id: ["atom:id","rdf:about"],
generator: ["generator"],
authors : ["authors"],
contributors: ["contributors"],
title: ["title","rss1:title", "atom03:title","atom:title"],
link: [["link",strToURI],["rss1:link",strToURI]],
categories: ["categories", "dc:subject"],
rights: ["atom03:rights","atom:rights"],
cloud: ["cloud"],
image: ["image", "rss1:image", "atom:logo"],
textInput: ["textInput", "rss1:textinput"],
skipDays: ["skipDays"],
skipHours: ["skipHours"],
updated: ["pubDate", "lastBuildDate", "atom03:modified", "dc:date",
"dcterms:modified", "atom:updated"]
},
normalize: function Feed_normalize() {
fieldsToObj(this, this.searchLists);
if (this.skipDays)
this.skipDays = this.skipDays.getProperty("days");
if (this.skipHours)
this.skipHours = this.skipHours.getProperty("hours");
if (this.updated)
this.updated = dateParse(this.updated);
// Assign Atom link if needed
if (bagHasKey(this.fields, "links"))
this._atomLinksToURI();
this._calcEnclosureCountAndFeedType();
// Resolve relative image links
if (this.image && bagHasKey(this.image, "url"))
this._resolveImageLink();
this._resetBagMembersToRawText([this.searchLists.subtitle,
this.searchLists.title]);
},
_calcEnclosureCountAndFeedType: function Feed_calcEnclosureCountAndFeedType() {
var entries_with_enclosures = 0;
var audio_count = 0;
var image_count = 0;
var video_count = 0;
var other_count = 0;
for (var i = 0; i < this.items.length; ++i) {
var entry = this.items.queryElementAt(i, Ci.nsIFeedEntry);
entry.QueryInterface(Ci.nsIFeedContainer);
if (entry.enclosures && entry.enclosures.length > 0) {
++entries_with_enclosures;
for (var e = 0; e < entry.enclosures.length; ++e) {
var enc = entry.enclosures.queryElementAt(e, Ci.nsIWritablePropertyBag2);
if (enc.hasKey("type")) {
var enctype = enc.get("type");
if (/^audio/.test(enctype)) {
++audio_count;
} else if (/^image/.test(enctype)) {
++image_count;
} else if (/^video/.test(enctype)) {
++video_count;
} else {
++other_count;
}
} else {
++other_count;
}
}
}
}
var feedtype = Ci.nsIFeed.TYPE_FEED;
// For a feed to be marked as TYPE_VIDEO, TYPE_AUDIO and TYPE_IMAGE,
// we enforce two things:
//
// 1. all entries must have at least one enclosure
// 2. all enclosures must be video for TYPE_VIDEO, audio for TYPE_AUDIO or image
// for TYPE_IMAGE
//
// Otherwise it's a TYPE_FEED.
if (entries_with_enclosures == this.items.length && other_count == 0) {
if (audio_count > 0 && !video_count && !image_count) {
feedtype = Ci.nsIFeed.TYPE_AUDIO;
} else if (image_count > 0 && !audio_count && !video_count) {
feedtype = Ci.nsIFeed.TYPE_IMAGE;
} else if (video_count > 0 && !audio_count && !image_count) {
feedtype = Ci.nsIFeed.TYPE_VIDEO;
}
}
this.type = feedtype;
this.enclosureCount = other_count + video_count + audio_count + image_count;
},
_atomLinksToURI: function Feed_linkToURI() {
var links = this.fields.getPropertyAsInterface("links", Ci.nsIArray);
var alternates = findAtomLinks("alternate", links);
if (alternates.length > 0) {
var href = alternates[0].getPropertyAsAString("href");
var base;
if (bagHasKey(alternates[0], "xml:base"))
base = alternates[0].getPropertyAsAString("xml:base");
this.link = this._resolveURI(href, base);
}
},
_resolveImageLink: function Feed_resolveImageLink() {
var base;
if (bagHasKey(this.image, "xml:base"))
base = this.image.getPropertyAsAString("xml:base");
var url = this._resolveURI(this.image.getPropertyAsAString("url"), base);
if (url)
this.image.setPropertyAsAString("url", url.spec);
},
_resolveURI: function Feed_resolveURI(linkSpec, baseSpec) {
var uri = null;
try {
var base = baseSpec ? strToURI(baseSpec, this.baseURI) : this.baseURI;
uri = strToURI(linkSpec, base);
}
catch(e) {
LOG(e);
}
return uri;
},
// reset the bag to raw contents, not text constructs
_resetBagMembersToRawText: function Feed_resetBagMembers(fieldLists) {
for (var i=0; i<fieldLists.length; i++) {
for (var j=0; j<fieldLists[i].length; j++) {
if (bagHasKey(this.fields, fieldLists[i][j])) {
var textConstruct = this.fields.getProperty(fieldLists[i][j]);
this.fields.setPropertyAsAString(fieldLists[i][j],
textConstruct.text);
}
}
}
},
// XPCOM stuff
classID: FEED_CLASSID,
QueryInterface: XPCOMUtils.generateQI([Ci.nsIFeed, Ci.nsIFeedContainer])
}
function Entry() {
this.summary = null;
this.content = null;
this.title = null;
this.fields = Cc["@mozilla.org/hash-property-bag;1"].
createInstance(Ci.nsIWritablePropertyBag2);
this.link = null;
this.id = null;
this.baseURI = null;
this.updated = null;
this.published = null;
this.authors = Cc[ARRAY_CONTRACTID].createInstance(Ci.nsIMutableArray);
this.contributors = Cc[ARRAY_CONTRACTID].createInstance(Ci.nsIMutableArray);
}
Entry.prototype = {
fields: null,
enclosures: null,
mediaContent: null,
searchLists: {
title: ["title", "rss1:title", "atom03:title", "atom:title"],
link: [["link",strToURI],["rss1:link",strToURI]],
id: [["guid", makePropGetter("guid")], "rdf:about",
"atom03:id", "atom:id"],
authors : ["authors"],
contributors: ["contributors"],
summary: ["description", "rss1:description", "dc:description",
"atom03:summary", "atom:summary"],
content: ["content:encoded","atom03:content","atom:content"],
rights: ["atom03:rights","atom:rights"],
published: ["pubDate", "atom03:issued", "dcterms:issued", "atom:published"],
updated: ["pubDate", "atom03:modified", "dc:date", "dcterms:modified",
"atom:updated"]
},
normalize: function Entry_normalize() {
fieldsToObj(this, this.searchLists);
// Assign Atom link if needed
if (bagHasKey(this.fields, "links"))
this._atomLinksToURI();
// Populate enclosures array
this._populateEnclosures();
// The link might be a guid w/ permalink=true
if (!this.link && bagHasKey(this.fields, "guid")) {
var guid = this.fields.getProperty("guid");
var isPermaLink = true;
if (bagHasKey(guid, "isPermaLink"))
isPermaLink = guid.getProperty("isPermaLink").toLowerCase() != "false";
if (guid && isPermaLink)
this.link = strToURI(guid.getProperty("guid"));
}
if (this.updated)
this.updated = dateParse(this.updated);
if (this.published)
this.published = dateParse(this.published);
this._resetBagMembersToRawText([this.searchLists.content,
this.searchLists.summary,
this.searchLists.title]);
},
_populateEnclosures: function Entry_populateEnclosures() {
if (bagHasKey(this.fields, "links"))
this._atomLinksToEnclosures();
// Add RSS2 enclosure to enclosures
if (bagHasKey(this.fields, "enclosure"))
this._enclosureToEnclosures();
// Add media:content to enclosures
if (bagHasKey(this.fields, "mediacontent"))
this._mediacontentToEnclosures();
// Add media:content in media:group to enclosures
if (bagHasKey(this.fields, "mediagroup"))
this._mediagroupToEnclosures();
},
__enclosure_map: null,
_addToEnclosures: function Entry_addToEnclosures(new_enc) {
// items we add to the enclosures array get displayed in the FeedWriter and
// they must have non-empty urls.
if (!bagHasKey(new_enc, "url") || new_enc.getPropertyAsAString("url") == "")
return;
if (this.__enclosure_map == null)
this.__enclosure_map = {};
var previous_enc = this.__enclosure_map[new_enc.getPropertyAsAString("url")];
if (previous_enc != undefined) {
previous_enc.QueryInterface(Ci.nsIWritablePropertyBag2);
if (!bagHasKey(previous_enc, "type") && bagHasKey(new_enc, "type"))
previous_enc.setPropertyAsAString("type", new_enc.getPropertyAsAString("type"));
if (!bagHasKey(previous_enc, "length") && bagHasKey(new_enc, "length"))
previous_enc.setPropertyAsAString("length", new_enc.getPropertyAsAString("length"));
return;
}
if (this.enclosures == null) {
this.enclosures = Cc[ARRAY_CONTRACTID].createInstance(Ci.nsIMutableArray);
this.enclosures.QueryInterface(Ci.nsIMutableArray);
}
this.enclosures.appendElement(new_enc, false);
this.__enclosure_map[new_enc.getPropertyAsAString("url")] = new_enc;
},
_atomLinksToEnclosures: function Entry_linkToEnclosure() {
var links = this.fields.getPropertyAsInterface("links", Ci.nsIArray);
var enc_links = findAtomLinks("enclosure", links);
if (enc_links.length == 0)
return;
for (var i = 0; i < enc_links.length; ++i) {
var link = enc_links[i];
// an enclosure must have an href
if (!(link.getProperty("href")))
return;
var enc = Cc[BAG_CONTRACTID].createInstance(Ci.nsIWritablePropertyBag2);
// copy Atom bits over to equivalent enclosure bits
enc.setPropertyAsAString("url", link.getPropertyAsAString("href"));
if (bagHasKey(link, "type"))
enc.setPropertyAsAString("type", link.getPropertyAsAString("type"));
if (bagHasKey(link, "length"))
enc.setPropertyAsAString("length", link.getPropertyAsAString("length"));
this._addToEnclosures(enc);
}
},
_enclosureToEnclosures: function Entry_enclosureToEnclosures() {
var enc = this.fields.getPropertyAsInterface("enclosure", Ci.nsIPropertyBag2);
if (!(enc.getProperty("url")))
return;
this._addToEnclosures(enc);
},
_mediacontentToEnclosures: function Entry_mediacontentToEnclosures() {
var mediacontent = this.fields.getPropertyAsInterface("mediacontent", Ci.nsIArray);
for (var i = 0; i < mediacontent.length; ++i) {
var contentElement = mediacontent.queryElementAt(i, Ci.nsIWritablePropertyBag2);
// media:content don't require url, but if it's not there, we should
// skip it.
if (!bagHasKey(contentElement, "url"))
continue;
var enc = Cc[BAG_CONTRACTID].createInstance(Ci.nsIWritablePropertyBag2);
// copy media:content bits over to equivalent enclosure bits
enc.setPropertyAsAString("url", contentElement.getPropertyAsAString("url"));
if (bagHasKey(contentElement, "type")) {
enc.setPropertyAsAString("type", contentElement.getPropertyAsAString("type"));
}
if (bagHasKey(contentElement, "fileSize")) {
enc.setPropertyAsAString("length", contentElement.getPropertyAsAString("fileSize"));
}
this._addToEnclosures(enc);
}
},
_mediagroupToEnclosures: function Entry_mediagroupToEnclosures() {
var group = this.fields.getPropertyAsInterface("mediagroup", Ci.nsIPropertyBag2);
var content = group.getPropertyAsInterface("mediacontent", Ci.nsIArray);
for (var i = 0; i < content.length; ++i) {
var contentElement = content.queryElementAt(i, Ci.nsIWritablePropertyBag2);
// media:content don't require url, but if it's not there, we should
// skip it.
if (!bagHasKey(contentElement, "url"))
continue;
var enc = Cc[BAG_CONTRACTID].createInstance(Ci.nsIWritablePropertyBag2);
// copy media:content bits over to equivalent enclosure bits
enc.setPropertyAsAString("url", contentElement.getPropertyAsAString("url"));
if (bagHasKey(contentElement, "type")) {
enc.setPropertyAsAString("type", contentElement.getPropertyAsAString("type"));
}
if (bagHasKey(contentElement, "fileSize")) {
enc.setPropertyAsAString("length", contentElement.getPropertyAsAString("fileSize"));
}
this._addToEnclosures(enc);
}
},
// XPCOM stuff
classID: ENTRY_CLASSID,
QueryInterface: XPCOMUtils.generateQI(
[Ci.nsIFeedEntry, Ci.nsIFeedContainer]
)
}
Entry.prototype._atomLinksToURI = Feed.prototype._atomLinksToURI;
Entry.prototype._resolveURI = Feed.prototype._resolveURI;
Entry.prototype._resetBagMembersToRawText =
Feed.prototype._resetBagMembersToRawText;
// TextConstruct represents and element that could contain (X)HTML
function TextConstruct() {
this.lang = null;
this.base = null;
this.type = "text";
this.text = null;
this.unescapeHTML = Cc[UNESCAPE_CONTRACTID].
getService(Ci.nsIScriptableUnescapeHTML);
}
TextConstruct.prototype = {
plainText: function TC_plainText() {
if (this.type != "text") {
return this.unescapeHTML.unescape(stripTags(this.text));
}
return this.text;
},
createDocumentFragment: function TC_createDocumentFragment(element) {
if (this.type == "text") {
var doc = element.ownerDocument;
var docFragment = doc.createDocumentFragment();
var node = doc.createTextNode(this.text);
docFragment.appendChild(node);
return docFragment;
}
var isXML;
if (this.type == "xhtml")
isXML = true
else if (this.type == "html")
isXML = false;
else
return null;
return this.unescapeHTML.parseFragment(this.text, isXML,
this.base, element);
},
// XPCOM stuff
classID: TEXTCONSTRUCT_CLASSID,
QueryInterface: XPCOMUtils.generateQI([Ci.nsIFeedTextConstruct])
}
// Generator represents the software that produced the feed
function Generator() {
this.lang = null;
this.agent = null;
this.version = null;
this.uri = null;
// nsIFeedElementBase
this._attributes = null;
this.baseURI = null;
}
Generator.prototype = {
get attributes() {
return this._attributes;
},
set attributes(value) {
this._attributes = value;
this.version = this._attributes.getValueFromName("","version");
var uriAttribute = this._attributes.getValueFromName("","uri") ||
this._attributes.getValueFromName("","url");
this.uri = strToURI(uriAttribute, this.baseURI);
// RSS1
uriAttribute = this._attributes.getValueFromName(RDF_NS,"resource");
if (uriAttribute) {
this.agent = uriAttribute;
this.uri = strToURI(uriAttribute, this.baseURI);
}
},
// XPCOM stuff
classID: GENERATOR_CLASSID,
QueryInterface: XPCOMUtils.generateQI(
[Ci.nsIFeedGenerator, Ci.nsIFeedElementBase]
)
}
function Person() {
this.name = null;
this.uri = null;
this.email = null;
// nsIFeedElementBase
this.attributes = null;
this.baseURI = null;
}
Person.prototype = {
// XPCOM stuff
classID: PERSON_CLASSID,
QueryInterface: XPCOMUtils.generateQI(
[Ci.nsIFeedPerson, Ci.nsIFeedElementBase]
)
}
/**
* Map a list of fields into properties on a container.
*
* @param container An nsIFeedContainer
* @param fields A list of fields to search for. List members can
* be a list, in which case the second member is
* transformation function (like parseInt).
*/
function fieldsToObj(container, fields) {
var props,prop,field,searchList;
for (var key in fields) {
searchList = fields[key];
for (var i=0; i < searchList.length; ++i) {
props = searchList[i];
prop = null;
field = isArray(props) ? props[0] : props;
try {
prop = container.fields.getProperty(field);
}
catch(e) {
}
if (prop) {
prop = isArray(props) ? props[1](prop) : prop;
container[key] = prop;
}
}
}
}
/**
* Lower cases an element's localName property
* @param element A DOM element.
*
* @returns The lower case localName property of the specified element
*/
function LC(element) {
return element.localName.toLowerCase();
}
// TODO move these post-processor functions
// create a generator element
function atomGenerator(s, generator) {
generator.QueryInterface(Ci.nsIFeedGenerator);
generator.agent = s.trim();
return generator;
}
// post-process atom:logo to create an RSS2-like structure
function atomLogo(s, logo) {
logo.setPropertyAsAString("url", s.trim());
}
// post-process an RSS category, map it to the Atom fields.
function rssCatTerm(s, cat) {
// add slash handling?
cat.setPropertyAsAString("term", s.trim());
return cat;
}
// post-process a GUID
function rssGuid(s, guid) {
guid.setPropertyAsAString("guid", s.trim());
return guid;
}
// post-process an RSS author element
//
// It can contain a field like this:
//
// <author>lawyer@boyer.net (Lawyer Boyer)</author>
//
// or, delightfully, a field like this:
//
// <dc:creator>Simon St.Laurent (mailto:simonstl@simonstl.com)</dc:creator>
//
// We want to split this up and assign it to corresponding Atom
// fields.
//
function rssAuthor(s,author) {
author.QueryInterface(Ci.nsIFeedPerson);
// check for RSS2 string format
var chars = s.trim();
var matches = chars.match(/(.*)\((.*)\)/);
var emailCheck =
/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (matches) {
var match1 = matches[1].trim();
var match2 = matches[2].trim();
if (match2.indexOf("mailto:") == 0)
match2 = match2.substring(7);
if (emailCheck.test(match1)) {
author.email = match1;
author.name = match2;
}
else if (emailCheck.test(match2)) {
author.email = match2;
author.name = match1;
}
else {
// put it back together
author.name = match1 + " (" + match2 + ")";
}
}
else {
author.name = chars;
if (chars.indexOf('@'))
author.email = chars;
}
return author;
}
//
// skipHours and skipDays map to arrays, so we need to change the
// string to an nsISupports in order to stick it in there.
//
function rssArrayElement(s) {
var str = Cc["@mozilla.org/supports-string;1"].
createInstance(Ci.nsISupportsString);
str.data = s;
str.QueryInterface(Ci.nsISupportsString);
return str;
}
/***** Some feed utils from TBird *****/
/**
* Tests a RFC822 date against a regex.
* @param aDateStr A string to test as an RFC822 date.
*
* @returns A boolean indicating whether the string is a valid RFC822 date.
*/
function isValidRFC822Date(aDateStr) {
var regex = new RegExp(RFC822_RE);
return regex.test(aDateStr);
}
// Regular expression matching RFC822 dates
const RFC822_RE = "^((Mon|Tue|Wed|Thu|Fri|Sat|Sun)([a-z]+)?,? *)?\\d\\d?"
+ " +(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)([a-z]+)?"
+ " +\\d\\d(\\d\\d)? +\\d?\\d:\\d\\d(:\\d\\d)?"
+ " +([+-]?\\d\\d\\d\\d|GMT|UT[C]?|(E|C|M|P)(ST|DT)|[A-IK-Z])$";
/**
* XXX -- need to decide what this should return.
* XXX -- Is there a Date class usable from C++?
*
* Tries tries parsing various date formats.
* @param dateString
* A string that is supposedly an RFC822 or RFC3339 date.
* @returns A Date.toString XXX--fixme
*/
function dateParse(dateString) {
var date = dateString.trim();
if (date.search(/^\d\d\d\d/) != -1) //Could be a ISO8601/W3C date
return W3CToIETFDate(dateString);
if (isValidRFC822Date(date))
return date;
if (!isNaN(parseInt(date, 10))) {
//It's an integer, so maybe it's a timestamp
var d = new Date(parseInt(date, 10) * 1000);
var now = new Date();
var yeardiff = now.getFullYear() - d.getFullYear();
if ((yeardiff >= 0) && (yeardiff < 3)) {
// it's quite likely the correct date. 3 years is an arbitrary cutoff,
// but this is an invalid date format, and there's no way to verify
// its correctness.
return d.toString();
}
}
// Can't help.
return null;
}
const XHTML_NS = "http://www.w3.org/1999/xhtml";
// The XHTMLHandler handles inline XHTML found in things like atom:summary
function XHTMLHandler(processor, isAtom, waiPrefixes) {
this._buf = "";
this._processor = processor;
this._depth = 0;
this._isAtom = isAtom;
// a stack of lists tracking in-scope namespaces
this._inScopeNS = [];
this._waiPrefixes = waiPrefixes;
}
// The fidelity can be improved here, to allow handling of stuff like
// SVG and MathML. XXX
XHTMLHandler.prototype = {
// look back up at the declared namespaces
// we always use the same prefixes for our safe stuff
_isInScope: function XH__isInScope(ns) {
for (var i in this._inScopeNS) {
for (var uri in this._inScopeNS[i]) {
if (this._inScopeNS[i][uri] == ns)
return true;
}
}
return false;
},
startDocument: function XH_startDocument() {
},
endDocument: function XH_endDocument() {
},
startElement: function XH_startElement(uri, localName, qName, attributes) {
++this._depth;
this._inScopeNS.push([]);
// RFC4287 requires XHTML to be wrapped in a div that is *not* part of
// the content. This prevents people from screwing up namespaces, but
// we need to skip it here.
if (this._isAtom && this._depth == 1 && localName == "div")
return;
// If it's an XHTML element, record it. Otherwise, it's ignored.
if (uri == XHTML_NS) {
this._buf += "<" + localName;
var uri;
for (var i=0; i < attributes.length; ++i) {
uri = attributes.getURI(i);
// XHTML attributes aren't in a namespace
if (uri == "") {
this._buf += (" " + attributes.getLocalName(i) + "='" +
xmlEscape(attributes.getValue(i)) + "'");
} else {
// write a small set of allowed attribute namespaces
var prefix = gAllowedXHTMLNamespaces[uri];
if (prefix != null) {
// The attribute value we'll attempt to write
var attributeValue = xmlEscape(attributes.getValue(i));
// More QName abuse from W3C
var rolePrefix = "";
if (attributes.getLocalName(i) == "role") {
for (var aPrefix in this._waiPrefixes) {
if (attributeValue.indexOf(aPrefix + ":") == 0) {
// Now, due to the terrible layer mismatch
// that is QNames in content, we have to see
// if the attribute value clashes with our
// namespace declarations.
var isCollision = false;
for (var uriKey in gAllowedXHTMLNamespaces) {
if (gAllowedXHTMLNamespaces[uriKey] == aPrefix)
isCollision = true;