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