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