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