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