Merge from gnus--rel--5.10
[gnus] / lisp / nnrss.el
1 ;;; nnrss.el --- interfacing with RSS
2
3 ;; Copyright (C) 2001, 2002, 2003, 2004, 2005,
4 ;;   2006, 2007 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         (insert (prog1
422                     (mm-decode-coding-string (buffer-string) cs)
423                   (erase-buffer)
424                   (mm-enable-multibyte))))
425       (goto-char (point-min))
426
427       ;; Because xml-parse-region can't deal with anything that isn't
428       ;; xml and w3-parse-buffer can't deal with some xml, we have to
429       ;; parse with xml-parse-region first and, if that fails, parse
430       ;; with w3-parse-buffer.  Yuck.  Eventually, someone should find out
431       ;; why w3-parse-buffer fails to parse some well-formed xml and
432       ;; fix it.
433
434       (condition-case err1
435           (setq xmlform (xml-parse-region (point-min) (point-max)))
436         (error
437          (condition-case err2
438              (setq htmlform (caddar (w3-parse-buffer
439                                      (current-buffer))))
440            (error
441             (message "\
442 nnrss: %s: Not valid XML %s and w3-parse doesn't work %s"
443                      url err1 err2)))))
444       (if htmlform
445           htmlform
446         xmlform))))
447
448 (defun nnrss-possibly-change-group (&optional group server)
449   (when (and server
450              (not (nnrss-server-opened server)))
451     (nnrss-open-server server))
452   (when (and group (not (equal group nnrss-group)))
453     (nnrss-read-group-data group server)
454     (setq nnrss-group group)))
455
456 (defvar nnrss-extra-categories '(nnrss-snarf-moreover-categories))
457
458 (defun nnrss-generate-active ()
459   (when (y-or-n-p "Fetch extra categories? ")
460     (mapc 'funcall nnrss-extra-categories))
461   (save-excursion
462     (set-buffer nntp-server-buffer)
463     (erase-buffer)
464     (dolist (elem nnrss-group-alist)
465       (insert (prin1-to-string (car elem)) " 0 1 y\n"))
466     (dolist (elem nnrss-server-data)
467       (unless (assoc (car elem) nnrss-group-alist)
468         (insert (prin1-to-string (car elem)) " 0 1 y\n")))))
469
470 (eval-and-compile (autoload 'timezone-parse-date "timezone"))
471
472 (defun nnrss-normalize-date (date)
473   "Return a date string of DATE in the RFC822 style.
474 This function handles the ISO 8601 date format described in
475 <URL:http://www.w3.org/TR/NOTE-datetime>, and also the RFC822 style
476 which RSS 2.0 allows."
477   (let (case-fold-search vector year month day time zone cts)
478     (cond ((null date))
479           ;; RFC822
480           ((string-match " [0-9]+ " date)
481            (setq vector (timezone-parse-date date)
482                  year (string-to-number (aref vector 0)))
483            (when (>= year 1969)
484              (setq month (string-to-number (aref vector 1))
485                    day (string-to-number (aref vector 2)))
486              (unless (>= (length (setq time (aref vector 3))) 3)
487                (setq time "00:00:00"))
488              (when (and (setq zone (aref vector 4))
489                         (not (string-match "\\`[A-Z+-]" zone)))
490                (setq zone nil))))
491           ;; ISO 8601
492           ((string-match
493             (eval-when-compile
494               (concat
495                ;; 1. year
496                "\\(199[0-9]\\|20[0-9][0-9]\\)"
497                "\\(?:-"
498                ;; 2. month
499                "\\([01][0-9]\\)"
500                "\\(?:-"
501                ;; 3. day
502                "\\([0-3][0-9]\\)"
503                "\\)?\\)?\\(?:T"
504                ;; 4. hh:mm
505                "\\([012][0-9]:[0-5][0-9]\\)"
506                "\\(?:"
507                ;; 5. :ss
508                "\\(:[0-5][0-9]\\)"
509                "\\(?:\\.[0-9]+\\)?\\)?\\)?"
510                ;; 6+7,8,9. zone
511                "\\(?:\\(?:\\([+-][012][0-9]\\):\\([0-5][0-9]\\)\\)"
512                "\\|\\([+-][012][0-9][0-5][0-9]\\)"
513                "\\|\\(Z\\)\\)?"))
514             date)
515            (setq year (string-to-number (match-string 1 date))
516                  month (string-to-number (or (match-string 2 date) "1"))
517                  day (string-to-number (or (match-string 3 date) "1"))
518                  time (if (match-beginning 5)
519                           (substring date (match-beginning 4) (match-end 5))
520                         (concat (or (match-string 4 date) "00:00") ":00"))
521                  zone (cond ((match-beginning 6)
522                              (concat (match-string 6 date)
523                                      (match-string 7 date)))
524                             ((match-beginning 9) ;; Z
525                              "+0000")
526                             (t ;; nil if zone is not provided.
527                              (match-string 8 date))))))
528     (if month
529         (progn
530           (setq cts (current-time-string (encode-time 0 0 0 day month year)))
531           (format "%s, %02d %s %04d %s%s"
532                   (substring cts 0 3) day (substring cts 4 7) year time
533                   (if zone
534                       (concat " " zone)
535                     "")))
536       (message-make-date))))
537
538 ;;; data functions
539
540 (defun nnrss-read-server-data (server)
541   (setq nnrss-server-data nil)
542   (let ((file (nnrss-make-filename "nnrss" server)))
543     (when (file-exists-p file)
544       ;; In Emacs 21.3 and earlier, `load' doesn't support non-ASCII
545       ;; file names.  So, we use `insert-file-contents' instead.
546       (mm-with-multibyte-buffer
547         (let ((coding-system-for-read nnrss-file-coding-system)
548               (file-name-coding-system nnmail-pathname-coding-system))
549           (insert-file-contents file)
550           (eval-region (point-min) (point-max)))))))
551
552 (defun nnrss-save-server-data (server)
553   (gnus-make-directory nnrss-directory)
554   (let ((coding-system-for-write nnrss-file-coding-system)
555         (file-name-coding-system nnmail-pathname-coding-system))
556     (with-temp-file (nnrss-make-filename "nnrss" server)
557       (insert (format ";; -*- coding: %s; -*-\n"
558                       nnrss-file-coding-system))
559       (gnus-prin1 `(setq nnrss-group-alist ',nnrss-group-alist))
560       (insert "\n")
561       (gnus-prin1 `(setq nnrss-server-data ',nnrss-server-data)))))
562
563 (defun nnrss-read-group-data (group server)
564   (setq nnrss-group-data nil)
565   (if (hash-table-p nnrss-group-hashtb)
566       (clrhash nnrss-group-hashtb)
567     (setq nnrss-group-hashtb (make-hash-table :test 'equal)))
568   (let ((pair (assoc group nnrss-server-data)))
569     (setq nnrss-group-max (or (cadr pair) 0))
570     (setq nnrss-group-min (+ nnrss-group-max 1)))
571   (let ((file (nnrss-make-filename group server)))
572     (when (file-exists-p file)
573       ;; In Emacs 21.3 and earlier, `load' doesn't support non-ASCII
574       ;; file names.  So, we use `insert-file-contents' instead.
575       (mm-with-multibyte-buffer
576         (let ((coding-system-for-read nnrss-file-coding-system)
577               (file-name-coding-system nnmail-pathname-coding-system))
578           (insert-file-contents file)
579           (eval-region (point-min) (point-max))))
580       (dolist (e nnrss-group-data)
581         (puthash (nth 9 e) t nnrss-group-hashtb)
582         (when (and (car e) (> nnrss-group-min (car e)))
583           (setq nnrss-group-min (car e)))
584         (when (and (car e) (< nnrss-group-max (car e)))
585           (setq nnrss-group-max (car e)))))))
586
587 (defun nnrss-save-group-data (group server)
588   (gnus-make-directory nnrss-directory)
589   (let ((coding-system-for-write nnrss-file-coding-system)
590         (file-name-coding-system nnmail-pathname-coding-system))
591     (with-temp-file (nnrss-make-filename group server)
592       (insert (format ";; -*- coding: %s; -*-\n"
593                       nnrss-file-coding-system))
594       (gnus-prin1 `(setq nnrss-group-data ',nnrss-group-data)))))
595
596 (defun nnrss-make-filename (name server)
597   (expand-file-name
598    (nnrss-translate-file-chars
599     (concat name
600             (and server
601                  (not (equal server ""))
602                  "-")
603             server
604             ".el"))
605    nnrss-directory))
606
607 (gnus-add-shutdown 'nnrss-close 'gnus)
608
609 (defun nnrss-close ()
610   "Clear internal nnrss variables."
611   (setq nnrss-group-data nil
612         nnrss-server-data nil
613         nnrss-group-hashtb nil
614         nnrss-group-alist nil))
615
616 ;;; URL interface
617
618 (defun nnrss-no-cache (url)
619   "")
620
621 (defun nnrss-insert-w3 (url)
622   (mm-with-unibyte-current-buffer
623     (condition-case err
624         (mm-url-insert url)
625       (error (if (or debug-on-quit debug-on-error)
626                  (signal (car err) (cdr err))
627                (message "nnrss: Failed to fetch %s" url))))))
628
629 (defun nnrss-decode-entities-string (string)
630   (if string
631       (mm-with-multibyte-buffer
632         (insert string)
633         (mm-url-decode-entities-nbsp)
634         (buffer-string))))
635
636 (defalias 'nnrss-insert 'nnrss-insert-w3)
637
638 (defun nnrss-mime-encode-string (string)
639   (mm-with-multibyte-buffer
640     (insert string)
641     (mm-url-decode-entities-nbsp)
642     (goto-char (point-min))
643     (while (re-search-forward "[\t\n ]+" nil t)
644       (replace-match " "))
645     (goto-char (point-min))
646     (skip-chars-forward " ")
647     (delete-region (point-min) (point))
648     (goto-char (point-max))
649     (skip-chars-forward " ")
650     (delete-region (point) (point-max))
651     (let ((rfc2047-encoding-type 'mime)
652           rfc2047-encode-max-chars)
653       (rfc2047-encode-region (point-min) (point-max)))
654     (goto-char (point-min))
655     (while (search-forward "\n" nil t)
656       (delete-backward-char 1))
657     (buffer-string)))
658
659 ;;; Snarf functions
660
661 (defun nnrss-check-group (group server)
662   (let (file xml subject url extra changed author date feed-subject
663              enclosure comments rss-ns rdf-ns content-ns dc-ns
664              hash-index)
665     (if (and nnrss-use-local
666              (file-exists-p (setq file (expand-file-name
667                                         (nnrss-translate-file-chars
668                                          (concat group ".xml"))
669                                         nnrss-directory))))
670         (setq xml (nnrss-fetch file t))
671       (setq url (or (nth 2 (assoc group nnrss-server-data))
672                     (second (assoc group nnrss-group-alist))))
673       (unless url
674         (setq url
675               (cdr
676                (assoc 'href
677                       (nnrss-discover-feed
678                        (read-string
679                         (format "URL to search for %s: " group) "http://")))))
680         (let ((pair (assoc group nnrss-server-data)))
681           (if pair
682               (setcdr (cdr pair) (list url))
683             (push (list group nnrss-group-max url) nnrss-server-data)))
684         (setq changed t))
685       (setq xml (nnrss-fetch url)))
686     ;; See
687     ;; http://feeds.archive.org/validator/docs/howto/declare_namespaces.html
688     ;; for more RSS namespaces.
689     (setq dc-ns (nnrss-get-namespace-prefix xml "http://purl.org/dc/elements/1.1/")
690           rdf-ns (nnrss-get-namespace-prefix xml "http://www.w3.org/1999/02/22-rdf-syntax-ns#")
691           rss-ns (nnrss-get-namespace-prefix xml "http://purl.org/rss/1.0/")
692           content-ns (nnrss-get-namespace-prefix xml "http://purl.org/rss/1.0/modules/content/"))
693     (dolist (item (nreverse (nnrss-find-el (intern (concat rss-ns "item")) xml)))
694       (when (and (listp item)
695                  (string= (concat rss-ns "item") (car item))
696                  (progn (setq hash-index (md5 (gnus-prin1-to-string item)))
697                         (not (gethash hash-index nnrss-group-hashtb))))
698         (setq subject (nnrss-node-text rss-ns 'title item))
699         (setq url (nnrss-decode-entities-string
700                    (nnrss-node-text rss-ns 'link (cddr item))))
701         (setq extra (or (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           hash-index)
745          nnrss-group-data)
746         (puthash hash-index t nnrss-group-hashtb)
747         (setq changed t))
748       (setq extra nil))
749     (when changed
750       (nnrss-save-group-data group server)
751       (let ((pair (assoc group nnrss-server-data)))
752         (if pair
753             (setcar (cdr pair) nnrss-group-max)
754           (push (list group nnrss-group-max) nnrss-server-data)))
755       (nnrss-save-server-data server))))
756
757 (defun nnrss-opml-import (opml-file)
758   "OPML subscriptions import.
759 Read the file and attempt to subscribe to each Feed in the file."
760   (interactive "fImport file: ")
761   (mapc
762    (lambda (node)
763      (let ((xmlurl (cdr (assq 'xmlUrl (cadr node)))))
764        (when (and xmlurl
765                   (not (string-match "\\`[\t ]*\\'" xmlurl))
766                   (prog1
767                       (y-or-n-p (format "Subscribe to %s " xmlurl))
768                     (message "")))
769          (condition-case err
770              (progn
771                (gnus-group-make-rss-group xmlurl)
772                (forward-line 1))
773            (error
774             (message
775              "Failed to subscribe to %s (%s); type any key to continue: "
776              xmlurl
777              (error-message-string err))
778             (let ((echo-keystrokes 0))
779               (read-char)))))))
780    (nnrss-find-el 'outline
781                   (mm-with-multibyte-buffer
782                     (insert-file-contents opml-file)
783                     (xml-parse-region (point-min) (point-max))))))
784
785 (defun nnrss-opml-export ()
786   "OPML subscription export.
787 Export subscriptions to a buffer in OPML Format."
788   (interactive)
789   (with-current-buffer (get-buffer-create "*OPML Export*")
790     (mm-set-buffer-file-coding-system 'utf-8)
791     (insert "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
792             "<!-- OPML generated by Emacs Gnus' nnrss.el -->\n"
793             "<opml version=\"1.1\">\n"
794             "  <head>\n"
795             "    <title>mySubscriptions</title>\n"
796             "    <dateCreated>" (format-time-string "%a, %d %b %Y %T %z")
797             "</dateCreated>\n"
798             "    <ownerEmail>" user-mail-address "</ownerEmail>\n"
799             "    <ownerName>" (user-full-name) "</ownerName>\n"
800             "  </head>\n"
801             "  <body>\n")
802     (dolist (sub nnrss-group-alist)
803       (insert "    <outline text=\"" (car sub)
804               "\" xmlUrl=\"" (cadr sub) "\"/>\n"))
805     (insert "  </body>\n"
806             "</opml>\n"))
807   (pop-to-buffer "*OPML Export*")
808   (when (fboundp 'sgml-mode)
809     (sgml-mode)))
810
811 (defun nnrss-generate-download-script ()
812   "Generate a download script in the current buffer.
813 It is useful when `(setq nnrss-use-local t)'."
814   (interactive)
815   (insert "#!/bin/sh\n")
816   (insert "WGET=wget\n")
817   (insert "RSSDIR='" (expand-file-name nnrss-directory) "'\n")
818   (dolist (elem nnrss-server-data)
819     (let ((url (or (nth 2 elem)
820                    (second (assoc (car elem) nnrss-group-alist)))))
821       (insert "$WGET -q -O \"$RSSDIR\"/'"
822               (nnrss-translate-file-chars (concat (car elem) ".xml"))
823               "' '" url "'\n"))))
824
825 (defun nnrss-translate-file-chars (name)
826   (let ((nnheader-file-name-translation-alist
827          (append nnheader-file-name-translation-alist '((?' . ?_)))))
828     (nnheader-translate-file-chars name)))
829
830 (defvar nnrss-moreover-url
831   "http://w.moreover.com/categories/category_list_rss.html"
832   "The url of moreover.com categories.")
833
834 (defun nnrss-snarf-moreover-categories ()
835   "Snarf RSS links from moreover.com."
836   (interactive)
837   (let (category name url changed)
838     (with-temp-buffer
839       (nnrss-insert nnrss-moreover-url)
840       (goto-char (point-min))
841       (while (re-search-forward
842               "<a name=\"\\([^\"]+\\)\">\\|<a href=\"\\(http://[^\"]*moreover\\.com[^\"]+page\\?c=\\([^\"&]+\\)&o=rss\\)" nil t)
843         (if (match-string 1)
844             (setq category (match-string 1))
845           (setq url (match-string 2)
846                 name (mm-url-decode-entities-string
847                       (rfc2231-decode-encoded-string
848                        (match-string 3))))
849           (if category
850               (setq name (concat category "." name)))
851           (unless (assoc name nnrss-server-data)
852             (setq changed t)
853             (push (list name 0 url) nnrss-server-data)))))
854     (if changed
855         (nnrss-save-server-data ""))))
856
857 (defun nnrss-node-text (namespace local-name element)
858   (let* ((node (assq (intern (concat namespace (symbol-name local-name)))
859                      element))
860          (text (if (and node (listp node))
861                    (nnrss-node-just-text node)
862                  node))
863          (cleaned-text (if text
864                            (gnus-replace-in-string
865                             (gnus-replace-in-string
866                              text "^[\000-\037\177]+\\|^ +\\| +$" "")
867                             "\r\n" "\n"))))
868     (if (string-equal "" cleaned-text)
869         nil
870       cleaned-text)))
871
872 (defun nnrss-node-just-text (node)
873   (if (and node (listp node))
874       (mapconcat 'nnrss-node-just-text (cddr node) " ")
875     node))
876
877 (defun nnrss-find-el (tag data &optional found-list)
878   "Find the all matching elements in the data.
879 Careful with this on large documents!"
880   (when (consp data)
881     (dolist (bit data)
882       (when (car-safe bit)
883         (when (equal tag (car bit))
884           ;; Old xml.el may return a list of string.
885           (when (and (consp (caddr bit))
886                      (stringp (caaddr bit)))
887             (setcar (cddr bit) (caaddr bit)))
888           (setq found-list
889                 (append found-list
890                         (list bit))))
891         (if (and (consp (car-safe (caddr bit)))
892                  (not (stringp (caddr bit))))
893             (setq found-list
894                   (append found-list
895                           (nnrss-find-el
896                            tag (caddr bit))))
897           (setq found-list
898                 (append found-list
899                         (nnrss-find-el
900                          tag (cddr bit))))))))
901   found-list)
902
903 (defun nnrss-rsslink-p (el)
904   "Test if the element we are handed is an RSS autodiscovery link."
905   (and (eq (car-safe el) 'link)
906        (string-equal (cdr (assoc 'rel (cadr el))) "alternate")
907        (or (string-equal (cdr (assoc 'type (cadr el)))
908                          "application/rss+xml")
909            (string-equal (cdr (assoc 'type (cadr el))) "text/xml"))))
910
911 (defun nnrss-get-rsslinks (data)
912   "Extract the <link> elements that are links to RSS from the parsed data."
913   (delq nil (mapcar
914              (lambda (el)
915                (if (nnrss-rsslink-p el) el))
916              (nnrss-find-el 'link data))))
917
918 (defun nnrss-extract-hrefs (data)
919   "Recursively extract hrefs from a page's source.
920 DATA should be the output of `xml-parse-region' or
921 `w3-parse-buffer'."
922   (mapcar (lambda (ahref)
923             (cdr (assoc 'href (cadr ahref))))
924           (nnrss-find-el 'a data)))
925
926 (defmacro nnrss-match-macro (base-uri item onsite-list offsite-list)
927   `(cond ((or (string-match (concat "^" ,base-uri) ,item)
928               (not (string-match "://" ,item)))
929           (setq ,onsite-list (append ,onsite-list (list ,item))))
930          (t (setq ,offsite-list (append ,offsite-list (list ,item))))))
931
932 (defun nnrss-order-hrefs (base-uri hrefs)
933   "Given a list of hrefs, sort them using the following priorities:
934   1. links ending in .rss
935   2. links ending in .rdf
936   3. links ending in .xml
937   4. links containing the above
938   5. offsite links
939
940 BASE-URI is used to determine the location of the links and
941 whether they are `offsite' or `onsite'."
942   (let (rss-onsite-end  rdf-onsite-end  xml-onsite-end
943         rss-onsite-in   rdf-onsite-in   xml-onsite-in
944         rss-offsite-end rdf-offsite-end xml-offsite-end
945         rss-offsite-in rdf-offsite-in xml-offsite-in)
946     (dolist (href hrefs)
947       (cond ((null href))
948             ((string-match "\\.rss$" href)
949              (nnrss-match-macro
950               base-uri href rss-onsite-end rss-offsite-end))
951             ((string-match "\\.rdf$" href)
952              (nnrss-match-macro
953               base-uri href rdf-onsite-end rdf-offsite-end))
954             ((string-match "\\.xml$" href)
955              (nnrss-match-macro
956               base-uri href xml-onsite-end xml-offsite-end))
957             ((string-match "rss" href)
958              (nnrss-match-macro
959               base-uri href rss-onsite-in rss-offsite-in))
960             ((string-match "rdf" href)
961              (nnrss-match-macro
962               base-uri href rdf-onsite-in rdf-offsite-in))
963             ((string-match "xml" href)
964              (nnrss-match-macro
965               base-uri href xml-onsite-in xml-offsite-in))))
966     (append
967      rss-onsite-end  rdf-onsite-end  xml-onsite-end
968      rss-onsite-in   rdf-onsite-in   xml-onsite-in
969      rss-offsite-end rdf-offsite-end xml-offsite-end
970      rss-offsite-in rdf-offsite-in xml-offsite-in)))
971
972 (defun nnrss-discover-feed (url)
973   "Given a page, find an RSS feed using Mark Pilgrim's
974 `ultra-liberal rss locator' (http://diveintomark.org/2002/08/15.html)."
975
976   (let ((parsed-page (nnrss-fetch url)))
977
978 ;;    1. if this url is the rss, use it.
979     (if (nnrss-rss-p parsed-page)
980         (let ((rss-ns (nnrss-get-namespace-prefix parsed-page "http://purl.org/rss/1.0/")))
981           (nnrss-rss-title-description rss-ns parsed-page url))
982
983 ;;    2. look for the <link rel="alternate"
984 ;;    type="application/rss+xml" and use that if it is there.
985       (let ((links (nnrss-get-rsslinks parsed-page)))
986         (if links
987             (let* ((xml (nnrss-fetch
988                          (cdr (assoc 'href (cadar links)))))
989                    (rss-ns (nnrss-get-namespace-prefix xml "http://purl.org/rss/1.0/")))
990               (nnrss-rss-title-description rss-ns xml (cdr (assoc 'href (cadar links)))))
991
992 ;;    3. look for links on the site in the following order:
993 ;;       - onsite links ending in .rss, .rdf, or .xml
994 ;;       - onsite links containing any of the above
995 ;;       - offsite links ending in .rss, .rdf, or .xml
996 ;;       - offsite links containing any of the above
997           (let* ((base-uri (progn (string-match ".*://[^/]+/?" url)
998                                   (match-string 0 url)))
999                  (hrefs (nnrss-order-hrefs
1000                          base-uri (nnrss-extract-hrefs parsed-page)))
1001                  (rss-link nil))
1002             (while (and (eq rss-link nil) (not (eq hrefs nil)))
1003               (let ((href-data (nnrss-fetch (car hrefs))))
1004                 (if (nnrss-rss-p href-data)
1005                     (let* ((rss-ns (nnrss-get-namespace-prefix href-data "http://purl.org/rss/1.0/")))
1006                       (setq rss-link (nnrss-rss-title-description
1007                                       rss-ns href-data (car hrefs))))
1008                   (setq hrefs (cdr hrefs)))))
1009             (if rss-link rss-link
1010
1011 ;;    4. check syndic8
1012               (nnrss-find-rss-via-syndic8 url))))))))
1013
1014 (defun nnrss-find-rss-via-syndic8 (url)
1015   "Query syndic8 for the rss feeds it has for URL."
1016   (if (not (locate-library "xml-rpc"))
1017       (progn
1018         (message "XML-RPC is not available... not checking Syndic8.")
1019         nil)
1020     (require 'xml-rpc)
1021     (let ((feedid (xml-rpc-method-call
1022                    "http://www.syndic8.com/xmlrpc.php"
1023                    'syndic8.FindSites
1024                    url)))
1025       (when feedid
1026         (let* ((feedinfo (xml-rpc-method-call
1027                           "http://www.syndic8.com/xmlrpc.php"
1028                           'syndic8.GetFeedInfo
1029                           feedid))
1030                (urllist
1031                 (delq nil
1032                       (mapcar
1033                        (lambda (listinfo)
1034                          (if (string-equal
1035                               (cdr (assoc "status" listinfo))
1036                               "Syndicated")
1037                              (cons
1038                               (cdr (assoc "sitename" listinfo))
1039                               (list
1040                                (cons 'title
1041                                      (cdr (assoc
1042                                            "sitename" listinfo)))
1043                                (cons 'href
1044                                      (cdr (assoc
1045                                            "dataurl" listinfo)))))))
1046                        feedinfo))))
1047           (if (not (> (length urllist) 1))
1048               (cdar urllist)
1049             (let ((completion-ignore-case t)
1050                   (selection
1051                    (mapcar (lambda (listinfo)
1052                              (cons (cdr (assoc "sitename" listinfo))
1053                                    (string-to-number
1054                                     (cdr (assoc "feedid" listinfo)))))
1055                            feedinfo)))
1056               (cdr (assoc
1057                     (completing-read
1058                      "Multiple feeds found.  Select one: "
1059                      selection nil t) urllist)))))))))
1060
1061 (defun nnrss-rss-p (data)
1062   "Test if DATA is an RSS feed.
1063 Simply ensures that the first element is rss or rdf."
1064   (or (eq (caar data) 'rss)
1065       (eq (caar data) 'rdf:RDF)))
1066
1067 (defun nnrss-rss-title-description (rss-namespace data url)
1068   "Return the title of an RSS feed."
1069   (if (nnrss-rss-p data)
1070       (let ((description (intern (concat rss-namespace "description")))
1071             (title (intern (concat rss-namespace "title")))
1072             (channel (nnrss-find-el (intern (concat rss-namespace "channel"))
1073                                     data)))
1074         (list
1075          (cons 'description (caddr (nth 0 (nnrss-find-el description channel))))
1076          (cons 'title (caddr (nth 0 (nnrss-find-el title channel))))
1077          (cons 'href url)))))
1078
1079 (defun nnrss-get-namespace-prefix (el uri)
1080   "Given EL (containing a parsed element) and URI (containing a string
1081 that gives the URI for which you want to retrieve the namespace
1082 prefix), return the prefix."
1083   (let* ((prefix (car (rassoc uri (cadar el))))
1084          (nslist (if prefix
1085                      (split-string (symbol-name prefix) ":")))
1086          (ns (cond ((eq (length nslist) 1) ; no prefix given
1087                     "")
1088                    ((eq (length nslist) 2) ; extract prefix
1089                     (cadr nslist)))))
1090     (if (and ns (not (string= ns "")))
1091         (concat ns ":")
1092       ns)))
1093
1094 (provide 'nnrss)
1095
1096
1097 ;;; nnrss.el ends here
1098
1099 ;;; arch-tag: 12910c07-0cdf-44fb-8d2c-416ded64c267