Fix translations.
[elisp/gnus.git-] / 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 'nnheader)
36 (require 'gnus-util)
37 (require 'time-date)
38 (require 'mime-parse)
39 (require 'mm-url)
40 (require 'eword-encode)
41 (require 'mime-edit)
42 (require 'mime-view)
43 (eval-when-compile
44   (ignore-errors
45    (require 'xml)))
46 (eval '(require 'xml))
47
48 ;; Reload mm-util emulating macros for compiling.
49 (eval-when-compile
50   (let ((features (delq 'mm-util (copy-sequence features))))
51     (load "nnheader" nil t)))
52
53 (nnoo-declare nnrss)
54
55 (defvoo nnrss-directory (nnheader-concat gnus-directory "rss/")
56   "Where nnrss will save its files.")
57
58 ;; (group max rss-url)
59 (defvoo nnrss-server-data nil)
60
61 ;; (num timestamp url subject author date extra)
62 (defvoo nnrss-group-data nil)
63 (defvoo nnrss-group-max 0)
64 (defvoo nnrss-group-min 1)
65 (defvoo nnrss-group nil)
66 (defvoo nnrss-group-hashtb (make-hash-table :test 'equal))
67 (defvoo nnrss-status-string "")
68
69 (defconst nnrss-version "nnrss 1.0")
70
71 (defvar nnrss-group-alist '()
72   "List of RSS addresses.")
73
74 (defvar nnrss-use-local nil)
75
76 (defvar nnrss-description-field 'X-Gnus-Description
77   "Field name used for DESCRIPTION.
78 To use the description in headers, put this name into `nnmail-extra-headers'.")
79
80 (defvar nnrss-url-field 'X-Gnus-Url
81   "Field name used for URL.
82 To use the description in headers, put this name into `nnmail-extra-headers'.")
83
84 (defvar nnrss-content-function nil
85   "A function which is called in `nnrss-request-article'.
86 The arguments are (ENTRY GROUP ARTICLE).
87 ENTRY is the record of the current headline.  GROUP is the group name.
88 ARTICLE is the article number of the current headline.")
89
90 (defvar nnrss-file-coding-system nnheader-auto-save-coding-system
91   "Coding system used when reading and writing files.")
92
93 (defvar nnrss-compatible-encoding-alist '((iso-8859-1 . windows-1252))
94   "Alist of encodings and those supersets.
95 The cdr of each element is used to decode data if it is available when
96 the car is what the data specify as the encoding. Or, the car is used
97 for decoding when the cdr that the data specify is not available.")
98
99 (nnoo-define-basics nnrss)
100
101 ;;; Interface functions
102
103 (defsubst nnrss-format-string (string)
104   (gnus-replace-in-string string " *\n *" " "))
105
106 (defun nnrss-decode-group-name (group)
107   (if (and group (mm-coding-system-p 'utf-8))
108       (setq group (mm-decode-coding-string group 'utf-8))
109     group))
110
111 (deffoo nnrss-retrieve-headers (articles &optional group server fetch-old)
112   (setq group (nnrss-decode-group-name group))
113   (nnrss-possibly-change-group group server)
114   (let (e)
115     (save-excursion
116       (set-buffer nntp-server-buffer)
117       (erase-buffer)
118       (dolist (article articles)
119         (if (setq e (assq article nnrss-group-data))
120             (insert (number-to-string (car e)) "\t" ;; number
121                     ;; subject
122                     (or (nth 3 e) "")
123                     "\t"
124                     ;; from
125                     (or (nth 4 e) "(nobody)")
126                     "\t"
127                     ;; date
128                     (or (nth 5 e) "")
129                     "\t"
130                     ;; id
131                     (format "<%d@%s.nnrss>" (car e) group)
132                     "\t"
133                     ;; refs
134                     "\t"
135                     ;; chars
136                     "-1" "\t"
137                     ;; lines
138                     "-1" "\t"
139                     ;; Xref
140                     "" "\t"
141                     (if (and (nth 6 e)
142                              (memq nnrss-description-field
143                                    nnmail-extra-headers))
144                         (concat (symbol-name nnrss-description-field)
145                                 ": "
146                                 (nnrss-format-string (nth 6 e))
147                                 "\t")
148                       "")
149                     (if (and (nth 2 e)
150                              (memq nnrss-url-field
151                                    nnmail-extra-headers))
152                         (concat (symbol-name nnrss-url-field)
153                                 ": "
154                                 (nnrss-format-string (nth 2 e))
155                                 "\t")
156                       "")
157                     "\n")))))
158   'nov)
159
160 (deffoo nnrss-request-group (group &optional server dont-check)
161   (setq group (nnrss-decode-group-name group))
162   (nnheader-message 6 "nnrss: Requesting %s..." group)
163   (nnrss-possibly-change-group group server)
164   (prog1
165       (if dont-check
166           t
167         (nnrss-check-group group server)
168         (nnheader-report 'nnrss "Opened group %s" group)
169         (nnheader-insert
170          "211 %d %d %d %s\n" nnrss-group-max nnrss-group-min nnrss-group-max
171          (prin1-to-string group)
172          t))
173     (nnheader-message 6 "nnrss: Requesting %s...done" group)))
174
175 (deffoo nnrss-close-group (group &optional server)
176   t)
177
178 (defun nnrss-body-presentation-method ()
179   "Return a body presentation method used with MIME-View.
180 The return value will be `html' or `text'."
181   (in-calist-package 'mime-view)
182   (let ((default (cdr (assq 'body-presentation-method
183                             (car (ctree-find-calist
184                                   mime-preview-condition
185                                   '((type . text) (subtype . t)))))))
186         (html (cdr (assq 'body-presentation-method
187                          (car (ctree-find-calist
188                                mime-preview-condition
189                                '((type . text) (subtype . html))))))))
190     (if (or (not default)
191             (not html)
192             (eq default html))
193         'text
194       'html)))
195
196 (deffoo nnrss-request-article (article &optional group server buffer)
197   (setq group (nnrss-decode-group-name group))
198   (when (stringp article)
199     (setq article (if (string-match "\\`<\\([0-9]+\\)@" article)
200                       (string-to-number (match-string 1 article))
201                     0)))
202   (nnrss-possibly-change-group group server)
203   (let ((e (assq article nnrss-group-data))
204         (nntp-server-buffer (or buffer nntp-server-buffer))
205         post err)
206     (when e
207       (with-current-buffer nntp-server-buffer
208         (erase-buffer)
209         (if group
210             (mm-with-unibyte-current-buffer
211               (insert "Newsgroups: "
212                       (if (mm-coding-system-p 'utf-8)
213                           (mm-encode-coding-string group 'utf-8)
214                         group)
215                       "\n")))
216         (if (nth 3 e)
217             (insert "Subject: " (nth 3 e) "\n"))
218         (if (nth 4 e)
219             (insert "From: " (nth 4 e) "\n"))
220         (if (nth 5 e)
221             (insert "Date: " (nnrss-format-string (nth 5 e)) "\n"))
222         (insert (format "Message-ID: <%d@%s.nnrss>\n"
223                         (car e)
224                         (gnus-replace-in-string group "[\t\n ]+" "_")))
225         (insert "\n")
226         (let ((text (if (nth 6 e)
227                         (mapconcat 'identity
228                                    (delete "" (split-string (nth 6 e) "\n+"))
229                                    " ")))
230               (link (nth 2 e))
231               (enclosure (nth 7 e))
232               (mail-header-separator "")
233               mime-edit-insert-user-agent-field)
234           (when (or text link enclosure)
235             (if (eq 'html (nnrss-body-presentation-method))
236                 (progn
237                   (mime-edit-insert-text "html")
238                   (insert "<html><head></head><body>\n")
239                   (when text
240                     (insert text "\n"))
241                   (when link
242                     (insert "<p><a href=\"" link "\">link</a></p>\n"))
243                   (when enclosure
244                     (insert "<p><a href=\"" (car enclosure) "\">"
245                             (cadr enclosure) "</a> " (nth 2 enclosure)
246                             " " (nth 3 enclosure) "</p>\n"))
247                   (insert "</body></html>\n"))
248               (mime-edit-insert-text "plain")
249               (when text
250                 (insert text "\n")
251                 (when (or link enclosure)
252                   (insert "\n")))
253               (when link
254                 (insert link "\n"))
255               (when enclosure
256                 (insert (car enclosure) " "
257                         (nth 2 enclosure) " "
258                         (nth 3 enclosure) "\n")))
259             (mime-edit-translate-body)))
260         (when nnrss-content-function
261           (funcall nnrss-content-function e group article))))
262     (cond
263      (err
264       (nnheader-report 'nnrss err))
265      ((not e)
266       (nnheader-report 'nnrss "no such id: %d" article))
267      (t
268       (nnheader-report 'nnrss "article %s retrieved" (car e))
269       ;; we return the article number.
270       (cons nnrss-group (car e))))))
271
272 (deffoo nnrss-request-list (&optional server)
273   (nnrss-possibly-change-group nil server)
274   (nnrss-generate-active)
275   t)
276
277 (deffoo nnrss-open-server (server &optional defs connectionless)
278   (nnrss-read-server-data server)
279   (nnoo-change-server 'nnrss server defs)
280   t)
281
282 (deffoo nnrss-request-expire-articles
283     (articles group &optional server force)
284   (setq group (nnrss-decode-group-name group))
285   (nnrss-possibly-change-group group server)
286   (let (e days not-expirable changed)
287     (dolist (art articles)
288       (if (and (setq e (assq art nnrss-group-data))
289                (nnmail-expired-article-p
290                 group
291                 (if (listp (setq days (nth 1 e))) days
292                   (days-to-time (- days (time-to-days '(0 0)))))
293                 force))
294           (setq nnrss-group-data (delq e nnrss-group-data)
295                 changed t)
296         (push art not-expirable)))
297     (if changed
298         (nnrss-save-group-data group server))
299     not-expirable))
300
301 (deffoo nnrss-request-delete-group (group &optional force server)
302   (setq group (nnrss-decode-group-name group))
303   (nnrss-possibly-change-group group server)
304   (let (elem)
305     ;; There may be two or more entries in `nnrss-group-alist' since
306     ;; this function didn't delete them formerly.
307     (while (setq elem (assoc group nnrss-group-alist))
308       (setq nnrss-group-alist (delq elem nnrss-group-alist))))
309   (setq nnrss-server-data
310         (delq (assoc group nnrss-server-data) nnrss-server-data))
311   (nnrss-save-server-data server)
312   (ignore-errors
313    (delete-file (nnrss-make-filename group server)))
314   t)
315
316 (deffoo nnrss-request-list-newsgroups (&optional server)
317   (nnrss-possibly-change-group nil server)
318   (save-excursion
319     (set-buffer nntp-server-buffer)
320     (erase-buffer)
321     (dolist (elem nnrss-group-alist)
322       (if (third elem)
323           (insert (car elem) "\t" (third elem) "\n"))))
324   t)
325
326 (nnoo-define-skeleton nnrss)
327
328 ;;; Internal functions
329 (eval-when-compile (defun xml-rpc-method-call (&rest args)))
330
331 (defun nnrss-get-encoding ()
332   "Return an encoding attribute specified in the current xml contents.
333 If `nnrss-compatible-encoding-alist' specifies the compatible encoding,
334 it is used instead.  If the xml contents doesn't specify the encoding,
335 return `utf-8' which is the default encoding for xml if it is available,
336 otherwise return nil."
337   (goto-char (point-min))
338   (if (re-search-forward
339        "<\\?[^>]*encoding=\\(?:\"\\([^\">]+\\)\"\\|'\\([^'>]+\\)'\\)"
340        nil t)
341       (let ((encoding (intern (downcase (or (match-string 1)
342                                             (match-string 2))))))
343         (or
344          (mm-coding-system-p (cdr (assq encoding
345                                         nnrss-compatible-encoding-alist)))
346          (mm-coding-system-p encoding)
347          (mm-coding-system-p (car (rassq encoding
348                                          nnrss-compatible-encoding-alist)))))
349     (mm-coding-system-p 'utf-8)))
350
351 (defun nnrss-fetch (url &optional local)
352   "Fetch URL and put it in a the expected Lisp structure."
353   (mm-with-unibyte-buffer
354     ;;some CVS versions of url.el need this to close the connection quickly
355     (let (cs xmlform htmlform)
356       ;; bit o' work necessary for w3 pre-cvs and post-cvs
357       (if local
358           (let ((coding-system-for-read 'binary))
359             (insert-file-contents url))
360         (let (;; FIXME: shouldn't binding `coding-system-for-read' be
361               ;; moved to `mm-url-insert'?
362               (coding-system-for-read 'binary)
363               ;; mm-url will load mm-util.  d-e-m-c should be bound to
364               ;; t then, because of `mm-emacs-mule'.
365               (default-enable-multibyte-characters t))
366           (mm-url-insert url)))
367       (nnheader-remove-cr-followed-by-lf)
368       ;; Decode text according to the encoding attribute.
369       (when (setq cs (nnrss-get-encoding))
370         (mm-decode-coding-region (point-min) (point-max) cs)
371         (mm-enable-multibyte))
372       (goto-char (point-min))
373
374       ;; Because xml-parse-region can't deal with anything that isn't
375       ;; xml and w3-parse-buffer can't deal with some xml, we have to
376       ;; parse with xml-parse-region first and, if that fails, parse
377       ;; with w3-parse-buffer.  Yuck.  Eventually, someone should find out
378       ;; why w3-parse-buffer fails to parse some well-formed xml and
379       ;; fix it.
380
381       (condition-case err1
382           (setq xmlform (xml-parse-region (point-min) (point-max)))
383         (error
384          (condition-case err2
385              (setq htmlform (caddar (w3-parse-buffer
386                                      (current-buffer))))
387            (error
388             (message "\
389 nnrss: %s: Not valid XML %s and w3-parse doesn't work %s"
390                      url err1 err2)))))
391       (if htmlform
392           htmlform
393         xmlform))))
394
395 (defun nnrss-possibly-change-group (&optional group server)
396   (when (and server
397              (not (nnrss-server-opened server)))
398     (nnrss-open-server server))
399   (when (and group (not (equal group nnrss-group)))
400     (nnrss-read-group-data group server)
401     (setq nnrss-group group)))
402
403 (defvar nnrss-extra-categories '(nnrss-snarf-moreover-categories))
404
405 (defun nnrss-generate-active ()
406   (when (y-or-n-p "Fetch extra categories? ")
407     (mapc 'funcall nnrss-extra-categories))
408   (save-excursion
409     (set-buffer nntp-server-buffer)
410     (erase-buffer)
411     (dolist (elem nnrss-group-alist)
412       (insert (prin1-to-string (car elem)) " 0 1 y\n"))
413     (dolist (elem nnrss-server-data)
414       (unless (assoc (car elem) nnrss-group-alist)
415         (insert (prin1-to-string (car elem)) " 0 1 y\n")))))
416
417 ;;; data functions
418
419 (defun nnrss-read-server-data (server)
420   (setq nnrss-server-data nil)
421   (let ((file (nnrss-make-filename "nnrss" server)))
422     (when (file-exists-p file)
423       ;; In Emacs 21.3 and earlier, `load' doesn't support non-ASCII
424       ;; file names.  So, we use `insert-file-contents' instead.
425       (mm-with-multibyte-buffer
426         (let ((coding-system-for-read nnrss-file-coding-system)
427               (file-name-coding-system nnmail-pathname-coding-system))
428           (insert-file-contents file)
429           (eval-region (point-min) (point-max)))))))
430
431 (defun nnrss-save-server-data (server)
432   (gnus-make-directory nnrss-directory)
433   (let ((coding-system-for-write nnrss-file-coding-system)
434         (file-name-coding-system nnmail-pathname-coding-system))
435     (with-temp-file (nnrss-make-filename "nnrss" server)
436       (insert (format ";; -*- coding: %s; -*-\n"
437                       nnrss-file-coding-system))
438       (gnus-prin1 `(setq nnrss-group-alist ',nnrss-group-alist))
439       (insert "\n")
440       (gnus-prin1 `(setq nnrss-server-data ',nnrss-server-data)))))
441
442 (defun nnrss-read-group-data (group server)
443   (setq nnrss-group-data nil)
444   (if (hash-table-p nnrss-group-hashtb)
445       (clrhash nnrss-group-hashtb)
446     (setq nnrss-group-hashtb (make-hash-table :test 'equal)))
447   (let ((pair (assoc group nnrss-server-data)))
448     (setq nnrss-group-max (or (cadr pair) 0))
449     (setq nnrss-group-min (+ nnrss-group-max 1)))
450   (let ((file (nnrss-make-filename group server)))
451     (when (file-exists-p file)
452       ;; In Emacs 21.3 and earlier, `load' doesn't support non-ASCII
453       ;; file names.  So, we use `insert-file-contents' instead.
454       (mm-with-multibyte-buffer
455         (let ((coding-system-for-read nnrss-file-coding-system)
456               (file-name-coding-system nnmail-pathname-coding-system))
457           (insert-file-contents file)
458           (eval-region (point-min) (point-max))))
459       (dolist (e nnrss-group-data)
460         (puthash (or (nth 2 e) (nth 6 e)) t nnrss-group-hashtb)
461         (when (and (car e) (> nnrss-group-min (car e)))
462           (setq nnrss-group-min (car e)))
463         (when (and (car e) (< nnrss-group-max (car e)))
464           (setq nnrss-group-max (car e)))))))
465
466 (defun nnrss-save-group-data (group server)
467   (gnus-make-directory nnrss-directory)
468   (let ((coding-system-for-write nnrss-file-coding-system)
469         (file-name-coding-system nnmail-pathname-coding-system))
470     (with-temp-file (nnrss-make-filename group server)
471       (insert (format ";; -*- coding: %s; -*-\n"
472                       nnrss-file-coding-system))
473       (gnus-prin1 `(setq nnrss-group-data ',nnrss-group-data)))))
474
475 (defun nnrss-make-filename (name server)
476   (expand-file-name
477    (nnrss-translate-file-chars
478     (concat name
479             (and server
480                  (not (equal server ""))
481                  "-")
482             server
483             ".el"))
484    nnrss-directory))
485
486 (gnus-add-shutdown 'nnrss-close 'gnus)
487
488 (defun nnrss-close ()
489   "Clear internal nnrss variables."
490   (setq nnrss-group-data nil
491         nnrss-server-data nil
492         nnrss-group-hashtb nil
493         nnrss-group-alist nil))
494
495 ;;; URL interface
496
497 (defun nnrss-no-cache (url)
498   "")
499
500 (defun nnrss-insert-w3 (url)
501   (mm-with-unibyte-current-buffer
502     (mm-url-insert url)))
503
504 (defun nnrss-decode-entities-string (string)
505   (if string
506       (mm-with-multibyte-buffer
507         (insert string)
508         (mm-url-decode-entities-nbsp)
509         (buffer-string))))
510
511 (defalias 'nnrss-insert 'nnrss-insert-w3)
512
513 (defun nnrss-mime-encode-string (string)
514   (mm-with-multibyte-buffer
515     (insert string)
516     (mm-url-decode-entities-nbsp)
517     (goto-char (point-min))
518     (while (re-search-forward "[\t\n ]+" nil t)
519       (replace-match " "))
520     (goto-char (point-min))
521     (skip-chars-forward " ")
522     (delete-region (point-min) (point))
523     (goto-char (point-max))
524     (skip-chars-forward " ")
525     (delete-region (point) (point-max))
526     (eword-encode-string (buffer-string) (eval '(- -1 (lsh -1 -1))))))
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                       (cadr (mime-decode-parameters
699                              (list "c*" (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