ShortURL.jsm 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
  2. const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
  3. XPCOMUtils.defineLazyServiceGetter(this, "IDNService", "@mozilla.org/network/idn-service;1", "nsIIDNService");
  4. XPCOMUtils.defineLazyGlobalGetters(this, ["URL"]);
  5. /**
  6. * Properly convert internationalized domain names.
  7. * @param {string} host Domain hostname.
  8. * @returns {string} Hostname suitable to be displayed.
  9. */
  10. function handleIDNHost(hostname) {
  11. try {
  12. return IDNService.convertToDisplayIDN(hostname, {});
  13. } catch (e) {
  14. // If something goes wrong (e.g. host is an IP address) just fail back
  15. // to the full domain.
  16. return hostname;
  17. }
  18. }
  19. /**
  20. * Get the effective top level domain of a host.
  21. * @param {string} host The host to be analyzed.
  22. * @return {str} The suffix or empty string if there's no suffix.
  23. */
  24. function getETLD(host) {
  25. try {
  26. return Services.eTLD.getPublicSuffixFromHost(host);
  27. } catch (err) {
  28. return "";
  29. }
  30. }
  31. /**
  32. * shortURL - Creates a short version of a link's url, used for display purposes
  33. * e.g. {url: http://www.foosite.com} => "foosite"
  34. *
  35. * @param {obj} link A link object
  36. * {str} link.url (required)- The url of the link
  37. * @return {str} A short url
  38. */
  39. function shortURL({url}) {
  40. if (!url) {
  41. return "";
  42. }
  43. // Make sure we have a valid / parseable url
  44. let parsed;
  45. try {
  46. parsed = new URL(url);
  47. } catch (ex) {
  48. // Not entirely sure what we have, but just give it back
  49. return url;
  50. }
  51. // Clean up the url (lowercase hostname via URL and remove www.)
  52. const hostname = parsed.hostname.replace(/^www\./i, "");
  53. // Remove the eTLD (e.g., com, net) and the preceding period from the hostname
  54. const eTLD = getETLD(hostname);
  55. const eTLDExtra = eTLD.length > 0 ? -(eTLD.length + 1) : Infinity;
  56. // Ideally get the short eTLD-less host but fall back to longer url parts
  57. return handleIDNHost(hostname.slice(0, eTLDExtra) || hostname) ||
  58. parsed.pathname || parsed.href;
  59. }
  60. const EXPORTED_SYMBOLS = ["shortURL", "getETLD"];