Use the normal HTML rendering code instead of the special HTML washing code.
[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 and XEmacs.
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
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       (load file nil t t))))
565
566 (defun nnrss-save-server-data (server)
567   (gnus-make-directory nnrss-directory)
568   (let ((coding-system-for-write nnrss-file-coding-system)
569         (file-name-coding-system nnmail-pathname-coding-system))
570     (with-temp-file (nnrss-make-filename "nnrss" server)
571       (insert (format ";; -*- coding: %s; -*-\n"
572                       nnrss-file-coding-system))
573       (gnus-prin1 `(setq nnrss-group-alist ',nnrss-group-alist))
574       (insert "\n")
575       (gnus-prin1 `(setq nnrss-server-data ',nnrss-server-data)))))
576
577 (defun nnrss-read-group-data (group server)
578   (setq nnrss-group-data nil)
579   (if (hash-table-p nnrss-group-hashtb)
580       (clrhash nnrss-group-hashtb)
581     (setq nnrss-group-hashtb (make-hash-table :test 'equal)))
582   (let ((pair (assoc group nnrss-server-data)))
583     (setq nnrss-group-max (or (cadr pair) 0))
584     (setq nnrss-group-min (+ nnrss-group-max 1)))
585   (let ((file (nnrss-make-filename group server))
586         (file-name-coding-system nnmail-pathname-coding-system))
587     (when (file-exists-p file)
588       (load file nil t t)
589       (dolist (e nnrss-group-data)
590         (puthash (nth 9 e) t nnrss-group-hashtb)
591         (when (and (car e) (> nnrss-group-min (car e)))
592           (setq nnrss-group-min (car e)))
593         (when (and (car e) (< nnrss-group-max (car e)))
594           (setq nnrss-group-max (car e)))))))
595
596 (defun nnrss-save-group-data (group server)
597   (gnus-make-directory nnrss-directory)
598   (let ((coding-system-for-write nnrss-file-coding-system)
599         (file-name-coding-system nnmail-pathname-coding-system))
600     (with-temp-file (nnrss-make-filename group server)
601       (insert (format ";; -*- coding: %s; -*-\n"
602                       nnrss-file-coding-system))
603       (gnus-prin1 `(setq nnrss-group-data ',nnrss-group-data)))))
604
605 (defun nnrss-make-filename (name server)
606   (expand-file-name
607    (nnrss-translate-file-chars
608     (concat name
609             (and server
610                  (not (equal server ""))
611                  "-")
612             server
613             ".el"))
614    nnrss-directory))
615
616 (gnus-add-shutdown 'nnrss-close 'gnus)
617
618 (defun nnrss-close ()
619   "Clear internal nnrss variables."
620   (setq nnrss-group-data nil
621         nnrss-server-data nil
622         nnrss-group-hashtb nil
623         nnrss-group-alist nil))
624
625 ;;; URL interface
626
627 (defun nnrss-no-cache (url)
628   "")
629
630 (defun nnrss-insert-w3 (url)
631   (mm-with-unibyte-current-buffer
632     (condition-case err
633         (mm-url-insert url)
634       (error (if (or debug-on-quit debug-on-error)
635                  (signal (car err) (cdr err))
636                (message "nnrss: Failed to fetch %s" url))))))
637
638 (defun nnrss-decode-entities-string (string)
639   (if string
640       (mm-with-multibyte-buffer
641         (insert string)
642         (mm-url-decode-entities-nbsp)
643         (buffer-string))))
644
645 (defalias 'nnrss-insert 'nnrss-insert-w3)
646
647 (defun nnrss-mime-encode-string (string)
648   (mm-with-multibyte-buffer
649     (insert string)
650     (mm-url-decode-entities-nbsp)
651     (goto-char (point-min))
652     (while (re-search-forward "[\t\n ]+" nil t)
653       (replace-match " "))
654     (goto-char (point-min))
655     (skip-chars-forward " ")
656     (delete-region (point-min) (point))
657     (goto-char (point-max))
658     (skip-chars-forward " ")
659     (delete-region (point) (point-max))
660     (let ((rfc2047-encoding-type 'mime)
661           rfc2047-encode-max-chars)
662       (rfc2047-encode-region (point-min) (point-max)))
663     (goto-char (point-min))
664     (while (search-forward "\n" nil t)
665       (delete-char -1))
666     (buffer-string)))
667
668 ;;; Snarf functions
669 (defun nnrss-make-hash-index (item)
670   (gnus-message 9 "nnrss: Making hash index of %s" (gnus-prin1-to-string item))
671   (setq item (gnus-remove-if
672               (lambda (field)
673                 (when (listp field)
674                   (memq (car field) nnrss-ignore-article-fields)))
675               item))
676   (md5 (gnus-prin1-to-string item)
677        nil nil
678        nnrss-file-coding-system))
679
680 (defun nnrss-check-group (group server)
681   (let (file xml subject url extra changed author date feed-subject
682              enclosure comments rss-ns rdf-ns content-ns dc-ns
683              hash-index)
684     (if (and nnrss-use-local
685              (file-exists-p (setq file (expand-file-name
686                                         (nnrss-translate-file-chars
687                                          (concat group ".xml"))
688                                         nnrss-directory))))
689         (setq xml (nnrss-fetch file t))
690       (setq url (or (nth 2 (assoc group nnrss-server-data))
691                     (second (assoc group nnrss-group-alist))))
692       (unless url
693         (setq url
694               (cdr
695                (assoc 'href
696                       (nnrss-discover-feed
697                        (read-string
698                         (format "URL to search for %s: " group) "http://")))))
699         (let ((pair (assoc group nnrss-server-data)))
700           (if pair
701               (setcdr (cdr pair) (list url))
702             (push (list group nnrss-group-max url) nnrss-server-data)))
703         (setq changed t))
704       (setq xml (nnrss-fetch url)))
705     (setq dc-ns (nnrss-get-namespace-prefix xml "http://purl.org/dc/elements/1.1/")
706           rdf-ns (nnrss-get-namespace-prefix xml "http://www.w3.org/1999/02/22-rdf-syntax-ns#")
707           rss-ns (nnrss-get-namespace-prefix xml "http://purl.org/rss/1.0/")
708           content-ns (nnrss-get-namespace-prefix xml "http://purl.org/rss/1.0/modules/content/"))
709     (dolist (item (nreverse (nnrss-find-el (intern (concat rss-ns "item")) xml)))
710       (when (and (listp item)
711                  (string= (concat rss-ns "item") (car item))
712                  (progn (setq hash-index (nnrss-make-hash-index item))
713                         (not (gethash hash-index nnrss-group-hashtb))))
714         (setq subject (nnrss-node-text rss-ns 'title item))
715         (setq url (nnrss-decode-entities-string
716                    (nnrss-node-text rss-ns 'link (cddr item))))
717         (setq extra (or (nnrss-node-text content-ns 'encoded item)
718                         (nnrss-node-text rss-ns 'description item)))
719         (if (setq feed-subject (nnrss-node-text dc-ns 'subject item))
720             (setq extra (concat feed-subject "<br /><br />" extra)))
721         (setq author (or (nnrss-node-text rss-ns 'author item)
722                          (nnrss-node-text dc-ns 'creator item)
723                          (nnrss-node-text dc-ns 'contributor item)))
724         (setq date (nnrss-normalize-date
725                     (or (nnrss-node-text dc-ns 'date item)
726                         (nnrss-node-text rss-ns 'pubDate item))))
727         (setq comments (nnrss-node-text rss-ns 'comments item))
728         (when (setq enclosure (cadr (assq (intern (concat rss-ns "enclosure")) item)))
729           (let ((url (cdr (assq 'url enclosure)))
730                 (len (cdr (assq 'length enclosure)))
731                 (type (cdr (assq 'type enclosure)))
732                 (name))
733             (setq len
734                   (if (and len (integerp (setq len (string-to-number len))))
735                       ;; actually already in `ls-lisp-format-file-size' but
736                       ;; probably not worth to require it for one function
737                       (do ((size (/ len 1.0) (/ size 1024.0))
738                            (post-fixes (list "" "k" "M" "G" "T" "P" "E")
739                                        (cdr post-fixes)))
740                           ((< size 1024)
741                            (format "%.1f%s" size (car post-fixes))))
742                     "0"))
743             (setq url (or url ""))
744             (setq name (if (string-match "/\\([^/]*\\)$" url)
745                            (match-string 1 url)
746                          "file"))
747             (setq type (or type ""))
748             (setq enclosure (list url name len type))))
749         (push
750          (list
751           (incf nnrss-group-max)
752           (current-time)
753           url
754           (and subject (nnrss-mime-encode-string subject))
755           (and author (nnrss-mime-encode-string author))
756           date
757           (and extra (nnrss-decode-entities-string extra))
758           enclosure
759           comments
760           hash-index)
761          nnrss-group-data)
762         (puthash hash-index t nnrss-group-hashtb)
763         (setq changed t))
764       (setq extra nil))
765     (when changed
766       (nnrss-save-group-data group server)
767       (let ((pair (assoc group nnrss-server-data)))
768         (if pair
769             (setcar (cdr pair) nnrss-group-max)
770           (push (list group nnrss-group-max) nnrss-server-data)))
771       (nnrss-save-server-data server))))
772
773 (declare-function gnus-group-make-rss-group "gnus-group" (&optional url))
774
775 (defun nnrss-opml-import (opml-file)
776   "OPML subscriptions import.
777 Read the file and attempt to subscribe to each Feed in the file."
778   (interactive "fImport file: ")
779   (mapc
780    (lambda (node)
781      (let ((xmlurl (cdr (assq 'xmlUrl (cadr node)))))
782        (when (and xmlurl
783                   (not (string-match "\\`[\t ]*\\'" xmlurl))
784                   (prog1
785                       (y-or-n-p (format "Subscribe to %s " xmlurl))
786                     (message "")))
787          (condition-case err
788              (progn
789                (gnus-group-make-rss-group xmlurl)
790                (forward-line 1))
791            (error
792             (message
793              "Failed to subscribe to %s (%s); type any key to continue: "
794              xmlurl
795              (error-message-string err))
796             (let ((echo-keystrokes 0))
797               (read-char)))))))
798    (nnrss-find-el 'outline
799                   (mm-with-multibyte-buffer
800                     (insert-file-contents opml-file)
801                     (xml-parse-region (point-min) (point-max))))))
802
803 (defun nnrss-opml-export ()
804   "OPML subscription export.
805 Export subscriptions to a buffer in OPML Format."
806   (interactive)
807   (with-current-buffer (get-buffer-create "*OPML Export*")
808     (mm-set-buffer-file-coding-system 'utf-8)
809     (insert "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
810             "<!-- OPML generated by Emacs Gnus' nnrss.el -->\n"
811             "<opml version=\"1.1\">\n"
812             "  <head>\n"
813             "    <title>mySubscriptions</title>\n"
814             "    <dateCreated>" (format-time-string "%a, %d %b %Y %T %z")
815             "</dateCreated>\n"
816             "    <ownerEmail>" user-mail-address "</ownerEmail>\n"
817             "    <ownerName>" (user-full-name) "</ownerName>\n"
818             "  </head>\n"
819             "  <body>\n")
820     (dolist (sub nnrss-group-alist)
821       (insert "    <outline text=\"" (car sub)
822               "\" xmlUrl=\"" (cadr sub) "\"/>\n"))
823     (insert "  </body>\n"
824             "</opml>\n"))
825   (pop-to-buffer "*OPML Export*")
826   (when (fboundp 'sgml-mode)
827     (sgml-mode)))
828
829 (defun nnrss-generate-download-script ()
830   "Generate a download script in the current buffer.
831 It is useful when `(setq nnrss-use-local t)'."
832   (interactive)
833   (insert "#!/bin/sh\n")
834   (insert "WGET=wget\n")
835   (insert "RSSDIR='" (expand-file-name nnrss-directory) "'\n")
836   (dolist (elem nnrss-server-data)
837     (let ((url (or (nth 2 elem)
838                    (second (assoc (car elem) nnrss-group-alist)))))
839       (insert "$WGET -q -O \"$RSSDIR\"/'"
840               (nnrss-translate-file-chars (concat (car elem) ".xml"))
841               "' '" url "'\n"))))
842
843 (defun nnrss-translate-file-chars (name)
844   (let ((nnheader-file-name-translation-alist
845          (append nnheader-file-name-translation-alist '((?' . ?_)))))
846     (nnheader-translate-file-chars name)))
847
848 (defun nnrss-node-text (namespace local-name element)
849   (let* ((node (assq (intern (concat namespace (symbol-name local-name)))
850                      element))
851          (text (if (and node (listp node))
852                    (nnrss-node-just-text node)
853                  node))
854          (cleaned-text (if text
855                            (gnus-replace-in-string
856                             (gnus-replace-in-string
857                              text "^[\000-\037\177]+\\|^ +\\| +$" "")
858                             "\r\n" "\n"))))
859     (if (string-equal "" cleaned-text)
860         nil
861       cleaned-text)))
862
863 (defun nnrss-node-just-text (node)
864   (if (and node (listp node))
865       (mapconcat 'nnrss-node-just-text (cddr node) " ")
866     node))
867
868 (defun nnrss-find-el (tag data &optional found-list)
869   "Find the all matching elements in the data.
870 Careful with this on large documents!"
871   (when (consp data)
872     (dolist (bit data)
873       (when (car-safe bit)
874         (when (equal tag (car bit))
875           ;; Old xml.el may return a list of string.
876           (when (and (consp (caddr bit))
877                      (stringp (caaddr bit)))
878             (setcar (cddr bit) (caaddr bit)))
879           (setq found-list
880                 (append found-list
881                         (list bit))))
882         (if (and (consp (car-safe (caddr bit)))
883                  (not (stringp (caddr bit))))
884             (setq found-list
885                   (append found-list
886                           (nnrss-find-el
887                            tag (caddr bit))))
888           (setq found-list
889                 (append found-list
890                         (nnrss-find-el
891                          tag (cddr bit))))))))
892   found-list)
893
894 (defun nnrss-rsslink-p (el)
895   "Test if the element we are handed is an RSS autodiscovery link."
896   (and (eq (car-safe el) 'link)
897        (string-equal (cdr (assoc 'rel (cadr el))) "alternate")
898        (or (string-equal (cdr (assoc 'type (cadr el)))
899                          "application/rss+xml")
900            (string-equal (cdr (assoc 'type (cadr el))) "text/xml"))))
901
902 (defun nnrss-get-rsslinks (data)
903   "Extract the <link> elements that are links to RSS from the parsed data."
904   (delq nil (mapcar
905              (lambda (el)
906                (if (nnrss-rsslink-p el) el))
907              (nnrss-find-el 'link data))))
908
909 (defun nnrss-extract-hrefs (data)
910   "Recursively extract hrefs from a page's source.
911 DATA should be the output of `xml-parse-region' or
912 `w3-parse-buffer'."
913   (mapcar (lambda (ahref)
914             (cdr (assoc 'href (cadr ahref))))
915           (nnrss-find-el 'a data)))
916
917 (defmacro nnrss-match-macro (base-uri item onsite-list offsite-list)
918   `(cond ((or (string-match (concat "^" ,base-uri) ,item)
919               (not (string-match "://" ,item)))
920           (setq ,onsite-list (append ,onsite-list (list ,item))))
921          (t (setq ,offsite-list (append ,offsite-list (list ,item))))))
922
923 (defun nnrss-order-hrefs (base-uri hrefs)
924   "Given a list of hrefs, sort them using the following priorities:
925   1. links ending in .rss
926   2. links ending in .rdf
927   3. links ending in .xml
928   4. links containing the above
929   5. offsite links
930
931 BASE-URI is used to determine the location of the links and
932 whether they are `offsite' or `onsite'."
933   (let (rss-onsite-end  rdf-onsite-end  xml-onsite-end
934         rss-onsite-in   rdf-onsite-in   xml-onsite-in
935         rss-offsite-end rdf-offsite-end xml-offsite-end
936         rss-offsite-in rdf-offsite-in xml-offsite-in)
937     (dolist (href hrefs)
938       (cond ((null href))
939             ((string-match "\\.rss$" href)
940              (nnrss-match-macro
941               base-uri href rss-onsite-end rss-offsite-end))
942             ((string-match "\\.rdf$" href)
943              (nnrss-match-macro
944               base-uri href rdf-onsite-end rdf-offsite-end))
945             ((string-match "\\.xml$" href)
946              (nnrss-match-macro
947               base-uri href xml-onsite-end xml-offsite-end))
948             ((string-match "rss" href)
949              (nnrss-match-macro
950               base-uri href rss-onsite-in rss-offsite-in))
951             ((string-match "rdf" href)
952              (nnrss-match-macro
953               base-uri href rdf-onsite-in rdf-offsite-in))
954             ((string-match "xml" href)
955              (nnrss-match-macro
956               base-uri href xml-onsite-in xml-offsite-in))))
957     (append
958      rss-onsite-end  rdf-onsite-end  xml-onsite-end
959      rss-onsite-in   rdf-onsite-in   xml-onsite-in
960      rss-offsite-end rdf-offsite-end xml-offsite-end
961      rss-offsite-in rdf-offsite-in xml-offsite-in)))
962
963 (defun nnrss-discover-feed (url)
964   "Given a page, find an RSS feed using Mark Pilgrim's
965 `ultra-liberal rss locator'."
966
967   (let ((parsed-page (nnrss-fetch url)))
968
969 ;;    1. if this url is the rss, use it.
970     (if (nnrss-rss-p parsed-page)
971         (let ((rss-ns (nnrss-get-namespace-prefix parsed-page "http://purl.org/rss/1.0/")))
972           (nnrss-rss-title-description rss-ns parsed-page url))
973
974 ;;    2. look for the <link rel="alternate"
975 ;;    type="application/rss+xml" and use that if it is there.
976       (let ((links (nnrss-get-rsslinks parsed-page)))
977         (if links
978             (let* ((xml (nnrss-fetch
979                          (cdr (assoc 'href (cadar links)))))
980                    (rss-ns (nnrss-get-namespace-prefix xml "http://purl.org/rss/1.0/")))
981               (nnrss-rss-title-description rss-ns xml (cdr (assoc 'href (cadar links)))))
982
983 ;;    3. look for links on the site in the following order:
984 ;;       - onsite links ending in .rss, .rdf, or .xml
985 ;;       - onsite links containing any of the above
986 ;;       - offsite links ending in .rss, .rdf, or .xml
987 ;;       - offsite links containing any of the above
988           (let* ((base-uri (progn (string-match ".*://[^/]+/?" url)
989                                   (match-string 0 url)))
990                  (hrefs (nnrss-order-hrefs
991                          base-uri (nnrss-extract-hrefs parsed-page)))
992                  (rss-link nil))
993             (while (and (eq rss-link nil) (not (eq hrefs nil)))
994               (let ((href-data (nnrss-fetch (car hrefs))))
995                 (if (nnrss-rss-p href-data)
996                     (let* ((rss-ns (nnrss-get-namespace-prefix href-data "http://purl.org/rss/1.0/")))
997                       (setq rss-link (nnrss-rss-title-description
998                                       rss-ns href-data (car hrefs))))
999                   (setq hrefs (cdr hrefs)))))
1000             (if rss-link rss-link
1001
1002 ;;    4. check syndic8
1003               (nnrss-find-rss-via-syndic8 url))))))))
1004
1005 (defun nnrss-find-rss-via-syndic8 (url)
1006   "Query syndic8 for the rss feeds it has for URL."
1007   (if (not (locate-library "xml-rpc"))
1008       (progn
1009         (message "XML-RPC is not available... not checking Syndic8.")
1010         nil)
1011     (require 'xml-rpc)
1012     (let ((feedid (xml-rpc-method-call
1013                    "http://www.syndic8.com/xmlrpc.php"
1014                    'syndic8.FindSites
1015                    url)))
1016       (when feedid
1017         (let* ((feedinfo (xml-rpc-method-call
1018                           "http://www.syndic8.com/xmlrpc.php"
1019                           'syndic8.GetFeedInfo
1020                           feedid))
1021                (urllist
1022                 (delq nil
1023                       (mapcar
1024                        (lambda (listinfo)
1025                          (if (string-equal
1026                               (cdr (assoc "status" listinfo))
1027                               "Syndicated")
1028                              (cons
1029                               (cdr (assoc "sitename" listinfo))
1030                               (list
1031                                (cons 'title
1032                                      (cdr (assoc
1033                                            "sitename" listinfo)))
1034                                (cons 'href
1035                                      (cdr (assoc
1036                                            "dataurl" listinfo)))))))
1037                        feedinfo))))
1038           (if (not (> (length urllist) 1))
1039               (cdar urllist)
1040             (let ((completion-ignore-case t)
1041                   (selection
1042                    (mapcar (lambda (listinfo)
1043                              (cons (cdr (assoc "sitename" listinfo))
1044                                    (string-to-number
1045                                     (cdr (assoc "feedid" listinfo)))))
1046                            feedinfo)))
1047               (cdr (assoc
1048                     (gnus-completing-read
1049                      "Multiple feeds found. Select one"
1050                      selection t) urllist)))))))))
1051
1052 (defun nnrss-rss-p (data)
1053   "Test if DATA is an RSS feed.
1054 Simply ensures that the first element is rss or rdf."
1055   (or (eq (caar data) 'rss)
1056       (eq (caar data) 'rdf:RDF)))
1057
1058 (defun nnrss-rss-title-description (rss-namespace data url)
1059   "Return the title of an RSS feed."
1060   (if (nnrss-rss-p data)
1061       (let ((description (intern (concat rss-namespace "description")))
1062             (title (intern (concat rss-namespace "title")))
1063             (channel (nnrss-find-el (intern (concat rss-namespace "channel"))
1064                                     data)))
1065         (list
1066          (cons 'description (caddr (nth 0 (nnrss-find-el description channel))))
1067          (cons 'title (caddr (nth 0 (nnrss-find-el title channel))))
1068          (cons 'href url)))))
1069
1070 (defun nnrss-get-namespace-prefix (el uri)
1071   "Given EL (containing a parsed element) and URI (containing a string
1072 that gives the URI for which you want to retrieve the namespace
1073 prefix), return the prefix."
1074   (let* ((prefix (car (rassoc uri (cadar el))))
1075          (nslist (if prefix
1076                      (split-string (symbol-name prefix) ":")))
1077          (ns (cond ((eq (length nslist) 1) ; no prefix given
1078                     "")
1079                    ((eq (length nslist) 2) ; extract prefix
1080                     (cadr nslist)))))
1081     (if (and ns (not (string= ns "")))
1082         (concat ns ":")
1083       ns)))
1084
1085 (provide 'nnrss)
1086
1087 ;;; nnrss.el ends here