Import No Gnus v0.4.
[elisp/gnus.git-] / lisp / nnweb.el
1 ;;; nnweb.el --- retrieving articles via web search engines
2
3 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003,
4 ;;   2004, 2005, 2006 Free Software Foundation, Inc.
5
6 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
7 ;; Keywords: news
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
23 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
24 ;; Boston, MA 02110-1301, USA.
25
26 ;;; Commentary:
27
28 ;; Note: You need to have `w3' installed for some functions to work.
29
30 ;;; Code:
31
32 (eval-when-compile (require 'cl))
33
34 (require 'nnoo)
35 (require 'message)
36 (require 'gnus-util)
37 (require 'gnus)
38 (require 'nnmail)
39 (require 'mm-util)
40 (require 'mm-url)
41 (eval-and-compile
42   (ignore-errors
43     (require 'url)))
44 (autoload 'w3-parse-buffer "w3-parse")
45
46 (nnoo-declare nnweb)
47
48 (defvoo nnweb-directory (nnheader-concat gnus-directory "nnweb/")
49   "Where nnweb will save its files.")
50
51 (defvoo nnweb-type 'google
52   "What search engine type is being used.
53 Valid types include `google', `dejanews', and `gmane'.")
54
55 (defvar nnweb-type-definition
56   '((google
57      (id . "http://www.google.com/groups?as_umsgid=%s&hl=en&dmode=source")
58      (result . "http://groups.google.com/group/%s/msg/%s?dmode=source")
59      (article . nnweb-google-wash-article)
60      (reference . identity)
61      (map . nnweb-google-create-mapping)
62      (search . nnweb-google-search)
63      (address . "http://groups.google.com/groups")
64      (base    . "http://groups.google.com")
65      (identifier . nnweb-google-identity))
66     (dejanews ;; alias of google
67      (id . "http://www.google.com/groups?as_umsgid=%s&hl=en&dmode=source")
68      (result . "http://groups.google.com/group/%s/msg/%s?dmode=source")
69      (article . nnweb-google-wash-article)
70      (reference . identity)
71      (map . nnweb-google-create-mapping)
72      (search . nnweb-google-search)
73      (address . "http://groups.google.com/groups")
74      (base    . "http://groups.google.com")
75      (identifier . nnweb-google-identity))
76     (gmane
77      (article . nnweb-gmane-wash-article)
78      (id . "http://gmane.org/view.php?group=%s")
79      (reference . identity)
80      (map . nnweb-gmane-create-mapping)
81      (search . nnweb-gmane-search)
82      (address . "http://search.gmane.org/nov.php")
83      (identifier . nnweb-gmane-identity)))
84   "Type-definition alist.")
85
86 (defvoo nnweb-search nil
87   "Search string to feed to Google.")
88
89 (defvoo nnweb-max-hits 999
90   "Maximum number of hits to display.")
91
92 (defvoo nnweb-ephemeral-p nil
93   "Whether this nnweb server is ephemeral.")
94
95 ;;; Internal variables
96
97 (defvoo nnweb-articles nil)
98 (defvoo nnweb-buffer nil)
99 (defvoo nnweb-group-alist nil)
100 (defvoo nnweb-group nil)
101 (defvoo nnweb-hashtb nil)
102
103 ;;; Interface functions
104
105 (nnoo-define-basics nnweb)
106
107 (deffoo nnweb-retrieve-headers (articles &optional group server fetch-old)
108   (nnweb-possibly-change-server group server)
109   (save-excursion
110     (set-buffer nntp-server-buffer)
111     (erase-buffer)
112     (let (article header)
113       (mm-with-unibyte-current-buffer
114         (while (setq article (pop articles))
115           (when (setq header (cadr (assq article nnweb-articles)))
116             (nnheader-insert-nov header))))
117       'nov)))
118
119 (deffoo nnweb-request-scan (&optional group server)
120   (nnweb-possibly-change-server group server)
121   (if nnweb-ephemeral-p
122       (setq nnweb-hashtb (gnus-make-hashtable 4095))
123     (unless nnweb-articles
124       (nnweb-read-overview group)))
125   (funcall (nnweb-definition 'map))
126   (unless nnweb-ephemeral-p
127     (nnweb-write-active)
128     (nnweb-write-overview group)))
129
130 (deffoo nnweb-request-group (group &optional server dont-check)
131   (nnweb-possibly-change-server group server)
132   (unless (or nnweb-ephemeral-p
133               dont-check
134               nnweb-articles)
135     (nnweb-read-overview group))
136   (cond
137    ((not nnweb-articles)
138     (nnheader-report 'nnweb "No matching articles"))
139    (t
140     (let ((active (if nnweb-ephemeral-p
141                       (cons (caar nnweb-articles)
142                             (caar (last nnweb-articles)))
143                     (cadr (assoc group nnweb-group-alist)))))
144       (nnheader-report 'nnweb "Opened group %s" group)
145       (nnheader-insert
146        "211 %d %d %d %s\n" (length nnweb-articles)
147        (car active) (cdr active) group)))))
148
149 (deffoo nnweb-close-group (group &optional server)
150   (nnweb-possibly-change-server group server)
151   (when (gnus-buffer-live-p nnweb-buffer)
152     (save-excursion
153       (set-buffer nnweb-buffer)
154       (set-buffer-modified-p nil)
155       (kill-buffer nnweb-buffer)))
156   t)
157
158 (deffoo nnweb-request-article (article &optional group server buffer)
159   (nnweb-possibly-change-server group server)
160   (save-excursion
161     (set-buffer (or buffer nntp-server-buffer))
162     (let* ((header (cadr (assq article nnweb-articles)))
163            (url (and header (mail-header-xref header))))
164       (when (or (and url
165                      (mm-with-unibyte-current-buffer
166                        (mm-url-insert url)))
167                 (and (stringp article)
168                      (nnweb-definition 'id t)
169                      (let ((fetch (nnweb-definition 'id))
170                            art active)
171                        (when (string-match "^<\\(.*\\)>$" article)
172                          (setq art (match-string 1 article)))
173                        (when (and fetch art)
174                          (setq url (format fetch art))
175                          (mm-with-unibyte-current-buffer
176                            (mm-url-insert url))
177                          (if (nnweb-definition 'reference t)
178                              (setq article
179                                    (funcall (nnweb-definition
180                                              'reference) article)))))))
181         (unless nnheader-callback-function
182           (funcall (nnweb-definition 'article)))
183         (nnheader-report 'nnweb "Fetched article %s" article)
184         (cons group (and (numberp article) article))))))
185
186 (deffoo nnweb-close-server (&optional server)
187   (when (and (nnweb-server-opened server)
188              (gnus-buffer-live-p nnweb-buffer))
189     (save-excursion
190       (set-buffer nnweb-buffer)
191       (set-buffer-modified-p nil)
192       (kill-buffer nnweb-buffer)))
193   (nnoo-close-server 'nnweb server))
194
195 (deffoo nnweb-request-list (&optional server)
196   (nnweb-possibly-change-server nil server)
197   (save-excursion
198     (set-buffer nntp-server-buffer)
199     (nnmail-generate-active (list (assoc server nnweb-group-alist)))
200     t))
201
202 (deffoo nnweb-request-update-info (group info &optional server)
203   (nnweb-possibly-change-server group server))
204
205 (deffoo nnweb-asynchronous-p ()
206   nil)
207
208 (deffoo nnweb-request-create-group (group &optional server args)
209   (nnweb-possibly-change-server nil server)
210   (nnweb-request-delete-group group)
211   (push `(,group ,(cons 1 0)) nnweb-group-alist)
212   (nnweb-write-active)
213   t)
214
215 (deffoo nnweb-request-delete-group (group &optional force server)
216   (nnweb-possibly-change-server group server)
217   (gnus-pull group nnweb-group-alist t)
218   (nnweb-write-active)
219   (gnus-delete-file (nnweb-overview-file group))
220   t)
221
222 (nnoo-define-skeleton nnweb)
223
224 ;;; Internal functions
225
226 (defun nnweb-read-overview (group)
227   "Read the overview of GROUP and build the map."
228   (when (file-exists-p (nnweb-overview-file group))
229     (mm-with-unibyte-buffer
230       (nnheader-insert-file-contents (nnweb-overview-file group))
231       (goto-char (point-min))
232       (let (header)
233         (while (not (eobp))
234           (setq header (nnheader-parse-nov))
235           (forward-line 1)
236           (push (list (mail-header-number header)
237                       header (mail-header-xref header))
238                 nnweb-articles)
239           (nnweb-set-hashtb header (car nnweb-articles)))))))
240
241 (defun nnweb-write-overview (group)
242   "Write the overview file for GROUP."
243   (with-temp-file (nnweb-overview-file group)
244     (let ((articles nnweb-articles))
245       (while articles
246         (nnheader-insert-nov (cadr (pop articles)))))))
247
248 (defun nnweb-set-hashtb (header data)
249   (gnus-sethash (nnweb-identifier (mail-header-xref header))
250                 data nnweb-hashtb))
251
252 (defun nnweb-get-hashtb (url)
253   (gnus-gethash (nnweb-identifier url) nnweb-hashtb))
254
255 (defun nnweb-identifier (ident)
256   (funcall (nnweb-definition 'identifier) ident))
257
258 (defun nnweb-overview-file (group)
259   "Return the name of the overview file of GROUP."
260   (nnheader-concat nnweb-directory group ".overview"))
261
262 (defun nnweb-write-active ()
263   "Save the active file."
264   (gnus-make-directory nnweb-directory)
265   (with-temp-file (nnheader-concat nnweb-directory "active")
266     (prin1 `(setq nnweb-group-alist ',nnweb-group-alist) (current-buffer))))
267
268 (defun nnweb-read-active ()
269   "Read the active file."
270   (load (nnheader-concat nnweb-directory "active") t t t))
271
272 (defun nnweb-definition (type &optional noerror)
273   "Return the definition of TYPE."
274   (let ((def (cdr (assq type (assq nnweb-type nnweb-type-definition)))))
275     (when (and (not def)
276                (not noerror))
277       (error "Undefined definition %s" type))
278     def))
279
280 (defun nnweb-possibly-change-server (&optional group server)
281   (when server
282     (unless (nnweb-server-opened server)
283       (nnweb-open-server server))
284     (nnweb-init server))
285   (unless nnweb-group-alist
286     (nnweb-read-active))
287   (unless nnweb-hashtb
288     (setq nnweb-hashtb (gnus-make-hashtable 4095)))
289   (when group
290     (setq nnweb-group group)))
291
292 (defun nnweb-init (server)
293   "Initialize buffers and such."
294   (unless (gnus-buffer-live-p nnweb-buffer)
295     (setq nnweb-buffer
296           (save-excursion
297             (mm-with-unibyte
298               (nnheader-set-temp-buffer
299                (format " *nnweb %s %s %s*"
300                        nnweb-type nnweb-search server))
301               (current-buffer))))))
302
303 ;;;
304 ;;; groups.google.com
305 ;;;
306
307 (defun nnweb-google-wash-article ()
308   ;; We have Google's masked e-mail addresses here.  :-/
309   (let ((case-fold-search t)
310         (start-re "<pre>\n *")
311         (end-re "\n *</pre>"))
312     (goto-char (point-min))
313     (if (save-excursion
314           (or (re-search-forward "The requested message.*could not be found."
315                                  nil t)
316               (not (and (re-search-forward start-re nil t)
317                         (re-search-forward end-re nil t)))))
318         ;; FIXME: Don't know how to indicate "not found".
319         ;; Should this function throw an error?  --rsteib
320         (progn
321           (gnus-message 3 "Requested article not found")
322           (erase-buffer))
323       (delete-region (point-min)
324                      (re-search-forward start-re))
325       (goto-char (point-min))
326       (delete-region (progn
327                        (re-search-forward end-re)
328                        (match-beginning 0))
329                      (point-max))
330       (mm-url-decode-entities))))
331
332 (defun nnweb-google-parse-1 (&optional Message-ID)
333   "Parse search result in current buffer."
334   (let ((i 0)
335         (case-fold-search t)
336         (active (cadr (assoc nnweb-group nnweb-group-alist)))
337         Subject Score Date Newsgroups From
338         map url mid)
339     (unless active
340       (push (list nnweb-group (setq active (cons 1 0)))
341             nnweb-group-alist))
342     ;; Go through all the article hits on this page.
343     (goto-char (point-min))
344     (while
345         (re-search-forward
346          "a +href=\"/group/\\([^>\"]+\\)/browse_thread/[^>]+#\\([0-9a-f]+\\)"
347          nil t)
348       (setq Newsgroups (match-string-no-properties 1)
349             ;; Note: Starting with Google Groups 2, `mid' is a Google-internal
350             ;; ID, not a proper Message-ID.
351             mid (match-string-no-properties 2)
352             url (format
353                  (nnweb-definition 'result) Newsgroups mid))
354       (narrow-to-region (search-forward ">" nil t)
355                         (search-forward "</a>" nil t))
356       (mm-url-remove-markup)
357       (mm-url-decode-entities)
358       (setq Subject (buffer-string))
359       (goto-char (point-max))
360       (widen)
361       (narrow-to-region (point)
362                         (search-forward "</td" nil t))
363
364       (mm-url-remove-markup)
365       (mm-url-decode-entities)
366       (search-backward " - ")
367       (when (looking-at
368              " - \\([a-zA-Z]+\\) \\([0-9]+\\)\\(?: \\([0-9]\\{4\\}\\)\\)?, [^\n]+by \\([^<\n]+\\)\n")
369         (setq From (match-string 4)
370               Date (format "%s %s 00:00:00 %s"
371                            (match-string 1)
372                            (match-string 2)
373                            (or (match-string 3)
374                                (substring (current-time-string) -4)))))
375
376       (widen)
377       (forward-line 1)
378       (incf i)
379       (unless (nnweb-get-hashtb url)
380         (push
381          (list
382           (incf (cdr active))
383           (make-full-mail-header
384            (cdr active) (if Newsgroups
385                             (concat  "(" Newsgroups ") " Subject)
386                           Subject)
387            From Date (or Message-ID mid)
388            nil 0 0 url))
389          map)
390         (nnweb-set-hashtb (cadar map) (car map))))
391     map))
392
393 (defun nnweb-google-reference (id)
394   (let ((map (nnweb-google-parse-1 id)) header)
395     (setq nnweb-articles
396           (nconc nnweb-articles map))
397     (when (setq header (cadar map))
398       (mm-with-unibyte-current-buffer
399         (mm-url-insert (mail-header-xref header)))
400       (caar map))))
401
402 (defun nnweb-google-create-mapping ()
403   "Perform the search and create a number-to-url alist."
404   (save-excursion
405     (set-buffer nnweb-buffer)
406     (erase-buffer)
407     (nnheader-message 7 "Searching google...")
408     (when (funcall (nnweb-definition 'search) nnweb-search)
409         (let ((more t)
410               (i 0))
411           (while more
412             (setq nnweb-articles
413                   (nconc nnweb-articles (nnweb-google-parse-1)))
414             ;; Check if there are more articles to fetch
415             (goto-char (point-min))
416             (incf i 100)
417             (if (or (not (re-search-forward
418                           "<a href=\"\n\\([^>\" \n\t]+\\)[^<]*<img src=[^>]+next"
419                           nil t))
420                     (>= i nnweb-max-hits))
421                 (setq more nil)
422               ;; Yup, there are more articles
423               (setq more (concat (nnweb-definition 'base) (match-string 1)))
424             (when more
425               (erase-buffer)
426               (nnheader-message 7 "Searching google...(%d)" i)
427               (mm-url-insert more))))
428           ;; Return the articles in the right order.
429           (nnheader-message 7 "Searching google...done")
430           (setq nnweb-articles
431                 (sort nnweb-articles 'car-less-than-car))))))
432
433 (defun nnweb-google-search (search)
434   (mm-url-insert
435    (concat
436     (nnweb-definition 'address)
437     "?"
438     (mm-url-encode-www-form-urlencoded
439      `(("q" . ,search)
440        ("num" . "100")
441        ("hq" . "")
442        ("hl" . "en")
443        ("lr" . "")
444        ("safe" . "off")
445        ("sites" . "groups")
446        ("filter" . "0")))))
447   t)
448
449 (defun nnweb-google-identity (url)
450   "Return an unique identifier based on URL."
451   (if (string-match "selm=\\([^ &>]+\\)" url)
452       (match-string 1 url)
453     url))
454
455 ;;;
456 ;;; gmane.org
457 ;;;
458 (defun nnweb-gmane-create-mapping ()
459   "Perform the search and create a number-to-url alist."
460   (save-excursion
461     (set-buffer nnweb-buffer)
462     (let ((case-fold-search t)
463           (active (or (cadr (assoc nnweb-group nnweb-group-alist))
464                       (cons 1 0)))
465           map)
466       (erase-buffer)
467       (nnheader-message 7 "Searching Gmane..." )
468       (when (funcall (nnweb-definition 'search) nnweb-search)
469         (goto-char (point-min))
470         ;; Skip the status line
471         (forward-line 1)
472         ;; Thanks to Olly Betts we now have NOV lines in our buffer!
473         (while (not (eobp))
474           (unless (or (eolp) (looking-at "\x0d"))
475             (let ((header (nnheader-parse-nov)))
476               (let ((xref (mail-header-xref header))
477                     (from (mail-header-from header))
478                     (subject (mail-header-subject header))
479                     (rfc2047-encoding-type 'mime))
480                 (when (string-match " \\([^:]+\\):\\([0-9]+\\)" xref)
481                   (mail-header-set-xref
482                    header
483                    (format "http://article.gmane.org/%s/%s/raw"
484                            (match-string 1 xref)
485                            (match-string 2 xref))))
486
487                 ;; Add host part to gmane-encrypted addresses
488                 (when (string-match "@$" from)
489                   (mail-header-set-from header
490                                         (concat from "public.gmane.org")))
491
492                 (mail-header-set-subject header
493                                          (rfc2047-encode-string subject))
494
495                 (unless (nnweb-get-hashtb (mail-header-xref header))
496                   (push
497                    (list
498                     (incf (cdr active))
499                     header)
500                    map)
501                   (nnweb-set-hashtb (cadar map) (car map))))))
502           (forward-line 1)))
503       (nnheader-message 7 "Searching Gmane...done")
504       (setq nnweb-articles
505             (sort (nconc nnweb-articles map) 'car-less-than-car)))))
506
507 (defun nnweb-gmane-wash-article ()
508   (let ((case-fold-search t))
509     (goto-char (point-min))
510     (when (search-forward "<!--X-Head-of-Message-->" nil t)
511       (delete-region (point-min) (point))
512       (goto-char (point-min))
513       (while (looking-at "^<li><em>\\([^ ]+\\)</em>.*</li>")
514         (replace-match "\\1\\2" t)
515         (forward-line 1))
516       (mm-url-remove-markup))))
517
518 (defun nnweb-gmane-search (search)
519   (mm-url-insert
520    (concat
521     (nnweb-definition 'address)
522     "?"
523     (mm-url-encode-www-form-urlencoded
524      `(("query" . ,search)
525        ("HITSPERPAGE" . ,(number-to-string nnweb-max-hits))))))
526   (setq buffer-file-name nil)
527   (set-buffer-multibyte t)
528   (mm-decode-coding-region (point-min) (point-max) 'utf-8)
529   t)
530
531 (defun nnweb-gmane-identity (url)
532   "Return a unique identifier based on URL."
533   (if (string-match "group=\\(.+\\)" url)
534       (match-string 1 url)
535     url))
536
537 ;;;
538 ;;; General web/w3 interface utility functions
539 ;;;
540
541 (defun nnweb-insert-html (parse)
542   "Insert HTML based on a w3 parse tree."
543   (if (stringp parse)
544       (insert (nnheader-string-as-multibyte parse))
545     (insert "<" (symbol-name (car parse)) " ")
546     (insert (mapconcat
547              (lambda (param)
548                (concat (symbol-name (car param)) "="
549                        (prin1-to-string
550                         (if (consp (cdr param))
551                             (cadr param)
552                           (cdr param)))))
553              (nth 1 parse)
554              " "))
555     (insert ">\n")
556     (mapc 'nnweb-insert-html (nth 2 parse))
557     (insert "</" (symbol-name (car parse)) ">\n")))
558
559 (defun nnweb-parse-find (type parse &optional maxdepth)
560   "Find the element of TYPE in PARSE."
561   (catch 'found
562     (nnweb-parse-find-1 type parse maxdepth)))
563
564 (defun nnweb-parse-find-1 (type contents maxdepth)
565   (when (or (null maxdepth)
566             (not (zerop maxdepth)))
567     (when (consp contents)
568       (when (eq (car contents) type)
569         (throw 'found contents))
570       (when (listp (cdr contents))
571         (dolist (element contents)
572           (when (consp element)
573             (nnweb-parse-find-1 type element
574                                 (and maxdepth (1- maxdepth)))))))))
575
576 (defun nnweb-parse-find-all (type parse)
577   "Find all elements of TYPE in PARSE."
578   (catch 'found
579     (nnweb-parse-find-all-1 type parse)))
580
581 (defun nnweb-parse-find-all-1 (type contents)
582   (let (result)
583     (when (consp contents)
584       (if (eq (car contents) type)
585           (push contents result)
586         (when (listp (cdr contents))
587           (dolist (element contents)
588             (when (consp element)
589               (setq result
590                     (nconc result (nnweb-parse-find-all-1 type element))))))))
591     result))
592
593 (defvar nnweb-text)
594 (defun nnweb-text (parse)
595   "Return a list of text contents in PARSE."
596   (let ((nnweb-text nil))
597     (nnweb-text-1 parse)
598     (nreverse nnweb-text)))
599
600 (defun nnweb-text-1 (contents)
601   (dolist (element contents)
602     (if (stringp element)
603         (push element nnweb-text)
604       (when (and (consp element)
605                  (listp (cdr element)))
606         (nnweb-text-1 element)))))
607
608 (provide 'nnweb)
609
610 ;;; arch-tag: f59307eb-c90f-479f-b7d2-dbd8bf51b697
611 ;;; nnweb.el ends here