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