* nnrss.el (nnrss-fetch): Fetch the local stuff.
[gnus] / 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 nil)
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         (nntp-server-buffer (or buffer nntp-server-buffer))
146         post err)
147     (when e
148       (catch 'error
149         (with-current-buffer nntp-server-buffer
150           (erase-buffer)
151           (goto-char (point-min))
152           (insert "Mime-Version: 1.0\nContent-Type: text/html\n")
153           (if group
154               (insert "Newsgroups: " group "\n"))
155           (if (nth 3 e)
156               (insert "Subject: " (nnrss-format-string (nth 3 e)) "\n"))
157           (if (nth 4 e)
158               (insert "From: " (nnrss-format-string (nth 4 e)) "\n"))
159           (if (nth 5 e)
160               (insert "Date: " (nnrss-format-string (nth 5 e)) "\n"))
161           (insert "Message-ID: " (format "<%d@%s.nnrss>" (car e) group) "\n")
162           (insert "\n")
163           (if (nth 6 e)
164               (let ((point (point)))
165                 (insert (nnrss-string-as-multibyte (nth 6 e)))
166                 (goto-char point)
167                 (while (re-search-forward "\n" nil t)
168                   (replace-match " "))
169                 (goto-char (point-max))
170                 (insert "\n\n")
171                 (fill-region point (point))))
172           (if (nth 2 e)
173               (insert "<p><a href='" (nth 2 e) "'>link</a></p>\n"))
174           (if nnrss-content-function
175               (funcall nnrss-content-function e group article)))))
176     (cond
177      (err
178       (nnheader-report 'nnrss err))
179      ((not e)
180       (nnheader-report 'nnrss "no such id: %d" article))
181      (t
182       (nnheader-report 'nnrss "article %s retrieved" (car e))
183       ;; we return the article number.
184       (cons nnrss-group (car e))))))
185
186 (deffoo nnrss-request-list (&optional server)
187   (nnrss-possibly-change-group nil server)
188   (nnrss-generate-active)
189   t)
190
191 (deffoo nnrss-open-server (server &optional defs connectionless)
192   (nnrss-read-server-data server)
193   (nnoo-change-server 'nnrss server defs)
194   t)
195
196 (deffoo nnrss-request-expire-articles
197     (articles group &optional server force)
198   (nnrss-possibly-change-group group server)
199   (let (e days not-expirable changed)
200     (dolist (art articles)
201       (if (and (setq e (assq art nnrss-group-data))
202                (nnmail-expired-article-p
203                 group
204                 (if (listp (setq days (nth 1 e))) days
205                   (days-to-time (- days (time-to-days '(0 0)))))
206                 force))
207           (setq nnrss-group-data (delq e nnrss-group-data)
208                 changed t)
209         (push art not-expirable)))
210     (if changed
211         (nnrss-save-group-data group server))
212     not-expirable))
213
214 (deffoo nnrss-request-delete-group (group &optional force server)
215   (nnrss-possibly-change-group group server)
216   (setq nnrss-server-data
217         (delq (assoc group nnrss-server-data) nnrss-server-data))
218   (nnrss-save-server-data server)
219   (let ((file (expand-file-name
220                (nnrss-translate-file-chars
221                 (concat group (and server
222                                    (not (equal server ""))
223                                    "-")
224                         server ".el")) nnrss-directory)))
225     (ignore-errors
226       (delete-file file)))
227   t)
228
229 (deffoo nnrss-request-list-newsgroups (&optional server)
230   (nnrss-possibly-change-group nil server)
231   (save-excursion
232     (set-buffer nntp-server-buffer)
233     (erase-buffer)
234     (dolist (elem nnrss-group-alist)
235       (if (third elem)
236           (insert (car elem) "\t" (third elem) "\n"))))
237   t)
238
239 (nnoo-define-skeleton nnrss)
240
241 ;;; Internal functions
242 (eval-when-compile (defun xml-rpc-method-call (&rest args)))
243 (defun nnrss-fetch (url &optional local)
244   "Fetch the url and put it in a the expected lisp structure."
245   (with-temp-buffer
246   ;some CVS versions of url.el need this to close the connection quickly
247     (let* (xmlform htmlform)
248       ;; bit o' work necessary for w3 pre-cvs and post-cvs
249       (if local
250           (let ((coding-system-for-read 'binary))
251             (insert-file-contents url))
252         (mm-url-insert url))
253
254 ;; Because xml-parse-region can't deal with anything that isn't
255 ;; xml and w3-parse-buffer can't deal with some xml, we have to
256 ;; parse with xml-parse-region first and, if that fails, parse
257 ;; with w3-parse-buffer.  Yuck.  Eventually, someone should find out
258 ;; why w3-parse-buffer fails to parse some well-formed xml and
259 ;; fix it.
260
261     (condition-case err
262         (setq xmlform (xml-parse-region (point-min) (point-max)))
263       (error (if (fboundp 'w3-parse-buffer)
264                  (setq htmlform (caddar (w3-parse-buffer
265                                          (current-buffer))))
266                (message "nnrss: Not valid XML and w3 parse not available (%s)"
267                         url))))
268     (if htmlform
269         htmlform
270       xmlform))))
271
272 (defun nnrss-possibly-change-group (&optional group server)
273   (when (and server
274              (not (nnrss-server-opened server)))
275     (nnrss-open-server server))
276   (when (and group (not (equal group nnrss-group)))
277     (nnrss-read-group-data group server)
278     (setq nnrss-group group)))
279
280 (defvar nnrss-extra-categories '(nnrss-snarf-moreover-categories))
281
282 (defun nnrss-generate-active ()
283   (if (y-or-n-p "fetch extra categories? ")
284       (dolist (func nnrss-extra-categories)
285         (funcall func)))
286   (save-excursion
287     (set-buffer nntp-server-buffer)
288     (erase-buffer)
289     (dolist (elem nnrss-group-alist)
290       (insert (prin1-to-string (car elem)) " 0 1 y\n"))
291     (dolist (elem nnrss-server-data)
292       (unless (assoc (car elem) nnrss-group-alist)
293         (insert (prin1-to-string (car elem)) " 0 1 y\n")))))
294
295 ;;; data functions
296
297 (defun nnrss-read-server-data (server)
298   (setq nnrss-server-data nil)
299   (let ((file (expand-file-name
300                (nnrss-translate-file-chars
301                 (concat "nnrss" (and server
302                                      (not (equal server ""))
303                                      "-")
304                         server
305                         ".el"))
306                nnrss-directory)))
307     (when (file-exists-p file)
308       (with-temp-buffer
309         (let ((coding-system-for-read 'binary)
310               emacs-lisp-mode-hook)
311           (insert-file-contents file)
312           (emacs-lisp-mode)
313           (goto-char (point-min))
314           (eval-buffer))))))
315
316 (defun nnrss-save-server-data (server)
317   (gnus-make-directory nnrss-directory)
318   (let ((file (expand-file-name
319                (nnrss-translate-file-chars
320                 (concat "nnrss" (and server
321                                      (not (equal server ""))
322                                      "-")
323                         server ".el"))
324                nnrss-directory)))
325     (let ((coding-system-for-write 'binary)
326           print-level print-length)
327       (with-temp-file file
328         (insert "(setq nnrss-group-alist '"
329                 (prin1-to-string nnrss-group-alist)
330                 ")\n")
331         (insert "(setq nnrss-server-data '"
332                 (prin1-to-string nnrss-server-data)
333                 ")\n")))))
334
335 (defun nnrss-read-group-data (group server)
336   (setq nnrss-group-data nil)
337   (setq nnrss-group-hashtb (gnus-make-hashtable))
338   (let ((pair (assoc group nnrss-server-data)))
339     (setq nnrss-group-max (or (cadr pair) 0))
340     (setq nnrss-group-min (+ nnrss-group-max 1)))
341   (let ((file (expand-file-name
342                (nnrss-translate-file-chars
343                 (concat group (and server
344                                    (not (equal server ""))
345                                    "-")
346                         server ".el"))
347                nnrss-directory)))
348     (when (file-exists-p file)
349       (with-temp-buffer
350         (let ((coding-system-for-read 'binary)
351               emacs-lisp-mode-hook)
352           (insert-file-contents file)
353           (emacs-lisp-mode)
354           (goto-char (point-min))
355           (eval-buffer)))
356       (dolist (e nnrss-group-data)
357         (gnus-sethash (nth 2 e) e nnrss-group-hashtb)
358         (if (and (car e) (> nnrss-group-min (car e)))
359             (setq nnrss-group-min (car e)))
360         (if (and (car e) (< nnrss-group-max (car e)))
361             (setq nnrss-group-max (car e)))))))
362
363 (defun nnrss-save-group-data (group server)
364   (gnus-make-directory nnrss-directory)
365   (let ((file (expand-file-name
366                (nnrss-translate-file-chars
367                 (concat group (and server
368                                    (not (equal server ""))
369                                    "-")
370                         server ".el"))
371                nnrss-directory)))
372     (let ((coding-system-for-write 'binary)
373           print-level print-length)
374       (with-temp-file file
375         (insert "(setq nnrss-group-data '"
376                 (prin1-to-string nnrss-group-data)
377                 ")\n")))))
378
379 ;;; URL interface
380
381 (defun nnrss-no-cache (url)
382   "")
383
384 (defun nnrss-insert-w3 (url)
385   (mm-with-unibyte-current-buffer
386     (mm-url-insert url)))
387
388 (defun nnrss-decode-entities-unibyte-string (string)
389   (if string
390       (mm-with-unibyte-buffer
391         (insert string)
392         (mm-url-decode-entities-nbsp)
393         (buffer-string))))
394
395 (defalias 'nnrss-insert 'nnrss-insert-w3)
396
397 (if (featurep 'xemacs)
398     (defalias 'nnrss-string-as-multibyte 'identity)
399   (defalias 'nnrss-string-as-multibyte 'string-as-multibyte))
400
401 ;;; Snarf functions
402
403 (defun nnrss-check-group (group server)
404   (let (file xml subject url extra changed author date rss-ns rdf-ns content-ns dc-ns)
405     (if (and nnrss-use-local
406              (file-exists-p (setq file (expand-file-name
407                                         (nnrss-translate-file-chars
408                                          (concat group ".xml"))
409                                         nnrss-directory))))
410         (nnrss-fetch file t)
411       (setq url (or (nth 2 (assoc group nnrss-server-data))
412                     (second (assoc group nnrss-group-alist))))
413       (unless url
414         (setq url
415               (nnrss-discover-feed (read-string (format "URL to search for %s: " group) "http://")))
416         (let ((pair (assoc group nnrss-server-data)))
417           (if pair
418               (setcdr (cdr pair) (list url))
419             (push (list group nnrss-group-max url) nnrss-server-data)))
420         (setq changed t))
421       (setq xml (nnrss-fetch url)))
422     ;; See
423     ;; http://feeds.archive.org/validator/docs/howto/declare_namespaces.html
424     ;; for more RSS namespaces.
425     (setq dc-ns (nnrss-get-namespace-prefix xml "http://purl.org/dc/elements/1.1/")
426           rdf-ns (nnrss-get-namespace-prefix xml "http://www.w3.org/1999/02/22-rdf-syntax-ns#")
427           rss-ns (nnrss-get-namespace-prefix xml "http://purl.org/rss/1.0/")
428           content-ns (nnrss-get-namespace-prefix xml "http://purl.org/rss/1.0/modules/content/"))
429     (dolist (item (nreverse (nnrss-find-el (intern (concat rss-ns "item")) xml)))
430       (when (and (listp item)
431                  (eq (intern (concat rss-ns "item")) (car item))
432                  (setq url (nnrss-decode-entities-unibyte-string
433                             (nnrss-node-text rss-ns 'link (cddr item))))
434                  (not (gnus-gethash url nnrss-group-hashtb)))
435         (setq subject (nnrss-node-text rss-ns 'title item))
436         (setq extra (or (nnrss-node-text content-ns 'encoded item)
437                         (nnrss-node-text rss-ns 'description item)))
438         (setq author (or (nnrss-node-text rss-ns 'author item)
439                          (nnrss-node-text dc-ns 'creator item)))
440         (setq date (or (nnrss-node-text dc-ns 'date item)
441                        (nnrss-node-text rss-ns 'pubDate item)
442                        (message-make-date)))
443         (push
444          (list
445           (incf nnrss-group-max)
446           (current-time)
447           url
448           (and subject (nnrss-decode-entities-unibyte-string subject))
449           (and author (nnrss-decode-entities-unibyte-string author))
450           date
451           (and extra (nnrss-decode-entities-unibyte-string extra)))
452          nnrss-group-data)
453         (gnus-sethash url (car nnrss-group-data) nnrss-group-hashtb)
454         (setq changed t)))
455     (when changed
456       (nnrss-save-group-data group server)
457       (let ((pair (assoc group nnrss-server-data)))
458         (if pair
459             (setcar (cdr pair) nnrss-group-max)
460           (push (list group nnrss-group-max) nnrss-server-data)))
461       (nnrss-save-server-data server))))
462
463 (defun nnrss-generate-download-script ()
464   "Generate a download script in the current buffer.
465 It is useful when `(setq nnrss-use-local t)'."
466   (interactive)
467   (insert "#!/bin/sh\n")
468   (insert "WGET=wget\n")
469   (insert "RSSDIR='" (expand-file-name nnrss-directory) "'\n")
470   (dolist (elem nnrss-server-data)
471     (let ((url (or (nth 2 elem)
472                    (second (assoc (car elem) nnrss-group-alist)))))
473       (insert "$WGET -q -O \"$RSSDIR\"/'"
474               (nnrss-translate-file-chars (concat (car elem) ".xml"))
475               "' '" url "'\n"))))
476
477 (defun nnrss-translate-file-chars (name)
478   (let ((nnheader-file-name-translation-alist
479          (append nnheader-file-name-translation-alist '((?' . ?_)))))
480     (nnheader-translate-file-chars name)))
481
482 (defvar nnrss-moreover-url
483   "http://w.moreover.com/categories/category_list_rss.html"
484   "The url of moreover.com categories.")
485
486 (defun nnrss-snarf-moreover-categories ()
487   "Snarf RSS links from moreover.com."
488   (interactive)
489   (let (category name url changed)
490     (with-temp-buffer
491       (nnrss-insert nnrss-moreover-url)
492       (goto-char (point-min))
493       (while (re-search-forward
494               "<a name=\"\\([^\"]+\\)\">\\|<a href=\"\\(http://[^\"]*moreover\\.com[^\"]+page\\?c=\\([^\"&]+\\)&o=rss\\)" nil t)
495         (if (match-string 1)
496             (setq category (match-string 1))
497           (setq url (match-string 2)
498                 name (mm-url-decode-entities-string
499                       (rfc2231-decode-encoded-string
500                        (match-string 3))))
501           (if category
502               (setq name (concat category "." name)))
503           (unless (assoc name nnrss-server-data)
504             (setq changed t)
505             (push (list name 0 url) nnrss-server-data)))))
506     (if changed
507         (nnrss-save-server-data ""))))
508
509 (defun nnrss-format-string (string)
510   (gnus-replace-in-string (nnrss-string-as-multibyte string) " *\n *" " "))
511
512 (defun nnrss-node-text (namespace local-name element)
513   (let* ((node (assq (intern (concat namespace (symbol-name local-name))) element))
514          (text (if (and node (listp node))
515                    (nnrss-node-just-text node)
516                  node))
517          (cleaned-text (if text
518                            (replace-regexp-in-string 
519                             " *$" "" (replace-regexp-in-string
520                                       "^ *" "" (replace-regexp-in-string
521                                                 "^[[:cntrl:]]+" "" text))))))
522     (if (string-equal "" cleaned-text)
523         nil
524       cleaned-text)))
525
526 (defun nnrss-node-just-text (node)
527   (if (and node (listp node))
528       (mapconcat 'nnrss-node-just-text (cddr node) " ")
529     node))
530
531 (defun nnrss-find-el (tag data &optional found-list)
532   "Find the all matching elements in the data.  Careful with this on
533 large documents!"
534   (if (listp data)
535       (mapcar (lambda (bit)
536                 (if (car-safe bit)
537                     (progn (if (equal tag (car bit))
538                                (setq found-list
539                                      (append found-list
540                                              (list bit))))
541                            (if (and (listp (car-safe (caddr bit)))
542                                     (not (stringp (caddr bit))))
543                                (setq found-list
544                                      (append found-list
545                                              (nnrss-find-el
546                                               tag (caddr bit))))
547                              (setq found-list
548                                    (append found-list
549                                            (nnrss-find-el
550                                             tag (cddr bit))))))))
551                 data))
552   found-list)
553
554 (defun nnrss-rsslink-p (el)
555   "Test if the element we are handed is an RSS autodiscovery link."
556   (and (eq (car-safe el) 'link)
557        (string-equal (cdr (assoc 'rel (cadr el))) "alternate")
558        (or (string-equal (cdr (assoc 'type (cadr el))) 
559                          "application/rss+xml")
560            (string-equal (cdr (assoc 'type (cadr el))) "text/xml"))))
561
562 (defun nnrss-get-rsslinks (data)
563   "Extract the <link> elements that are links to RSS from the parsed data."
564   (delq nil (mapcar 
565              (lambda (el)
566                (if (nnrss-rsslink-p el) el))
567              (nnrss-find-el 'link data))))
568
569 (defun nnrss-extract-hrefs (data)
570   "Recursively extract hrefs from a page's source.  DATA should be
571 the output of xml-parse-region or w3-parse-buffer."
572   (mapcar (lambda (ahref)
573             (cdr (assoc 'href (cadr ahref))))
574           (nnrss-find-el 'a data)))
575
576 (defmacro nnrss-match-macro (base-uri item 
577                                            onsite-list offsite-list)
578   `(cond ((or (string-match (concat "^" ,base-uri) ,item)
579                (not (string-match "://" ,item)))
580            (setq ,onsite-list (append ,onsite-list (list ,item))))
581           (t (setq ,offsite-list (append ,offsite-list (list ,item))))))
582
583 (defun nnrss-order-hrefs (base-uri hrefs)
584   "Given a list of hrefs, sort them using the following priorities:
585   1. links ending in .rss
586   2. links ending in .rdf
587   3. links ending in .xml
588   4. links containing the above
589   5. offsite links
590
591 BASE-URI is used to determine the location of the links and
592 whether they are `offsite' or `onsite'."
593   (let (rss-onsite-end  rdf-onsite-end  xml-onsite-end
594         rss-onsite-in   rdf-onsite-in   xml-onsite-in
595         rss-offsite-end rdf-offsite-end xml-offsite-end
596         rss-offsite-in rdf-offsite-in xml-offsite-in)
597     (mapcar (lambda (href)
598               (if (not (null href))
599               (cond ((string-match "\\.rss$" href)
600                      (nnrss-match-macro
601                       base-uri href rss-onsite-end rss-offsite-end))
602                     ((string-match "\\.rdf$" href)
603                      (nnrss-match-macro 
604                       base-uri href rdf-onsite-end rdf-offsite-end))
605                     ((string-match "\\.xml$" href)
606                      (nnrss-match-macro
607                       base-uri href xml-onsite-end xml-offsite-end))
608                     ((string-match "rss" href)
609                      (nnrss-match-macro
610                       base-uri href rss-onsite-in rss-offsite-in))
611                     ((string-match "rdf" href)
612                      (nnrss-match-macro
613                       base-uri href rdf-onsite-in rdf-offsite-in))
614                     ((string-match "xml" href)
615                      (nnrss-match-macro
616                       base-uri href xml-onsite-in xml-offsite-in)))))
617             hrefs)
618     (append 
619      rss-onsite-end  rdf-onsite-end  xml-onsite-end
620      rss-onsite-in   rdf-onsite-in   xml-onsite-in
621      rss-offsite-end rdf-offsite-end xml-offsite-end
622      rss-offsite-in rdf-offsite-in xml-offsite-in)))
623
624 (defun nnrss-discover-feed (url)
625   "Given a page, find an RSS feed using Mark Pilgrim's
626 `ultra-liberal rss locator' (http://diveintomark.org/2002/08/15.html)."
627
628   (let ((parsed-page (nnrss-fetch url)))
629
630 ;;    1. if this url is the rss, use it.
631     (if (nnrss-rss-p parsed-page)
632         (let ((rss-ns (nnrss-get-namespace-prefix parsed-page "http://purl.org/rss/1.0/")))
633           (nnrss-rss-title-description rss-ns parsed-page url))
634
635 ;;    2. look for the <link rel="alternate"
636 ;;    type="application/rss+xml" and use that if it is there.
637       (let ((links (nnrss-get-rsslinks parsed-page)))
638         (if links
639             (let* ((xml (nnrss-fetch
640                          (cdr (assoc 'href (cadar links)))))
641                    (rss-ns (nnrss-get-namespace-prefix xml "http://purl.org/rss/1.0/")))
642               (nnrss-rss-title-description rss-ns xml (cdr (assoc 'href (cadar links)))))
643
644 ;;    3. look for links on the site in the following order:
645 ;;       - onsite links ending in .rss, .rdf, or .xml
646 ;;       - onsite links containing any of the above
647 ;;       - offsite links ending in .rss, .rdf, or .xml
648 ;;       - offsite links containing any of the above
649           (let* ((base-uri (progn (string-match ".*://[^/]+/?" url)
650                                   (match-string 0 url)))
651                  (hrefs (nnrss-order-hrefs 
652                          base-uri (nnrss-extract-hrefs parsed-page)))
653                  (rss-link nil))
654           (while (and (eq rss-link nil) (not (eq hrefs nil)))
655             (let ((href-data (nnrss-fetch (car hrefs))))
656               (if (nnrss-rss-p href-data)
657                   (let* ((rss-ns (nnrss-get-namespace-prefix href-data "http://purl.org/rss/1.0/")))
658                     (setq rss-link (nnrss-rss-title-description
659                                     rss-ns href-data (car hrefs))))
660                 (setq hrefs (cdr hrefs)))))
661           (if rss-link rss-link
662
663 ;;    4. check syndic8
664             (nnrss-find-rss-via-syndic8 url))))))))
665
666 (defun nnrss-find-rss-via-syndic8 (url)
667   "query syndic8 for the rss feeds it has for the url."
668   (condition-case nil
669       (progn (require 'xml-rpc)
670              (let ((feedid (xml-rpc-method-call
671                             "http://www.syndic8.com/xmlrpc.php"
672                             'syndic8.FindSites
673                             url)))
674                (if feedid
675                    (let* ((feedinfo (xml-rpc-method-call 
676                                      "http://www.syndic8.com/xmlrpc.php"
677                                      'syndic8.GetFeedInfo
678                                      feedid))
679                           (urllist
680                            (delq nil 
681                                  (mapcar
682                                   (lambda (listinfo)
683                                     (if (string-equal 
684                                          (cdr (assoc "status" listinfo))
685                                          "Syndicated")
686                                         (cons
687                                          (cdr (assoc "sitename" listinfo))
688                                          (list
689                                           (cons 'title
690                                                 (cdr (assoc 
691                                                       "sitename" listinfo)))
692                                           (cons 'href
693                                                 (cdr (assoc
694                                                       "dataurl" listinfo)))))))
695                                   feedinfo))))
696                      (if (> (length urllist) 1)
697                          (let ((completion-ignore-case t)
698                                (selection 
699                                 (mapcar (lambda (listinfo)
700                                           (cons (cdr (assoc "sitename" listinfo)) 
701                                                 (string-to-int 
702                                                  (cdr (assoc "feedid" listinfo)))))
703                                         feedinfo)))
704                            (cdr (assoc 
705                                  (completing-read
706                                   "Multiple feeds found.  Select one: "
707                                   selection nil t) urllist)))
708                        (cdar urllist))))))
709     (message "XML-RPC is not available... not checking Syndic8.")))
710
711 (defun nnrss-rss-p (data)
712   "Test if data is an RSS feed.  Simply ensures that the first
713 element is rss or rdf."
714   (or (eq (caar data) 'rss)
715       (eq (caar data) 'rdf:RDF)))
716
717 (defun nnrss-rss-title-description (rss-namespace data url)
718   "Return the title of an RSS feed."
719   (if (nnrss-rss-p data)
720       (let ((description (intern (concat rss-namespace "description")))
721             (title (intern (concat rss-namespace "title")))
722             (channel (nnrss-find-el (intern (concat rss-namespace "channel"))
723                                     data)))
724         (list
725          (cons 'description (caddr (nth 0 (nnrss-find-el description channel))))
726          (cons 'title (caddr (nth 0 (nnrss-find-el title channel))))
727          (cons 'href url)))))
728
729 (defun nnrss-get-namespace-prefix (el uri)
730   "Given EL (containing a parsed element) and URI (containing a string
731 that gives the URI for which you want to retrieve the namespace
732 prefix), return the prefix."
733   (let* ((prefix (car (rassoc uri (cadar el))))
734          (nslist (if prefix 
735                      (split-string (symbol-name prefix) ":")))
736          (ns (cond ((eq (length nslist) 1) ; no prefix given
737                     "")
738                    ((eq (length nslist) 2) ; extract prefix
739                     (cadr nslist)))))
740     (if (and ns (not (eq ns "")))
741         (concat ns ":")
742       ns)))
743
744 (provide 'nnrss)
745
746
747 ;;; nnrss.el ends here
748