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