(mm-codepage-setup): New helper function.
[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 "\n")
216               (when (or link enclosure)
217                 (insert "\n")))
218             (when link
219               (insert link "\n"))
220             (when enclosure
221               (insert (car enclosure) " "
222                       (nth 2 enclosure) " "
223                       (nth 3 enclosure) "\n"))
224             (when comments
225               (insert comments "\n"))
226             (setq body (buffer-substring body (point)))
227             (insert "<#/part>\n"
228                     "<#part type=\"text/html\">\n"
229                     "<html><head></head><body>\n")
230             (when text
231               (insert text "\n"))
232             (when link
233               (insert "<p><a href=\"" link "\">link</a></p>\n"))
234             (when enclosure
235               (insert "<p><a href=\"" (car enclosure) "\">"
236                       (cadr enclosure) "</a> " (nth 2 enclosure)
237                       " " (nth 3 enclosure) "</p>\n"))
238             (when comments
239               (insert "<p><a href=\"" comments "\">comments</a></p>\n"))
240             (insert "</body></html>\n"
241                     "<#/part>\n"
242                     "<#/multipart>\n"))
243           (condition-case nil
244               (mml-to-mime)
245             (error
246              (erase-buffer)
247              (insert header
248                      "Content-Type: text/plain; charset=gnus-decoded\n"
249                      "Content-Transfer-Encoding: 8bit\n\n"
250                      body)
251              (nnheader-message
252               3 "Warning - there might be invalid characters"))))
253         (goto-char (point-min))
254         (search-forward "\n\n")
255         (forward-line -1)
256         (insert (format "Message-ID: <%d@%s.nnrss>\n"
257                         (car e)
258                         (let ((rfc2047-encoding-type 'mime)
259                               rfc2047-encode-max-chars)
260                           (rfc2047-encode-string
261                            (gnus-replace-in-string group "[\t\n ]+" "_")))))
262         (when nnrss-content-function
263           (funcall nnrss-content-function e group article))))
264     (cond
265      (err
266       (nnheader-report 'nnrss err))
267      ((not e)
268       (nnheader-report 'nnrss "no such id: %d" article))
269      (t
270       (nnheader-report 'nnrss "article %s retrieved" (car e))
271       ;; we return the article number.
272       (cons nnrss-group (car e))))))
273
274 (deffoo nnrss-request-list (&optional server)
275   (nnrss-possibly-change-group nil server)
276   (nnrss-generate-active)
277   t)
278
279 (deffoo nnrss-open-server (server &optional defs connectionless)
280   (nnrss-read-server-data server)
281   (nnoo-change-server 'nnrss server defs)
282   t)
283
284 (deffoo nnrss-request-expire-articles
285     (articles group &optional server force)
286   (setq group (nnrss-decode-group-name group))
287   (nnrss-possibly-change-group group server)
288   (let (e days not-expirable changed)
289     (dolist (art articles)
290       (if (and (setq e (assq art nnrss-group-data))
291                (nnmail-expired-article-p
292                 group
293                 (if (listp (setq days (nth 1 e))) days
294                   (days-to-time (- days (time-to-days '(0 0)))))
295                 force))
296           (setq nnrss-group-data (delq e nnrss-group-data)
297                 changed t)
298         (push art not-expirable)))
299     (if changed
300         (nnrss-save-group-data group server))
301     not-expirable))
302
303 (deffoo nnrss-request-delete-group (group &optional force server)
304   (setq group (nnrss-decode-group-name group))
305   (nnrss-possibly-change-group group server)
306   (let (elem)
307     ;; There may be two or more entries in `nnrss-group-alist' since
308     ;; this function didn't delete them formerly.
309     (while (setq elem (assoc group nnrss-group-alist))
310       (setq nnrss-group-alist (delq elem nnrss-group-alist))))
311   (setq nnrss-server-data
312         (delq (assoc group nnrss-server-data) nnrss-server-data))
313   (nnrss-save-server-data server)
314   (ignore-errors
315    (delete-file (nnrss-make-filename group server)))
316   t)
317
318 (deffoo nnrss-request-list-newsgroups (&optional server)
319   (nnrss-possibly-change-group nil server)
320   (save-excursion
321     (set-buffer nntp-server-buffer)
322     (erase-buffer)
323     (dolist (elem nnrss-group-alist)
324       (if (third elem)
325           (insert (car elem) "\t" (third elem) "\n"))))
326   t)
327
328 (nnoo-define-skeleton nnrss)
329
330 ;;; Internal functions
331 (eval-when-compile (defun xml-rpc-method-call (&rest args)))
332
333 (defun nnrss-get-encoding ()
334   "Return an encoding attribute specified in the current xml contents.
335 If `nnrss-compatible-encoding-alist' specifies the compatible encoding,
336 it is used instead.  If the xml contents doesn't specify the encoding,
337 return `utf-8' which is the default encoding for xml if it is available,
338 otherwise return nil."
339   (goto-char (point-min))
340   (if (re-search-forward
341        "<\\?[^>]*encoding=\\(?:\"\\([^\">]+\\)\"\\|'\\([^'>]+\\)'\\)"
342        nil t)
343       (let ((encoding (intern (downcase (or (match-string 1)
344                                             (match-string 2))))))
345         (or
346          (mm-coding-system-p (cdr (assq encoding
347                                         nnrss-compatible-encoding-alist)))
348          (mm-coding-system-p encoding)
349          (mm-coding-system-p (car (rassq encoding
350                                          nnrss-compatible-encoding-alist)))))
351     (mm-coding-system-p 'utf-8)))
352
353 (defun nnrss-fetch (url &optional local)
354   "Fetch URL and put it in a the expected Lisp structure."
355   (mm-with-unibyte-buffer
356     ;;some CVS versions of url.el need this to close the connection quickly
357     (let (cs xmlform htmlform)
358       ;; bit o' work necessary for w3 pre-cvs and post-cvs
359       (if local
360           (let ((coding-system-for-read 'binary))
361             (insert-file-contents url))
362         ;; FIXME: shouldn't binding `coding-system-for-read' be moved
363         ;; to `mm-url-insert'?
364         (let ((coding-system-for-read 'binary))
365           (mm-url-insert url)))
366       (nnheader-remove-cr-followed-by-lf)
367       ;; Decode text according to the encoding attribute.
368       (when (setq cs (nnrss-get-encoding))
369         (mm-decode-coding-region (point-min) (point-max) cs)
370         (mm-enable-multibyte))
371       (goto-char (point-min))
372
373       ;; Because xml-parse-region can't deal with anything that isn't
374       ;; xml and w3-parse-buffer can't deal with some xml, we have to
375       ;; parse with xml-parse-region first and, if that fails, parse
376       ;; with w3-parse-buffer.  Yuck.  Eventually, someone should find out
377       ;; why w3-parse-buffer fails to parse some well-formed xml and
378       ;; fix it.
379
380       (condition-case err1
381           (setq xmlform (xml-parse-region (point-min) (point-max)))
382         (error
383          (condition-case err2
384              (setq htmlform (caddar (w3-parse-buffer
385                                      (current-buffer))))
386            (error
387             (message "\
388 nnrss: %s: Not valid XML %s and w3-parse doesn't work %s"
389                      url err1 err2)))))
390       (if htmlform
391           htmlform
392         xmlform))))
393
394 (defun nnrss-possibly-change-group (&optional group server)
395   (when (and server
396              (not (nnrss-server-opened server)))
397     (nnrss-open-server server))
398   (when (and group (not (equal group nnrss-group)))
399     (nnrss-read-group-data group server)
400     (setq nnrss-group group)))
401
402 (defvar nnrss-extra-categories '(nnrss-snarf-moreover-categories))
403
404 (defun nnrss-generate-active ()
405   (when (y-or-n-p "Fetch extra categories? ")
406     (mapc 'funcall nnrss-extra-categories))
407   (save-excursion
408     (set-buffer nntp-server-buffer)
409     (erase-buffer)
410     (dolist (elem nnrss-group-alist)
411       (insert (prin1-to-string (car elem)) " 0 1 y\n"))
412     (dolist (elem nnrss-server-data)
413       (unless (assoc (car elem) nnrss-group-alist)
414         (insert (prin1-to-string (car elem)) " 0 1 y\n")))))
415
416 ;;; data functions
417
418 (defun nnrss-read-server-data (server)
419   (setq nnrss-server-data nil)
420   (let ((file (nnrss-make-filename "nnrss" server)))
421     (when (file-exists-p file)
422       ;; In Emacs 21.3 and earlier, `load' doesn't support non-ASCII
423       ;; file names.  So, we use `insert-file-contents' instead.
424       (mm-with-multibyte-buffer
425         (let ((coding-system-for-read nnrss-file-coding-system)
426               (file-name-coding-system nnmail-pathname-coding-system))
427           (insert-file-contents file)
428           (eval-region (point-min) (point-max)))))))
429
430 (defun nnrss-save-server-data (server)
431   (gnus-make-directory nnrss-directory)
432   (let ((coding-system-for-write nnrss-file-coding-system)
433         (file-name-coding-system nnmail-pathname-coding-system))
434     (with-temp-file (nnrss-make-filename "nnrss" server)
435       (insert (format ";; -*- coding: %s; -*-\n"
436                       nnrss-file-coding-system))
437       (gnus-prin1 `(setq nnrss-group-alist ',nnrss-group-alist))
438       (insert "\n")
439       (gnus-prin1 `(setq nnrss-server-data ',nnrss-server-data)))))
440
441 (defun nnrss-read-group-data (group server)
442   (setq nnrss-group-data nil)
443   (if (hash-table-p nnrss-group-hashtb)
444       (clrhash nnrss-group-hashtb)
445     (setq nnrss-group-hashtb (make-hash-table :test 'equal)))
446   (let ((pair (assoc group nnrss-server-data)))
447     (setq nnrss-group-max (or (cadr pair) 0))
448     (setq nnrss-group-min (+ nnrss-group-max 1)))
449   (let ((file (nnrss-make-filename group server)))
450     (when (file-exists-p file)
451       ;; In Emacs 21.3 and earlier, `load' doesn't support non-ASCII
452       ;; file names.  So, we use `insert-file-contents' instead.
453       (mm-with-multibyte-buffer
454         (let ((coding-system-for-read nnrss-file-coding-system)
455               (file-name-coding-system nnmail-pathname-coding-system))
456           (insert-file-contents file)
457           (eval-region (point-min) (point-max))))
458       (dolist (e nnrss-group-data)
459         (puthash (or (nth 2 e) (nth 6 e)) t nnrss-group-hashtb)
460         (when (and (car e) (> nnrss-group-min (car e)))
461           (setq nnrss-group-min (car e)))
462         (when (and (car e) (< nnrss-group-max (car e)))
463           (setq nnrss-group-max (car e)))))))
464
465 (defun nnrss-save-group-data (group server)
466   (gnus-make-directory nnrss-directory)
467   (let ((coding-system-for-write nnrss-file-coding-system)
468         (file-name-coding-system nnmail-pathname-coding-system))
469     (with-temp-file (nnrss-make-filename group server)
470       (insert (format ";; -*- coding: %s; -*-\n"
471                       nnrss-file-coding-system))
472       (gnus-prin1 `(setq nnrss-group-data ',nnrss-group-data)))))
473
474 (defun nnrss-make-filename (name server)
475   (expand-file-name
476    (nnrss-translate-file-chars
477     (concat name
478             (and server
479                  (not (equal server ""))
480                  "-")
481             server
482             ".el"))
483    nnrss-directory))
484
485 (gnus-add-shutdown 'nnrss-close 'gnus)
486
487 (defun nnrss-close ()
488   "Clear internal nnrss variables."
489   (setq nnrss-group-data nil
490         nnrss-server-data nil
491         nnrss-group-hashtb nil
492         nnrss-group-alist nil))
493
494 ;;; URL interface
495
496 (defun nnrss-no-cache (url)
497   "")
498
499 (defun nnrss-insert-w3 (url)
500   (mm-with-unibyte-current-buffer
501     (mm-url-insert url)))
502
503 (defun nnrss-decode-entities-string (string)
504   (if string
505       (mm-with-multibyte-buffer
506         (insert string)
507         (mm-url-decode-entities-nbsp)
508         (buffer-string))))
509
510 (defalias 'nnrss-insert 'nnrss-insert-w3)
511
512 (defun nnrss-mime-encode-string (string)
513   (mm-with-multibyte-buffer
514     (insert string)
515     (mm-url-decode-entities-nbsp)
516     (goto-char (point-min))
517     (while (re-search-forward "[\t\n ]+" nil t)
518       (replace-match " "))
519     (goto-char (point-min))
520     (skip-chars-forward " ")
521     (delete-region (point-min) (point))
522     (goto-char (point-max))
523     (skip-chars-forward " ")
524     (delete-region (point) (point-max))
525     (let ((rfc2047-encoding-type 'mime)
526           rfc2047-encode-max-chars)
527       (rfc2047-encode-region (point-min) (point-max)))
528     (goto-char (point-min))
529     (while (search-forward "\n" nil t)
530       (delete-backward-char 1))
531     (buffer-string)))
532
533 ;;; Snarf functions
534
535 (defun nnrss-check-group (group server)
536   (let (file xml subject url extra changed author date
537              enclosure comments rss-ns rdf-ns content-ns dc-ns)
538     (if (and nnrss-use-local
539              (file-exists-p (setq file (expand-file-name
540                                         (nnrss-translate-file-chars
541                                          (concat group ".xml"))
542                                         nnrss-directory))))
543         (setq xml (nnrss-fetch file t))
544       (setq url (or (nth 2 (assoc group nnrss-server-data))
545                     (second (assoc group nnrss-group-alist))))
546       (unless url
547         (setq url
548               (cdr
549                (assoc 'href
550                       (nnrss-discover-feed
551                        (read-string
552                         (format "URL to search for %s: " group) "http://")))))
553         (let ((pair (assoc group nnrss-server-data)))
554           (if pair
555               (setcdr (cdr pair) (list url))
556             (push (list group nnrss-group-max url) nnrss-server-data)))
557         (setq changed t))
558       (setq xml (nnrss-fetch url)))
559     ;; See
560     ;; http://feeds.archive.org/validator/docs/howto/declare_namespaces.html
561     ;; for more RSS namespaces.
562     (setq dc-ns (nnrss-get-namespace-prefix xml "http://purl.org/dc/elements/1.1/")
563           rdf-ns (nnrss-get-namespace-prefix xml "http://www.w3.org/1999/02/22-rdf-syntax-ns#")
564           rss-ns (nnrss-get-namespace-prefix xml "http://purl.org/rss/1.0/")
565           content-ns (nnrss-get-namespace-prefix xml "http://purl.org/rss/1.0/modules/content/"))
566     (dolist (item (nreverse (nnrss-find-el (intern (concat rss-ns "item")) xml)))
567       (when (and (listp item)
568                  (string= (concat rss-ns "item") (car item))
569                  (if (setq url (nnrss-decode-entities-string
570                                 (nnrss-node-text rss-ns 'link (cddr item))))
571                      (not (gethash url nnrss-group-hashtb))
572                    (setq extra (or (nnrss-node-text content-ns 'encoded item)
573                                    (nnrss-node-text rss-ns 'description item)))
574                    (not (gethash extra nnrss-group-hashtb))))
575         (setq subject (nnrss-node-text rss-ns 'title item))
576         (setq extra (or extra
577                         (nnrss-node-text content-ns 'encoded item)
578                         (nnrss-node-text rss-ns 'description item)))
579         (setq author (or (nnrss-node-text rss-ns 'author item)
580                          (nnrss-node-text dc-ns 'creator item)
581                          (nnrss-node-text dc-ns 'contributor item)))
582         (setq date (or (nnrss-node-text dc-ns 'date item)
583                        (nnrss-node-text rss-ns 'pubDate item)
584                        (message-make-date)))
585         (setq comments (nnrss-node-text rss-ns 'comments item))
586         (when (setq enclosure (cadr (assq (intern (concat rss-ns "enclosure")) item)))
587           (let ((url (cdr (assq 'url enclosure)))
588                 (len (cdr (assq 'length enclosure)))
589                 (type (cdr (assq 'type enclosure)))
590                 (name))
591             (setq len
592                   (if (and len (integerp (setq len (string-to-number len))))
593                       ;; actually already in `ls-lisp-format-file-size' but
594                       ;; probably not worth to require it for one function
595                       (do ((size (/ len 1.0) (/ size 1024.0))
596                            (post-fixes (list "" "k" "M" "G" "T" "P" "E")
597                                        (cdr post-fixes)))
598                           ((< size 1024)
599                            (format "%.1f%s" size (car post-fixes))))
600                     "0"))
601             (setq url (or url ""))
602             (setq name (if (string-match "/\\([^/]*\\)$" url)
603                            (match-string 1 url)
604                          "file"))
605             (setq type (or type ""))
606             (setq enclosure (list url name len type))))
607         (push
608          (list
609           (incf nnrss-group-max)
610           (current-time)
611           url
612           (and subject (nnrss-mime-encode-string subject))
613           (and author (nnrss-mime-encode-string author))
614           date
615           (and extra (nnrss-decode-entities-string extra))
616           enclosure
617           comments)
618          nnrss-group-data)
619         (puthash (or url extra) t nnrss-group-hashtb)
620         (setq changed t))
621       (setq extra nil))
622     (when changed
623       (nnrss-save-group-data group server)
624       (let ((pair (assoc group nnrss-server-data)))
625         (if pair
626             (setcar (cdr pair) nnrss-group-max)
627           (push (list group nnrss-group-max) nnrss-server-data)))
628       (nnrss-save-server-data server))))
629
630 (defun nnrss-opml-import (opml-file)
631   "OPML subscriptions import.
632 Read the file and attempt to subscribe to each Feed in the file."
633   (interactive "fImport file: ")
634   (mapcar
635    (lambda (node) (gnus-group-make-rss-group
636                    (cdr (assq 'xmlUrl (cadr node)))))
637    (nnrss-find-el 'outline
638                   (progn
639                     (find-file opml-file)
640                     (xml-parse-region (point-min)
641                                       (point-max))))))
642
643 (defun nnrss-opml-export ()
644   "OPML subscription export.
645 Export subscriptions to a buffer in OPML Format."
646   (interactive)
647   (with-current-buffer (get-buffer-create "*OPML Export*")
648     (mm-set-buffer-file-coding-system 'utf-8)
649     (insert "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
650             "<!-- OPML generated by Emacs Gnus' nnrss.el -->\n"
651             "<opml version=\"1.1\">\n"
652             "  <head>\n"
653             "    <title>mySubscriptions</title>\n"
654             "    <dateCreated>" (format-time-string "%a, %d %b %Y %T %z")
655             "</dateCreated>\n"
656             "    <ownerEmail>" user-mail-address "</ownerEmail>\n"
657             "    <ownerName>" (user-full-name) "</ownerName>\n"
658             "  </head>\n"
659             "  <body>\n")
660     (dolist (sub nnrss-group-alist)
661       (insert "    <outline text=\"" (car sub)
662               "\" xmlUrl=\"" (cadr sub) "\"/>\n"))
663     (insert "  </body>\n"
664             "</opml>\n"))
665   (pop-to-buffer "*OPML Export*")
666   (when (fboundp 'sgml-mode)
667     (sgml-mode)))
668
669 (defun nnrss-generate-download-script ()
670   "Generate a download script in the current buffer.
671 It is useful when `(setq nnrss-use-local t)'."
672   (interactive)
673   (insert "#!/bin/sh\n")
674   (insert "WGET=wget\n")
675   (insert "RSSDIR='" (expand-file-name nnrss-directory) "'\n")
676   (dolist (elem nnrss-server-data)
677     (let ((url (or (nth 2 elem)
678                    (second (assoc (car elem) nnrss-group-alist)))))
679       (insert "$WGET -q -O \"$RSSDIR\"/'"
680               (nnrss-translate-file-chars (concat (car elem) ".xml"))
681               "' '" url "'\n"))))
682
683 (defun nnrss-translate-file-chars (name)
684   (let ((nnheader-file-name-translation-alist
685          (append nnheader-file-name-translation-alist '((?' . ?_)))))
686     (nnheader-translate-file-chars name)))
687
688 (defvar nnrss-moreover-url
689   "http://w.moreover.com/categories/category_list_rss.html"
690   "The url of moreover.com categories.")
691
692 (defun nnrss-snarf-moreover-categories ()
693   "Snarf RSS links from moreover.com."
694   (interactive)
695   (let (category name url changed)
696     (with-temp-buffer
697       (nnrss-insert nnrss-moreover-url)
698       (goto-char (point-min))
699       (while (re-search-forward
700               "<a name=\"\\([^\"]+\\)\">\\|<a href=\"\\(http://[^\"]*moreover\\.com[^\"]+page\\?c=\\([^\"&]+\\)&o=rss\\)" nil t)
701         (if (match-string 1)
702             (setq category (match-string 1))
703           (setq url (match-string 2)
704                 name (mm-url-decode-entities-string
705                       (rfc2231-decode-encoded-string
706                        (match-string 3))))
707           (if category
708               (setq name (concat category "." name)))
709           (unless (assoc name nnrss-server-data)
710             (setq changed t)
711             (push (list name 0 url) nnrss-server-data)))))
712     (if changed
713         (nnrss-save-server-data ""))))
714
715 (defun nnrss-node-text (namespace local-name element)
716   (let* ((node (assq (intern (concat namespace (symbol-name local-name)))
717                      element))
718          (text (if (and node (listp node))
719                    (nnrss-node-just-text node)
720                  node))
721          (cleaned-text (if text
722                            (gnus-replace-in-string
723                             (gnus-replace-in-string
724                              text "^[\000-\037\177]+\\|^ +\\| +$" "")
725                             "\r\n" "\n"))))
726     (if (string-equal "" cleaned-text)
727         nil
728       cleaned-text)))
729
730 (defun nnrss-node-just-text (node)
731   (if (and node (listp node))
732       (mapconcat 'nnrss-node-just-text (cddr node) " ")
733     node))
734
735 (defun nnrss-find-el (tag data &optional found-list)
736   "Find the all matching elements in the data.
737 Careful with this on large documents!"
738   (when (consp data)
739     (dolist (bit data)
740       (when (car-safe bit)
741         (when (equal tag (car bit))
742           ;; Old xml.el may return a list of string.
743           (when (and (consp (caddr bit))
744                      (stringp (caaddr bit)))
745             (setcar (cddr bit) (caaddr bit)))
746           (setq found-list
747                 (append found-list
748                         (list bit))))
749         (if (and (consp (car-safe (caddr bit)))
750                  (not (stringp (caddr bit))))
751             (setq found-list
752                   (append found-list
753                           (nnrss-find-el
754                            tag (caddr bit))))
755           (setq found-list
756                 (append found-list
757                         (nnrss-find-el
758                          tag (cddr bit))))))))
759   found-list)
760
761 (defun nnrss-rsslink-p (el)
762   "Test if the element we are handed is an RSS autodiscovery link."
763   (and (eq (car-safe el) 'link)
764        (string-equal (cdr (assoc 'rel (cadr el))) "alternate")
765        (or (string-equal (cdr (assoc 'type (cadr el)))
766                          "application/rss+xml")
767            (string-equal (cdr (assoc 'type (cadr el))) "text/xml"))))
768
769 (defun nnrss-get-rsslinks (data)
770   "Extract the <link> elements that are links to RSS from the parsed data."
771   (delq nil (mapcar
772              (lambda (el)
773                (if (nnrss-rsslink-p el) el))
774              (nnrss-find-el 'link data))))
775
776 (defun nnrss-extract-hrefs (data)
777   "Recursively extract hrefs from a page's source.
778 DATA should be the output of `xml-parse-region' or
779 `w3-parse-buffer'."
780   (mapcar (lambda (ahref)
781             (cdr (assoc 'href (cadr ahref))))
782           (nnrss-find-el 'a data)))
783
784 (defmacro nnrss-match-macro (base-uri item onsite-list offsite-list)
785   `(cond ((or (string-match (concat "^" ,base-uri) ,item)
786               (not (string-match "://" ,item)))
787           (setq ,onsite-list (append ,onsite-list (list ,item))))
788          (t (setq ,offsite-list (append ,offsite-list (list ,item))))))
789
790 (defun nnrss-order-hrefs (base-uri hrefs)
791   "Given a list of hrefs, sort them using the following priorities:
792   1. links ending in .rss
793   2. links ending in .rdf
794   3. links ending in .xml
795   4. links containing the above
796   5. offsite links
797
798 BASE-URI is used to determine the location of the links and
799 whether they are `offsite' or `onsite'."
800   (let (rss-onsite-end  rdf-onsite-end  xml-onsite-end
801         rss-onsite-in   rdf-onsite-in   xml-onsite-in
802         rss-offsite-end rdf-offsite-end xml-offsite-end
803         rss-offsite-in rdf-offsite-in xml-offsite-in)
804     (dolist (href hrefs)
805       (cond ((null href))
806             ((string-match "\\.rss$" href)
807              (nnrss-match-macro
808               base-uri href rss-onsite-end rss-offsite-end))
809             ((string-match "\\.rdf$" href)
810              (nnrss-match-macro
811               base-uri href rdf-onsite-end rdf-offsite-end))
812             ((string-match "\\.xml$" href)
813              (nnrss-match-macro
814               base-uri href xml-onsite-end xml-offsite-end))
815             ((string-match "rss" href)
816              (nnrss-match-macro
817               base-uri href rss-onsite-in rss-offsite-in))
818             ((string-match "rdf" href)
819              (nnrss-match-macro
820               base-uri href rdf-onsite-in rdf-offsite-in))
821             ((string-match "xml" href)
822              (nnrss-match-macro
823               base-uri href xml-onsite-in xml-offsite-in))))
824     (append
825      rss-onsite-end  rdf-onsite-end  xml-onsite-end
826      rss-onsite-in   rdf-onsite-in   xml-onsite-in
827      rss-offsite-end rdf-offsite-end xml-offsite-end
828      rss-offsite-in rdf-offsite-in xml-offsite-in)))
829
830 (defun nnrss-discover-feed (url)
831   "Given a page, find an RSS feed using Mark Pilgrim's
832 `ultra-liberal rss locator' (http://diveintomark.org/2002/08/15.html)."
833
834   (let ((parsed-page (nnrss-fetch url)))
835
836 ;;    1. if this url is the rss, use it.
837     (if (nnrss-rss-p parsed-page)
838         (let ((rss-ns (nnrss-get-namespace-prefix parsed-page "http://purl.org/rss/1.0/")))
839           (nnrss-rss-title-description rss-ns parsed-page url))
840
841 ;;    2. look for the <link rel="alternate"
842 ;;    type="application/rss+xml" and use that if it is there.
843       (let ((links (nnrss-get-rsslinks parsed-page)))
844         (if links
845             (let* ((xml (nnrss-fetch
846                          (cdr (assoc 'href (cadar links)))))
847                    (rss-ns (nnrss-get-namespace-prefix xml "http://purl.org/rss/1.0/")))
848               (nnrss-rss-title-description rss-ns xml (cdr (assoc 'href (cadar links)))))
849
850 ;;    3. look for links on the site in the following order:
851 ;;       - onsite links ending in .rss, .rdf, or .xml
852 ;;       - onsite links containing any of the above
853 ;;       - offsite links ending in .rss, .rdf, or .xml
854 ;;       - offsite links containing any of the above
855           (let* ((base-uri (progn (string-match ".*://[^/]+/?" url)
856                                   (match-string 0 url)))
857                  (hrefs (nnrss-order-hrefs
858                          base-uri (nnrss-extract-hrefs parsed-page)))
859                  (rss-link nil))
860             (while (and (eq rss-link nil) (not (eq hrefs nil)))
861               (let ((href-data (nnrss-fetch (car hrefs))))
862                 (if (nnrss-rss-p href-data)
863                     (let* ((rss-ns (nnrss-get-namespace-prefix href-data "http://purl.org/rss/1.0/")))
864                       (setq rss-link (nnrss-rss-title-description
865                                       rss-ns href-data (car hrefs))))
866                   (setq hrefs (cdr hrefs)))))
867             (if rss-link rss-link
868
869 ;;    4. check syndic8
870               (nnrss-find-rss-via-syndic8 url))))))))
871
872 (defun nnrss-find-rss-via-syndic8 (url)
873   "Query syndic8 for the rss feeds it has for URL."
874   (if (not (locate-library "xml-rpc"))
875       (progn
876         (message "XML-RPC is not available... not checking Syndic8.")
877         nil)
878     (require 'xml-rpc)
879     (let ((feedid (xml-rpc-method-call
880                    "http://www.syndic8.com/xmlrpc.php"
881                    'syndic8.FindSites
882                    url)))
883       (when feedid
884         (let* ((feedinfo (xml-rpc-method-call
885                           "http://www.syndic8.com/xmlrpc.php"
886                           'syndic8.GetFeedInfo
887                           feedid))
888                (urllist
889                 (delq nil
890                       (mapcar
891                        (lambda (listinfo)
892                          (if (string-equal
893                               (cdr (assoc "status" listinfo))
894                               "Syndicated")
895                              (cons
896                               (cdr (assoc "sitename" listinfo))
897                               (list
898                                (cons 'title
899                                      (cdr (assoc
900                                            "sitename" listinfo)))
901                                (cons 'href
902                                      (cdr (assoc
903                                            "dataurl" listinfo)))))))
904                        feedinfo))))
905           (if (not (> (length urllist) 1))
906               (cdar urllist)
907             (let ((completion-ignore-case t)
908                   (selection
909                    (mapcar (lambda (listinfo)
910                              (cons (cdr (assoc "sitename" listinfo))
911                                    (string-to-number
912                                     (cdr (assoc "feedid" listinfo)))))
913                            feedinfo)))
914               (cdr (assoc
915                     (completing-read
916                      "Multiple feeds found.  Select one: "
917                      selection nil t) urllist)))))))))
918
919 (defun nnrss-rss-p (data)
920   "Test if DATA is an RSS feed.
921 Simply ensures that the first element is rss or rdf."
922   (or (eq (caar data) 'rss)
923       (eq (caar data) 'rdf:RDF)))
924
925 (defun nnrss-rss-title-description (rss-namespace data url)
926   "Return the title of an RSS feed."
927   (if (nnrss-rss-p data)
928       (let ((description (intern (concat rss-namespace "description")))
929             (title (intern (concat rss-namespace "title")))
930             (channel (nnrss-find-el (intern (concat rss-namespace "channel"))
931                                     data)))
932         (list
933          (cons 'description (caddr (nth 0 (nnrss-find-el description channel))))
934          (cons 'title (caddr (nth 0 (nnrss-find-el title channel))))
935          (cons 'href url)))))
936
937 (defun nnrss-get-namespace-prefix (el uri)
938   "Given EL (containing a parsed element) and URI (containing a string
939 that gives the URI for which you want to retrieve the namespace
940 prefix), return the prefix."
941   (let* ((prefix (car (rassoc uri (cadar el))))
942          (nslist (if prefix
943                      (split-string (symbol-name prefix) ":")))
944          (ns (cond ((eq (length nslist) 1) ; no prefix given
945                     "")
946                    ((eq (length nslist) 2) ; extract prefix
947                     (cadr nslist)))))
948     (if (and ns (not (string= ns "")))
949         (concat ns ":")
950       ns)))
951
952 (provide 'nnrss)
953
954
955 ;;; nnrss.el ends here
956
957 ;;; arch-tag: 12910c07-0cdf-44fb-8d2c-416ded64c267