3368bb182aaa3fb770a97d13ea2fb909a714e671
[elisp/gnus.git-] / lisp / nnrss.el
1 ;;; nnrss.el --- interfacing with RSS
2 ;; Copyright (C) 2001, 2002, 2003  Free Software Foundation, Inc.
3
4 ;; Author: Shenghuo Zhu <zsh@cs.rochester.edu>
5 ;; Keywords: RSS
6
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published
11 ;; by the Free Software Foundation; either version 2, or (at your
12 ;; option) any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful, but
15 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17 ;; General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
21 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 ;; Boston, MA 02111-1307, USA.
23
24 ;;; Commentary:
25
26 ;;; Code:
27
28 (eval-when-compile (require 'cl))
29
30 (require 'gnus)
31 (require 'nnoo)
32 (require 'nnmail)
33 (require 'message)
34 (require 'mm-util)
35 (require 'gnus-util)
36 (require 'time-date)
37 (require 'rfc2231)
38 (require 'mm-url)
39 (eval-when-compile
40   (ignore-errors
41     (require 'xml)))
42 (eval '(require 'xml))
43
44 (nnoo-declare nnrss)
45
46 (defvoo nnrss-directory (nnheader-concat gnus-directory "rss/")
47   "Where nnrss will save its files.")
48
49 ;; (group max rss-url)
50 (defvoo nnrss-server-data nil)
51
52 ;; (num timestamp url subject author date extra)
53 (defvoo nnrss-group-data nil)
54 (defvoo nnrss-group-max 0)
55 (defvoo nnrss-group-min 1)
56 (defvoo nnrss-group nil)
57 (defvoo nnrss-group-hashtb (make-hash-table :test 'equal))
58 (defvoo nnrss-status-string "")
59
60 (defconst nnrss-version "nnrss 1.0")
61
62 (defvar nnrss-group-alist '()
63   "List of RSS addresses.")
64
65 (defvar nnrss-use-local nil)
66
67 (defvar nnrss-description-field 'X-Gnus-Description
68   "Field name used for DESCRIPTION.
69 To use the description in headers, put this name into `nnmail-extra-headers'.")
70
71 (defvar nnrss-url-field 'X-Gnus-Url
72   "Field name used for URL.
73 To use the description in headers, put this name into `nnmail-extra-headers'.")
74
75 (defvar nnrss-content-function nil
76   "A function which is called in `nnrss-request-article'.
77 The arguments are (ENTRY GROUP ARTICLE).
78 ENTRY is the record of the current headline. GROUP is the group name.
79 ARTICLE is the article number of the current headline.")
80
81 (nnoo-define-basics nnrss)
82
83 ;;; Interface functions
84
85 (deffoo nnrss-retrieve-headers (articles &optional group server fetch-old)
86   (nnrss-possibly-change-group group server)
87   (let (e)
88     (save-excursion
89       (set-buffer nntp-server-buffer)
90       (erase-buffer)
91       (dolist (article articles)
92         (if (setq e (assq article nnrss-group-data))
93             (insert (number-to-string (car e)) "\t" ;; number
94                     (if (nth 3 e)
95                         (nnrss-format-string (nth 3 e)) "")
96                     "\t" ;; subject
97                     (if (nth 4 e)
98                         (nnrss-format-string (nth 4 e))
99                       "(nobody)")
100                     "\t" ;;from
101                     (or (nth 5 e) "")
102                     "\t" ;; date
103                     (format "<%d@%s.nnrss>" (car e) group)
104                     "\t" ;; id
105                     "\t" ;; refs
106                     "-1" "\t" ;; chars
107                     "-1" "\t" ;; lines
108                     "" "\t" ;; Xref
109                     (if (and (nth 6 e)
110                              (memq nnrss-description-field
111                                    nnmail-extra-headers))
112                         (concat (symbol-name nnrss-description-field)
113                                 ": "
114                                 (nnrss-format-string (nth 6 e))
115                                 "\t")
116                       "")
117                     (if (and (nth 2 e)
118                              (memq nnrss-url-field
119                                    nnmail-extra-headers))
120                         (concat (symbol-name nnrss-url-field)
121                                 ": "
122                                 (nnrss-format-string (nth 2 e))
123                                 "\t")
124                       "")
125                     "\n")))))
126   'nov)
127
128 (deffoo nnrss-request-group (group &optional server dont-check)
129   (nnrss-possibly-change-group group server)
130   (if dont-check
131       t
132     (nnrss-check-group group server)
133     (nnheader-report 'nnrss "Opened group %s" group)
134     (nnheader-insert
135      "211 %d %d %d %s\n" nnrss-group-max nnrss-group-min nnrss-group-max
136      (prin1-to-string group)
137      t)))
138
139 (deffoo nnrss-close-group (group &optional server)
140   t)
141
142 (deffoo nnrss-request-article (article &optional group server buffer)
143   (nnrss-possibly-change-group group server)
144   (let ((e (assq article nnrss-group-data))
145         (boundary "=-=-=-=-=-=-=-=-=-")
146         (nntp-server-buffer (or buffer nntp-server-buffer))
147         post err)
148     (when e
149       (catch 'error
150         (with-current-buffer nntp-server-buffer
151           (erase-buffer)
152           (goto-char (point-min))
153           (insert "Mime-Version: 1.0\nContent-Type: multipart/alternative; boundary=\"" boundary "\"\n")
154           (if group
155               (insert "Newsgroups: " group "\n"))
156           (if (nth 3 e)
157               (insert "Subject: " (nnrss-format-string (nth 3 e)) "\n"))
158           (if (nth 4 e)
159               (insert "From: " (nnrss-format-string (nth 4 e)) "\n"))
160           (if (nth 5 e)
161               (insert "Date: " (nnrss-format-string (nth 5 e)) "\n"))
162           (insert "Message-ID: " (format "<%d@%s.nnrss>" (car e) group) "\n")
163           (insert "\n")
164           (let ((text (if (nth 6 e)
165                           (nnrss-string-as-multibyte (nth 6 e))))
166                 (link (if (nth 2 e)
167                           (nth 2 e))))
168             (insert "\n\n--" boundary "\nContent-Type: text/plain\n\n")
169             (let ((point (point)))
170               (if text
171                   (progn (insert text)
172                          (goto-char point)
173                          (while (re-search-forward "\n" nil t)
174                            (replace-match " "))
175                          (goto-char (point-max))
176                          (insert "\n\n")))
177               (if link
178                   (insert link)))
179             (insert "\n\n--" boundary "\nContent-Type: text/html\n\n")
180             (let ((point (point)))
181               (if text
182                   (progn (insert "<html><head></head><body>\n" text "\n</body></html>")
183                          (goto-char point)
184                          (while (re-search-forward "\n" nil t)
185                            (replace-match " "))
186                          (goto-char (point-max))
187                          (insert "\n\n")))
188               (if link
189                   (insert "<p><a href=\"" link "\">link</a></p>\n"))))
190           (if nnrss-content-function
191               (funcall nnrss-content-function e group article)))))
192     (cond
193      (err
194       (nnheader-report 'nnrss err))
195      ((not e)
196       (nnheader-report 'nnrss "no such id: %d" article))
197      (t
198       (nnheader-report 'nnrss "article %s retrieved" (car e))
199       ;; we return the article number.
200       (cons nnrss-group (car e))))))
201
202 (deffoo nnrss-request-list (&optional server)
203   (nnrss-possibly-change-group nil server)
204   (nnrss-generate-active)
205   t)
206
207 (deffoo nnrss-open-server (server &optional defs connectionless)
208   (nnrss-read-server-data server)
209   (nnoo-change-server 'nnrss server defs)
210   t)
211
212 (deffoo nnrss-request-expire-articles
213     (articles group &optional server force)
214   (nnrss-possibly-change-group group server)
215   (let (e days not-expirable changed)
216     (dolist (art articles)
217       (if (and (setq e (assq art nnrss-group-data))
218                (nnmail-expired-article-p
219                 group
220                 (if (listp (setq days (nth 1 e))) days
221                   (days-to-time (- days (time-to-days '(0 0)))))
222                 force))
223           (setq nnrss-group-data (delq e nnrss-group-data)
224                 changed t)
225         (push art not-expirable)))
226     (if changed
227         (nnrss-save-group-data group server))
228     not-expirable))
229
230 (deffoo nnrss-request-delete-group (group &optional force server)
231   (nnrss-possibly-change-group group server)
232   (setq nnrss-server-data
233         (delq (assoc group nnrss-server-data) nnrss-server-data))
234   (nnrss-save-server-data server)
235   (ignore-errors
236     (delete-file (nnrss-make-filename group server)))
237   t)
238
239 (deffoo nnrss-request-list-newsgroups (&optional server)
240   (nnrss-possibly-change-group nil server)
241   (save-excursion
242     (set-buffer nntp-server-buffer)
243     (erase-buffer)
244     (dolist (elem nnrss-group-alist)
245       (if (third elem)
246           (insert (car elem) "\t" (third elem) "\n"))))
247   t)
248
249 (nnoo-define-skeleton nnrss)
250
251 ;;; Internal functions
252 (eval-when-compile (defun xml-rpc-method-call (&rest args)))
253 (defun nnrss-fetch (url &optional local)
254   "Fetch the url and put it in a the expected lisp structure."
255   (with-temp-buffer
256   ;some CVS versions of url.el need this to close the connection quickly
257     (let* (xmlform htmlform)
258       ;; bit o' work necessary for w3 pre-cvs and post-cvs
259       (if local
260           (let ((coding-system-for-read 'binary))
261             (insert-file-contents url))
262         (mm-url-insert url))
263
264 ;; Because xml-parse-region can't deal with anything that isn't
265 ;; xml and w3-parse-buffer can't deal with some xml, we have to
266 ;; parse with xml-parse-region first and, if that fails, parse
267 ;; with w3-parse-buffer.  Yuck.  Eventually, someone should find out
268 ;; why w3-parse-buffer fails to parse some well-formed xml and
269 ;; fix it.
270
271     (condition-case err
272         (setq xmlform (xml-parse-region (point-min) (point-max)))
273       (error (if (fboundp 'w3-parse-buffer)
274                  (setq htmlform (caddar (w3-parse-buffer
275                                          (current-buffer))))
276                (message "nnrss: Not valid XML and w3 parse not available (%s)"
277                         url))))
278     (if htmlform
279         htmlform
280       xmlform))))
281
282 (defun nnrss-possibly-change-group (&optional group server)
283   (when (and server
284              (not (nnrss-server-opened server)))
285     (nnrss-open-server server))
286   (when (and group (not (equal group nnrss-group)))
287     (nnrss-read-group-data group server)
288     (setq nnrss-group group)))
289
290 (defvar nnrss-extra-categories '(nnrss-snarf-moreover-categories))
291
292 (defun nnrss-generate-active ()
293   (if (y-or-n-p "fetch extra categories? ")
294       (dolist (func nnrss-extra-categories)
295         (funcall func)))
296   (save-excursion
297     (set-buffer nntp-server-buffer)
298     (erase-buffer)
299     (dolist (elem nnrss-group-alist)
300       (insert (prin1-to-string (car elem)) " 0 1 y\n"))
301     (dolist (elem nnrss-server-data)
302       (unless (assoc (car elem) nnrss-group-alist)
303         (insert (prin1-to-string (car elem)) " 0 1 y\n")))))
304
305 ;;; data functions
306
307 (defun nnrss-read-server-data (server)
308   (setq nnrss-server-data nil)
309   (let ((file (nnrss-make-filename "nnrss" server)))
310     (when (file-exists-p file)
311       (let ((coding-system-for-read 'binary))
312         (load file nil nil t)))))
313
314 (defun nnrss-save-server-data (server)
315   (gnus-make-directory nnrss-directory)
316   (let ((coding-system-for-write 'binary))
317     (with-temp-file (nnrss-make-filename "nnrss" server)
318       (gnus-prin1 `(setq nnrss-group-alist ',nnrss-group-alist))
319       (gnus-prin1 `(setq nnrss-server-data ',nnrss-server-data)))))
320
321 (defun nnrss-read-group-data (group server)
322   (setq nnrss-group-data nil)
323   (clrhash nnrss-group-hashtb)
324   (let ((pair (assoc group nnrss-server-data)))
325     (setq nnrss-group-max (or (cadr pair) 0))
326     (setq nnrss-group-min (+ nnrss-group-max 1)))
327   (let ((file (nnrss-make-filename group server)))
328     (when (file-exists-p file)
329       (let ((coding-system-for-read 'binary))
330         (load file nil t t))
331       (dolist (e nnrss-group-data)
332         (puthash (nth 2 e) e nnrss-group-hashtb)
333         (when (and (car e) (> nnrss-group-min (car e)))
334           (setq nnrss-group-min (car e)))
335         (when (and (car e) (< nnrss-group-max (car e)))
336           (setq nnrss-group-max (car e)))))))
337
338 (defun nnrss-save-group-data (group server)
339   (gnus-make-directory nnrss-directory)
340   (let ((coding-system-for-write 'binary))
341     (with-temp-file (nnrss-make-filename group server)
342       (gnus-prin1 `(setq nnrss-group-data ',nnrss-group-data )))))
343
344 (defun nnrss-make-filename (name server)
345   (expand-file-name
346    (nnrss-translate-file-chars
347     (concat name
348             (and server
349                  (not (equal server ""))
350                  "-")
351             server
352             ".el"))
353    nnrss-directory))
354
355 (gnus-add-shutdown 'nnrss-close 'gnus)
356
357 (defun nnrss-close ()
358   "Clear internal nnrss variables."
359   (setq nnrss-group-data nil
360         nnrss-server-data nil
361         nnrss-group-hashtb nil
362         nnrss-group-alist nil))
363
364 ;;; URL interface
365
366 (defun nnrss-no-cache (url)
367   "")
368
369 (defun nnrss-insert-w3 (url)
370   (mm-with-unibyte-current-buffer
371     (mm-url-insert url)))
372
373 (defun nnrss-decode-entities-unibyte-string (string)
374   (if string
375       (mm-with-unibyte-buffer
376         (insert string)
377         (mm-url-decode-entities-nbsp)
378         (buffer-string))))
379
380 (defalias 'nnrss-insert 'nnrss-insert-w3)
381
382 (if (featurep 'xemacs)
383     (defalias 'nnrss-string-as-multibyte 'identity)
384   (defalias 'nnrss-string-as-multibyte 'string-as-multibyte))
385
386 ;;; Snarf functions
387
388 (defun nnrss-check-group (group server)
389   (let (file xml subject url extra changed author
390              date rss-ns rdf-ns content-ns dc-ns)
391     (if (and nnrss-use-local
392              (file-exists-p (setq file (expand-file-name
393                                         (nnrss-translate-file-chars
394                                          (concat group ".xml"))
395                                         nnrss-directory))))
396         (setq xml (nnrss-fetch file t))
397       (setq url (or (nth 2 (assoc group nnrss-server-data))
398                     (second (assoc group nnrss-group-alist))))
399       (unless url
400         (setq url
401              (cdr
402               (assoc 'href
403                      (nnrss-discover-feed
404                       (read-string
405                        (format "URL to search for %s: " group) "http://")))))
406         (let ((pair (assoc group nnrss-server-data)))
407           (if pair
408               (setcdr (cdr pair) (list url))
409             (push (list group nnrss-group-max url) nnrss-server-data)))
410         (setq changed t))
411       (setq xml (nnrss-fetch url)))
412     ;; See
413     ;; http://feeds.archive.org/validator/docs/howto/declare_namespaces.html
414     ;; for more RSS namespaces.
415     (setq dc-ns (nnrss-get-namespace-prefix xml "http://purl.org/dc/elements/1.1/")
416           rdf-ns (nnrss-get-namespace-prefix xml "http://www.w3.org/1999/02/22-rdf-syntax-ns#")
417           rss-ns (nnrss-get-namespace-prefix xml "http://purl.org/rss/1.0/")
418           content-ns (nnrss-get-namespace-prefix xml "http://purl.org/rss/1.0/modules/content/"))
419     (dolist (item (nreverse (nnrss-find-el (intern (concat rss-ns "item")) xml)))
420       (when (and (listp item)
421                  (eq (intern (concat rss-ns "item")) (car item))
422                  (setq url (nnrss-decode-entities-unibyte-string
423                             (nnrss-node-text rss-ns 'link (cddr item))))
424                  (not (gethash url nnrss-group-hashtb)))
425         (setq subject (nnrss-node-text rss-ns 'title item))
426         (setq extra (or (nnrss-node-text content-ns 'encoded item)
427                         (nnrss-node-text rss-ns 'description item)))
428         (setq author (or (nnrss-node-text rss-ns 'author item)
429                          (nnrss-node-text dc-ns 'creator item)
430                          (nnrss-node-text dc-ns 'contributor item)))
431         (setq date (or (nnrss-node-text dc-ns 'date item)
432                        (nnrss-node-text rss-ns 'pubDate item)
433                        (message-make-date)))
434         (push
435          (list
436           (incf nnrss-group-max)
437           (current-time)
438           url
439           (and subject (nnrss-decode-entities-unibyte-string subject))
440           (and author (nnrss-decode-entities-unibyte-string author))
441           date
442           (and extra (nnrss-decode-entities-unibyte-string extra)))
443          nnrss-group-data)
444         (puthash url (car nnrss-group-data) nnrss-group-hashtb)
445         (setq changed t)))
446     (when changed
447       (nnrss-save-group-data group server)
448       (let ((pair (assoc group nnrss-server-data)))
449         (if pair
450             (setcar (cdr pair) nnrss-group-max)
451           (push (list group nnrss-group-max) nnrss-server-data)))
452       (nnrss-save-server-data server))))
453
454 (defun nnrss-generate-download-script ()
455   "Generate a download script in the current buffer.
456 It is useful when `(setq nnrss-use-local t)'."
457   (interactive)
458   (insert "#!/bin/sh\n")
459   (insert "WGET=wget\n")
460   (insert "RSSDIR='" (expand-file-name nnrss-directory) "'\n")
461   (dolist (elem nnrss-server-data)
462     (let ((url (or (nth 2 elem)
463                    (second (assoc (car elem) nnrss-group-alist)))))
464       (insert "$WGET -q -O \"$RSSDIR\"/'"
465               (nnrss-translate-file-chars (concat (car elem) ".xml"))
466               "' '" url "'\n"))))
467
468 (defun nnrss-translate-file-chars (name)
469   (let ((nnheader-file-name-translation-alist
470          (append nnheader-file-name-translation-alist '((?' . ?_)))))
471     (nnheader-translate-file-chars name)))
472
473 (defvar nnrss-moreover-url
474   "http://w.moreover.com/categories/category_list_rss.html"
475   "The url of moreover.com categories.")
476
477 (defun nnrss-snarf-moreover-categories ()
478   "Snarf RSS links from moreover.com."
479   (interactive)
480   (let (category name url changed)
481     (with-temp-buffer
482       (nnrss-insert nnrss-moreover-url)
483       (goto-char (point-min))
484       (while (re-search-forward
485               "<a name=\"\\([^\"]+\\)\">\\|<a href=\"\\(http://[^\"]*moreover\\.com[^\"]+page\\?c=\\([^\"&]+\\)&o=rss\\)" nil t)
486         (if (match-string 1)
487             (setq category (match-string 1))
488           (setq url (match-string 2)
489                 name (mm-url-decode-entities-string
490                       (rfc2231-decode-encoded-string
491                        (match-string 3))))
492           (if category
493               (setq name (concat category "." name)))
494           (unless (assoc name nnrss-server-data)
495             (setq changed t)
496             (push (list name 0 url) nnrss-server-data)))))
497     (if changed
498         (nnrss-save-server-data ""))))
499
500 (defun nnrss-format-string (string)
501   (gnus-replace-in-string (nnrss-string-as-multibyte string) " *\n *" " "))
502
503 (defun nnrss-node-text (namespace local-name element)
504   (let* ((node (assq (intern (concat namespace (symbol-name local-name)))
505                      element))
506          (text (if (and node (listp node))
507                    (nnrss-node-just-text node)
508                  node))
509          (cleaned-text (if text (gnus-replace-in-string
510                                  text "^[\000-\037\177]+\\|^ +\\| +$" ""))))
511     (if (string-equal "" cleaned-text)
512         nil
513       cleaned-text)))
514
515 (defun nnrss-node-just-text (node)
516   (if (and node (listp node))
517       (mapconcat 'nnrss-node-just-text (cddr node) " ")
518     node))
519
520 (defun nnrss-find-el (tag data &optional found-list)
521   "Find the all matching elements in the data.  Careful with this on
522 large documents!"
523   (if (listp data)
524       (mapcar (lambda (bit)
525                 (if (car-safe bit)
526                     (progn (if (equal tag (car bit))
527                                (setq found-list
528                                      (append found-list
529                                              (list bit))))
530                            (if (and (listp (car-safe (caddr bit)))
531                                     (not (stringp (caddr bit))))
532                                (setq found-list
533                                      (append found-list
534                                              (nnrss-find-el
535                                               tag (caddr bit))))
536                              (setq found-list
537                                    (append found-list
538                                            (nnrss-find-el
539                                             tag (cddr bit))))))))
540                 data))
541   found-list)
542
543 (defun nnrss-rsslink-p (el)
544   "Test if the element we are handed is an RSS autodiscovery link."
545   (and (eq (car-safe el) 'link)
546        (string-equal (cdr (assoc 'rel (cadr el))) "alternate")
547        (or (string-equal (cdr (assoc 'type (cadr el))) 
548                          "application/rss+xml")
549            (string-equal (cdr (assoc 'type (cadr el))) "text/xml"))))
550
551 (defun nnrss-get-rsslinks (data)
552   "Extract the <link> elements that are links to RSS from the parsed data."
553   (delq nil (mapcar 
554              (lambda (el)
555                (if (nnrss-rsslink-p el) el))
556              (nnrss-find-el 'link data))))
557
558 (defun nnrss-extract-hrefs (data)
559   "Recursively extract hrefs from a page's source.  DATA should be
560 the output of xml-parse-region or w3-parse-buffer."
561   (mapcar (lambda (ahref)
562             (cdr (assoc 'href (cadr ahref))))
563           (nnrss-find-el 'a data)))
564
565 (defmacro nnrss-match-macro (base-uri item 
566                                            onsite-list offsite-list)
567   `(cond ((or (string-match (concat "^" ,base-uri) ,item)
568                (not (string-match "://" ,item)))
569            (setq ,onsite-list (append ,onsite-list (list ,item))))
570           (t (setq ,offsite-list (append ,offsite-list (list ,item))))))
571
572 (defun nnrss-order-hrefs (base-uri hrefs)
573   "Given a list of hrefs, sort them using the following priorities:
574   1. links ending in .rss
575   2. links ending in .rdf
576   3. links ending in .xml
577   4. links containing the above
578   5. offsite links
579
580 BASE-URI is used to determine the location of the links and
581 whether they are `offsite' or `onsite'."
582   (let (rss-onsite-end  rdf-onsite-end  xml-onsite-end
583         rss-onsite-in   rdf-onsite-in   xml-onsite-in
584         rss-offsite-end rdf-offsite-end xml-offsite-end
585         rss-offsite-in rdf-offsite-in xml-offsite-in)
586     (mapcar (lambda (href)
587               (if (not (null href))
588               (cond ((string-match "\\.rss$" href)
589                      (nnrss-match-macro
590                       base-uri href rss-onsite-end rss-offsite-end))
591                     ((string-match "\\.rdf$" href)
592                      (nnrss-match-macro 
593                       base-uri href rdf-onsite-end rdf-offsite-end))
594                     ((string-match "\\.xml$" href)
595                      (nnrss-match-macro
596                       base-uri href xml-onsite-end xml-offsite-end))
597                     ((string-match "rss" href)
598                      (nnrss-match-macro
599                       base-uri href rss-onsite-in rss-offsite-in))
600                     ((string-match "rdf" href)
601                      (nnrss-match-macro
602                       base-uri href rdf-onsite-in rdf-offsite-in))
603                     ((string-match "xml" href)
604                      (nnrss-match-macro
605                       base-uri href xml-onsite-in xml-offsite-in)))))
606             hrefs)
607     (append 
608      rss-onsite-end  rdf-onsite-end  xml-onsite-end
609      rss-onsite-in   rdf-onsite-in   xml-onsite-in
610      rss-offsite-end rdf-offsite-end xml-offsite-end
611      rss-offsite-in rdf-offsite-in xml-offsite-in)))
612
613 (defun nnrss-discover-feed (url)
614   "Given a page, find an RSS feed using Mark Pilgrim's
615 `ultra-liberal rss locator' (http://diveintomark.org/2002/08/15.html)."
616
617   (let ((parsed-page (nnrss-fetch url)))
618
619 ;;    1. if this url is the rss, use it.
620     (if (nnrss-rss-p parsed-page)
621         (let ((rss-ns (nnrss-get-namespace-prefix parsed-page "http://purl.org/rss/1.0/")))
622           (nnrss-rss-title-description rss-ns parsed-page url))
623
624 ;;    2. look for the <link rel="alternate"
625 ;;    type="application/rss+xml" and use that if it is there.
626       (let ((links (nnrss-get-rsslinks parsed-page)))
627         (if links
628             (let* ((xml (nnrss-fetch
629                          (cdr (assoc 'href (cadar links)))))
630                    (rss-ns (nnrss-get-namespace-prefix xml "http://purl.org/rss/1.0/")))
631               (nnrss-rss-title-description rss-ns xml (cdr (assoc 'href (cadar links)))))
632
633 ;;    3. look for links on the site in the following order:
634 ;;       - onsite links ending in .rss, .rdf, or .xml
635 ;;       - onsite links containing any of the above
636 ;;       - offsite links ending in .rss, .rdf, or .xml
637 ;;       - offsite links containing any of the above
638           (let* ((base-uri (progn (string-match ".*://[^/]+/?" url)
639                                   (match-string 0 url)))
640                  (hrefs (nnrss-order-hrefs 
641                          base-uri (nnrss-extract-hrefs parsed-page)))
642                  (rss-link nil))
643           (while (and (eq rss-link nil) (not (eq hrefs nil)))
644             (let ((href-data (nnrss-fetch (car hrefs))))
645               (if (nnrss-rss-p href-data)
646                   (let* ((rss-ns (nnrss-get-namespace-prefix href-data "http://purl.org/rss/1.0/")))
647                     (setq rss-link (nnrss-rss-title-description
648                                     rss-ns href-data (car hrefs))))
649                 (setq hrefs (cdr hrefs)))))
650           (if rss-link rss-link
651
652 ;;    4. check syndic8
653             (nnrss-find-rss-via-syndic8 url))))))))
654
655 (defun nnrss-find-rss-via-syndic8 (url)
656   "query syndic8 for the rss feeds it has for the url."
657   (if (not (locate-library "xml-rpc"))
658       (progn
659         (message "XML-RPC is not available... not checking Syndic8.")
660         nil)
661     (require 'xml-rpc)
662     (let ((feedid (xml-rpc-method-call
663                    "http://www.syndic8.com/xmlrpc.php"
664                    'syndic8.FindSites
665                    url)))
666       (when feedid
667         (let* ((feedinfo (xml-rpc-method-call 
668                           "http://www.syndic8.com/xmlrpc.php"
669                           'syndic8.GetFeedInfo
670                           feedid))
671                (urllist
672                 (delq nil 
673                       (mapcar
674                        (lambda (listinfo)
675                          (if (string-equal 
676                               (cdr (assoc "status" listinfo))
677                               "Syndicated")
678                              (cons
679                               (cdr (assoc "sitename" listinfo))
680                               (list
681                                (cons 'title
682                                      (cdr (assoc 
683                                            "sitename" listinfo)))
684                                (cons 'href
685                                      (cdr (assoc
686                                            "dataurl" listinfo)))))))
687                        feedinfo))))
688           (if (not (> (length urllist) 1))
689               (cdar urllist)
690             (let ((completion-ignore-case t)
691                   (selection 
692                    (mapcar (lambda (listinfo)
693                              (cons (cdr (assoc "sitename" listinfo)) 
694                                    (string-to-int 
695                                     (cdr (assoc "feedid" listinfo)))))
696                            feedinfo)))
697               (cdr (assoc 
698                     (completing-read
699                      "Multiple feeds found.  Select one: "
700                      selection nil t) urllist)))))))))
701
702 (defun nnrss-rss-p (data)
703   "Test if data is an RSS feed.  Simply ensures that the first
704 element is rss or rdf."
705   (or (eq (caar data) 'rss)
706       (eq (caar data) 'rdf:RDF)))
707
708 (defun nnrss-rss-title-description (rss-namespace data url)
709   "Return the title of an RSS feed."
710   (if (nnrss-rss-p data)
711       (let ((description (intern (concat rss-namespace "description")))
712             (title (intern (concat rss-namespace "title")))
713             (channel (nnrss-find-el (intern (concat rss-namespace "channel"))
714                                     data)))
715         (list
716          (cons 'description (caddr (nth 0 (nnrss-find-el description channel))))
717          (cons 'title (caddr (nth 0 (nnrss-find-el title channel))))
718          (cons 'href url)))))
719
720 (defun nnrss-get-namespace-prefix (el uri)
721   "Given EL (containing a parsed element) and URI (containing a string
722 that gives the URI for which you want to retrieve the namespace
723 prefix), return the prefix."
724   (let* ((prefix (car (rassoc uri (cadar el))))
725          (nslist (if prefix 
726                      (split-string (symbol-name prefix) ":")))
727          (ns (cond ((eq (length nslist) 1) ; no prefix given
728                     "")
729                    ((eq (length nslist) 2) ; extract prefix
730                     (cadr nslist)))))
731     (if (and ns (not (eq ns "")))
732         (concat ns ":")
733       ns)))
734
735 (provide 'nnrss)
736
737
738 ;;; nnrss.el ends here
739