Revision: miles@gnu.org--gnu-2005/gnus--devo--0--patch-47
[gnus] / lisp / nnrss.el
1 ;;; nnrss.el --- interfacing with RSS
2 ;; Copyright (C) 2001, 2002, 2003, 2004, 2005  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 (require 'rfc2047)
40 (require 'mml)
41 (eval-when-compile
42   (ignore-errors
43     (require 'xml)))
44 (eval '(require 'xml))
45
46 (nnoo-declare nnrss)
47
48 (defvoo nnrss-directory (nnheader-concat gnus-directory "rss/")
49   "Where nnrss will save its files.")
50
51 ;; (group max rss-url)
52 (defvoo nnrss-server-data nil)
53
54 ;; (num timestamp url subject author date extra)
55 (defvoo nnrss-group-data nil)
56 (defvoo nnrss-group-max 0)
57 (defvoo nnrss-group-min 1)
58 (defvoo nnrss-group nil)
59 (defvoo nnrss-group-hashtb (make-hash-table :test 'equal))
60 (defvoo nnrss-status-string "")
61
62 (defconst nnrss-version "nnrss 1.0")
63
64 (defvar nnrss-group-alist '()
65   "List of RSS addresses.")
66
67 (defvar nnrss-use-local nil)
68
69 (defvar nnrss-description-field 'X-Gnus-Description
70   "Field name used for DESCRIPTION.
71 To use the description in headers, put this name into `nnmail-extra-headers'.")
72
73 (defvar nnrss-url-field 'X-Gnus-Url
74   "Field name used for URL.
75 To use the description in headers, put this name into `nnmail-extra-headers'.")
76
77 (defvar nnrss-content-function nil
78   "A function which is called in `nnrss-request-article'.
79 The arguments are (ENTRY GROUP ARTICLE).
80 ENTRY is the record of the current headline.  GROUP is the group name.
81 ARTICLE is the article number of the current headline.")
82
83 (defvar nnrss-file-coding-system mm-universal-coding-system
84   "Coding system used when reading and writing files.")
85
86 (nnoo-define-basics nnrss)
87
88 ;;; Interface functions
89
90 (defsubst nnrss-format-string (string)
91   (gnus-replace-in-string string " *\n *" " "))
92
93 (defun nnrss-decode-group-name (group)
94   (if (and group (mm-coding-system-p 'utf-8))
95       (setq group (mm-decode-coding-string group 'utf-8))
96     group))
97
98 (deffoo nnrss-retrieve-headers (articles &optional group server fetch-old)
99   (setq group (nnrss-decode-group-name group))
100   (nnrss-possibly-change-group group server)
101   (let (e)
102     (save-excursion
103       (set-buffer nntp-server-buffer)
104       (erase-buffer)
105       (dolist (article articles)
106         (if (setq e (assq article nnrss-group-data))
107             (insert (number-to-string (car e)) "\t" ;; number
108                     ;; subject
109                     (or (nth 3 e) "")
110                     "\t"
111                     ;; from
112                     (or (nth 4 e) "(nobody)")
113                     "\t"
114                     ;; date
115                     (or (nth 5 e) "")
116                     "\t"
117                     ;; id
118                     (format "<%d@%s.nnrss>" (car e) group)
119                     "\t"
120                     ;; refs
121                     "\t"
122                     ;; chars
123                     "-1" "\t"
124                     ;; lines
125                     "-1" "\t"
126                     ;; Xref
127                     "" "\t"
128                     (if (and (nth 6 e)
129                              (memq nnrss-description-field
130                                    nnmail-extra-headers))
131                         (concat (symbol-name nnrss-description-field)
132                                 ": "
133                                 (nnrss-format-string (nth 6 e))
134                                 "\t")
135                       "")
136                     (if (and (nth 2 e)
137                              (memq nnrss-url-field
138                                    nnmail-extra-headers))
139                         (concat (symbol-name nnrss-url-field)
140                                 ": "
141                                 (nnrss-format-string (nth 2 e))
142                                 "\t")
143                       "")
144                     "\n")))))
145   'nov)
146
147 (deffoo nnrss-request-group (group &optional server dont-check)
148   (setq group (nnrss-decode-group-name group))
149   (nnrss-possibly-change-group group server)
150   (if dont-check
151       t
152     (nnrss-check-group group server)
153     (nnheader-report 'nnrss "Opened group %s" group)
154     (nnheader-insert
155      "211 %d %d %d %s\n" nnrss-group-max nnrss-group-min nnrss-group-max
156      (prin1-to-string group)
157      t)))
158
159 (deffoo nnrss-close-group (group &optional server)
160   t)
161
162 (deffoo nnrss-request-article (article &optional group server buffer)
163   (setq group (nnrss-decode-group-name group))
164   (when (stringp article)
165     (setq article (if (string-match "\\`<\\([0-9]+\\)@" article)
166                       (string-to-number (match-string 1 article))
167                     0)))
168   (nnrss-possibly-change-group group server)
169   (let ((e (assq article nnrss-group-data))
170         (nntp-server-buffer (or buffer nntp-server-buffer))
171         post err)
172     (when e
173       (catch 'error
174         (with-current-buffer nntp-server-buffer
175           (erase-buffer)
176           (if group
177               (insert "Newsgroups: " group "\n"))
178           (if (nth 3 e)
179               (insert "Subject: " (nth 3 e) "\n"))
180           (if (nth 4 e)
181               (insert "From: " (nth 4 e) "\n"))
182           (if (nth 5 e)
183               (insert "Date: " (nnrss-format-string (nth 5 e)) "\n"))
184           (insert "\n")
185           (let ((text (if (nth 6 e)
186                           (mapconcat 'identity
187                                      (delete "" (split-string (nth 6 e) "\n+"))
188                                      " ")))
189                 (link (nth 2 e))
190                 ;; Enable encoding of Newsgroups header in XEmacs.
191                 (default-enable-multibyte-characters t)
192                 (rfc2047-header-encoding-alist
193                  (if (mm-coding-system-p 'utf-8)
194                      (cons '("Newsgroups" . utf-8)
195                            rfc2047-header-encoding-alist)
196                    rfc2047-header-encoding-alist))
197                 rfc2047-encode-encoded-words)
198             (when (or text link)
199               (insert "<#multipart type=alternative>\n"
200                       "<#part type=\"text/plain\">\n")
201               (if text
202                   (progn
203                     (insert text "\n")
204                     (when link
205                       (insert "\n" link "\n")))
206                 (when link
207                   (insert link "\n")))
208               (insert "<#/part>\n"
209                       "<#part type=\"text/html\">\n"
210                       "<html><head></head><body>\n")
211               (when text
212                 (insert text "\n"))
213               (when link
214                 (insert "<p><a href=\"" link "\">link</a></p>\n"))
215               (insert "</body></html>\n"
216                       "<#/part>\n"
217                       "<#/multipart>\n")
218               (mml-to-mime)))
219           (goto-char (point-min))
220           (search-forward "\n\n")
221           (forward-line -1)
222           (insert (format "Message-ID: <%d@%s.nnrss>\n"
223                           (car e)
224                           (let ((rfc2047-encoding-type 'mime)
225                                 rfc2047-encode-max-chars)
226                             (rfc2047-encode-string
227                              (gnus-replace-in-string group "[\t\n ]+" "_")))))
228           (when nnrss-content-function
229             (funcall nnrss-content-function e group article)))))
230     (cond
231      (err
232       (nnheader-report 'nnrss err))
233      ((not e)
234       (nnheader-report 'nnrss "no such id: %d" article))
235      (t
236       (nnheader-report 'nnrss "article %s retrieved" (car e))
237       ;; we return the article number.
238       (cons nnrss-group (car e))))))
239
240 (deffoo nnrss-request-list (&optional server)
241   (nnrss-possibly-change-group nil server)
242   (nnrss-generate-active)
243   t)
244
245 (deffoo nnrss-open-server (server &optional defs connectionless)
246   (nnrss-read-server-data server)
247   (nnoo-change-server 'nnrss server defs)
248   t)
249
250 (deffoo nnrss-request-expire-articles
251     (articles group &optional server force)
252   (setq group (nnrss-decode-group-name group))
253   (nnrss-possibly-change-group group server)
254   (let (e days not-expirable changed)
255     (dolist (art articles)
256       (if (and (setq e (assq art nnrss-group-data))
257                (nnmail-expired-article-p
258                 group
259                 (if (listp (setq days (nth 1 e))) days
260                   (days-to-time (- days (time-to-days '(0 0)))))
261                 force))
262           (setq nnrss-group-data (delq e nnrss-group-data)
263                 changed t)
264         (push art not-expirable)))
265     (if changed
266         (nnrss-save-group-data group server))
267     not-expirable))
268
269 (deffoo nnrss-request-delete-group (group &optional force server)
270   (setq group (nnrss-decode-group-name group))
271   (nnrss-possibly-change-group group server)
272   (let (elem)
273     ;; There may be two or more entries in `nnrss-group-alist' since
274     ;; this function didn't delete them formerly.
275     (while (setq elem (assoc group nnrss-group-alist))
276       (setq nnrss-group-alist (delq elem nnrss-group-alist))))
277   (setq nnrss-server-data
278         (delq (assoc group nnrss-server-data) nnrss-server-data))
279   (nnrss-save-server-data server)
280   (ignore-errors
281     (delete-file (nnrss-make-filename group server)))
282   t)
283
284 (deffoo nnrss-request-list-newsgroups (&optional server)
285   (nnrss-possibly-change-group nil server)
286   (save-excursion
287     (set-buffer nntp-server-buffer)
288     (erase-buffer)
289     (dolist (elem nnrss-group-alist)
290       (if (third elem)
291           (insert (car elem) "\t" (third elem) "\n"))))
292   t)
293
294 (nnoo-define-skeleton nnrss)
295
296 ;;; Internal functions
297 (eval-when-compile (defun xml-rpc-method-call (&rest args)))
298
299 (defun nnrss-get-encoding ()
300   "Return an encoding attribute specified in the current xml contents."
301   (goto-char (point-min))
302   (mm-coding-system-p
303    (if (re-search-forward
304         "<\\?[^>]*encoding=\\(?:\"\\([^\">]+\\)\"\\|'\\([^'>]+\\)'\\)"
305         nil t)
306        (intern-soft (downcase (or (match-string-no-properties 1)
307                                   (match-string-no-properties 2))))
308      ;; The default encoding for xml.
309      'utf-8)))
310
311 (defun nnrss-fetch (url &optional local)
312   "Fetch URL and put it in a the expected Lisp structure."
313   (mm-with-unibyte-buffer
314     ;;some CVS versions of url.el need this to close the connection quickly
315     (let (cs xmlform htmlform)
316       ;; bit o' work necessary for w3 pre-cvs and post-cvs
317       (if local
318           (let ((coding-system-for-read 'binary))
319             (insert-file-contents url))
320         ;; FIXME: shouldn't binding `coding-system-for-read' be moved
321         ;; to `mm-url-insert'?
322         (let ((coding-system-for-read 'binary))
323           (mm-url-insert url)))
324       (nnheader-remove-cr-followed-by-lf)
325       ;; Decode text according to the encoding attribute.
326       (when (setq cs (nnrss-get-encoding))
327         (mm-decode-coding-region (point-min) (point-max) cs)
328         (mm-enable-multibyte))
329       (goto-char (point-min))
330
331       ;; Because xml-parse-region can't deal with anything that isn't
332       ;; xml and w3-parse-buffer can't deal with some xml, we have to
333       ;; parse with xml-parse-region first and, if that fails, parse
334       ;; with w3-parse-buffer.  Yuck.  Eventually, someone should find out
335       ;; why w3-parse-buffer fails to parse some well-formed xml and
336       ;; fix it.
337
338       (condition-case err1
339           (setq xmlform (xml-parse-region (point-min) (point-max)))
340         (error
341          (condition-case err2
342              (setq htmlform (caddar (w3-parse-buffer
343                                      (current-buffer))))
344            (error
345             (message "\
346 nnrss: %s: Not valid XML %s and w3-parse doesn't work %s"
347                      url err1 err2)))))
348       (if htmlform
349           htmlform
350         xmlform))))
351
352 (defun nnrss-possibly-change-group (&optional group server)
353   (when (and server
354              (not (nnrss-server-opened server)))
355     (nnrss-open-server server))
356   (when (and group (not (equal group nnrss-group)))
357     (nnrss-read-group-data group server)
358     (setq nnrss-group group)))
359
360 (defvar nnrss-extra-categories '(nnrss-snarf-moreover-categories))
361
362 (defun nnrss-generate-active ()
363   (when (y-or-n-p "Fetch extra categories? ")
364     (mapc 'funcall nnrss-extra-categories))
365   (save-excursion
366     (set-buffer nntp-server-buffer)
367     (erase-buffer)
368     (dolist (elem nnrss-group-alist)
369       (insert (prin1-to-string (car elem)) " 0 1 y\n"))
370     (dolist (elem nnrss-server-data)
371       (unless (assoc (car elem) nnrss-group-alist)
372         (insert (prin1-to-string (car elem)) " 0 1 y\n")))))
373
374 ;;; data functions
375
376 (defun nnrss-read-server-data (server)
377   (setq nnrss-server-data nil)
378   (let ((file (nnrss-make-filename "nnrss" server)))
379     (when (file-exists-p file)
380       ;; In Emacs 21.3 and earlier, `load' doesn't support non-ASCII
381       ;; file names.  So, we use `insert-file-contents' instead.
382       (mm-with-multibyte-buffer
383         (let ((coding-system-for-read nnrss-file-coding-system)
384               (file-name-coding-system nnmail-pathname-coding-system))
385           (insert-file-contents file)
386           (eval-region (point-min) (point-max)))))))
387
388 (defun nnrss-save-server-data (server)
389   (gnus-make-directory nnrss-directory)
390   (let ((coding-system-for-write nnrss-file-coding-system)
391         (file-name-coding-system nnmail-pathname-coding-system))
392     (with-temp-file (nnrss-make-filename "nnrss" server)
393       (insert (format ";; -*- coding: %s; -*-\n"
394                       nnrss-file-coding-system))
395       (gnus-prin1 `(setq nnrss-group-alist ',nnrss-group-alist))
396       (insert "\n")
397       (gnus-prin1 `(setq nnrss-server-data ',nnrss-server-data)))))
398
399 (defun nnrss-read-group-data (group server)
400   (setq nnrss-group-data nil)
401   (if (hash-table-p nnrss-group-hashtb)
402       (clrhash nnrss-group-hashtb)
403     (setq nnrss-group-hashtb (make-hash-table :test 'equal)))
404   (let ((pair (assoc group nnrss-server-data)))
405     (setq nnrss-group-max (or (cadr pair) 0))
406     (setq nnrss-group-min (+ nnrss-group-max 1)))
407   (let ((file (nnrss-make-filename group server)))
408     (when (file-exists-p file)
409       ;; In Emacs 21.3 and earlier, `load' doesn't support non-ASCII
410       ;; file names.  So, we use `insert-file-contents' instead.
411       (mm-with-multibyte-buffer
412         (let ((coding-system-for-read nnrss-file-coding-system)
413               (file-name-coding-system nnmail-pathname-coding-system))
414           (insert-file-contents file)
415           (eval-region (point-min) (point-max))))
416       (dolist (e nnrss-group-data)
417         (puthash (or (nth 2 e) (nth 6 e)) t nnrss-group-hashtb)
418         (when (and (car e) (> nnrss-group-min (car e)))
419           (setq nnrss-group-min (car e)))
420         (when (and (car e) (< nnrss-group-max (car e)))
421           (setq nnrss-group-max (car e)))))))
422
423 (defun nnrss-save-group-data (group server)
424   (gnus-make-directory nnrss-directory)
425   (let ((coding-system-for-write nnrss-file-coding-system)
426         (file-name-coding-system nnmail-pathname-coding-system))
427     (with-temp-file (nnrss-make-filename group server)
428       (insert (format ";; -*- coding: %s; -*-\n"
429                       nnrss-file-coding-system))
430       (gnus-prin1 `(setq nnrss-group-data ',nnrss-group-data)))))
431
432 (defun nnrss-make-filename (name server)
433   (expand-file-name
434    (nnrss-translate-file-chars
435     (concat name
436             (and server
437                  (not (equal server ""))
438                  "-")
439             server
440             ".el"))
441    nnrss-directory))
442
443 (gnus-add-shutdown 'nnrss-close 'gnus)
444
445 (defun nnrss-close ()
446   "Clear internal nnrss variables."
447   (setq nnrss-group-data nil
448         nnrss-server-data nil
449         nnrss-group-hashtb nil
450         nnrss-group-alist nil))
451
452 ;;; URL interface
453
454 (defun nnrss-no-cache (url)
455   "")
456
457 (defun nnrss-insert-w3 (url)
458   (mm-with-unibyte-current-buffer
459     (mm-url-insert url)))
460
461 (defun nnrss-decode-entities-string (string)
462   (if string
463       (mm-with-multibyte-buffer
464         (insert string)
465         (mm-url-decode-entities-nbsp)
466         (buffer-string))))
467
468 (defalias 'nnrss-insert 'nnrss-insert-w3)
469
470 (defun nnrss-mime-encode-string (string)
471   (mm-with-multibyte-buffer
472     (insert string)
473     (mm-url-decode-entities-nbsp)
474     (goto-char (point-min))
475     (while (re-search-forward "[\t\n ]+" nil t)
476       (replace-match " "))
477     (goto-char (point-min))
478     (skip-chars-forward " ")
479     (delete-region (point-min) (point))
480     (goto-char (point-max))
481     (skip-chars-forward " ")
482     (delete-region (point) (point-max))
483     (let ((rfc2047-encoding-type 'mime)
484           rfc2047-encode-max-chars)
485       (rfc2047-encode-region (point-min) (point-max)))
486     (goto-char (point-min))
487     (while (search-forward "\n" nil t)
488       (delete-backward-char 1))
489     (buffer-string)))
490
491 ;;; Snarf functions
492
493 (defun nnrss-check-group (group server)
494   (let (file xml subject url extra changed author
495              date rss-ns rdf-ns content-ns dc-ns)
496     (if (and nnrss-use-local
497              (file-exists-p (setq file (expand-file-name
498                                         (nnrss-translate-file-chars
499                                          (concat group ".xml"))
500                                         nnrss-directory))))
501         (setq xml (nnrss-fetch file t))
502       (setq url (or (nth 2 (assoc group nnrss-server-data))
503                     (second (assoc group nnrss-group-alist))))
504       (unless url
505         (setq url
506              (cdr
507               (assoc 'href
508                      (nnrss-discover-feed
509                       (read-string
510                        (format "URL to search for %s: " group) "http://")))))
511         (let ((pair (assoc group nnrss-server-data)))
512           (if pair
513               (setcdr (cdr pair) (list url))
514             (push (list group nnrss-group-max url) nnrss-server-data)))
515         (setq changed t))
516       (setq xml (nnrss-fetch url)))
517     ;; See
518     ;; http://feeds.archive.org/validator/docs/howto/declare_namespaces.html
519     ;; for more RSS namespaces.
520     (setq dc-ns (nnrss-get-namespace-prefix xml "http://purl.org/dc/elements/1.1/")
521           rdf-ns (nnrss-get-namespace-prefix xml "http://www.w3.org/1999/02/22-rdf-syntax-ns#")
522           rss-ns (nnrss-get-namespace-prefix xml "http://purl.org/rss/1.0/")
523           content-ns (nnrss-get-namespace-prefix xml "http://purl.org/rss/1.0/modules/content/"))
524     (dolist (item (nreverse (nnrss-find-el (intern (concat rss-ns "item")) xml)))
525       (when (and (listp item)
526                  (string= (concat rss-ns "item") (car item))
527                  (if (setq url (nnrss-decode-entities-string
528                                 (nnrss-node-text rss-ns 'link (cddr item))))
529                      (not (gethash url nnrss-group-hashtb))
530                    (setq extra (or (nnrss-node-text content-ns 'encoded item)
531                                    (nnrss-node-text rss-ns 'description item)))
532                    (not (gethash extra nnrss-group-hashtb))))
533         (setq subject (nnrss-node-text rss-ns 'title item))
534         (setq extra (or extra
535                         (nnrss-node-text content-ns 'encoded item)
536                         (nnrss-node-text rss-ns 'description item)))
537         (setq author (or (nnrss-node-text rss-ns 'author item)
538                          (nnrss-node-text dc-ns 'creator item)
539                          (nnrss-node-text dc-ns 'contributor item)))
540         (setq date (or (nnrss-node-text dc-ns 'date item)
541                        (nnrss-node-text rss-ns 'pubDate item)
542                        (message-make-date)))
543         (push
544          (list
545           (incf nnrss-group-max)
546           (current-time)
547           url
548           (and subject (nnrss-mime-encode-string subject))
549           (and author (nnrss-mime-encode-string author))
550           date
551           (and extra (nnrss-decode-entities-string extra)))
552          nnrss-group-data)
553         (puthash (or url extra) t nnrss-group-hashtb)
554         (setq changed t))
555         (setq extra nil))
556     (when changed
557       (nnrss-save-group-data group server)
558       (let ((pair (assoc group nnrss-server-data)))
559         (if pair
560             (setcar (cdr pair) nnrss-group-max)
561           (push (list group nnrss-group-max) nnrss-server-data)))
562       (nnrss-save-server-data server))))
563
564 (defun nnrss-opml-import (opml-file)
565   "OPML subscriptions import.
566 Read the file and attempt to subscribe to each Feed in the file."
567   (interactive "fImport file: ")
568   (mapcar
569    (lambda (node) (gnus-group-make-rss-group
570                    (cdr (assq 'xmlUrl (cadr node)))))
571    (nnrss-find-el 'outline
572                   (progn
573                     (find-file opml-file)
574                     (xml-parse-region (point-min)
575                                       (point-max))))))
576
577 (defun nnrss-opml-export ()
578   "OPML subscription export.
579 Export subscriptions to a buffer in OPML Format."
580   (interactive)
581   (with-current-buffer (get-buffer-create "*OPML Export*")
582     (mm-set-buffer-file-coding-system 'utf-8)
583     (insert (concat
584              "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
585              "<!-- OPML generated by Emacs Gnus' nnrss.el -->\n"
586              "<opml version=\"1.1\">\n"
587              "  <head>\n"
588              "    <title>mySubscriptions</title>\n"
589              "    <dateCreated>" (format-time-string "%a, %d %b %Y %T %z")
590              "</dateCreated>\n"
591              "    <ownerEmail>" user-mail-address "</ownerEmail>\n"
592              "    <ownerName>" (user-full-name) "</ownerName>\n"
593              "  </head>\n"
594              "  <body>\n"))
595     (mapc (lambda (sub)
596             (insert (concat
597                      "    <outline text=\"" (car sub) "\" xmlUrl=\""
598                      (cadr sub) "\"/>\n")))
599           nnrss-group-alist)
600     (insert (concat
601              "  </body>\n"
602            "</opml>\n")))
603   (pop-to-buffer "*OPML Export*")
604   (when (fboundp 'sgml-mode)
605     (sgml-mode)))
606
607 (defun nnrss-generate-download-script ()
608   "Generate a download script in the current buffer.
609 It is useful when `(setq nnrss-use-local t)'."
610   (interactive)
611   (insert "#!/bin/sh\n")
612   (insert "WGET=wget\n")
613   (insert "RSSDIR='" (expand-file-name nnrss-directory) "'\n")
614   (dolist (elem nnrss-server-data)
615     (let ((url (or (nth 2 elem)
616                    (second (assoc (car elem) nnrss-group-alist)))))
617       (insert "$WGET -q -O \"$RSSDIR\"/'"
618               (nnrss-translate-file-chars (concat (car elem) ".xml"))
619               "' '" url "'\n"))))
620
621 (defun nnrss-translate-file-chars (name)
622   (let ((nnheader-file-name-translation-alist
623          (append nnheader-file-name-translation-alist '((?' . ?_)))))
624     (nnheader-translate-file-chars name)))
625
626 (defvar nnrss-moreover-url
627   "http://w.moreover.com/categories/category_list_rss.html"
628   "The url of moreover.com categories.")
629
630 (defun nnrss-snarf-moreover-categories ()
631   "Snarf RSS links from moreover.com."
632   (interactive)
633   (let (category name url changed)
634     (with-temp-buffer
635       (nnrss-insert nnrss-moreover-url)
636       (goto-char (point-min))
637       (while (re-search-forward
638               "<a name=\"\\([^\"]+\\)\">\\|<a href=\"\\(http://[^\"]*moreover\\.com[^\"]+page\\?c=\\([^\"&]+\\)&o=rss\\)" nil t)
639         (if (match-string 1)
640             (setq category (match-string 1))
641           (setq url (match-string 2)
642                 name (mm-url-decode-entities-string
643                       (rfc2231-decode-encoded-string
644                        (match-string 3))))
645           (if category
646               (setq name (concat category "." name)))
647           (unless (assoc name nnrss-server-data)
648             (setq changed t)
649             (push (list name 0 url) nnrss-server-data)))))
650     (if changed
651         (nnrss-save-server-data ""))))
652
653 (defun nnrss-node-text (namespace local-name element)
654   (let* ((node (assq (intern (concat namespace (symbol-name local-name)))
655                      element))
656          (text (if (and node (listp node))
657                    (nnrss-node-just-text node)
658                  node))
659          (cleaned-text (if text (gnus-replace-in-string
660                                  text "^[\000-\037\177]+\\|^ +\\| +$" ""))))
661     (if (string-equal "" cleaned-text)
662         nil
663       cleaned-text)))
664
665 (defun nnrss-node-just-text (node)
666   (if (and node (listp node))
667       (mapconcat 'nnrss-node-just-text (cddr node) " ")
668     node))
669
670 (defun nnrss-find-el (tag data &optional found-list)
671   "Find the all matching elements in the data.
672 Careful with this on large documents!"
673   (when (listp data)
674     (mapc (lambda (bit)
675             (when (car-safe bit)
676               (when (equal tag (car bit))
677                 ;; Old xml.el may return a list of string.
678                 (when (and (consp (caddr bit))
679                            (stringp (caaddr bit)))
680                   (setcar (cddr bit) (caaddr bit)))
681                 (setq found-list
682                       (append found-list
683                               (list bit))))
684               (if (and (listp (car-safe (caddr bit)))
685                        (not (stringp (caddr bit))))
686                   (setq found-list
687                         (append found-list
688                                 (nnrss-find-el
689                                  tag (caddr bit))))
690                 (setq found-list
691                       (append found-list
692                               (nnrss-find-el
693                                tag (cddr bit)))))))
694           data))
695   found-list)
696
697 (defun nnrss-rsslink-p (el)
698   "Test if the element we are handed is an RSS autodiscovery link."
699   (and (eq (car-safe el) 'link)
700        (string-equal (cdr (assoc 'rel (cadr el))) "alternate")
701        (or (string-equal (cdr (assoc 'type (cadr el)))
702                          "application/rss+xml")
703            (string-equal (cdr (assoc 'type (cadr el))) "text/xml"))))
704
705 (defun nnrss-get-rsslinks (data)
706   "Extract the <link> elements that are links to RSS from the parsed data."
707   (delq nil (mapcar
708              (lambda (el)
709                (if (nnrss-rsslink-p el) el))
710              (nnrss-find-el 'link data))))
711
712 (defun nnrss-extract-hrefs (data)
713   "Recursively extract hrefs from a page's source.
714 DATA should be the output of `xml-parse-region' or
715 `w3-parse-buffer'."
716   (mapcar (lambda (ahref)
717             (cdr (assoc 'href (cadr ahref))))
718           (nnrss-find-el 'a data)))
719
720 (defmacro nnrss-match-macro (base-uri item
721                                            onsite-list offsite-list)
722   `(cond ((or (string-match (concat "^" ,base-uri) ,item)
723                (not (string-match "://" ,item)))
724            (setq ,onsite-list (append ,onsite-list (list ,item))))
725           (t (setq ,offsite-list (append ,offsite-list (list ,item))))))
726
727 (defun nnrss-order-hrefs (base-uri hrefs)
728   "Given a list of hrefs, sort them using the following priorities:
729   1. links ending in .rss
730   2. links ending in .rdf
731   3. links ending in .xml
732   4. links containing the above
733   5. offsite links
734
735 BASE-URI is used to determine the location of the links and
736 whether they are `offsite' or `onsite'."
737   (let (rss-onsite-end  rdf-onsite-end  xml-onsite-end
738         rss-onsite-in   rdf-onsite-in   xml-onsite-in
739         rss-offsite-end rdf-offsite-end xml-offsite-end
740         rss-offsite-in rdf-offsite-in xml-offsite-in)
741     (mapc (lambda (href)
742             (if (not (null href))
743                 (cond ((string-match "\\.rss$" href)
744                        (nnrss-match-macro
745                         base-uri href rss-onsite-end rss-offsite-end))
746                       ((string-match "\\.rdf$" href)
747                        (nnrss-match-macro
748                         base-uri href rdf-onsite-end rdf-offsite-end))
749                       ((string-match "\\.xml$" href)
750                        (nnrss-match-macro
751                         base-uri href xml-onsite-end xml-offsite-end))
752                       ((string-match "rss" href)
753                        (nnrss-match-macro
754                         base-uri href rss-onsite-in rss-offsite-in))
755                       ((string-match "rdf" href)
756                        (nnrss-match-macro
757                         base-uri href rdf-onsite-in rdf-offsite-in))
758                       ((string-match "xml" href)
759                        (nnrss-match-macro
760                         base-uri href xml-onsite-in xml-offsite-in)))))
761           hrefs)
762     (append
763      rss-onsite-end  rdf-onsite-end  xml-onsite-end
764      rss-onsite-in   rdf-onsite-in   xml-onsite-in
765      rss-offsite-end rdf-offsite-end xml-offsite-end
766      rss-offsite-in rdf-offsite-in xml-offsite-in)))
767
768 (defun nnrss-discover-feed (url)
769   "Given a page, find an RSS feed using Mark Pilgrim's
770 `ultra-liberal rss locator' (http://diveintomark.org/2002/08/15.html)."
771
772   (let ((parsed-page (nnrss-fetch url)))
773
774 ;;    1. if this url is the rss, use it.
775     (if (nnrss-rss-p parsed-page)
776         (let ((rss-ns (nnrss-get-namespace-prefix parsed-page "http://purl.org/rss/1.0/")))
777           (nnrss-rss-title-description rss-ns parsed-page url))
778
779 ;;    2. look for the <link rel="alternate"
780 ;;    type="application/rss+xml" and use that if it is there.
781       (let ((links (nnrss-get-rsslinks parsed-page)))
782         (if links
783             (let* ((xml (nnrss-fetch
784                          (cdr (assoc 'href (cadar links)))))
785                    (rss-ns (nnrss-get-namespace-prefix xml "http://purl.org/rss/1.0/")))
786               (nnrss-rss-title-description rss-ns xml (cdr (assoc 'href (cadar links)))))
787
788 ;;    3. look for links on the site in the following order:
789 ;;       - onsite links ending in .rss, .rdf, or .xml
790 ;;       - onsite links containing any of the above
791 ;;       - offsite links ending in .rss, .rdf, or .xml
792 ;;       - offsite links containing any of the above
793           (let* ((base-uri (progn (string-match ".*://[^/]+/?" url)
794                                   (match-string 0 url)))
795                  (hrefs (nnrss-order-hrefs
796                          base-uri (nnrss-extract-hrefs parsed-page)))
797                  (rss-link nil))
798           (while (and (eq rss-link nil) (not (eq hrefs nil)))
799             (let ((href-data (nnrss-fetch (car hrefs))))
800               (if (nnrss-rss-p href-data)
801                   (let* ((rss-ns (nnrss-get-namespace-prefix href-data "http://purl.org/rss/1.0/")))
802                     (setq rss-link (nnrss-rss-title-description
803                                     rss-ns href-data (car hrefs))))
804                 (setq hrefs (cdr hrefs)))))
805           (if rss-link rss-link
806
807 ;;    4. check syndic8
808             (nnrss-find-rss-via-syndic8 url))))))))
809
810 (defun nnrss-find-rss-via-syndic8 (url)
811   "Query syndic8 for the rss feeds it has for URL."
812   (if (not (locate-library "xml-rpc"))
813       (progn
814         (message "XML-RPC is not available... not checking Syndic8.")
815         nil)
816     (require 'xml-rpc)
817     (let ((feedid (xml-rpc-method-call
818                    "http://www.syndic8.com/xmlrpc.php"
819                    'syndic8.FindSites
820                    url)))
821       (when feedid
822         (let* ((feedinfo (xml-rpc-method-call
823                           "http://www.syndic8.com/xmlrpc.php"
824                           'syndic8.GetFeedInfo
825                           feedid))
826                (urllist
827                 (delq nil
828                       (mapcar
829                        (lambda (listinfo)
830                          (if (string-equal
831                               (cdr (assoc "status" listinfo))
832                               "Syndicated")
833                              (cons
834                               (cdr (assoc "sitename" listinfo))
835                               (list
836                                (cons 'title
837                                      (cdr (assoc
838                                            "sitename" listinfo)))
839                                (cons 'href
840                                      (cdr (assoc
841                                            "dataurl" listinfo)))))))
842                        feedinfo))))
843           (if (not (> (length urllist) 1))
844               (cdar urllist)
845             (let ((completion-ignore-case t)
846                   (selection
847                    (mapcar (lambda (listinfo)
848                              (cons (cdr (assoc "sitename" listinfo))
849                                    (string-to-int
850                                     (cdr (assoc "feedid" listinfo)))))
851                            feedinfo)))
852               (cdr (assoc
853                     (completing-read
854                      "Multiple feeds found.  Select one: "
855                      selection nil t) urllist)))))))))
856
857 (defun nnrss-rss-p (data)
858   "Test if DATA is an RSS feed.
859 Simply ensures that the first element is rss or rdf."
860   (or (eq (caar data) 'rss)
861       (eq (caar data) 'rdf:RDF)))
862
863 (defun nnrss-rss-title-description (rss-namespace data url)
864   "Return the title of an RSS feed."
865   (if (nnrss-rss-p data)
866       (let ((description (intern (concat rss-namespace "description")))
867             (title (intern (concat rss-namespace "title")))
868             (channel (nnrss-find-el (intern (concat rss-namespace "channel"))
869                                     data)))
870         (list
871          (cons 'description (caddr (nth 0 (nnrss-find-el description channel))))
872          (cons 'title (caddr (nth 0 (nnrss-find-el title channel))))
873          (cons 'href url)))))
874
875 (defun nnrss-get-namespace-prefix (el uri)
876   "Given EL (containing a parsed element) and URI (containing a string
877 that gives the URI for which you want to retrieve the namespace
878 prefix), return the prefix."
879   (let* ((prefix (car (rassoc uri (cadar el))))
880          (nslist (if prefix
881                      (split-string (symbol-name prefix) ":")))
882          (ns (cond ((eq (length nslist) 1) ; no prefix given
883                     "")
884                    ((eq (length nslist) 2) ; extract prefix
885                     (cadr nslist)))))
886     (if (and ns (not (string= ns "")))
887         (concat ns ":")
888       ns)))
889
890 (provide 'nnrss)
891
892
893 ;;; nnrss.el ends here
894
895 ;;; arch-tag: 12910c07-0cdf-44fb-8d2c-416ded64c267