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