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