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