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