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