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