home *** CD-ROM | disk | FTP | other *** search
- //-------------------------------------------------------------------------------------------
- // Utils module.
- //-------------------------------------------------------------------------------------------
-
- const Cc = Components.classes;
- const Ci = Components.interfaces;
-
- var EXPORTED_SYMBOLS = ["samfind_modutils"];
-
- var samfind_modutils =
- {
- _io_service : null,
- _pref_branch : null,
-
- _init : function()
- {
- samfind_modutils._io_service = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
- samfind_modutils._pref_branch = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getBranch("samfind.");
- },
-
- getWindow : function()
- {
- var wm = Cc["@mozilla.org/appshell/window-mediator;1"].getService(Ci.nsIWindowMediator);
- return wm.getMostRecentWindow("navigator:browser");
- },
-
- openTab : function(url, isWebsite, target, event)
- {
- var win = samfind_modutils.getWindow();
- var browser = win.getBrowser();
- //
- var found = false;
- for (var i=0; i<browser.mTabs.length; ++i)
- {
- var current_uri = browser.browsers[i].currentURI;
- if (current_uri.spec == url || current_uri.spec == (url + "/"))
- {
- browser.selectedTab = browser.mTabs[i];
- found = true;
- break;
- }
- }
- //
- if (!found)
- {
- var referrer = samfind_modutils._io_service.newURI("http://samfind.com", null, null);
- var website_open = isWebsite ? samfind_modutils._pref_branch.getIntPref("websites.open") : 1;
- switch (website_open)
- {
- case 0:
- {
- win.open("about:blank");
- win = samfind_modutils.getWindow();
- browser = win.getBrowser();
- browser.loadURI(url, referrer);
- }
- break;
- case 1:
- {
- browser.selectedTab = browser.addTab(url, referrer);
- }
- break;
- case 2:
- {
- browser.loadURI(url, referrer);
- }
- break;
- }
- if (target != null)
- {
- browser.selectedTab.setAttribute("samfindhome", target.getAttribute("homeurl"));
- }
- }
- //
- browser.selectedTab.focus();
- //
- if (event != null)
- {
- event.stopPropagation();
- }
- //
- return browser.selectedTab;
- },
-
- loadIframe : function(url, loadedObserver)
- {
- var win = samfind_modutils.getWindow();
- var document = win.document;
- var loader = document.createElement("iframe");
- loader.setAttribute("id", "samfind-loader");
- loader.setAttribute("collapsed", true);
- loader.setAttribute("type", "content");
- document.documentElement.appendChild(loader);
- var webNav = loader.docShell.QueryInterface(Ci.nsIWebNavigation);
- webNav.stop(Ci.nsIWebNavigation.STOP_ALL);
- loader.addEventListener("load",
- function(event)
- {
- win.setTimeout(function()
- {
- var loader = document.getElementById("samfind-loader");
- if (loader == null)
- {
- return;
- }
- loader = document.documentElement.removeChild(loader);
- loader = null;
- if (url == "http://samfind.com/")
- {
- samfind_modutils.loadIframe("http://samfind.com/customize.php", loadedObserver);
- return;
- }
- if (loadedObserver)
- {
- loadedObserver.iframeLoaded();
- }
- },
- 10);
- },
- true);
- var referrer = samfind_modutils._io_service.newURI("http://samfind.com", null, null);
- try
- {
- webNav.loadURI(url, 0, referrer, null, null);
- }
- catch (e)
- {
- loader = document.documentElement.removeChild(loader);
- loader = null;
- }
- referrer = null;
- },
-
- removeCachedEntry : function(url)
- {
- try
- {
- var cache_service = Cc["@mozilla.org/network/cache-service;1"].getService(Ci.nsICacheService);
- var cache_session = cache_service.createSession("HTTP", 0, true);
- var cache_entry = cache_session.openCacheEntry(url, Ci.nsICache.ACCESS_WRITE, false);
- try
- {
- cache_entry.file.remove(false);
- }
- catch (e)
- {}
- cache_entry.doom();
- cache_entry.close();
- cache_session = null;
- cache_service = null;
- }
- catch (e)
- {}
- },
-
- loadXML : function(file)
- {
- var stream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance(Ci.nsIFileInputStream);
- stream.init(file, 0x01, 0666, 0);
- var len = stream.available();
- var dom_parser = Cc["@mozilla.org/xmlextras/domparser;1"].createInstance(Ci.nsIDOMParser);
- var dom = dom_parser.parseFromStream(stream, "UTF-8", len, "text/xml");
- dom_parser = null;
- stream.close();
- stream = null;
- return dom;
- },
-
- saveXML : function(fileName, dom)
- {
- var file = Cc["@mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties).get("ProfD", Ci.nsIFile);
- file.append(fileName);
- var stream = Cc["@mozilla.org/network/file-output-stream;1"].createInstance(Ci.nsIFileOutputStream);
- stream.init(file, 0x02 | 0x08 | 0x20, 0666, 0); // write, create, truncate, rw-rw-rw-
- var dom_serializer = Cc["@mozilla.org/xmlextras/xmlserializer;1"].createInstance(Ci.nsIDOMSerializer);
- dom_serializer.serializeToStream(dom, stream, "UTF-8");
- dom_serializer = null;
- stream.close();
- stream = null;
- file = null;
- },
-
- setIntervalWithParams : function(win, func, delay)
- {
- if (typeof func == "function")
- {
- var l_args = Array.prototype.slice.call(arguments, 3);
- var l_func = (function(){func.apply(null, l_args);});
- return win.setInterval(l_func, delay);
- }
- return win.setInterval(func, delay);
- },
-
- setTimeoutWithParams : function(win, func, delay)
- {
- if (typeof func == "function")
- {
- var l_args = Array.prototype.slice.call(arguments, 3);
- var l_func = (function(){func.apply(null, l_args);});
- return win.setTimeout(l_func, delay);
- }
- return win.setTimeout(func, delay);
- },
-
- setXhrAbortTimeout : function(xhr, delay)
- {
- var timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
- timer.initWithCallback({ notify : function() { samfind_modutils.abortXhr(xhr); } }, delay, Ci.nsITimer.TYPE_ONE_SHOT);
- return timer;
- },
-
- abortXhr : function(xhr)
- {
- try
- {
- if (xhr.readyState > 0 && xhr.readyState < 4)
- {
- xhr.abort();
- }
- }
- catch (e)
- {}
- },
-
- getLoginManager : function()
- {
- if (Cc["@mozilla.org/login-manager;1"])
- {
- return Cc["@mozilla.org/login-manager;1"].getService(Ci.nsILoginManager);
- }
- return null;
- },
-
- getAuth : function(aHostname, aActionURL)
- {
- var login_manager = samfind_modutils.getLoginManager();
- var logins = login_manager.findLogins({}, aHostname, aActionURL, null);
- var auth = {};
- for (var i=0; i<logins.length; i++)
- {
- auth.username = logins[i].username;
- auth.password = logins[i].password;
- break;
- }
- if (typeof auth.username == "undefined") auth.username = "";
- if (typeof auth.password == "undefined") auth.password = "";
- return auth;
- },
-
- getRssUrl : function(aDocument)
- {
- try
- {
- var links = aDocument.getElementsByTagName("link");
- for (var i=0; i<links.length; ++i)
- {
- var link = links[i];
- if (link.getAttribute("rel") == "alternate")
- {
- var type = link.getAttribute("type");
- if (type == "application/rss+xml" || type == "application/atom+xml")
- {
- var href = link.getAttribute("href");
- if (href.indexOf("http") == -1)
- {
- var base_uri = aDocument.baseURIObject;
- if (href.charAt(0) == '/')
- {
- href = base_uri.prePath + href;
- }
- else
- {
- var spec = base_uri.spec;
- href = spec.substring(0, spec.lastIndexOf("/") + 1) + href;
- }
- }
- return href;
- }
- }
- }
- }
- catch (e)
- {}
- return "";
- },
-
- getSearchAcceleratorsText : function()
- {
- try
- {
- var file = Cc["@mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties).get("ProfD", Ci.nsIFile);
- file.append("samfindsearchaccelerators.json");
- if (file.exists())
- {
- var stream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance(Ci.nsIFileInputStream);
- stream.init(file, 0x01, 0666, 0);
- stream.QueryInterface(Ci.nsILineInputStream);
- var line = {}, lines = [], hasmore;
- do {
- hasmore = stream.readLine(line);
- lines.push(line.value);
- }
- while(hasmore);
- stream.close();
- return lines[0];
- }
- }
- catch (e)
- {}
- return null;
- },
-
- startPrivateBrowsing : function()
- {
- try
- {
- var pbs = Cc["@mozilla.org/privatebrowsing;1"].getService(Ci.nsIPrivateBrowsingService);
- if (pbs.privateBrowsingEnabled == false)
- {
- pbs.privateBrowsingEnabled = true;
- }
- }
- catch (e)
- {}
- },
-
- stopPrivateBrowsing : function(event)
- {
- try
- {
- var pbs = Cc["@mozilla.org/privatebrowsing;1"].getService(Ci.nsIPrivateBrowsingService);
- if (pbs.privateBrowsingEnabled)
- {
- pbs.privateBrowsingEnabled = false;
- }
- }
- catch (e)
- {}
- event.stopPropagation();
- },
-
- isMacOSX : function()
- {
- var os = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime).OS;
- return (os == "Darwin");
- },
-
- isSidebarShown : function(document, commandId)
- {
- var sidebar_broadcaster = document.getElementById(commandId);
- return (sidebar_broadcaster.getAttribute("checked") == "true");
- },
-
- sendNotification : function(topic, data)
- {
- try
- {
- var observer_service = Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService);
- observer_service.notifyObservers(null, topic, data);
- observer_service = null;
- }
- catch (e)
- {}
- },
-
- arrayHas : function(a, el)
- {
- for (var i=0; i<a.length; ++i)
- {
- if (a[i] == el)
- {
- return true;
- }
- }
- return false;
- },
-
- trim : function(text)
- {
- text = text.replace(/^\s\s*/, '');
- text = text.replace(/\s\s*$/, '');
- text = text.replace(/\n/g, " ");
- text = text.replace(/\s+/, " ");
- return text;
- },
-
- checkSiteMenu : function(event, prefix)
- {
- var menupopup = event.target;
- if (menupopup != event.currentTarget)
- {
- return;
- }
- //
- var sidesam_item = (menupopup.getElementsByAttribute("id", (prefix + "-sidesam")))[0];
- if (sidesam_item != null)
- {
- var acceltext = samfind_modutils._pref_branch.getCharPref("sidesam.hotkey.modifiers") + "+" + samfind_modutils._pref_branch.getCharPref("sidesam.hotkey.key");
- sidesam_item.setAttribute("acceltext", acceltext);
- }
- //
- var register_item = (menupopup.getElementsByAttribute("id", (prefix + "-register")))[0];
- if (register_item != null)
- {
- try
- {
- if (samfind_modutils._pref_branch.getBoolPref("why.register"))
- {
- register_item.hidden = false;
- }
- }
- catch (e)
- {
- register_item.hidden = true;
- }
- }
- //
- var login_item = (menupopup.getElementsByAttribute("id", (prefix + "-login")))[0];
- var logout_item = (menupopup.getElementsByAttribute("id", (prefix + "-logout")))[0];
- if (login_item != null && logout_item != null)
- {
- if (samfind_modutils._pref_branch.getBoolPref("isuser"))
- {
- login_item.hidden = true;
- logout_item.hidden = false;
- }
- else
- {
- login_item.hidden = false;
- logout_item.hidden = true;
- }
- }
- //
- event.stopPropagation();
- },
-
- clearMenupopup : function(menupopup)
- {
- while (menupopup.firstChild)
- {
- menupopup.removeChild(menupopup.firstChild);
- }
- },
-
- clearMenupopupByEvent : function(event)
- {
- var menupopup = event.target;
- if (menupopup != event.currentTarget)
- {
- return;
- }
- samfind_modutils.clearMenupopup(menupopup);
- event.stopPropagation();
- },
-
- genGUID : function()
- {
- return (samfind_modutils.genS4()
- + samfind_modutils.genS4()
- + "-" + samfind_modutils.genS4()
- + "-" + samfind_modutils.genS4()
- + "-" + samfind_modutils.genS4()
- + "-" + samfind_modutils.genS4()
- + samfind_modutils.genS4()
- + samfind_modutils.genS4());
- },
-
- genS4 : function()
- {
- return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
- },
-
- getTimestamp : function(time)
- {
- //--------------------------------------------------------------
- // http://af-design.com/blog/2009/02/10/twitter-like-timestamps/
- //--------------------------------------------------------------
- var system_date = new Date(time);
- var user_date = new Date();
- var diff = Math.floor((user_date - system_date) / 1000);
- if (diff <= 1) return "just now";
- if (diff < 20) return diff + " seconds ago";
- if (diff < 40) return "half a minute ago";
- if (diff < 60) return "less than a minute ago";
- if (diff <= 90) return "one minute ago";
- if (diff <= 3540) return Math.round(diff / 60) + " minutes ago";
- if (diff <= 5400) return "1 hour ago";
- if (diff <= 86400) return Math.round(diff / 3600) + " hours ago";
- if (diff <= 129600) return "1 day ago";
- if (diff < 604800) return Math.round(diff / 86400) + " days ago";
- if (diff <= 777600) return "1 week ago";
- return "on " + time;
- },
-
- getSelection : function(win)
- {
- var selection = win.content.getSelection();
- if (selection == null)
- {
- selection = "";
- }
- else
- {
- selection = selection.toString().replace(/^\s+/, "").replace(/\s+$/, "").replace(/\s+/g, " ");
- }
- return selection;
- }
- };
-
- /**
- * Constructor.
- */
- (function() { this._init(); }).apply(samfind_modutils);