home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / pluginy Firefox / 9866 / 9866.xpi / modules / samfind_modutils.jsm < prev   
Encoding:
Text File  |  2009-12-11  |  13.1 KB  |  513 lines

  1. //-------------------------------------------------------------------------------------------
  2. // Utils module.
  3. //-------------------------------------------------------------------------------------------
  4.  
  5. const Cc = Components.classes;
  6. const Ci = Components.interfaces;
  7.  
  8. var EXPORTED_SYMBOLS = ["samfind_modutils"];
  9.  
  10. var samfind_modutils =
  11. {
  12.     _io_service : null,
  13.     _pref_branch : null,
  14.  
  15.     _init : function()
  16.     {
  17.         samfind_modutils._io_service = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
  18.         samfind_modutils._pref_branch = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getBranch("samfind.");
  19.       },
  20.  
  21.     getWindow : function()
  22.     {
  23.         var wm = Cc["@mozilla.org/appshell/window-mediator;1"].getService(Ci.nsIWindowMediator);
  24.         return wm.getMostRecentWindow("navigator:browser");
  25.     },
  26.  
  27.     openTab : function(url, isWebsite, target, event)
  28.     {
  29.         var win = samfind_modutils.getWindow();
  30.         var browser = win.getBrowser();
  31.         //
  32.         var found = false;
  33.         for (var i=0; i<browser.mTabs.length; ++i)
  34.         {
  35.             var current_uri = browser.browsers[i].currentURI;
  36.             if (current_uri.spec == url || current_uri.spec == (url + "/"))
  37.             {
  38.                 browser.selectedTab = browser.mTabs[i];
  39.                 found = true;
  40.                 break;
  41.             }
  42.         }
  43.         //
  44.         if (!found)
  45.         {
  46.             var referrer = samfind_modutils._io_service.newURI("http://samfind.com", null, null);
  47.             var website_open = isWebsite ? samfind_modutils._pref_branch.getIntPref("websites.open") : 1;
  48.             switch (website_open)
  49.             {
  50.                 case 0:
  51.                     {
  52.                         win.open("about:blank");
  53.                         win = samfind_modutils.getWindow();
  54.                         browser = win.getBrowser();
  55.                         browser.loadURI(url, referrer);
  56.                     }
  57.                     break;
  58.                 case 1:
  59.                     {
  60.                         browser.selectedTab = browser.addTab(url, referrer);
  61.                     }
  62.                     break;
  63.                 case 2:
  64.                     {
  65.                         browser.loadURI(url, referrer);
  66.                     }
  67.                     break;
  68.             }
  69.             if (target != null)
  70.             {
  71.                 browser.selectedTab.setAttribute("samfindhome", target.getAttribute("homeurl"));
  72.             }
  73.         }
  74.         //
  75.         browser.selectedTab.focus();
  76.         //
  77.         if (event != null)
  78.         {
  79.             event.stopPropagation();
  80.         }
  81.         //
  82.         return browser.selectedTab;
  83.     },
  84.  
  85.     loadIframe : function(url, loadedObserver)
  86.     {
  87.         var win = samfind_modutils.getWindow();
  88.         var document = win.document;
  89.         var loader = document.createElement("iframe");
  90.         loader.setAttribute("id", "samfind-loader");
  91.         loader.setAttribute("collapsed", true);
  92.            loader.setAttribute("type", "content");
  93.         document.documentElement.appendChild(loader);
  94.         var webNav = loader.docShell.QueryInterface(Ci.nsIWebNavigation);
  95.         webNav.stop(Ci.nsIWebNavigation.STOP_ALL);
  96.         loader.addEventListener("load",
  97.                                 function(event)
  98.                                 {
  99.                                     win.setTimeout(function()
  100.                                     {
  101.                                         var loader = document.getElementById("samfind-loader");
  102.                                         if (loader == null)
  103.                                         {
  104.                                             return;
  105.                                         }
  106.                                         loader = document.documentElement.removeChild(loader);
  107.                                         loader = null;
  108.                                         if (url == "http://samfind.com/")
  109.                                         {
  110.                                             samfind_modutils.loadIframe("http://samfind.com/customize.php", loadedObserver);
  111.                                             return;
  112.                                         }
  113.                                         if (loadedObserver)
  114.                                         {
  115.                                             loadedObserver.iframeLoaded();
  116.                                         }
  117.                                     },
  118.                                     10);
  119.                                 },
  120.                                 true);
  121.         var referrer = samfind_modutils._io_service.newURI("http://samfind.com", null, null);
  122.         try
  123.         {
  124.             webNav.loadURI(url, 0, referrer, null, null);
  125.         }
  126.         catch (e)
  127.         {
  128.             loader = document.documentElement.removeChild(loader);
  129.             loader = null;
  130.         }
  131.         referrer = null;
  132.     },
  133.  
  134.     removeCachedEntry : function(url)
  135.     {
  136.         try
  137.         {
  138.             var cache_service = Cc["@mozilla.org/network/cache-service;1"].getService(Ci.nsICacheService);
  139.             var cache_session = cache_service.createSession("HTTP", 0, true);
  140.             var cache_entry = cache_session.openCacheEntry(url, Ci.nsICache.ACCESS_WRITE, false);
  141.             try
  142.             {
  143.                 cache_entry.file.remove(false);
  144.             }
  145.             catch (e)
  146.             {}
  147.             cache_entry.doom();
  148.             cache_entry.close();
  149.             cache_session = null;
  150.             cache_service = null;
  151.         }
  152.         catch (e)
  153.         {}
  154.     },
  155.  
  156.     loadXML : function(file)
  157.     {
  158.         var stream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance(Ci.nsIFileInputStream);
  159.         stream.init(file, 0x01, 0666, 0);
  160.         var len = stream.available();
  161.         var dom_parser = Cc["@mozilla.org/xmlextras/domparser;1"].createInstance(Ci.nsIDOMParser);
  162.         var dom = dom_parser.parseFromStream(stream, "UTF-8", len, "text/xml");
  163.         dom_parser = null;
  164.         stream.close();
  165.         stream = null;
  166.         return dom;
  167.     },
  168.  
  169.     saveXML : function(fileName, dom)
  170.     {
  171.         var file = Cc["@mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties).get("ProfD", Ci.nsIFile);
  172.         file.append(fileName);
  173.         var stream = Cc["@mozilla.org/network/file-output-stream;1"].createInstance(Ci.nsIFileOutputStream);
  174.         stream.init(file, 0x02 | 0x08 | 0x20, 0666, 0); // write, create, truncate, rw-rw-rw-
  175.         var dom_serializer = Cc["@mozilla.org/xmlextras/xmlserializer;1"].createInstance(Ci.nsIDOMSerializer);
  176.         dom_serializer.serializeToStream(dom, stream, "UTF-8");
  177.         dom_serializer = null;
  178.         stream.close();
  179.         stream = null;
  180.         file = null;
  181.     },
  182.  
  183.     setIntervalWithParams : function(win, func, delay)
  184.     {
  185.         if (typeof func == "function")
  186.         {
  187.             var l_args = Array.prototype.slice.call(arguments, 3); 
  188.             var l_func = (function(){func.apply(null, l_args);});
  189.             return win.setInterval(l_func, delay);
  190.         }
  191.         return win.setInterval(func, delay);
  192.     },
  193.  
  194.     setTimeoutWithParams : function(win, func, delay)
  195.     {
  196.         if (typeof func == "function")
  197.         {
  198.             var l_args = Array.prototype.slice.call(arguments, 3); 
  199.             var l_func = (function(){func.apply(null, l_args);});
  200.             return win.setTimeout(l_func, delay);
  201.         }
  202.         return win.setTimeout(func, delay);
  203.     },
  204.  
  205.     setXhrAbortTimeout : function(xhr, delay)
  206.     {
  207.         var timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
  208.         timer.initWithCallback({ notify : function() { samfind_modutils.abortXhr(xhr); } }, delay, Ci.nsITimer.TYPE_ONE_SHOT);
  209.         return timer;
  210.     },
  211.  
  212.     abortXhr : function(xhr)
  213.     {
  214.         try
  215.         {
  216.             if (xhr.readyState > 0 && xhr.readyState < 4)
  217.             {
  218.                 xhr.abort();
  219.             }
  220.         }
  221.         catch (e)
  222.         {}
  223.     },
  224.  
  225.     getLoginManager : function()
  226.     {
  227.         if (Cc["@mozilla.org/login-manager;1"])
  228.         {
  229.             return Cc["@mozilla.org/login-manager;1"].getService(Ci.nsILoginManager);
  230.         }
  231.         return null;
  232.     },
  233.  
  234.     getAuth : function(aHostname, aActionURL)
  235.     {
  236.         var login_manager = samfind_modutils.getLoginManager();
  237.         var logins = login_manager.findLogins({}, aHostname, aActionURL, null);
  238.         var auth = {};
  239.         for (var i=0; i<logins.length; i++)
  240.         {
  241.             auth.username = logins[i].username;
  242.             auth.password = logins[i].password;
  243.             break;
  244.         }
  245.         if (typeof auth.username == "undefined") auth.username = "";
  246.         if (typeof auth.password == "undefined") auth.password = "";
  247.         return auth;
  248.     },
  249.  
  250.     getRssUrl : function(aDocument)
  251.     {
  252.         try
  253.         {
  254.             var links = aDocument.getElementsByTagName("link");
  255.             for (var i=0; i<links.length; ++i)
  256.             {
  257.                 var link = links[i];
  258.                 if (link.getAttribute("rel") == "alternate")
  259.                 {
  260.                     var type = link.getAttribute("type");
  261.                     if (type == "application/rss+xml" || type == "application/atom+xml")
  262.                     {
  263.                         var href = link.getAttribute("href");
  264.                         if (href.indexOf("http") == -1)
  265.                         {
  266.                             var base_uri = aDocument.baseURIObject;
  267.                             if (href.charAt(0) == '/')
  268.                             {
  269.                                 href = base_uri.prePath + href;
  270.                             }
  271.                             else
  272.                             {
  273.                                 var spec =  base_uri.spec;
  274.                                 href = spec.substring(0, spec.lastIndexOf("/") + 1) + href;
  275.                             }
  276.                         }
  277.                         return href;
  278.                     }
  279.                 }
  280.             }
  281.         }
  282.         catch (e)
  283.         {}
  284.         return "";
  285.     },
  286.  
  287.     getSearchAcceleratorsText : function()
  288.     {
  289.         try
  290.         {
  291.             var file = Cc["@mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties).get("ProfD", Ci.nsIFile);
  292.             file.append("samfindsearchaccelerators.json");
  293.             if (file.exists())
  294.             {
  295.                 var stream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance(Ci.nsIFileInputStream);
  296.                 stream.init(file, 0x01, 0666, 0);
  297.                 stream.QueryInterface(Ci.nsILineInputStream);
  298.                 var line = {}, lines = [], hasmore;
  299.                 do {
  300.                     hasmore = stream.readLine(line);
  301.                     lines.push(line.value); 
  302.                 }
  303.                 while(hasmore);
  304.                 stream.close();
  305.                 return lines[0];
  306.             }
  307.         }
  308.         catch (e)
  309.         {}
  310.         return null;
  311.     },
  312.  
  313.     startPrivateBrowsing : function()
  314.     {
  315.         try
  316.         {
  317.             var pbs = Cc["@mozilla.org/privatebrowsing;1"].getService(Ci.nsIPrivateBrowsingService);
  318.             if (pbs.privateBrowsingEnabled == false)
  319.             {
  320.                  pbs.privateBrowsingEnabled = true;
  321.             }
  322.         }
  323.         catch (e)
  324.         {}
  325.     },
  326.  
  327.     stopPrivateBrowsing : function(event)
  328.     {
  329.         try
  330.         {
  331.             var pbs = Cc["@mozilla.org/privatebrowsing;1"].getService(Ci.nsIPrivateBrowsingService);
  332.             if (pbs.privateBrowsingEnabled)
  333.             {
  334.                  pbs.privateBrowsingEnabled = false;
  335.             }
  336.         }
  337.         catch (e)
  338.         {}
  339.         event.stopPropagation();
  340.     },
  341.  
  342.     isMacOSX : function()
  343.     {
  344.         var os = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime).OS;
  345.         return (os == "Darwin");
  346.     },
  347.  
  348.     isSidebarShown : function(document, commandId)
  349.     {
  350.         var sidebar_broadcaster = document.getElementById(commandId);
  351.         return (sidebar_broadcaster.getAttribute("checked") == "true");
  352.     },
  353.  
  354.     sendNotification : function(topic, data)
  355.     {
  356.         try
  357.         {
  358.             var observer_service = Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService);
  359.             observer_service.notifyObservers(null, topic, data);
  360.             observer_service = null;
  361.         }
  362.         catch (e)
  363.         {}
  364.     },
  365.  
  366.     arrayHas : function(a, el)
  367.     {
  368.         for (var i=0; i<a.length; ++i)
  369.         {
  370.             if (a[i] == el)
  371.             {
  372.                 return true;
  373.             }
  374.         }
  375.         return false;
  376.     },
  377.  
  378.     trim : function(text)
  379.     {
  380.         text = text.replace(/^\s\s*/, '');
  381.         text = text.replace(/\s\s*$/, '');
  382.         text = text.replace(/\n/g, " ");
  383.         text = text.replace(/\s+/, " ");
  384.         return text;
  385.     },
  386.  
  387.     checkSiteMenu : function(event, prefix)
  388.     {
  389.         var menupopup = event.target;
  390.         if (menupopup != event.currentTarget)
  391.         {
  392.             return;    
  393.         }
  394.         //
  395.         var sidesam_item = (menupopup.getElementsByAttribute("id", (prefix + "-sidesam")))[0];
  396.         if (sidesam_item != null)
  397.         {
  398.             var acceltext = samfind_modutils._pref_branch.getCharPref("sidesam.hotkey.modifiers") + "+" + samfind_modutils._pref_branch.getCharPref("sidesam.hotkey.key"); 
  399.             sidesam_item.setAttribute("acceltext", acceltext);
  400.         }
  401.         //
  402.         var register_item = (menupopup.getElementsByAttribute("id", (prefix + "-register")))[0];
  403.         if (register_item != null)
  404.         {
  405.             try
  406.             {
  407.                 if (samfind_modutils._pref_branch.getBoolPref("why.register"))
  408.                 {
  409.                     register_item.hidden = false;
  410.                 }
  411.             }
  412.             catch (e)
  413.             {
  414.                 register_item.hidden = true;    
  415.             }
  416.         }
  417.         //
  418.         var login_item = (menupopup.getElementsByAttribute("id", (prefix + "-login")))[0];
  419.         var logout_item = (menupopup.getElementsByAttribute("id", (prefix + "-logout")))[0];
  420.         if (login_item != null && logout_item != null)
  421.         {
  422.             if (samfind_modutils._pref_branch.getBoolPref("isuser"))
  423.             {
  424.                 login_item.hidden = true;
  425.                 logout_item.hidden = false;
  426.             }
  427.             else
  428.             {
  429.                 login_item.hidden = false;
  430.                 logout_item.hidden = true;
  431.             }
  432.         }
  433.         //
  434.         event.stopPropagation();
  435.     },
  436.  
  437.     clearMenupopup : function(menupopup)
  438.     {
  439.         while (menupopup.firstChild)
  440.         {
  441.             menupopup.removeChild(menupopup.firstChild);
  442.         }
  443.     },
  444.  
  445.     clearMenupopupByEvent : function(event)
  446.     {
  447.         var menupopup = event.target;
  448.         if (menupopup != event.currentTarget)
  449.         {
  450.             return;
  451.         }
  452.         samfind_modutils.clearMenupopup(menupopup);
  453.         event.stopPropagation();
  454.     },
  455.  
  456.     genGUID : function()
  457.     {
  458.         return (samfind_modutils.genS4()
  459.                 + samfind_modutils.genS4()
  460.                 + "-" + samfind_modutils.genS4()
  461.                 + "-" + samfind_modutils.genS4()
  462.                 + "-" + samfind_modutils.genS4()
  463.                 + "-" + samfind_modutils.genS4()
  464.                 + samfind_modutils.genS4()
  465.                 + samfind_modutils.genS4());
  466.     },
  467.  
  468.     genS4 : function()
  469.     {
  470.         return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  471.     },
  472.  
  473.     getTimestamp : function(time)
  474.     {
  475.         //--------------------------------------------------------------
  476.         // http://af-design.com/blog/2009/02/10/twitter-like-timestamps/
  477.         //--------------------------------------------------------------
  478.         var system_date = new Date(time);
  479.         var user_date = new Date();
  480.         var diff = Math.floor((user_date - system_date) / 1000);
  481.         if (diff <= 1) return "just now";
  482.         if (diff < 20) return diff + " seconds ago";
  483.         if (diff < 40) return "half a minute ago";
  484.         if (diff < 60) return "less than a minute ago";
  485.         if (diff <= 90) return "one minute ago";
  486.         if (diff <= 3540) return Math.round(diff / 60) + " minutes ago";
  487.         if (diff <= 5400) return "1 hour ago";
  488.         if (diff <= 86400) return Math.round(diff / 3600) + " hours ago";
  489.         if (diff <= 129600) return "1 day ago";
  490.         if (diff < 604800) return Math.round(diff / 86400) + " days ago";
  491.         if (diff <= 777600) return "1 week ago";
  492.         return "on " + time;
  493.     },
  494.  
  495.     getSelection : function(win)
  496.     {
  497.         var selection = win.content.getSelection();
  498.         if (selection == null)
  499.         {
  500.             selection = "";    
  501.         }
  502.         else
  503.         {
  504.             selection = selection.toString().replace(/^\s+/, "").replace(/\s+$/, "").replace(/\s+/g, " ");
  505.         }
  506.         return selection;
  507.     }
  508. };
  509.  
  510. /**
  511.  * Constructor.
  512.  */
  513. (function() { this._init(); }).apply(samfind_modutils);