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