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