15583f13c41d6670719c0ad31615d6e96a935d8f
[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 (defvar 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     (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 "^<pre>" nil t)
318                         (re-search-forward "^</pre>" 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                      (1+ (re-search-forward "^<pre>" nil t)))
326       (goto-char (point-min))
327       (delete-region (- (re-search-forward "^</pre>" nil t) (length "</pre>"))
328                      (point-max))
329       (mm-url-decode-entities))))
330
331 (defun nnweb-google-parse-1 (&optional Message-ID)
332   "Parse search result in current buffer."
333   (let ((i 0)
334         (case-fold-search t)
335         (active (cadr (assoc nnweb-group nnweb-group-alist)))
336         Subject Score Date Newsgroups From
337         map url mid)
338     (unless active
339       (push (list nnweb-group (setq active (cons 1 0)))
340             nnweb-group-alist))
341     ;; Go through all the article hits on this page.
342     (goto-char (point-min))
343     (while
344         (re-search-forward
345          "a +href=\"/group/\\([^>\"]+\\)/browse_thread/[^>]+#\\([0-9a-f]+\\)"
346          nil t)
347       (setq Newsgroups (match-string-no-properties 1)
348             ;; Note: Starting with Google Groups 2, `mid' is a Google-internal
349             ;; ID, not a proper Message-ID.
350             mid (match-string-no-properties 2)
351             url (format
352                  (nnweb-definition 'result) Newsgroups mid))
353       (narrow-to-region (search-forward ">" nil t)
354                         (search-forward "</a>" nil t))
355       (mm-url-remove-markup)
356       (mm-url-decode-entities)
357       (setq Subject (buffer-string))
358       (goto-char (point-max))
359       (widen)
360       (narrow-to-region (point)
361                         (search-forward "</td" nil t))
362
363       (mm-url-remove-markup)
364       (mm-url-decode-entities)
365       (search-backward " - ")
366       (when (looking-at
367              " - \\([a-zA-Z]+\\) \\([0-9]+\\)\\(?: \\([0-9]\\{4\\}\\)\\)?, [^\n]+by \\([^<\n]+\\)\n")
368         (setq From (match-string 4)
369               Date (format "%s %s 00:00:00 %s"
370                            (match-string 1)
371                            (match-string 2)
372                            (or (match-string 3)
373                                (substring (current-time-string) -4)))))
374
375       (widen)
376       (forward-line 1)
377       (incf i)
378       (unless (nnweb-get-hashtb url)
379         (push
380          (list
381           (incf (cdr active))
382           (make-full-mail-header
383            (cdr active) (if Newsgroups
384                             (concat  "(" Newsgroups ") " Subject)
385                           Subject)
386            From Date (or Message-ID mid)
387            nil 0 0 url))
388          map)
389         (nnweb-set-hashtb (cadar map) (car map))))
390     map))
391
392 (defun nnweb-google-reference (id)
393   (let ((map (nnweb-google-parse-1 id)) header)
394     (setq nnweb-articles
395           (nconc nnweb-articles map))
396     (when (setq header (cadar map))
397       (mm-with-unibyte-current-buffer
398         (mm-url-insert (mail-header-xref header)))
399       (caar map))))
400
401 (defun nnweb-google-create-mapping ()
402   "Perform the search and create a number-to-url alist."
403   (save-excursion
404     (set-buffer nnweb-buffer)
405     (erase-buffer)
406     (when (funcall (nnweb-definition 'search) nnweb-search)
407         (let ((more t)
408               (i 0))
409           (while more
410             (setq nnweb-articles
411                   (nconc nnweb-articles (nnweb-google-parse-1)))
412             ;; Check if there are more articles to fetch
413             (goto-char (point-min))
414             (incf i 100)
415             (if (or (not (re-search-forward
416                           "<td><a href=\"\n\\([^>\"]+\\)\"><img src=\"/img/nav_next" nil t))
417                     (>= i nnweb-max-hits))
418                 (setq more nil)
419               ;; Yup, there are more articles
420               (setq more (concat (nnweb-definition 'base) (match-string 1)))
421             (when more
422               (erase-buffer)
423               (mm-url-insert more))))
424           ;; Return the articles in the right order.
425           (setq nnweb-articles
426                 (sort nnweb-articles 'car-less-than-car))))))
427
428 (defun nnweb-google-search (search)
429   (mm-url-insert
430    (concat
431     (nnweb-definition 'address)
432     "?"
433     (mm-url-encode-www-form-urlencoded
434      `(("q" . ,search)
435        ("num" . "100")
436        ("hq" . "")
437        ("hl" . "en")
438        ("lr" . "")
439        ("safe" . "off")
440        ("sites" . "groups")
441        ("filter" . "0")))))
442   t)
443
444 (defun nnweb-google-identity (url)
445   "Return an unique identifier based on URL."
446   (if (string-match "selm=\\([^ &>]+\\)" url)
447       (match-string 1 url)
448     url))
449
450 ;;;
451 ;;; gmane.org
452 ;;;
453 (defun nnweb-gmane-create-mapping ()
454   "Perform the search and create a number-to-url alist."
455   (save-excursion
456     (set-buffer nnweb-buffer)
457     (erase-buffer)
458     (when (funcall (nnweb-definition 'search) nnweb-search)
459       (let ((more t)
460             (case-fold-search t)
461             (active (or (cadr (assoc nnweb-group nnweb-group-alist))
462                         (cons 1 0)))
463             subject group url
464             map)
465           ;; Remove stuff from the beginning of results
466         (goto-char (point-min))
467         (search-forward "Search Results</h1><ul>" nil t)
468         (delete-region (point-min) (point))
469         (goto-char (point-min))
470         ;; Iterate over the actual hits
471         (while (re-search-forward ".*href=\"\\([^\"]+\\)\">\\(.*\\)" nil t)
472             (setq url (concat "http://gmane.org/" (match-string 1)))
473             (setq subject (match-string 2))
474           (unless (nnweb-get-hashtb url)
475             (push
476              (list
477               (incf (cdr active))
478               (make-full-mail-header
479                (cdr active) (concat  "(" group ") " subject) nil nil
480                nil nil 0 0 url))
481              map)
482             (nnweb-set-hashtb (cadar map) (car map))))
483         ;; Return the articles in the right order.
484         (setq nnweb-articles
485               (sort (nconc nnweb-articles map) 'car-less-than-car))))))
486
487 (defun nnweb-gmane-wash-article ()
488   (let ((case-fold-search t))
489     (goto-char (point-min))
490     (search-forward "<!--X-Head-of-Message-->" nil t)
491     (delete-region (point-min) (point))
492     (goto-char (point-min))
493     (while (looking-at "^<li><em>\\([^ ]+\\)</em>.*</li>")
494       (replace-match "\\1\\2" t)
495       (forward-line 1))
496     (mm-url-remove-markup)))
497
498 (defun nnweb-gmane-search (search)
499   (mm-url-insert
500    (concat
501     (nnweb-definition 'address)
502     "?"
503     (mm-url-encode-www-form-urlencoded
504      `(("query" . ,search)))))
505   (setq buffer-file-name nil)
506   t)
507
508
509 (defun nnweb-gmane-identity (url)
510   "Return a unique identifier based on URL."
511   (if (string-match "group=\\(.+\\)" url)
512       (match-string 1 url)
513     url))
514
515 ;;;
516 ;;; General web/w3 interface utility functions
517 ;;;
518
519 (defun nnweb-insert-html (parse)
520   "Insert HTML based on a w3 parse tree."
521   (if (stringp parse)
522       (insert (nnheader-string-as-multibyte parse))
523     (insert "<" (symbol-name (car parse)) " ")
524     (insert (mapconcat
525              (lambda (param)
526                (concat (symbol-name (car param)) "="
527                        (prin1-to-string
528                         (if (consp (cdr param))
529                             (cadr param)
530                           (cdr param)))))
531              (nth 1 parse)
532              " "))
533     (insert ">\n")
534     (mapc 'nnweb-insert-html (nth 2 parse))
535     (insert "</" (symbol-name (car parse)) ">\n")))
536
537 (defun nnweb-parse-find (type parse &optional maxdepth)
538   "Find the element of TYPE in PARSE."
539   (catch 'found
540     (nnweb-parse-find-1 type parse maxdepth)))
541
542 (defun nnweb-parse-find-1 (type contents maxdepth)
543   (when (or (null maxdepth)
544             (not (zerop maxdepth)))
545     (when (consp contents)
546       (when (eq (car contents) type)
547         (throw 'found contents))
548       (when (listp (cdr contents))
549         (dolist (element contents)
550           (when (consp element)
551             (nnweb-parse-find-1 type element
552                                 (and maxdepth (1- maxdepth)))))))))
553
554 (defun nnweb-parse-find-all (type parse)
555   "Find all elements of TYPE in PARSE."
556   (catch 'found
557     (nnweb-parse-find-all-1 type parse)))
558
559 (defun nnweb-parse-find-all-1 (type contents)
560   (let (result)
561     (when (consp contents)
562       (if (eq (car contents) type)
563           (push contents result)
564         (when (listp (cdr contents))
565           (dolist (element contents)
566             (when (consp element)
567               (setq result
568                     (nconc result (nnweb-parse-find-all-1 type element))))))))
569     result))
570
571 (defvar nnweb-text)
572 (defun nnweb-text (parse)
573   "Return a list of text contents in PARSE."
574   (let ((nnweb-text nil))
575     (nnweb-text-1 parse)
576     (nreverse nnweb-text)))
577
578 (defun nnweb-text-1 (contents)
579   (dolist (element contents)
580     (if (stringp element)
581         (push element nnweb-text)
582       (when (and (consp element)
583                  (listp (cdr element)))
584         (nnweb-text-1 element)))))
585
586 (provide 'nnweb)
587
588 ;;; arch-tag: f59307eb-c90f-479f-b7d2-dbd8bf51b697
589 ;;; nnweb.el ends here