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