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