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