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