BrowserView.js
[app.webkitpdf] / BrowserView.js
1 Gtk = imports.gi.Gtk;
2 GLib = imports.gi.GLib;
3 WebKit = imports.gi.WebKit;
4 Soup = imports.gi.Soup;
5
6 TabbedBrowser = imports.TabbedBrowser;
7 BrowserSettings = imports.BrowserSettings;
8 BrowserTab = imports.BrowserTab;
9
10 File = imports.File.File;
11
12 base64 = imports.base64.base64;
13
14 BrowserView = new GType({
15     parent: WebKit.WebView.type,
16     name: "BrowserView",
17     init: function ()
18     {
19         // Private
20         
21         var sess  = WebKit.get_default_session();
22         sess.proxy_uri = new Soup.URI.c_new('http://localhost:3128');       
23         var _t = this;
24         
25         var tab = BrowserTab;
26         var browsePage = false;
27         var maxQueue = 0;
28         var injected = {};
29         
30         var current_url = '';
31  
32         var update_title = function (web_view, web_frame, title)
33         {
34             
35             print("calling update title");
36             if(title.length > 25)
37                 title = title.slice(0,25) + "...";
38
39             tab.get_tab_label().label = title;
40         };
41         
42         
43         
44            
45         
46         var traversedom = function(doc, fn, sub ) {
47             print("TRAVERSE DOM?");
48             sub = sub || 0;
49             
50             var ret = '<HTML>';
51             
52             var cb =  function(s) {
53                 //print("CB:" + s);
54                 ret+=s;
55             };
56             cb.fn = fn;
57             cb.sub = sub +1;
58             print(doc);
59             print(doc.head);
60             print (doc.body);
61             
62              //Roo.select('body > div',true).each(function(el) {
63             traverseDOMTree(cb, doc.head, 1);
64             traverseDOMTree(cb, doc.body, 1);
65            //print(ret);   
66             File.write(cb.fn.replace(/\.html$/, '')+ (sub ? ('.' + sub  ) : '') + '.html' , ret +'</HTML>');
67         
68         };
69          
70         
71         
72         var traverseDOMTree = function(cb, currentElement, depth) {
73             if (currentElement) {
74                 
75                 //if (currentElement.class_name.match(/roo-dynamic/)) {
76                 //    return;
77                 //}
78                 //print(currentElement.node_name);
79                 var j;
80                 var nodeName = currentElement.node_name;
81                 var tagName = currentElement.tag_name;
82                 
83                 if  (nodeName == '#text') {
84                     cb(currentElement.node_value);
85                     return;
86                 
87                 }
88                 if(nodeName == 'BR'){
89                     cb("<BR/>");
90                     return;
91                 }
92                
93                 if (nodeName == 'SCRIPT') {
94                      
95                     return;
96                 }
97                 //if (nodeName == 'STYLE') {  return; }
98                 var i = 0;
99               // Prints the node tagName, such as <A>, <IMG>, etc
100                 var outNodeName = nodeName;
101                 if (nodeName == 'IFRAME') {
102                     //outNodeName  = 'DIV';
103                 }
104                 if (tagName) {
105                     
106                     
107                     
108                     
109                     var attr = [];
110                     
111                     for(i = 0; i < currentElement.attributes.length;i++) {
112                         var aname = currentElement.attributes.item(i).name;
113                         //if (aname =='class' || aname == 'style') {
114                         //    continue;
115                         //}
116                         if (aname =='src' && tagName == 'IFRAME') {
117                             continue;
118                         }
119                         
120                         attr.push(aname + '="' + currentElement.attributes.item(i).value + '"' );
121                     }
122                     if (tagName == 'IFRAME') {
123                         attr.push('src="' + File.basename(cb.fn).replace(/\.html$/, '')+ '.' + cb.sub + '.html"' );
124                     }
125                     
126                     //if (nodeName == 'IFRAME') {
127                     //    attr.push('src="' + currentElement.attributes.item(i).value + embeded_file '"' );
128                     //}
129                     
130                     //var style = elClassToStyle(currentElement);
131                     //if (style.length) {
132                     //    attr.push('style="' + style + '"' );
133                     //}
134                     
135                     
136                     //if (depth > 1000 && (tagName == 'BODY' || tagName == 'HEAD' )) {
137                      //   cb("<DIV"+ ( attr.length ? (' ' + attr.join(' ') ) : '') + ">");
138                     //} else {
139                         cb("<"+outNodeName + ( attr.length ? (' ' + attr.join(' ') ) : '') + ">");
140                         
141                     //}
142                 } 
143                 else {
144                   cb("[unknown tag]");
145                 }
146                 
147                  if (nodeName == 'IFRAME') {
148                     
149                    
150                     traversedom(currentElement.content_document,  cb.fn,  cb.sub )
151                     cb.sub++;
152                     cb("</IFRAME>");
153                     return;
154                 }
155                 
156                 
157                 // Traverse the tree
158                 i = 0;
159                 var currentElementChild = currentElement.child_nodes.item(i);
160                 var allText = true;
161                 while (currentElementChild) {
162                     // Formatting code (indent the tree so it looks nice on the screen)
163                     
164                     if  (currentElementChild.node_name == '#text') {
165                        // if (currentElementChild.node_value.length) {
166                             cb(currentElementChild.node_value);
167                        // }
168                         
169                         i++;
170                         currentElementChild=currentElement.child_nodes.item(i);
171                         continue;
172                     }   
173                     allText = false;
174                     //cb("\n");
175                     //for (j = 0; j < depth; j++) {
176                       // &#166 is just a vertical line
177                     //  cb("  ");
178                     //}//               
179                     
180                         
181                     // Recursively traverse the tree structure of the child node
182                     traverseDOMTree(cb, currentElementChild, depth+1);
183                     i++;
184                     currentElementChild=currentElement.child_nodes.item(i);
185                 }
186                 if (!allText) {
187                     // The remaining code is mostly for formatting the tree
188                     //cb("\n");
189                     //for (j = 0; j < depth - 1; j++) {
190                       //cb("  ");
191                     //}     
192                 }
193                 if (tagName) {
194                    // if (depth > 1000 && (tagName == 'BODY' || tagName == 'HEAD' )) {
195                    //     cb("</DIV>");
196                    // } else {
197                         cb("</"+outNodeName+">");
198                    // }
199                     
200                 }
201             }
202         };
203         
204
205         var update_url = function (web_view, web_frame)
206         {
207             var toolbar = tab.get_toolbar();
208
209             toolbar.set_url(web_frame.get_uri());
210             toolbar.set_can_go_back(web_view.can_go_back());
211             toolbar.set_can_go_forward(web_view.can_go_forward());
212             
213             
214             
215             
216         };
217
218     
219       
220
221         var create_new_tab = function (web_view, web_frame, new_web_view)
222         {
223             new_web_view = new BrowserView();
224             new_web_view.signal.web_view_ready.connect(show_new_tab);
225             return new_web_view;
226         };
227
228         var show_new_tab = function (new_web_view)
229         {
230             TabbedBrowser.browser.new_tab("", new_web_view);
231
232             return false;
233         };
234
235         var hover_link = function (web_view, link, url)
236         {
237             tab.get_statusbar().set_status(url);
238         };
239          
240         /*
241         
242         this.add_inject = function(force)
243         {
244             
245             if (force || (typeof(injected[this.uri]) == 'undefined' )) {
246                 injected[this.uri] = 0;
247             }
248             if (injected[this.uri] > 2) {
249                 return;
250             }
251             injected[this.uri]++;
252             var fn = __script_path__ + "/inject.js";
253             if (File.exists(fn)) {
254 //                print("Adding inject");
255                 var newjs = File.read(__script_path__ + "/inject.js");
256                 TabbedBrowser.browser.current_tab().get_web_view().execute_script(
257                     newjs
258                     
259                 );
260             }
261             
262         }
263         */
264         var after_login = false;
265         
266         
267         var load_finished_called = false;
268         
269         var done_print = false;
270         var do_print = function(web_frame) {
271             
272             
273             if (done_print) {
274                 print("do_print called -- while already doing this...");
275                 return;
276             }
277             done_print = true;
278             print("do_print called");
279             
280             var scr_a =  " var r = document.getElementsByTagName('link');" +
281                 "for (var i=0;i < r.length;i++) { " +
282                     "var a = r[i]; " +
283                     "if (  a.getAttribute('media') == '')  { continue; } " +
284                     "if (  a.getAttribute('media') == 'screen')  { "+
285                         "a.removeAttribute('media'); continue;" +
286                     "} " +
287                     //"a.parentNode.removeChild(a);" +
288                 "}";
289             var scr_b =  "var a = document.body.querySelectorAll('*'); "+
290                 "var dnodes=[]; "+
291                 "for(var i =i;i<a.length;i++) { "+
292                 "   var cs = window.getComputedStyle(a[i],null);"+
293                 "   if ('none' == cs.display) {"+
294                 "    dnodes.push(a[i]); "+
295                 "  }"+ 
296                 "}"+
297                 "console.log(dnodes.length);" +
298                 "dnodes.forEach(function(n) { "+
299                 "    try {  n.parentNode.removeChild(n);   } catch(e) { } "+
300                 "});";
301             
302             
303             //TabbedBrowser.browser.current_tab().get_web_view().execute_script(
304             //    scr_a
305             //);
306             //print(scr_b);
307             //TabbedBrowser.browser.current_tab().get_web_view().execute_script(
308             //    scr_b
309             //);
310             
311             if (current_url.match(/\.coconuts\.co\//) ) {
312                 TabbedBrowser.browser.current_tab().get_web_view().execute_script(
313                     File.read( __script_path__ + "/domains/coconuts.co.js")
314                 );
315                               
316             }
317             if (current_url.match(/\.inquirer\.net\//) ) {
318                 print("add inquirer.net code");
319                 TabbedBrowser.browser.current_tab().get_web_view().execute_script(
320                     File.read( __script_path__ + "/domains/inquirer.net.js")
321                 );
322                               
323             }
324             
325             
326             // motorme - requires a scroll to make content appear..
327             if (current_url.match(/\.motorme\.my\//) ) {
328                 TabbedBrowser.browser.current_tab().get_web_view().execute_script("window.scrollTo(0,500);"); 
329                               
330             }
331             
332             if (current_url.match(/\.efytimes\.com\//) ||  current_url.match(/\/efytimes\.com\//) ) {
333                 TabbedBrowser.browser.current_tab().get_web_view().execute_script(
334                     File.read( __script_path__ + "/domains/efytimes.com.js")
335                 );
336             }
337             
338            
339             print("Delay:" + BrowserSettings.delay);
340          
341             GLib.timeout_add(GLib.PRIORITY_DEFAULT, BrowserSettings.delay *1, function() {
342                 
343                 try {
344                     
345                     if (current_url.match(/theindependent\.sg\//) ) {
346                         TabbedBrowser.browser.current_tab().get_web_view().execute_script(
347                             File.read( __script_path__ + "/domains/theindependent.sg.js")
348                         );
349                                       
350                     }
351                     print("FETCHING");
352                     //print(web_frame);
353                     if (web_frame &&  BrowserSettings.export_filename_html  ) {
354                         var html = traversedom(web_frame.get_dom_document(), BrowserSettings.export_filename_html);
355                         //File.write(BrowserSettings.export_filename_html, html);
356                         
357                     } 
358                      
359                     if (!BrowserSettings.export_filename) {
360                         if (!BrowserSettings.export_filename_html) {
361                              print("no export filename / and html filename");
362                             return;
363                         }
364                         
365                         Seed.quit();
366                     }
367                     var mf = _t.get_main_frame();
368                      
369                     print("Creating paper");
370                     var ar = Gtk.PaperSize.get_paper_sizes();
371                     var psetup = new Gtk.PageSetup();
372                     for(var i = 0; i < ar.length; i++) {
373                         if (ar[i].get_name() =='iso_a2') {
374                             psetup.set_paper_size(ar[i]);
375                         }
376                     }
377                     print("doing print operation");
378                     var p = new Gtk.PrintOperation({ export_filename : BrowserSettings.export_filename });
379                     print("doing print operation - set page"); 
380
381                     p.set_default_page_setup(psetup);
382                     
383                     print("doing print operation - print_full"); 
384                     mf.print_full(p, Gtk.PrintOperationAction.EXPORT);
385                     print("made image - exiting");
386                     
387                     Seed.quit();
388                     return true;
389                 } catch(e) {
390                     print("error occured");
391                     print(JSON.stringify(e));
392                 }
393             });
394         }
395         
396         
397         var weibo_added = false;
398         
399         var is_weibo = false;
400         
401         
402         var load_finished = function (webkit, web_frame, wb)
403         {
404             
405            
406             
407             if (!is_weibo) {
408                 do_print(web_frame);
409                 return;
410             }
411              
412              
413              print("load finished");
414              if (weibo_added) {
415                  
416                  if (after_login === true) {
417                      print("do print");
418                      do_print();
419                      return;
420                      
421                  }
422                  if (after_login === false) {
423                      return; // not here?
424                  }
425                  print("adding timeout?");
426                  //return;
427                 GLib.timeout_add(GLib.PRIORITY_LOW, 2000, function() {
428                     print("Redirecting after login?" + after_login);
429                     
430                     _t.browse(after_login);
431                     after_login  = true;
432                 });
433                 return;
434              }
435             
436             weibo_added = true;
437             TabbedBrowser.browser.current_tab().get_web_view().execute_script(
438                 File.read( __script_path__ + "/weibo.js") 
439             );
440             print("run_weibo(" + JSON.stringify( BrowserSettings.username ) + ", " + JSON.stringify(BrowserSettings.passwd) + ");");
441     
442             TabbedBrowser.browser.current_tab().get_web_view().execute_script(
443                     "run_weibo(" + JSON.stringify( BrowserSettings.username ) + ", " + JSON.stringify(BrowserSettings.passwd) + ");"
444             );
445             return;
446     
447             //    return;
448             print(after_login);
449             if (after_login !== false) {
450                 
451 //                return;
452                 // wait a bit then load the real page..
453                 GLib.timeout_add(GLib.PRIORITY_LOW, 500, function() {
454                     print("Redirecting after login?");
455                     _t.browse(after_login);
456                 });
457                 
458                 return;
459             }
460          
461             if (load_finished_called) {
462                 return ;
463             
464             }
465             load_finished_called = true;
466             
467           
468             
469 //            if(document.location.host=='weibo.com') {
470 //                // clear login dialog from weibo.
471 //                //check and hidden the login dialog and overlay .....
472 //                var els = document.querySelectorAll('div[node-type]');
473 //                var bbc = [];
474 //                for (i = 0; i < els.length; i++) {
475 //                    if (els[i].hasAttribute('node-type')) {
476 //                        if(els[i].getAttribute('node-type') == 'outer'){
477 //                            bbc.push(els[i]);
478 //                        }
479 //                    }
480 //                }
481 //                for (i = 0; i < bbc.length; i++) {// hide all the outer.....
482 //                    bbc[i].style.display = 'none';
483 //                }
484 //                
485 //                //try to login 
486 //                if(document.location.pathname == '/login.php'){
487 //                    
488 //                    // fills in the user name and password 
489 //                    var els = document.querySelectorAll('input[node-type]');
490 //                    
491 //                    for (i = 0; i < els.length; i++) {
492 //                        if (els[i].hasAttribute('node-type')) {
493 //                            if(els[i].getAttribute('node-type') == 'username'){
494 //                                els[i].value = BrowserSettings.username;
495 //                            }
496 //                            if(els[i].getAttribute('node-type') == 'password'){
497 //                                els[i].value = BrowserSettings.passwd;
498 //                            }
499 //                        }
500 //                    }
501 //                    
502 //                    
503 //                    // simulating click event to login ....
504 //                    var elss = document.querySelectorAll('a[node-type]');
505 //                    
506 //                    for (i = 0; i < elss.length; i++) {
507 //                        if (elss[i].hasAttribute('node-type')) {
508 //                            if(elss[i].getAttribute('node-type') == 'submitBtn'){
509 //                                elss[i].click();
510 //                            }
511 //                        }
512 //                    }
513 //                    
514 //                    
515 //                }
516 //                
517 //            }
518             
519             
520             // clear login dialog from weibo.
521 //            TabbedBrowser.browser.current_tab().get_web_view().execute_script(
522 //                " if (document.location.host=='weibo.com') { " +
523 //                " try {  " + 
524 //                " var a = document.getElementsByClassName('W_layer')[0]; " + 
525 //                " a.parentNode.removeChild(a.previousSibling); " + 
526 //                " a.parentNode.removeChild(a); " + 
527 //                " } catch(e) { }  } " );
528             
529             
530             return;
531             GLib.timeout_add(GLib.PRIORITY_LOW, BrowserSettings.delay, function() {
532                  
533                 var mf = _t.get_main_frame();
534                 
535                 var ar = Gtk.PaperSize.get_paper_sizes();
536                 var psetup = new Gtk.PageSetup();
537                 for(var i = 0; i < ar.length; i++) {
538                     if (ar[i].get_name() =='iso_a2') {
539                         psetup.set_paper_size(ar[i]);
540                     }
541                 }
542                 
543                 var p = new Gtk.PrintOperation({ export_filename : BrowserSettings.export_filename });
544                 p.set_default_page_setup(psetup);
545                 mf.print_full(p, Gtk.PrintOperationAction.EXPORT);
546                 print("made image - exiting");
547                 
548                 Seed.quit();
549                 return true;
550             });
551             
552             return;
553         };
554  
555  
556  
557         
558         var load_committed = function (web_view, web_frame)
559         {
560             print("load commited");
561             
562             update_url(web_view, web_frame);
563              
564             // call load finished after 20seconds??
565             // so even if it never complets we try and print the thing.
566             GLib.timeout_add(GLib.PRIORITY_LOW, 40000, function() {
567                 print("load commited - 3000 ms?");
568                 load_finished();
569             });
570             
571         };
572
573         var clicked_link = function (web_view, web_frame, request,
574                                      action, decision, window)
575         {
576             if(action.get_reason() == WebKit.WebNavigationReason.LINK_CLICKED &&
577                action.get_button() == 2)
578             {
579                 browser.new_tab(request.get_uri(), null);
580                 return true;
581             }
582
583             return false;
584         };
585
586         // Public
587         
588         
589         this.browse = function (url)
590         {
591             if(url.search("://") < 0)
592                 url = "http://" + url;
593             
594             current_url = url;
595             
596             print("BROWSE: " + url);
597             if (url.match(/\/weibo\.com\//) && after_login === false) {
598                 is_weibo = true;
599                 after_login = url;
600                 url = "http://weibo.com/login.php";
601             }
602             else  if (url.match(/\/weibo\.com\//) && after_login !== false) {
603                 after_login = false;
604             }
605             print("BROWSE -really: " + url);
606             this.open(url);
607         };
608
609         this.set_tab = function (new_tab)
610         {
611             tab = new_tab;
612         };
613
614         this.get_tab = function ()
615         {
616             return tab;
617         };
618
619     
620         // Implementation
621         //this.set_scroll_adjustments(null, null);
622         
623         //this.signal.title_changed.connect(update_title);
624         //this.signal.load_committed.connect(load_committed);
625         this.signal.load_finished.connect(load_finished);
626        
627         
628         // For some reason, this segfaults seed in the instance init closure handler
629         // Once that's fixed, uncommenting the next line will give middle-click-open-in-new tab
630         //this.signal.navigation_policy_decision_requested.connect(clicked_link);
631
632         //this.signal.hovering_over_link.connect(hover_link);
633
634         this.signal.create_web_view.connect(create_new_tab);
635         
636         
637          
638 //        print("ADDing console message sig handler");
639         
640         
641          
642         
643         this.toFilename = function(url)
644         {
645             url = url.replace(/^http[s]*:\/\//, '');
646             var p = url.split('/');
647             p.unshift(storedir+'/output');
648             for (var i =1 ;i < p.length; i++) {
649                 p[i] = encodeURIComponent(p[i]);
650             
651             }
652             p[p.length-1] = decodeURIComponent(p[p.length-1]);
653             ret = p.join('/');
654             var dir = File.dirname(ret);
655             File.mkdirall(dir);
656             return ret;
657             
658         }
659         this.checkdomain = function(comp)
660         {
661             var b = parseUri(this.uri);
662             var d = parseUri(comp);
663             return (d.host == b.host && d.protocol == b.protocol);
664             
665             
666         }
667         
668         this.dupeCheck = function(url)
669         {
670             
671            // order - return highest up the queue first..
672             if (File.exists(downloaddir +'/' + encodeURIComponent(url))) {
673                 return downloaddir +'/' + encodeURIComponent(url);
674             }
675              if (File.exists(parsedir +'/' + encodeURIComponent(url))) {
676                 return parsedir +'/' + encodeURIComponent(url);
677             }
678             if (File.exists(donedir +'/' + encodeURIComponent(url))) {
679                 return donedir +'/' + encodeURIComponent(url);
680             }
681             return  false;
682             
683             
684         }
685         this.moveToParse = function(url)
686         {
687             var old = this.dupeCheck(url);
688             var target =parsedir +'/' + encodeURIComponent(url);
689             if (old == target) {
690                 return;
691             }
692             File.write(target, old ? File.read(old) : '');
693             if (old) {
694                 File.remove(old);
695             }
696             
697         }
698         
699         this.moveToDownload= function(url)
700         {
701             var old = this.dupeCheck(url);
702             var target =downloaddir +'/' + encodeURIComponent(url);
703             if (old == target) {
704                 return;
705             }
706             File.write(target, old ? File.read(old) : '');
707             if (old) {
708                 File.remove(old);
709             }
710             
711         }
712         this.moveToDone= function(url)
713         {
714             var old = this.dupeCheck(url);
715             var target = donedir +'/' + encodeURIComponent(url);
716             if (old == target) {
717                 return;
718             }
719             File.write(target, old ? File.read(old) : '');
720             if (old) {
721                 File.remove(old);
722             }
723             
724         }
725         
726     }
727 });
728
729 function parseUri (str) {
730         var     o   = parseUri.options,
731                 m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
732                 uri = {},
733                 i   = 14;
734
735         while (i--) uri[o.key[i]] = m[i] || "";
736
737         uri[o.q.name] = {};
738         uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
739                 if ($1) uri[o.q.name][$1] = $2;
740         });
741
742         return uri;
743 };
744
745 parseUri.options = {
746         strictMode: false,
747         key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
748         q:   {
749                 name:   "queryKey",
750                 parser: /(?:^|&)([^&=]*)=?([^&]*)/g
751         },
752         parser: {
753                 strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
754                 loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
755         }
756 };