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