TabbedBrowser.js
[app.wkmirror] / BrowserView.js
1 Gtk = imports.gi.Gtk;
2 GLib = imports.gi.GLib;
3 WebKit = imports.gi.WebKit;
4
5 TabbedBrowser = imports.TabbedBrowser;
6 File = imports.File.File;
7
8 base64 = imports.base64.base64;
9
10 BrowserView = new GType({
11     parent: WebKit.WebView.type,
12     name: "BrowserView",
13     init: function ()
14     {
15         // Private
16         
17         
18         var _t = this;
19         
20         var tab;
21         var browsePage = false;
22         var maxQueue = 0;
23         var injected = {};
24         
25         var storedir = '/home/alan/wkqueue';
26         if (!File.exists(storedir)) {
27             File.mkdir(storedir);
28         }
29         var parsedir = storedir + '/parse_queue';
30         var downloaddir = storedir + '/download_queue';
31         var donedir = storedir + '/downloaded_queue';
32         if (!File.exists(parsedir)) {
33             File.mkdir(parsedir);
34         }
35         if (!File.exists(downloaddir)) {
36             File.mkdir(downloaddir);
37         }
38         if (!File.exists(donedir)) {
39             File.mkdir(donedir);
40         }
41         
42         var update_title = function (web_view, web_frame, title)
43         {
44             if(title.length > 25)
45                 title = title.slice(0,25) + "...";
46
47             tab.get_tab_label().label = title;
48         };
49
50         var update_url = function (web_view, web_frame)
51         {
52             var toolbar = tab.get_toolbar();
53
54             toolbar.set_url(web_frame.get_uri());
55             toolbar.set_can_go_back(web_view.can_go_back());
56             toolbar.set_can_go_forward(web_view.can_go_forward());
57         };
58
59         var update_progress = function (bar, progress)
60         {
61             tab.get_toolbar().set_progress(progress / 100);
62         };
63
64         var create_new_tab = function (web_view, web_frame, new_web_view)
65         {
66             new_web_view = new BrowserView();
67             new_web_view.signal.web_view_ready.connect(show_new_tab);
68             return new_web_view;
69         };
70
71         var show_new_tab = function (new_web_view)
72         {
73             TabbedBrowser.browser.new_tab("", new_web_view);
74
75             return false;
76         };
77
78         var hover_link = function (web_view, link, url)
79         {
80             tab.get_statusbar().set_status(url);
81         };
82
83         
84         
85         
86         this.add_inject = function(force)
87         {
88             
89             if (force || (typeof(injected[this.uri]) == 'undefined' )) {
90                 injected[this.uri] = 0;
91             }
92             if (injected[this.uri] > 2) {
93                 return;
94             }
95             injected[this.uri]++;
96             var fn = __script_path__ + "/inject.js";
97             if (File.exists(fn)) {
98                 print("Adding inject");
99                 var newjs = File.read(__script_path__ + "/inject.js");
100                 TabbedBrowser.browser.current_tab().get_web_view().execute_script(
101                     newjs
102                     
103                 );
104             }
105             
106         }
107          this.add_nsinject = function(force)
108         {
109             
110             //if (force || (typeof(injected[this.uri]) == 'undefined' )) {
111             //    injected[this.uri] = 0;
112             //}
113             //if (injected[this.uri] > 2) {
114             //    return;
115             //}
116             //injected[this.uri]++;
117             var fn = __script_path__ + "/nsinject.js";
118             //if (File.exists(fn)) {
119                 print("Adding inject");
120                 var newjs = File.read(__script_path__ + "/nsinject.js");
121                 TabbedBrowser.browser.current_tab().get_web_view().execute_script(
122                     newjs
123                     
124                 );
125             //}
126             
127         }
128         
129         
130         
131         
132         
133         var load_finished = function ()
134         {
135             print("load finished");
136             
137             GLib.timeout_add(GLib.PRIORITY_LOW, 1000, function() { 
138                  
139                 var mf = _t.get_main_frame();
140                 
141                 var ar = Gtk.PaperSize.get_paper_sizes();
142                 var psetup = new Gtk.PageSetup();
143                 for(var i = 0; i < ar.length; i++) {
144                     if (ar[i].get_name() =='iso_a2') {
145                         psetup.set_paper_size(ar[i]);
146                     }
147                 }
148                 
149                 var p = new Gtk.PrintOperation({ export_filename : '/home/chris/test_pdf/test2.pdf' });
150                 p.set_default_page_setup(psetup);
151                 mf.print_full(p, Gtk.PrintOperationAction.EXPORT)
152                 //Seed.quit();
153             });
154             
155             return;
156             tab.get_toolbar().set_progress(0);
157             
158             _t.add_inject(true);
159           
160             _t.add_nsinject(true);
161               print(typeof(Seed.argv[2]));
162             if (Seed.argv[2] == null) {
163                 print("NEED ID!");
164                 Seed.quit();
165             
166             }
167             _t.nsdownloadNext(Seed.argv[2]  * 1)
168           
169             
170             if (browsePage) {
171                 print("onload: calling gather links");
172                 TabbedBrowser.browser.current_tab().get_web_view().execute_script(
173                     'BrowserMirror.gatherlinks();'
174                     
175                 );
176                 
177             }
178             
179             
180         };
181
182         var load_committed = function (web_view, web_frame)
183         {
184             update_url(web_view, web_frame);
185         };
186
187         var clicked_link = function (web_view, web_frame, request,
188                                      action, decision, window)
189         {
190             if(action.get_reason() == WebKit.WebNavigationReason.LINK_CLICKED &&
191                action.get_button() == 2)
192             {
193                 browser.new_tab(request.get_uri(), null);
194                 return true;
195             }
196
197             return false;
198         };
199
200         // Public
201         
202         
203         this.browse = function (url)
204         {
205             if(url.search("://") < 0)
206                 url = "http://" + url;
207
208             this.open(url);
209         };
210
211         this.set_tab = function (new_tab)
212         {
213             tab = new_tab;
214         };
215
216         this.get_tab = function ()
217         {
218             return tab;
219         };
220
221
222         this.downloadqueue = function()
223         {
224             var filesList = File.list(downloaddir);
225             print("DOWNLOAD QUEUE LENGTH: " + filesList.length);
226             if (!maxQueue || maxQueue < filesList.length) {
227                 maxQueue  = filesList.length;
228             }
229             
230             tab.get_toolbar().set_progress(filesList.length / Math.max(maxQueue, filesList.length ));
231             if (filesList == null || filesList.length == 0  ){
232                 
233                 return false;
234             }  
235             var url = decodeURIComponent(filesList[0]);
236             if (!this.checkdomain(url)) {
237                 print("SKIP (external domain) : " + url);
238                 File.remove(downloaddir + '/' + filesList[0]);
239                 return this.downloadqueue();
240                 
241             }
242             this.downloadhead( url);
243             return true;
244             
245         };
246         
247     
248         this.queuerun = function()
249         {
250             if (this.downloadqueue()) return true;
251             return this.parsequeue();
252         };
253         
254         this.parsequeue = function(){
255             var filesList = File.list(parsedir);
256             if (filesList == null || filesList.length == 0  ){
257                 return false;
258             } 
259             
260             browsePage = decodeURIComponent(filesList[0]);
261             print("parsing page:" + browsePage );
262             this.browse(browsePage);
263             
264              
265             
266             
267             
268             return true;
269         };
270         
271         
272         this.downloadpage = function(link){
273             print("calling download page: " + link);
274             _t.add_inject(); // just in case..
275                 //var url = File.read(__script_path__+"/downloadqueue/"+link);
276             this.execute_script(
277                 "BrowserMirror.downloadpage(" + JSON.stringify(link) +");"
278             );          
279                 
280             
281         };
282  
283         this.downloadhead = function(link){
284             print("calling download head: " + link);
285             _t.add_inject(); // just in case..
286                 //var url = File.read(__script_path__+"/downloadqueue/"+link);
287             this.execute_script(
288                 "BrowserMirror.downloadhead(" + JSON.stringify(link) +");"
289             );          
290                  
291         };
292         var nsqueue = false;
293         this.nsdownloadNext = function()
294         {
295             /*if (nsqueue === false) {
296                 nsqueue = [
297                            //282,273,285,395,271,272,278,394,402,279,432,280,284,281,433,437,404,444,151,152,1,283,287,288,418,407,398,449,147,150,131,149,443,148,411,405,415,417,416,406,408,399,410,409,412,400,155,133,124,157,118,183,450,434,301,435,130,286,162,292,431,161,290,146,145,158,159,120,137,128,139,163,293,160,289,291,141,140,138,142,144,110,401,156,154,153,170,167,295,166,294,277,425,164,165,168,296,169,297,113,171,119,180,300,176,175,172,302,299,
298                            //298,421,187,307,428,275,269,304,181,182,174,173,184,303,112,179,114,305,177,178,186,306,403,420,111,109,309,188,308,446,445,310,311,53,189,52,312,419,270,190,191,192,193,54,194,108,268,121,195,206,396,205,207,324,220,340,212,331,219,339,222,342,436,209,327,424,208,326,210,328,330,325,211,329,218,337,338,224,223,217,336,214,333,213,332,216,335,221,341,215,334,197,314,
299                             //196,313,198,316,201,320,317,204,323,203,322,202,321,200,319,199,318,346,58,267,393,265,391,438,264,390,261,387,262,388,260,386,266,392,413,414,263,389,347,225,343,227,345,226,344,422,228,348,237,358,231,352,229,349,351,233,354,238,359,360,239,361,230,350,232,353,234,355,439,236,357,240,362,235,356,254,380,257,383,259,385,255,381,256,448,382,258,384,374,252,375,376,251,373,378,429,430,379,253,244,366,247,
300                            //369,363,242,364,241,243,365,246,368,245,367,377,427,
301                            426,250,447,372,249,371,248,370,442,397,129,441,440,116,122,123,125,126,136,115,117,127
302                         ];
303             }
304             
305             if (!nsqueue.length) {
306                 print("DONE");
307                 return;
308             }
309             var pg = nsqueue.shift() ;
310             
311             
312             */
313             
314             //print(typeof(Seed.argv[2]));
315             if (!Seed.argv[2]) {
316                 print("NEED ID!");
317                 Seed.quit();
318             
319             }
320             var pg = Seed.argv[2]  * 1;
321             if ( File.exists( storedir+'/output/' + pg + '.csv')) {
322                 print("DONE : " + storedir+'/output/' + pg + '.csv');
323                 Seed.quit();
324                 return;
325             }
326             
327             var pd = JSON.parse(File.read('/home/alan/.nspasswd'));
328             
329             print("downloadnext : " + pg);
330             this.execute_script(
331                 'NS.login(' +  JSON.stringify(pd.username) + ',' + JSON.stringify(pd.password) + ',' + pg + ' );'
332                 
333             );
334             
335             
336             
337         }
338
339         // Implementation
340         //this.set_scroll_adjustments(null, null);
341         
342         this.signal.title_changed.connect(update_title);
343         this.signal.load_committed.connect(load_committed);
344         this.signal.load_finished.connect(load_finished);
345         this.signal.load_progress_changed.connect(update_progress);
346         
347         // For some reason, this segfaults seed in the instance init closure handler
348         // Once that's fixed, uncommenting the next line will give middle-click-open-in-new tab
349         //this.signal.navigation_policy_decision_requested.connect(clicked_link);
350
351         this.signal.hovering_over_link.connect(hover_link);
352
353         this.signal.create_web_view.connect(create_new_tab);
354         
355         
356          
357         print("ADDing console message sig handler");
358         
359         
360         
361         
362         this.signal.console_message.connect(function(wv, msg, line, sid) {
363             // print('BrowserView.js got ' + msg);
364             var methodname;
365             var ret;
366             try {
367                 ret = JSON.parse(msg);
368             
369             } catch(e) {
370                 print("GOT INVALID message:" + msg)
371                 return true;
372                 
373                 
374             }
375             print("got method : " + ret.method);
376             
377             if (ret.method == 'exit') {
378                 Seed.quit();
379             }
380             
381             
382             if (ret.method == 'nsdownloadpage'){
383                 try { 
384                     var mt = ret.contentType.split(';').shift();
385                 } catch( e) {
386                     print("INVALID CONTENT TYPE? \n" + JSON.stringify(ret));
387                     mt='';
388                 }
389                 
390                 switch(mt) {
391                    
392                     case '':
393                         print("CONSOLE GOT BLANK - call download next?");
394                           Seed.quit();
395                          //_t.nsdownloadNext();
396                        // _t.moveToDone(ret.requesturl);
397                         break;
398                     
399                     default:
400                         var info = false;
401                         var info_f = _t.dupeCheck(ret.requesturl);
402                         if (info_f) {
403                             info  = JSON.parse(File.read(info_f));
404                         }
405                          var target  = storedir+'/output/' + ret.filename 
406                          // flag it as done..
407                        
408                         
409                         
410                         
411                         
412                         //File.write(target ,decodeURIComponent(escape(base64.decode( ret.data))));
413                         print("GOT array sized: " + ret.data.length);
414                         
415                         File.writeBinaryArray(target,ret.data);
416                         print("Wrote to file: " + target);
417                         // get next..
418                         return true;
419                         //Seed.quit();
420                         //_t.nsdownloadNext();
421                         
422                         
423                         
424                         break;
425                 }
426                 return true; //???
427             }
428             
429             if (ret.method == 'gatherlinks'){
430                 // flag the page as parsed.
431                 
432                 if (browsePage) {
433                     _t.moveToDone(browsePage);
434                     
435                 }
436                 var sourcePage = browsePage;
437                 browsePage = false;
438                 print(typeof(ret.data));
439                 if (typeof(ret.data) != 'object' ) {
440                     print("GOT INVALID DATA?:" + JSON.stringify(ret,null,4));
441                     ret.data= [];
442                     
443                 }
444                 ret.data.forEach(function(ln) {
445                     if (!ln.href.match(/^http[s]*:\/\//)) {
446                         print("SKIP link: " + ln.href);
447                         return;
448                     }
449                     ln.href= ln.href.replace(/#.*$/,'');
450                     
451                     if (!_t.checkdomain(ln.href) ) {
452                         print("SKIP link (external domain): " + ln.href);
453                         return;
454                     }
455                     
456                     // this is just for our purposes..
457                     
458                     if (ln.href.match(/\/pages\/[0-9]+$/)) {
459                         print("SKIP link (ingore unnamed pages): " + ln.href);
460                         return;
461                     }
462                     
463                     
464                     
465                     var fn = encodeURIComponent(ln.href);
466                     
467                     var dupe  = _t.dupeCheck(ln.href);
468                     if (dupe) {
469                         
470                         if (dupe == downloaddir + '/'  + fn) {
471                             var info = JSON.parse(File.read(dupe));
472                             if (info && info.fromUrl && info.fromUrl.length > sourcePage.length) {
473                                 print("SKIP link (in queue already): " + ln.href);
474                                 return;
475                             }
476                             print("found a longer link for url")
477                         } else {
478                             print("SKIP link (in another queue): " + ln.href);
479                             return;
480                         }
481                     }
482                      
483                     File.write(downloaddir + '/'  + fn, JSON.stringify( {
484                         label : ln.label,
485                         fromURL : sourcePage
486                     })); // write an empyt file indicating it needs downloading..
487                 });         
488                 var filesList = File.list(downloaddir);
489             
490                 maxQueue =  filesList.length;
491             }
492             
493             if (ret.method == 'downloadpage'){
494                 // got the results from download page:
495                 // requesturl 
496                 // remove from downloadqueue.
497              
498                 
499                 //
500                 try { 
501                     var mt = ret.contentType.split(';').shift();
502                 } catch( e) {
503                     print("INVALID CONTENT TYPE? \n" + JSON.stringify(ret));
504                     mt='';
505                 }
506                 
507                 switch(mt) {
508                    
509                     case '':
510                         _t.moveToDone(ret.requesturl);
511                         break;
512                     
513                     default:
514                         var info = false;
515                         var info_f = _t.dupeCheck(ret.requesturl);
516                         if (info_f) {
517                             info  = JSON.parse(File.read(info_f));
518                         }
519                     
520                         _t.moveToDone(ret.requesturl);
521                         // flag it as done..
522                        
523                         // write it...
524                         var target  = _t.toFilename(ret.requesturl);
525                         if (info && info.fromURL) {
526                             var bn = decodeURIComponent(File.basename(target));
527                             target = _t.toFilename(info.fromURL+'/'+ bn);
528                         }
529                         
530                         
531                         
532                         
533                         //File.write(target ,decodeURIComponent(escape(base64.decode( ret.data))));
534                         print("GOT array sized: " + ret.data.length);
535                         
536                         File.writeBinaryArray(target,ret.data);
537                         print("Wrote to file: " + target);
538                         break;
539                 }
540                 
541                 // if it's HTML then add it to parse queue
542                 // otehrwise save it.. and run the queue again.
543                
544                 
545                 //File.write(storedir+"/parsequeue/"+Math.random(), msg);
546             }
547             
548            
549             if (ret.method == 'downloadhead'){
550                 // got the results from download page:
551                 // requesturl 
552                 // remove from downloadqueue.
553                 
554                 //
555                 try { 
556                     var mt = ret.contentType.split(';').shift();
557                 } catch( e) {
558                     print("INVALID CONTENT TYPE? \n" + JSON.stringify(ret));
559                     mt='';
560                 }
561                 
562                 switch(mt) {
563                     case 'text/html':
564                         // add to parse QUEUE..
565                         print("moving to parse queue");
566                         _t.moveToParse(ret.requesturl);
567                         break;
568                     // stuf we do not care about..
569                     case 'application/atom+xml':
570                     case '':
571                         print("moving to done queue");
572                          _t.moveToDone(ret.requesturl);
573                         break;
574                     
575                     default:
576                         print("calling download file");
577                         _t.downloadpage( ret.requesturl );
578                         // keep it on the queue..
579                         // do not run the queue..
580                         return true;
581                      
582                 }
583                 
584                 // if it's HTML then add it to parse queue
585                 // otehrwise save it.. and run the queue again.
586                
587                 
588                 //File.write(storedir+"/parsequeue/"+Math.random(), msg);
589             }
590             _t.queuerun();
591             
592             return true;
593         });
594         
595         
596         this.toFilename = function(url)
597         {
598             url = url.replace(/^http[s]*:\/\//, '');
599             var p = url.split('/');
600             p.unshift(storedir+'/output');
601             for (var i =1 ;i < p.length; i++) {
602                 p[i] = encodeURIComponent(p[i]);
603             
604             }
605             p[p.length-1] = decodeURIComponent(p[p.length-1]);
606             ret = p.join('/');
607             var dir = File.dirname(ret);
608             File.mkdirall(dir);
609             return ret;
610             
611         }
612         this.checkdomain = function(comp)
613         {
614             var b = parseUri(this.uri);
615             var d = parseUri(comp);
616             return (d.host == b.host && d.protocol == b.protocol);
617             
618             
619         }
620         
621         this.dupeCheck = function(url)
622         {
623             
624            // order - return highest up the queue first..
625             if (File.exists(downloaddir +'/' + encodeURIComponent(url))) {
626                 return downloaddir +'/' + encodeURIComponent(url);
627             }
628              if (File.exists(parsedir +'/' + encodeURIComponent(url))) {
629                 return parsedir +'/' + encodeURIComponent(url);
630             }
631             if (File.exists(donedir +'/' + encodeURIComponent(url))) {
632                 return donedir +'/' + encodeURIComponent(url);
633             }
634             return  false;
635             
636             
637         }
638         this.moveToParse = function(url)
639         {
640             var old = this.dupeCheck(url);
641             var target =parsedir +'/' + encodeURIComponent(url);
642             if (old == target) {
643                 return;
644             }
645             File.write(target, old ? File.read(old) : '');
646             if (old) {
647                 File.remove(old);
648             }
649             
650         }
651         
652         this.moveToDownload= function(url)
653         {
654             var old = this.dupeCheck(url);
655             var target =downloaddir +'/' + encodeURIComponent(url);
656             if (old == target) {
657                 return;
658             }
659             File.write(target, old ? File.read(old) : '');
660             if (old) {
661                 File.remove(old);
662             }
663             
664         }
665         this.moveToDone= function(url)
666         {
667             var old = this.dupeCheck(url);
668             var target = donedir +'/' + encodeURIComponent(url);
669             if (old == target) {
670                 return;
671             }
672             File.write(target, old ? File.read(old) : '');
673             if (old) {
674                 File.remove(old);
675             }
676             
677         }
678         
679     }
680 });
681
682 function parseUri (str) {
683         var     o   = parseUri.options,
684                 m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
685                 uri = {},
686                 i   = 14;
687
688         while (i--) uri[o.key[i]] = m[i] || "";
689
690         uri[o.q.name] = {};
691         uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
692                 if ($1) uri[o.q.name][$1] = $2;
693         });
694
695         return uri;
696 };
697
698 parseUri.options = {
699         strictMode: false,
700         key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
701         q:   {
702                 name:   "queryKey",
703                 parser: /(?:^|&)([^&=]*)=?([^&]*)/g
704         },
705         parser: {
706                 strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
707                 loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
708         }
709 };