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