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