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