nmbug.js: Extract the Gmane article id and convert to a Message-ID
[nmhive.git] / nmbug.js
1 var nmbug_server = 'http://localhost:5000';
2
3 nmbug = {
4         show: function (message_id) {
5                 alert(message_id);
6         },
7 };
8
9 var _gmane_handler = {
10         regexp: /gmane[.]org/,
11         handle: function (callback) {
12                 var article = this._get_article();
13                 this._get_message_id(article, callback);
14         },
15         _article_from_url: function (url) {
16                 var regexp = new RegExp('http://article.gmane.org/([^/]+)/([0-9]+)');
17                 var match = regexp.exec(url);
18                 console.log('nmbug: get article from ' + url, match);
19                 if (match) {
20                         return {'group': match[1], 'id': parseInt(match[2])};
21                 }
22         },
23         _get_article: function () {
24                 var article = this._article_from_url(document.URL);
25                 var i = 0;
26                 for (var i = 0; !article && i < window.frames.length; i++) {
27                         article = this._article_from_url(window.frames[i].document.URL);
28                 }
29                 if (!article) {
30                         throw "Cannot extract an article from Gmane's " + document.URL;
31                 }
32                 return article;
33         },
34         _get_message_id: function (article, callback) {
35                 var url = [
36                         nmbug_server,
37                         'gmane',
38                         article.group,
39                         article.id,
40                 ].join('/');
41                 console.log('nmbug: get Message-ID from ' + url);
42                 var request = new XMLHttpRequest();
43                 request.onload = function () {
44                         var message_id = this.responseText;
45                         callback(message_id);
46                 };
47                 request.open('get', url, true);
48                 request.send();
49         },
50 };
51
52 var handlers = [
53         _gmane_handler,
54 ];
55
56 function _check_handler(handler) {
57         var match = handler.regexp.test(document.URL);
58         console.log('nmbug: testing', handler, match);
59         if (match) {
60                 console.log('nmbug: matched', handler);
61                 handler.handle(nmbug.show);
62         }
63         return match;  /* break after the first match */
64 }
65
66 function run() {
67         var matched = handlers.some(_check_handler);
68         if (!matched) {
69                 throw 'No handler for ' + document.URL;
70         }
71 }