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