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