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