5600ad88e34e3e7181b156b6b36cba35e583e329
[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 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      (article . ignore)
58      (id . "http://groups.google.de/groups?selm=%s&output=gplain")
59      (reference . identity)
60      (map . nnweb-google-create-mapping)
61      (search . nnweb-google-search)
62      (address . "http://groups.google.de/groups")
63      (base    . "http://groups.google.de")
64      (identifier . nnweb-google-identity))
65     (dejanews ;; alias of google
66      (article . ignore)
67      (id . "http://groups.google.com/groups?selm=%s&output=gplain")
68      (reference . identity)
69      (map . nnweb-google-create-mapping)
70      (search . nnweb-google-search)
71      (address . "http://groups.google.com/groups")
72      (base    . "http://groups.google.com")
73      (identifier . nnweb-google-identity))
74     (gmane
75      (article . nnweb-gmane-wash-article)
76      (id . "http://gmane.org/view.php?group=%s")
77      (reference . identity)
78      (map . nnweb-gmane-create-mapping)
79      (search . nnweb-gmane-search)
80      (address . "http://gmane.org/")
81      (identifier . nnweb-gmane-identity)))
82   "Type-definition alist.")
83
84 (defvoo nnweb-search nil
85   "Search string to feed to Google.")
86
87 (defvoo nnweb-max-hits 999
88   "Maximum number of hits to display.")
89
90 (defvoo nnweb-ephemeral-p nil
91   "Whether this nnweb server is ephemeral.")
92
93 ;;; Internal variables
94
95 (defvoo nnweb-articles nil)
96 (defvoo nnweb-buffer nil)
97 (defvoo nnweb-group-alist nil)
98 (defvoo nnweb-group nil)
99 (defvoo nnweb-hashtb nil)
100
101 ;;; Interface functions
102
103 (nnoo-define-basics nnweb)
104
105 (deffoo nnweb-retrieve-headers (articles &optional group server fetch-old)
106   (nnweb-possibly-change-server group server)
107   (save-excursion
108     (set-buffer nntp-server-buffer)
109     (erase-buffer)
110     (let (article header)
111       (mm-with-unibyte-current-buffer
112         (while (setq article (pop articles))
113           (when (setq header (cadr (assq article nnweb-articles)))
114             (nnheader-insert-nov header))))
115       'nov)))
116
117 (deffoo nnweb-request-scan (&optional group server)
118   (nnweb-possibly-change-server group server)
119   (if nnweb-ephemeral-p
120       (setq nnweb-hashtb (gnus-make-hashtable 4095)))
121   (funcall (nnweb-definition 'map))
122   (unless nnweb-ephemeral-p
123     (nnweb-write-active)
124     (nnweb-write-overview group)))
125
126 (deffoo nnweb-request-group (group &optional server dont-check)
127   (nnweb-possibly-change-server nil server)
128   (when (and group
129              (not (equal group nnweb-group))
130              (not nnweb-ephemeral-p))
131     (setq nnweb-group group
132           nnweb-articles nil)
133     (let ((info (assoc group nnweb-group-alist)))
134       (when info
135         (setq nnweb-type (nth 2 info))
136         (setq nnweb-search (nth 3 info))
137         (unless dont-check
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 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) ,@args) 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   (nnweb-init server)
285   (when server
286     (unless (nnweb-server-opened server)
287       (nnweb-open-server 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     (when (and (not nnweb-ephemeral-p)
294                (equal group nnweb-group))
295       (nnweb-request-group group nil t))))
296
297 (defun nnweb-init (server)
298   "Initialize buffers and such."
299   (unless (gnus-buffer-live-p nnweb-buffer)
300     (setq nnweb-buffer
301           (save-excursion
302             (mm-with-unibyte
303               (nnheader-set-temp-buffer
304                (format " *nnweb %s %s %s*"
305                        nnweb-type nnweb-search server))
306               (current-buffer))))))
307
308 ;;;
309 ;;; Deja bought by google.com
310 ;;;
311
312 (defun nnweb-google-wash-article ()
313   (let ((case-fold-search t) url)
314     (goto-char (point-min))
315     (re-search-forward "^<pre>" nil t)
316     (narrow-to-region (point-min) (point))
317     (search-backward "<table " nil t 2)
318     (delete-region (point-min) (point))
319     (if (re-search-forward "Search Result [0-9]+" nil t)
320         (replace-match ""))
321     (if (re-search-forward "View complete thread ([0-9]+ articles?)" nil t)
322         (replace-match ""))
323     (goto-char (point-min))
324     (while (search-forward "<br>" nil t)
325       (replace-match "\n"))
326     (mm-url-remove-markup)
327     (goto-char (point-min))
328     (while (re-search-forward "^[ \t]*\n" nil t)
329       (replace-match ""))
330     (goto-char (point-max))
331     (insert "\n")
332     (widen)
333     (narrow-to-region (point) (point-max))
334     (search-forward "</pre>" nil t)
335     (delete-region (point) (point-max))
336     (mm-url-remove-markup)
337     (widen)))
338
339 (defun nnweb-google-parse-1 (&optional Message-ID)
340   (let ((i 0)
341         (case-fold-search t)
342         (active (cadr (assoc nnweb-group nnweb-group-alist)))
343         Subject Score Date Newsgroups From
344         map url mid)
345     (unless active
346       (push (list nnweb-group (setq active (cons 1 0))
347                   nnweb-type nnweb-search)
348             nnweb-group-alist))
349     ;; Go through all the article hits on this page.
350     (goto-char (point-min))
351     (while (re-search-forward
352             "a href=/groups\\(\\?[^ \">]*selm=\\([^ &\">]+\\)\\)" nil t)
353       (setq mid (match-string 2)
354             url (format
355                  (nnweb-definition 'id) mid))
356       (narrow-to-region (search-forward ">" nil t)
357                         (search-forward "</a>" nil t))
358       (mm-url-remove-markup)
359       (mm-url-decode-entities)
360       (setq Subject (buffer-string))
361       (goto-char (point-max))
362       (widen)
363       (forward-line 2)
364       (when (looking-at "<br><font[^>]+>")
365         (goto-char (match-end 0)))
366       (if (not (looking-at "<a[^>]+>"))
367           (skip-chars-forward " \t")
368         (narrow-to-region (point)
369                           (search-forward "</a>" nil t))
370         (mm-url-remove-markup)
371         (mm-url-decode-entities)
372         (setq Newsgroups (buffer-string))
373         (goto-char (point-max))
374         (widen)
375         (skip-chars-forward "- \t"))
376       (when (looking-at
377              "\\([0-9]+\\)[/ ]\\([A-Za-z]+\\)[/ ]\\([0-9]+\\)[ \t]*by[ \t]*\\([^<]*\\) - <a")
378         (setq From (match-string 4)
379               Date (format "%s %s 00:00:00 %s"
380                            (match-string 2) (match-string 1)
381                            (match-string 3))))
382       (forward-line 1)
383       (incf i)
384       (unless (nnweb-get-hashtb url)
385         (push
386          (list
387           (incf (cdr active))
388           (make-full-mail-header
389            (cdr active) (if Newsgroups
390                             (concat  "(" Newsgroups ") " Subject)
391                           Subject)
392            From Date (or Message-ID mid)
393            nil 0 0 url))
394          map)
395         (nnweb-set-hashtb (cadar map) (car map))))
396     map))
397
398 (defun nnweb-google-reference (id)
399   (let ((map (nnweb-google-parse-1 id)) header)
400     (setq nnweb-articles
401           (nconc nnweb-articles map))
402     (when (setq header (cadar map))
403       (mm-with-unibyte-current-buffer
404         (mm-url-insert (mail-header-xref header)))
405       (caar map))))
406
407 (defun nnweb-google-create-mapping ()
408   "Perform the search and create a number-to-url alist."
409   (save-excursion
410     (set-buffer nnweb-buffer)
411     (erase-buffer)
412     (when (funcall (nnweb-definition 'search) nnweb-search)
413         (let ((more t)
414               (i 0))
415           (while more
416             (setq nnweb-articles
417                   (nconc nnweb-articles (nnweb-google-parse-1)))
418             ;; Check if there are more articles to fetch
419             (goto-char (point-min))
420             (incf i 100)
421             (if (or (not (re-search-forward
422                           "<td nowrap><a href=\\([^>]+\\).*<span class=b>Next</span>" nil t))
423                     (>= i nnweb-max-hits))
424                 (setq more nil)
425               ;; Yup, there are more articles
426               (setq more (concat (nnweb-definition 'base) (match-string 1)))
427             (when more
428               (erase-buffer)
429               (mm-url-insert more))))
430           ;; Return the articles in the right order.
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   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     (erase-buffer)
463     (when (funcall (nnweb-definition 'search) nnweb-search)
464       (let ((more t)
465             (case-fold-search t)
466             (active (or (cadr (assoc nnweb-group nnweb-group-alist))
467                         (cons 1 0)))
468             subject group url
469             map)
470           ;; Remove stuff from the beginning of results
471         (goto-char (point-min))
472         (search-forward "Search Results</h1><ul>" nil t)
473         (delete-region (point-min) (point))
474         (goto-char (point-min))
475         ;; Iterate over the actual hits
476         (while (re-search-forward ".*href=\"\\([^\"]+\\)\">\\(.*\\)" nil t)
477             (setq url (concat "http://gmane.org/" (match-string 1)))
478             (setq subject (match-string 2))
479           (unless (nnweb-get-hashtb url)
480             (push
481              (list
482               (incf (cdr active))
483               (make-full-mail-header
484                (cdr active) (concat  "(" group ") " subject) nil nil
485                nil nil 0 0 url))
486              map)
487             (nnweb-set-hashtb (cadar map) (car map))))
488         ;; Return the articles in the right order.
489         (setq nnweb-articles
490               (sort (nconc nnweb-articles map) 'car-less-than-car))))))
491
492 (defun nnweb-gmane-wash-article ()
493   (let ((case-fold-search t))
494     (goto-char (point-min))
495     (search-forward "<!--X-Head-of-Message-->" nil t)
496     (delete-region (point-min) (point))
497     (goto-char (point-min))
498     (while (looking-at "^<li><em>\\([^ ]+\\)</em>.*</li>")
499       (replace-match "\\1\\2" t)
500       (forward-line 1))
501     (mm-url-remove-markup)))
502
503 (defun nnweb-gmane-search (search)
504   (mm-url-insert
505    (concat
506     (nnweb-definition 'address)
507     "?"
508     (mm-url-encode-www-form-urlencoded
509      `(("query" . ,search)))))
510   (setq buffer-file-name nil)
511   t)
512
513
514 (defun nnweb-gmane-identity (url)
515   "Return a unique identifier based on URL."
516   (if (string-match "group=\\(.+\\)" url)
517       (match-string 1 url)
518     url))
519
520 ;;;
521 ;;; General web/w3 interface utility functions
522 ;;;
523
524 (defun nnweb-insert-html (parse)
525   "Insert HTML based on a w3 parse tree."
526   (if (stringp parse)
527       (insert (nnheader-string-as-multibyte parse))
528     (insert "<" (symbol-name (car parse)) " ")
529     (insert (mapconcat
530              (lambda (param)
531                (concat (symbol-name (car param)) "="
532                        (prin1-to-string
533                         (if (consp (cdr param))
534                             (cadr param)
535                           (cdr param)))))
536              (nth 1 parse)
537              " "))
538     (insert ">\n")
539     (mapc 'nnweb-insert-html (nth 2 parse))
540     (insert "</" (symbol-name (car parse)) ">\n")))
541
542 (defun nnweb-parse-find (type parse &optional maxdepth)
543   "Find the element of TYPE in PARSE."
544   (catch 'found
545     (nnweb-parse-find-1 type parse maxdepth)))
546
547 (defun nnweb-parse-find-1 (type contents maxdepth)
548   (when (or (null maxdepth)
549             (not (zerop maxdepth)))
550     (when (consp contents)
551       (when (eq (car contents) type)
552         (throw 'found contents))
553       (when (listp (cdr contents))
554         (dolist (element contents)
555           (when (consp element)
556             (nnweb-parse-find-1 type element
557                                 (and maxdepth (1- maxdepth)))))))))
558
559 (defun nnweb-parse-find-all (type parse)
560   "Find all elements of TYPE in PARSE."
561   (catch 'found
562     (nnweb-parse-find-all-1 type parse)))
563
564 (defun nnweb-parse-find-all-1 (type contents)
565   (let (result)
566     (when (consp contents)
567       (if (eq (car contents) type)
568           (push contents result)
569         (when (listp (cdr contents))
570           (dolist (element contents)
571             (when (consp element)
572               (setq result
573                     (nconc result (nnweb-parse-find-all-1 type element))))))))
574     result))
575
576 (defvar nnweb-text)
577 (defun nnweb-text (parse)
578   "Return a list of text contents in PARSE."
579   (let ((nnweb-text nil))
580     (nnweb-text-1 parse)
581     (nreverse nnweb-text)))
582
583 (defun nnweb-text-1 (contents)
584   (dolist (element contents)
585     (if (stringp element)
586         (push element nnweb-text)
587       (when (and (consp element)
588                  (listp (cdr element)))
589         (nnweb-text-1 element)))))
590
591 (provide 'nnweb)
592
593 ;;; arch-tag: f59307eb-c90f-479f-b7d2-dbd8bf51b697
594 ;;; nnweb.el ends here