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