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