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