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 queue_print = 0;
271         
272         
273         var load_started = function(fr)
274         {
275             print("load started");
276             
277         }
278         
279         
280         var do_print = function(web_frame) {
281             
282         
283             var realprint = function() {
284                 print("realprint called - queue is " + queue_print);
285                 if (queue_print > 0) {
286                     print("ignore print - queue is " + queue_print);
287                     queue_print--;
288                     return;
289                 }
290                 
291                 try {
292                     
293                     if (current_url.match(/theindependent\.sg\//) ) {
294                         TabbedBrowser.browser.current_tab().get_web_view().execute_script(
295                             File.read( __script_path__ + "/domains/theindependent.sg.js")
296                         );
297                                       
298                     }
299                     print("FETCHING");
300                     //print(web_frame);
301                     if (web_frame &&  BrowserSettings.export_filename_html  ) {
302                         var html = traversedom(web_frame.get_dom_document(), BrowserSettings.export_filename_html);
303                         //File.write(BrowserSettings.export_filename_html, html);
304                         
305                     } 
306                      
307                     if (!BrowserSettings.export_filename) {
308                         if (!BrowserSettings.export_filename_html) {
309                              print("no export filename / and html filename");
310                             return;
311                         }
312                         
313                         Seed.quit();
314                     }
315                     var mf = _t.get_main_frame();
316                      
317                     print("Creating paper");
318                     var ar = Gtk.PaperSize.get_paper_sizes();
319                     var psetup = new Gtk.PageSetup();
320                     for(var i = 0; i < ar.length; i++) {
321                         if (ar[i].get_name() =='iso_a2') {
322                             psetup.set_paper_size(ar[i]);
323                         }
324                     }
325                     print("doing print operation");
326                     var p = new Gtk.PrintOperation({ export_filename : BrowserSettings.export_filename });
327                     print("doing print operation - set page"); 
328
329                     p.set_default_page_setup(psetup);
330                     
331                     print("doing print operation - print_full"); 
332                     mf.print_full(p, Gtk.PrintOperationAction.EXPORT);
333                     print("made image - exiting");
334                     
335                     Seed.quit();
336                     return true;
337                 } catch(e) {
338                     print("error occured");
339                     print(JSON.stringify(e));
340                 }
341             };
342          
343             
344             
345             if (done_print) {
346                 queue_print++;
347                 print("do_print called -- while already doing this... - restarting queue...");
348                 GLib.timeout_add(GLib.PRIORITY_DEFAULT, BrowserSettings.delay *1, realprint);
349                 
350                 return;
351             }
352             done_print = true;
353             print("do_print called");
354             
355         
356             TabbedBrowser.browser.current_tab().get_web_view().execute_script(
357                     File.read( __script_path__ + "/domains/remove_print_css.js")
358             );
359             
360             var url_p = current_url.split('/');
361             var dom = url_p[2];
362             var dom_p = url_p[2].split('.');
363             var chk = dom_p.pop();
364             chk = dom_p.pop() + '.' + chk;
365             
366             
367             
368             print("CHECK: " + chk +"\n");
369             if (File.exists( __script_path__ + "/domains/" + chk + '.js')) {
370                 print("INCLUDING: " + __script_path__ + "/domains/"+ chk + ".js\n");
371                 TabbedBrowser.browser.current_tab().get_web_view().execute_script(
372                     File.read( __script_path__ + "/domains/"+ chk + ".js")
373                 );
374             }
375              
376             
377             // motorme - requires a scroll to make content appear..
378             if (current_url.match(/\.motorme\.my\//) ) {
379                 TabbedBrowser.browser.current_tab().get_web_view().execute_script("window.scrollTo(0,500);"); 
380                               
381             }
382             
383            
384             print("Delay:" + BrowserSettings.delay);
385          
386          
387          
388             GLib.timeout_add(GLib.PRIORITY_DEFAULT, BrowserSettings.delay *1, realprint);
389         }
390         
391         
392         var weibo_added = false;
393         
394         var is_weibo = false;
395         
396         
397         var load_finished = function (webkit, web_frame, wb)
398         {
399             
400            
401             
402             if (!is_weibo) {
403                 do_print(web_frame);
404                 return;
405             }
406              
407              
408              print("load finished");
409              if (weibo_added) {
410                  
411                  if (after_login === true) {
412                      print("do print");
413                      do_print();
414                      return;
415                      
416                  }
417                  if (after_login === false) {
418                      return; // not here?
419                  }
420                  print("adding timeout?");
421                  //return;
422                 GLib.timeout_add(GLib.PRIORITY_LOW, 2000, function() {
423                     print("Redirecting after login?" + after_login);
424                     
425                     _t.browse(after_login);
426                     after_login  = true;
427                 });
428                 return;
429              }
430             
431             weibo_added = true;
432             TabbedBrowser.browser.current_tab().get_web_view().execute_script(
433                 File.read( __script_path__ + "/weibo.js") 
434             );
435             print("run_weibo(" + JSON.stringify( BrowserSettings.username ) + ", " + JSON.stringify(BrowserSettings.passwd) + ");");
436     
437             TabbedBrowser.browser.current_tab().get_web_view().execute_script(
438                     "run_weibo(" + JSON.stringify( BrowserSettings.username ) + ", " + JSON.stringify(BrowserSettings.passwd) + ");"
439             );
440             return;
441     
442             //    return;
443             print(after_login);
444             if (after_login !== false) {
445                 
446 //                return;
447                 // wait a bit then load the real page..
448                 GLib.timeout_add(GLib.PRIORITY_LOW, 500, function() {
449                     print("Redirecting after login?");
450                     _t.browse(after_login);
451                 });
452                 
453                 return;
454             }
455          
456             if (load_finished_called) {
457                 return ;
458             
459             }
460             load_finished_called = true;
461             
462           
463                
464         };
465  
466  
467  
468         
469         var load_committed = function (web_view, web_frame)
470         {
471             print("load commited");
472             
473             update_url(web_view, web_frame);
474              
475             // call load finished after 20seconds??
476             // so even if it never complets we try and print the thing.
477             GLib.timeout_add(GLib.PRIORITY_LOW, 40000, function() {
478                 print("load commited - 3000 ms?");
479                 load_finished();
480             });
481             
482         };
483
484         var clicked_link = function (web_view, web_frame, request,
485                                      action, decision, window)
486         {
487             if(action.get_reason() == WebKit.WebNavigationReason.LINK_CLICKED &&
488                action.get_button() == 2)
489             {
490                 browser.new_tab(request.get_uri(), null);
491                 return true;
492             }
493
494             return false;
495         };
496
497         // Public
498         
499         
500         this.browse = function (url)
501         {
502             if(url.search("://") < 0)
503                 url = "http://" + url;
504             
505             current_url = url;
506             
507             print("BROWSE: " + url);
508             if (url.match(/\/weibo\.com\//) && after_login === false) {
509                 is_weibo = true;
510                 after_login = url;
511                 url = "http://weibo.com/login.php";
512             }
513             else  if (url.match(/\/weibo\.com\//) && after_login !== false) {
514                 after_login = false;
515             }
516             print("BROWSE -really: " + url);
517             this.open(url);
518         };
519
520         this.set_tab = function (new_tab)
521         {
522             tab = new_tab;
523         };
524
525         this.get_tab = function ()
526         {
527             return tab;
528         };
529
530     
531         // Implementation
532         //this.set_scroll_adjustments(null, null);
533         
534         //this.signal.title_changed.connect(update_title);
535         //this.signal.load_committed.connect(load_committed);
536         this.signal.load_finished.connect(load_finished);
537         this.signal.load_started.connect(load_started);
538        
539         
540         // For some reason, this segfaults seed in the instance init closure handler
541         // Once that's fixed, uncommenting the next line will give middle-click-open-in-new tab
542         //this.signal.navigation_policy_decision_requested.connect(clicked_link);
543
544         //this.signal.hovering_over_link.connect(hover_link);
545
546         this.signal.create_web_view.connect(create_new_tab);
547         
548         
549          
550 //        print("ADDing console message sig handler");
551         
552         
553          
554         
555         this.toFilename = function(url)
556         {
557             url = url.replace(/^http[s]*:\/\//, '');
558             var p = url.split('/');
559             p.unshift(storedir+'/output');
560             for (var i =1 ;i < p.length; i++) {
561                 p[i] = encodeURIComponent(p[i]);
562             
563             }
564             p[p.length-1] = decodeURIComponent(p[p.length-1]);
565             ret = p.join('/');
566             var dir = File.dirname(ret);
567             File.mkdirall(dir);
568             return ret;
569             
570         }
571         this.checkdomain = function(comp)
572         {
573             var b = parseUri(this.uri);
574             var d = parseUri(comp);
575             return (d.host == b.host && d.protocol == b.protocol);
576             
577             
578         }
579         
580         this.dupeCheck = function(url)
581         {
582             
583            // order - return highest up the queue first..
584             if (File.exists(downloaddir +'/' + encodeURIComponent(url))) {
585                 return downloaddir +'/' + encodeURIComponent(url);
586             }
587              if (File.exists(parsedir +'/' + encodeURIComponent(url))) {
588                 return parsedir +'/' + encodeURIComponent(url);
589             }
590             if (File.exists(donedir +'/' + encodeURIComponent(url))) {
591                 return donedir +'/' + encodeURIComponent(url);
592             }
593             return  false;
594             
595             
596         }
597         this.moveToParse = function(url)
598         {
599             var old = this.dupeCheck(url);
600             var target =parsedir +'/' + encodeURIComponent(url);
601             if (old == target) {
602                 return;
603             }
604             File.write(target, old ? File.read(old) : '');
605             if (old) {
606                 File.remove(old);
607             }
608             
609         }
610         
611         this.moveToDownload= function(url)
612         {
613             var old = this.dupeCheck(url);
614             var target =downloaddir +'/' + encodeURIComponent(url);
615             if (old == target) {
616                 return;
617             }
618             File.write(target, old ? File.read(old) : '');
619             if (old) {
620                 File.remove(old);
621             }
622             
623         }
624         this.moveToDone= function(url)
625         {
626             var old = this.dupeCheck(url);
627             var target = donedir +'/' + encodeURIComponent(url);
628             if (old == target) {
629                 return;
630             }
631             File.write(target, old ? File.read(old) : '');
632             if (old) {
633                 File.remove(old);
634             }
635             
636         }
637         
638     }
639 });
640
641 function parseUri (str) {
642         var     o   = parseUri.options,
643                 m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
644                 uri = {},
645                 i   = 14;
646
647         while (i--) uri[o.key[i]] = m[i] || "";
648
649         uri[o.q.name] = {};
650         uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
651                 if ($1) uri[o.q.name][$1] = $2;
652         });
653
654         return uri;
655 };
656
657 parseUri.options = {
658         strictMode: false,
659         key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
660         q:   {
661                 name:   "queryKey",
662                 parser: /(?:^|&)([^&=]*)=?([^&]*)/g
663         },
664         parser: {
665                 strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
666                 loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
667         }
668 };