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