(nnrss-check-group): Put the RSS dc:subject in the article. From Mark Plaksin.
[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 feed-subject
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         (if (setq feed-subject (nnrss-node-text dc-ns 'subject item))
580             (setq extra (concat feed-subject "<br /><br />\n" extra)))
581         (setq author (or (nnrss-node-text rss-ns 'author item)
582                          (nnrss-node-text dc-ns 'creator item)
583                          (nnrss-node-text dc-ns 'contributor item)))
584         (setq date (or (nnrss-node-text dc-ns 'date item)
585                        (nnrss-node-text rss-ns 'pubDate item)
586                        (message-make-date)))
587         (setq comments (nnrss-node-text rss-ns 'comments item))
588         (when (setq enclosure (cadr (assq (intern (concat rss-ns "enclosure")) item)))
589           (let ((url (cdr (assq 'url enclosure)))
590                 (len (cdr (assq 'length enclosure)))
591                 (type (cdr (assq 'type enclosure)))
592                 (name))
593             (setq len
594                   (if (and len (integerp (setq len (string-to-number len))))
595                       ;; actually already in `ls-lisp-format-file-size' but
596                       ;; probably not worth to require it for one function
597                       (do ((size (/ len 1.0) (/ size 1024.0))
598                            (post-fixes (list "" "k" "M" "G" "T" "P" "E")
599                                        (cdr post-fixes)))
600                           ((< size 1024)
601                            (format "%.1f%s" size (car post-fixes))))
602                     "0"))
603             (setq url (or url ""))
604             (setq name (if (string-match "/\\([^/]*\\)$" url)
605                            (match-string 1 url)
606                          "file"))
607             (setq type (or type ""))
608             (setq enclosure (list url name len type))))
609         (push
610          (list
611           (incf nnrss-group-max)
612           (current-time)
613           url
614           (and subject (nnrss-mime-encode-string subject))
615           (and author (nnrss-mime-encode-string author))
616           date
617           (and extra (nnrss-decode-entities-string extra))
618           enclosure
619           comments)
620          nnrss-group-data)
621         (puthash (or url extra) t nnrss-group-hashtb)
622         (setq changed t))
623       (setq extra nil))
624     (when changed
625       (nnrss-save-group-data group server)
626       (let ((pair (assoc group nnrss-server-data)))
627         (if pair
628             (setcar (cdr pair) nnrss-group-max)
629           (push (list group nnrss-group-max) nnrss-server-data)))
630       (nnrss-save-server-data server))))
631
632 (defun nnrss-opml-import (opml-file)
633   "OPML subscriptions import.
634 Read the file and attempt to subscribe to each Feed in the file."
635   (interactive "fImport file: ")
636   (mapcar
637    (lambda (node) (gnus-group-make-rss-group
638                    (cdr (assq 'xmlUrl (cadr node)))))
639    (nnrss-find-el 'outline
640                   (progn
641                     (find-file opml-file)
642                     (xml-parse-region (point-min)
643                                       (point-max))))))
644
645 (defun nnrss-opml-export ()
646   "OPML subscription export.
647 Export subscriptions to a buffer in OPML Format."
648   (interactive)
649   (with-current-buffer (get-buffer-create "*OPML Export*")
650     (mm-set-buffer-file-coding-system 'utf-8)
651     (insert "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
652             "<!-- OPML generated by Emacs Gnus' nnrss.el -->\n"
653             "<opml version=\"1.1\">\n"
654             "  <head>\n"
655             "    <title>mySubscriptions</title>\n"
656             "    <dateCreated>" (format-time-string "%a, %d %b %Y %T %z")
657             "</dateCreated>\n"
658             "    <ownerEmail>" user-mail-address "</ownerEmail>\n"
659             "    <ownerName>" (user-full-name) "</ownerName>\n"
660             "  </head>\n"
661             "  <body>\n")
662     (dolist (sub nnrss-group-alist)
663       (insert "    <outline text=\"" (car sub)
664               "\" xmlUrl=\"" (cadr sub) "\"/>\n"))
665     (insert "  </body>\n"
666             "</opml>\n"))
667   (pop-to-buffer "*OPML Export*")
668   (when (fboundp 'sgml-mode)
669     (sgml-mode)))
670
671 (defun nnrss-generate-download-script ()
672   "Generate a download script in the current buffer.
673 It is useful when `(setq nnrss-use-local t)'."
674   (interactive)
675   (insert "#!/bin/sh\n")
676   (insert "WGET=wget\n")
677   (insert "RSSDIR='" (expand-file-name nnrss-directory) "'\n")
678   (dolist (elem nnrss-server-data)
679     (let ((url (or (nth 2 elem)
680                    (second (assoc (car elem) nnrss-group-alist)))))
681       (insert "$WGET -q -O \"$RSSDIR\"/'"
682               (nnrss-translate-file-chars (concat (car elem) ".xml"))
683               "' '" url "'\n"))))
684
685 (defun nnrss-translate-file-chars (name)
686   (let ((nnheader-file-name-translation-alist
687          (append nnheader-file-name-translation-alist '((?' . ?_)))))
688     (nnheader-translate-file-chars name)))
689
690 (defvar nnrss-moreover-url
691   "http://w.moreover.com/categories/category_list_rss.html"
692   "The url of moreover.com categories.")
693
694 (defun nnrss-snarf-moreover-categories ()
695   "Snarf RSS links from moreover.com."
696   (interactive)
697   (let (category name url changed)
698     (with-temp-buffer
699       (nnrss-insert nnrss-moreover-url)
700       (goto-char (point-min))
701       (while (re-search-forward
702               "<a name=\"\\([^\"]+\\)\">\\|<a href=\"\\(http://[^\"]*moreover\\.com[^\"]+page\\?c=\\([^\"&]+\\)&o=rss\\)" nil t)
703         (if (match-string 1)
704             (setq category (match-string 1))
705           (setq url (match-string 2)
706                 name (mm-url-decode-entities-string
707                       (rfc2231-decode-encoded-string
708                        (match-string 3))))
709           (if category
710               (setq name (concat category "." name)))
711           (unless (assoc name nnrss-server-data)
712             (setq changed t)
713             (push (list name 0 url) nnrss-server-data)))))
714     (if changed
715         (nnrss-save-server-data ""))))
716
717 (defun nnrss-node-text (namespace local-name element)
718   (let* ((node (assq (intern (concat namespace (symbol-name local-name)))
719                      element))
720          (text (if (and node (listp node))
721                    (nnrss-node-just-text node)
722                  node))
723          (cleaned-text (if text
724                            (gnus-replace-in-string
725                             (gnus-replace-in-string
726                              text "^[\000-\037\177]+\\|^ +\\| +$" "")
727                             "\r\n" "\n"))))
728     (if (string-equal "" cleaned-text)
729         nil
730       cleaned-text)))
731
732 (defun nnrss-node-just-text (node)
733   (if (and node (listp node))
734       (mapconcat 'nnrss-node-just-text (cddr node) " ")
735     node))
736
737 (defun nnrss-find-el (tag data &optional found-list)
738   "Find the all matching elements in the data.
739 Careful with this on large documents!"
740   (when (consp data)
741     (dolist (bit data)
742       (when (car-safe bit)
743         (when (equal tag (car bit))
744           ;; Old xml.el may return a list of string.
745           (when (and (consp (caddr bit))
746                      (stringp (caaddr bit)))
747             (setcar (cddr bit) (caaddr bit)))
748           (setq found-list
749                 (append found-list
750                         (list bit))))
751         (if (and (consp (car-safe (caddr bit)))
752                  (not (stringp (caddr bit))))
753             (setq found-list
754                   (append found-list
755                           (nnrss-find-el
756                            tag (caddr bit))))
757           (setq found-list
758                 (append found-list
759                         (nnrss-find-el
760                          tag (cddr bit))))))))
761   found-list)
762
763 (defun nnrss-rsslink-p (el)
764   "Test if the element we are handed is an RSS autodiscovery link."
765   (and (eq (car-safe el) 'link)
766        (string-equal (cdr (assoc 'rel (cadr el))) "alternate")
767        (or (string-equal (cdr (assoc 'type (cadr el)))
768                          "application/rss+xml")
769            (string-equal (cdr (assoc 'type (cadr el))) "text/xml"))))
770
771 (defun nnrss-get-rsslinks (data)
772   "Extract the <link> elements that are links to RSS from the parsed data."
773   (delq nil (mapcar
774              (lambda (el)
775                (if (nnrss-rsslink-p el) el))
776              (nnrss-find-el 'link data))))
777
778 (defun nnrss-extract-hrefs (data)
779   "Recursively extract hrefs from a page's source.
780 DATA should be the output of `xml-parse-region' or
781 `w3-parse-buffer'."
782   (mapcar (lambda (ahref)
783             (cdr (assoc 'href (cadr ahref))))
784           (nnrss-find-el 'a data)))
785
786 (defmacro nnrss-match-macro (base-uri item onsite-list offsite-list)
787   `(cond ((or (string-match (concat "^" ,base-uri) ,item)
788               (not (string-match "://" ,item)))
789           (setq ,onsite-list (append ,onsite-list (list ,item))))
790          (t (setq ,offsite-list (append ,offsite-list (list ,item))))))
791
792 (defun nnrss-order-hrefs (base-uri hrefs)
793   "Given a list of hrefs, sort them using the following priorities:
794   1. links ending in .rss
795   2. links ending in .rdf
796   3. links ending in .xml
797   4. links containing the above
798   5. offsite links
799
800 BASE-URI is used to determine the location of the links and
801 whether they are `offsite' or `onsite'."
802   (let (rss-onsite-end  rdf-onsite-end  xml-onsite-end
803         rss-onsite-in   rdf-onsite-in   xml-onsite-in
804         rss-offsite-end rdf-offsite-end xml-offsite-end
805         rss-offsite-in rdf-offsite-in xml-offsite-in)
806     (dolist (href hrefs)
807       (cond ((null href))
808             ((string-match "\\.rss$" href)
809              (nnrss-match-macro
810               base-uri href rss-onsite-end rss-offsite-end))
811             ((string-match "\\.rdf$" href)
812              (nnrss-match-macro
813               base-uri href rdf-onsite-end rdf-offsite-end))
814             ((string-match "\\.xml$" href)
815              (nnrss-match-macro
816               base-uri href xml-onsite-end xml-offsite-end))
817             ((string-match "rss" href)
818              (nnrss-match-macro
819               base-uri href rss-onsite-in rss-offsite-in))
820             ((string-match "rdf" href)
821              (nnrss-match-macro
822               base-uri href rdf-onsite-in rdf-offsite-in))
823             ((string-match "xml" href)
824              (nnrss-match-macro
825               base-uri href xml-onsite-in xml-offsite-in))))
826     (append
827      rss-onsite-end  rdf-onsite-end  xml-onsite-end
828      rss-onsite-in   rdf-onsite-in   xml-onsite-in
829      rss-offsite-end rdf-offsite-end xml-offsite-end
830      rss-offsite-in rdf-offsite-in xml-offsite-in)))
831
832 (defun nnrss-discover-feed (url)
833   "Given a page, find an RSS feed using Mark Pilgrim's
834 `ultra-liberal rss locator' (http://diveintomark.org/2002/08/15.html)."
835
836   (let ((parsed-page (nnrss-fetch url)))
837
838 ;;    1. if this url is the rss, use it.
839     (if (nnrss-rss-p parsed-page)
840         (let ((rss-ns (nnrss-get-namespace-prefix parsed-page "http://purl.org/rss/1.0/")))
841           (nnrss-rss-title-description rss-ns parsed-page url))
842
843 ;;    2. look for the <link rel="alternate"
844 ;;    type="application/rss+xml" and use that if it is there.
845       (let ((links (nnrss-get-rsslinks parsed-page)))
846         (if links
847             (let* ((xml (nnrss-fetch
848                          (cdr (assoc 'href (cadar links)))))
849                    (rss-ns (nnrss-get-namespace-prefix xml "http://purl.org/rss/1.0/")))
850               (nnrss-rss-title-description rss-ns xml (cdr (assoc 'href (cadar links)))))
851
852 ;;    3. look for links on the site in the following order:
853 ;;       - onsite links ending in .rss, .rdf, or .xml
854 ;;       - onsite links containing any of the above
855 ;;       - offsite links ending in .rss, .rdf, or .xml
856 ;;       - offsite links containing any of the above
857           (let* ((base-uri (progn (string-match ".*://[^/]+/?" url)
858                                   (match-string 0 url)))
859                  (hrefs (nnrss-order-hrefs
860                          base-uri (nnrss-extract-hrefs parsed-page)))
861                  (rss-link nil))
862             (while (and (eq rss-link nil) (not (eq hrefs nil)))
863               (let ((href-data (nnrss-fetch (car hrefs))))
864                 (if (nnrss-rss-p href-data)
865                     (let* ((rss-ns (nnrss-get-namespace-prefix href-data "http://purl.org/rss/1.0/")))
866                       (setq rss-link (nnrss-rss-title-description
867                                       rss-ns href-data (car hrefs))))
868                   (setq hrefs (cdr hrefs)))))
869             (if rss-link rss-link
870
871 ;;    4. check syndic8
872               (nnrss-find-rss-via-syndic8 url))))))))
873
874 (defun nnrss-find-rss-via-syndic8 (url)
875   "Query syndic8 for the rss feeds it has for URL."
876   (if (not (locate-library "xml-rpc"))
877       (progn
878         (message "XML-RPC is not available... not checking Syndic8.")
879         nil)
880     (require 'xml-rpc)
881     (let ((feedid (xml-rpc-method-call
882                    "http://www.syndic8.com/xmlrpc.php"
883                    'syndic8.FindSites
884                    url)))
885       (when feedid
886         (let* ((feedinfo (xml-rpc-method-call
887                           "http://www.syndic8.com/xmlrpc.php"
888                           'syndic8.GetFeedInfo
889                           feedid))
890                (urllist
891                 (delq nil
892                       (mapcar
893                        (lambda (listinfo)
894                          (if (string-equal
895                               (cdr (assoc "status" listinfo))
896                               "Syndicated")
897                              (cons
898                               (cdr (assoc "sitename" listinfo))
899                               (list
900                                (cons 'title
901                                      (cdr (assoc
902                                            "sitename" listinfo)))
903                                (cons 'href
904                                      (cdr (assoc
905                                            "dataurl" listinfo)))))))
906                        feedinfo))))
907           (if (not (> (length urllist) 1))
908               (cdar urllist)
909             (let ((completion-ignore-case t)
910                   (selection
911                    (mapcar (lambda (listinfo)
912                              (cons (cdr (assoc "sitename" listinfo))
913                                    (string-to-number
914                                     (cdr (assoc "feedid" listinfo)))))
915                            feedinfo)))
916               (cdr (assoc
917                     (completing-read
918                      "Multiple feeds found.  Select one: "
919                      selection nil t) urllist)))))))))
920
921 (defun nnrss-rss-p (data)
922   "Test if DATA is an RSS feed.
923 Simply ensures that the first element is rss or rdf."
924   (or (eq (caar data) 'rss)
925       (eq (caar data) 'rdf:RDF)))
926
927 (defun nnrss-rss-title-description (rss-namespace data url)
928   "Return the title of an RSS feed."
929   (if (nnrss-rss-p data)
930       (let ((description (intern (concat rss-namespace "description")))
931             (title (intern (concat rss-namespace "title")))
932             (channel (nnrss-find-el (intern (concat rss-namespace "channel"))
933                                     data)))
934         (list
935          (cons 'description (caddr (nth 0 (nnrss-find-el description channel))))
936          (cons 'title (caddr (nth 0 (nnrss-find-el title channel))))
937          (cons 'href url)))))
938
939 (defun nnrss-get-namespace-prefix (el uri)
940   "Given EL (containing a parsed element) and URI (containing a string
941 that gives the URI for which you want to retrieve the namespace
942 prefix), return the prefix."
943   (let* ((prefix (car (rassoc uri (cadar el))))
944          (nslist (if prefix
945                      (split-string (symbol-name prefix) ":")))
946          (ns (cond ((eq (length nslist) 1) ; no prefix given
947                     "")
948                    ((eq (length nslist) 2) ; extract prefix
949                     (cadr nslist)))))
950     (if (and ns (not (string= ns "")))
951         (concat ns ":")
952       ns)))
953
954 (provide 'nnrss)
955
956
957 ;;; nnrss.el ends here
958
959 ;;; arch-tag: 12910c07-0cdf-44fb-8d2c-416ded64c267