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