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