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