2006-04-30 Andreas Seltenreich <uwi7@rz.uni-karlsruhe.de>
[gnus] / 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
175                                            (mm-url-form-encode-xwfu art)))
176                          (mm-with-unibyte-current-buffer
177                            (mm-url-insert url))
178                          (if (nnweb-definition 'reference t)
179                              (setq article
180                                    (funcall (nnweb-definition
181                                              'reference) article)))))))
182         (unless nnheader-callback-function
183           (funcall (nnweb-definition 'article)))
184         (nnheader-report 'nnweb "Fetched article %s" article)
185         (cons group (and (numberp article) article))))))
186
187 (deffoo nnweb-close-server (&optional server)
188   (when (and (nnweb-server-opened server)
189              (gnus-buffer-live-p nnweb-buffer))
190     (save-excursion
191       (set-buffer nnweb-buffer)
192       (set-buffer-modified-p nil)
193       (kill-buffer nnweb-buffer)))
194   (nnoo-close-server 'nnweb server))
195
196 (deffoo nnweb-request-list (&optional server)
197   (nnweb-possibly-change-server nil server)
198   (save-excursion
199     (set-buffer nntp-server-buffer)
200     (nnmail-generate-active (list (assoc server nnweb-group-alist)))
201     t))
202
203 (deffoo nnweb-request-update-info (group info &optional server)
204   (nnweb-possibly-change-server group server))
205
206 (deffoo nnweb-asynchronous-p ()
207   nil)
208
209 (deffoo nnweb-request-create-group (group &optional server args)
210   (nnweb-possibly-change-server nil server)
211   (nnweb-request-delete-group group)
212   (push `(,group ,(cons 1 0)) nnweb-group-alist)
213   (nnweb-write-active)
214   t)
215
216 (deffoo nnweb-request-delete-group (group &optional force server)
217   (nnweb-possibly-change-server group server)
218   (gnus-pull group nnweb-group-alist t)
219   (nnweb-write-active)
220   (gnus-delete-file (nnweb-overview-file group))
221   t)
222
223 (nnoo-define-skeleton nnweb)
224
225 ;;; Internal functions
226
227 (defun nnweb-read-overview (group)
228   "Read the overview of GROUP and build the map."
229   (when (file-exists-p (nnweb-overview-file group))
230     (mm-with-unibyte-buffer
231       (nnheader-insert-file-contents (nnweb-overview-file group))
232       (goto-char (point-min))
233       (let (header)
234         (while (not (eobp))
235           (setq header (nnheader-parse-nov))
236           (forward-line 1)
237           (push (list (mail-header-number header)
238                       header (mail-header-xref header))
239                 nnweb-articles)
240           (nnweb-set-hashtb header (car nnweb-articles)))))))
241
242 (defun nnweb-write-overview (group)
243   "Write the overview file for GROUP."
244   (with-temp-file (nnweb-overview-file group)
245     (let ((articles nnweb-articles))
246       (while articles
247         (nnheader-insert-nov (cadr (pop articles)))))))
248
249 (defun nnweb-set-hashtb (header data)
250   (gnus-sethash (nnweb-identifier (mail-header-xref header))
251                 data nnweb-hashtb))
252
253 (defun nnweb-get-hashtb (url)
254   (gnus-gethash (nnweb-identifier url) nnweb-hashtb))
255
256 (defun nnweb-identifier (ident)
257   (funcall (nnweb-definition 'identifier) ident))
258
259 (defun nnweb-overview-file (group)
260   "Return the name of the overview file of GROUP."
261   (nnheader-concat nnweb-directory group ".overview"))
262
263 (defun nnweb-write-active ()
264   "Save the active file."
265   (gnus-make-directory nnweb-directory)
266   (with-temp-file (nnheader-concat nnweb-directory "active")
267     (prin1 `(setq nnweb-group-alist ',nnweb-group-alist) (current-buffer))))
268
269 (defun nnweb-read-active ()
270   "Read the active file."
271   (load (nnheader-concat nnweb-directory "active") t t t))
272
273 (defun nnweb-definition (type &optional noerror)
274   "Return the definition of TYPE."
275   (let ((def (cdr (assq type (assq nnweb-type nnweb-type-definition)))))
276     (when (and (not def)
277                (not noerror))
278       (error "Undefined definition %s" type))
279     def))
280
281 (defun nnweb-possibly-change-server (&optional group server)
282   (when server
283     (unless (nnweb-server-opened server)
284       (nnweb-open-server server))
285     (nnweb-init server))
286   (unless nnweb-group-alist
287     (nnweb-read-active))
288   (unless nnweb-hashtb
289     (setq nnweb-hashtb (gnus-make-hashtable 4095)))
290   (when group
291     (setq nnweb-group group)))
292
293 (defun nnweb-init (server)
294   "Initialize buffers and such."
295   (unless (gnus-buffer-live-p nnweb-buffer)
296     (setq nnweb-buffer
297           (save-excursion
298             (mm-with-unibyte
299               (nnheader-set-temp-buffer
300                (format " *nnweb %s %s %s*"
301                        nnweb-type nnweb-search server))
302               (current-buffer))))))
303
304 ;;;
305 ;;; groups.google.com
306 ;;;
307
308 (defun nnweb-google-wash-article ()
309   ;; We have Google's masked e-mail addresses here.  :-/
310   (let ((case-fold-search t)
311         (start-re "<pre>[\r\n ]*")
312         (end-re "[\r\n ]*</pre>"))
313     (goto-char (point-min))
314     (if (save-excursion
315           (or (re-search-forward "The requested message.*could not be found."
316                                  nil t)
317               (not (and (re-search-forward start-re nil t)
318                         (re-search-forward end-re nil t)))))
319         ;; FIXME: Don't know how to indicate "not found".
320         ;; Should this function throw an error?  --rsteib
321         (progn
322           (gnus-message 3 "Requested article not found")
323           (erase-buffer))
324       (delete-region (point-min)
325                      (re-search-forward start-re))
326       (goto-char (point-min))
327       (delete-region (progn
328                        (re-search-forward end-re)
329                        (match-beginning 0))
330                      (point-max))
331       (mm-url-decode-entities))))
332
333 (defun nnweb-google-parse-1 (&optional Message-ID)
334   "Parse search result in current buffer."
335   (let ((i 0)
336         (case-fold-search t)
337         (active (cadr (assoc nnweb-group nnweb-group-alist)))
338         Subject Score Date Newsgroups From
339         map url mid)
340     (unless active
341       (push (list nnweb-group (setq active (cons 1 0)))
342             nnweb-group-alist))
343     ;; Go through all the article hits on this page.
344     (goto-char (point-min))
345     (while
346         (re-search-forward
347          "a +href=\"/group/\\([^>\"]+\\)/browse_thread/[^>]+#\\([0-9a-f]+\\)"
348          nil t)
349       (setq Newsgroups (match-string-no-properties 1)
350             ;; Note: Starting with Google Groups 2, `mid' is a Google-internal
351             ;; ID, not a proper Message-ID.
352             mid (match-string-no-properties 2)
353             url (format
354                  (nnweb-definition 'result) Newsgroups mid))
355       (narrow-to-region (search-forward ">" nil t)
356                         (search-forward "</a>" nil t))
357       (mm-url-remove-markup)
358       (mm-url-decode-entities)
359       (setq Subject (buffer-string))
360       (goto-char (point-max))
361       (widen)
362       (narrow-to-region (point)
363                         (search-forward "</td" nil t))
364
365       (mm-url-remove-markup)
366       (mm-url-decode-entities)
367       (search-backward " - ")
368       (when (looking-at
369              " - \\([a-zA-Z]+\\) \\([0-9]+\\)\\(?: \\([0-9]\\{4\\}\\)\\)?, [^\n]+by \\([^<\n]+\\)\n")
370         (setq From (match-string 4)
371               Date (format "%s %s 00:00:00 %s"
372                            (match-string 1)
373                            (match-string 2)
374                            (or (match-string 3)
375                                (substring (current-time-string) -4)))))
376
377       (widen)
378       (forward-line 1)
379       (incf i)
380       (unless (nnweb-get-hashtb url)
381         (push
382          (list
383           (incf (cdr active))
384           (make-full-mail-header
385            (cdr active) (if Newsgroups
386                             (concat  "(" Newsgroups ") " Subject)
387                           Subject)
388            From Date (or Message-ID mid)
389            nil 0 0 url))
390          map)
391         (nnweb-set-hashtb (cadar map) (car map))))
392     map))
393
394 (defun nnweb-google-reference (id)
395   (let ((map (nnweb-google-parse-1 id)) header)
396     (setq nnweb-articles
397           (nconc nnweb-articles map))
398     (when (setq header (cadar map))
399       (mm-with-unibyte-current-buffer
400         (mm-url-insert (mail-header-xref header)))
401       (caar map))))
402
403 (defun nnweb-google-create-mapping ()
404   "Perform the search and create a number-to-url alist."
405   (save-excursion
406     (set-buffer nnweb-buffer)
407     (erase-buffer)
408     (nnheader-message 7 "Searching google...")
409     (when (funcall (nnweb-definition 'search) nnweb-search)
410         (let ((more t)
411               (i 0))
412           (while more
413             (setq nnweb-articles
414                   (nconc nnweb-articles (nnweb-google-parse-1)))
415             ;; Check if there are more articles to fetch
416             (goto-char (point-min))
417             (incf i 100)
418             (if (or (not (re-search-forward
419                           "<a href=\"\n\\([^>\" \n\t]+\\)[^<]*<img src=[^>]+next"
420                           nil t))
421                     (>= i nnweb-max-hits))
422                 (setq more nil)
423               ;; Yup, there are more articles
424               (setq more (concat (nnweb-definition 'base) (match-string 1)))
425             (when more
426               (erase-buffer)
427               (nnheader-message 7 "Searching google...(%d)" i)
428               (mm-url-insert more))))
429           ;; Return the articles in the right order.
430           (nnheader-message 7 "Searching google...done")
431           (setq nnweb-articles
432                 (sort nnweb-articles 'car-less-than-car))))))
433
434 (defun nnweb-google-search (search)
435   (mm-url-insert
436    (concat
437     (nnweb-definition 'address)
438     "?"
439     (mm-url-encode-www-form-urlencoded
440      `(("q" . ,search)
441        ("num" . "100")
442        ("hq" . "")
443        ("hl" . "en")
444        ("lr" . "")
445        ("safe" . "off")
446        ("sites" . "groups")
447        ("filter" . "0")))))
448   t)
449
450 (defun nnweb-google-identity (url)
451   "Return an unique identifier based on URL."
452   (if (string-match "selm=\\([^ &>]+\\)" url)
453       (match-string 1 url)
454     url))
455
456 ;;;
457 ;;; gmane.org
458 ;;;
459 (defun nnweb-gmane-create-mapping ()
460   "Perform the search and create a number-to-url alist."
461   (save-excursion
462     (set-buffer nnweb-buffer)
463     (let ((case-fold-search t)
464           (active (or (cadr (assoc nnweb-group nnweb-group-alist))
465                       (cons 1 0)))
466           map)
467       (erase-buffer)
468       (nnheader-message 7 "Searching Gmane..." )
469       (when (funcall (nnweb-definition 'search) nnweb-search)
470         (goto-char (point-min))
471         ;; Skip the status line
472         (forward-line 1)
473         ;; Thanks to Olly Betts we now have NOV lines in our buffer!
474         (while (not (eobp))
475           (unless (or (eolp) (looking-at "\x0d"))
476             (let ((header (nnheader-parse-nov)))
477               (let ((xref (mail-header-xref header))
478                     (from (mail-header-from header))
479                     (subject (mail-header-subject header))
480                     (rfc2047-encoding-type 'mime))
481                 (when (string-match " \\([^:]+\\):\\([0-9]+\\)" xref)
482                   (mail-header-set-xref
483                    header
484                    (format "http://article.gmane.org/%s/%s/raw"
485                            (match-string 1 xref)
486                            (match-string 2 xref))))
487
488                 ;; Add host part to gmane-encrypted addresses
489                 (when (string-match "@$" from)
490                   (mail-header-set-from header
491                                         (concat from "public.gmane.org")))
492
493                 (mail-header-set-subject header
494                                          (rfc2047-encode-string subject))
495
496                 (unless (nnweb-get-hashtb (mail-header-xref header))
497                   (push
498                    (list
499                     (incf (cdr active))
500                     header)
501                    map)
502                   (nnweb-set-hashtb (cadar map) (car map))))))
503           (forward-line 1)))
504       (nnheader-message 7 "Searching Gmane...done")
505       (setq nnweb-articles
506             (sort (nconc nnweb-articles map) 'car-less-than-car)))))
507
508 (defun nnweb-gmane-wash-article ()
509   (let ((case-fold-search t))
510     (goto-char (point-min))
511     (when (search-forward "<!--X-Head-of-Message-->" nil t)
512       (delete-region (point-min) (point))
513       (goto-char (point-min))
514       (while (looking-at "^<li><em>\\([^ ]+\\)</em>.*</li>")
515         (replace-match "\\1\\2" t)
516         (forward-line 1))
517       (mm-url-remove-markup))))
518
519 (defun nnweb-gmane-search (search)
520   (mm-url-insert
521    (concat
522     (nnweb-definition 'address)
523     "?"
524     (mm-url-encode-www-form-urlencoded
525      `(("query" . ,search)
526        ("HITSPERPAGE" . ,(number-to-string nnweb-max-hits))))))
527   (setq buffer-file-name nil)
528   (set-buffer-multibyte t)
529   (mm-decode-coding-region (point-min) (point-max) 'utf-8)
530   t)
531
532 (defun nnweb-gmane-identity (url)
533   "Return a unique identifier based on URL."
534   (if (string-match "group=\\(.+\\)" url)
535       (match-string 1 url)
536     url))
537
538 ;;;
539 ;;; General web/w3 interface utility functions
540 ;;;
541
542 (defun nnweb-insert-html (parse)
543   "Insert HTML based on a w3 parse tree."
544   (if (stringp parse)
545       (insert (nnheader-string-as-multibyte parse))
546     (insert "<" (symbol-name (car parse)) " ")
547     (insert (mapconcat
548              (lambda (param)
549                (concat (symbol-name (car param)) "="
550                        (prin1-to-string
551                         (if (consp (cdr param))
552                             (cadr param)
553                           (cdr param)))))
554              (nth 1 parse)
555              " "))
556     (insert ">\n")
557     (mapc 'nnweb-insert-html (nth 2 parse))
558     (insert "</" (symbol-name (car parse)) ">\n")))
559
560 (defun nnweb-parse-find (type parse &optional maxdepth)
561   "Find the element of TYPE in PARSE."
562   (catch 'found
563     (nnweb-parse-find-1 type parse maxdepth)))
564
565 (defun nnweb-parse-find-1 (type contents maxdepth)
566   (when (or (null maxdepth)
567             (not (zerop maxdepth)))
568     (when (consp contents)
569       (when (eq (car contents) type)
570         (throw 'found contents))
571       (when (listp (cdr contents))
572         (dolist (element contents)
573           (when (consp element)
574             (nnweb-parse-find-1 type element
575                                 (and maxdepth (1- maxdepth)))))))))
576
577 (defun nnweb-parse-find-all (type parse)
578   "Find all elements of TYPE in PARSE."
579   (catch 'found
580     (nnweb-parse-find-all-1 type parse)))
581
582 (defun nnweb-parse-find-all-1 (type contents)
583   (let (result)
584     (when (consp contents)
585       (if (eq (car contents) type)
586           (push contents result)
587         (when (listp (cdr contents))
588           (dolist (element contents)
589             (when (consp element)
590               (setq result
591                     (nconc result (nnweb-parse-find-all-1 type element))))))))
592     result))
593
594 (defvar nnweb-text)
595 (defun nnweb-text (parse)
596   "Return a list of text contents in PARSE."
597   (let ((nnweb-text nil))
598     (nnweb-text-1 parse)
599     (nreverse nnweb-text)))
600
601 (defun nnweb-text-1 (contents)
602   (dolist (element contents)
603     (if (stringp element)
604         (push element nnweb-text)
605       (when (and (consp element)
606                  (listp (cdr element)))
607         (nnweb-text-1 element)))))
608
609 (provide 'nnweb)
610
611 ;;; arch-tag: f59307eb-c90f-479f-b7d2-dbd8bf51b697
612 ;;; nnweb.el ends here