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