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