<commit_before>import copyToClipboard from './clipboard';
import notify from './notify';

const _ = browser.i18n.getMessage;

// Service default.
const default_service = 'isgd';

// Specify 'url' for plain-text GET APIs, or request/result for more complex
// variants. Note: return a fetch() promise.
// Do not forget to add origins to permissions in manifest.
const serviceUrls = {
  isgd: {
    url: 'https://is.gd/api.php?longurl=%URL%'
  },
  tinyurl: {
    url: 'https://tinyurl.com/api-create.php?url=%URL%'
  },
  googl: {
    // https://developers.google.com/url-shortener/v1/getting_started
    request: url => {
      return browser.storage.local.get('prefs').then(ret => {
        let prefs = ret['prefs'] || {};
        if (prefs.google_apikey) {
          let headers = new Headers({
            'Content-Type': 'application/json'
          });
          return fetch('https://www.googleapis.com/urlshortener/v1/url?key=' +
                       prefs.google_apikey, {
            method: 'POST',
            headers: headers,
            body: JSON.stringify({ longUrl: url })
          });
        }
        throw new Error(_('apikey_error'));
      });
    },
    result: response => {
      return response.text().then(txt => {
        let shortened = JSON.parse(txt);
        return shortened.id;
      })
    }
}}


/** Create a short URL from is.gd, tinyurl, etc. */
function createShortUrl(url) {
  let req;

  try {
    // Get shortening service from prefs.
    browser.storage.local.get('prefs').then(ret => {
      let prefs = ret['prefs'] || {};
      let service;
      if (prefs['service'] === 'custom') {
        service = { url: prefs.custom_url };
      } else {
        service = serviceUrls[prefs['service'] || default_service];
      }

      if (service.request) {
        req = service.request(url);
      } else {
        let _uri = service.url.replace('%URL%', encodeURIComponent(url));
        req = fetch(_uri);
      }

      req.then(response => {
        if (response.ok) {
          let result = service.result ? service.result(response) : response.text();
          return result;
        } else {
          throw new Error(_('shorten_error'));
        }
      }).then(result => {
        finalizeUrl(url, result);
      });

    }, err => {
      throw new Error(_('shorten_error'));
    });

  } catch (e) {<commit_msg>Catch API settings error and bubble up as notification<commit_after>import copyToClipboard from './clipboard';
import notify from './notify';

const _ = browser.i18n.getMessage;

// Service default.
const default_service = 'isgd';

// Specify 'url' for plain-text GET APIs, or request/result for more complex
// variants. Note: return a fetch() promise.
// Do not forget to add origins to permissions in manifest.
const serviceUrls = {
  isgd: {
    url: 'https://is.gd/api.php?longurl=%URL%'
  },
  tinyurl: {
    url: 'https://tinyurl.com/api-create.php?url=%URL%'
  },
  googl: {
    // https://developers.google.com/url-shortener/v1/getting_started
    request: url => {
      return browser.storage.local.get('prefs').then(ret => {
        let prefs = ret['prefs'] || {};
        if (!prefs.google_apikey) {
          throw new Error(_('apikey_error'));
        }

        let headers = new Headers({
          'Content-Type': 'application/json'
        });
        return fetch('https://www.googleapis.com/urlshortener/v1/url?key=' +
                     prefs.google_apikey, {
          method: 'POST',
          headers: headers,
          body: JSON.stringify({ longUrl: url })
        });
      });
    },
    result: response => {
      return response.text().then(txt => {
        let shortened = JSON.parse(txt);
        return shortened.id;
      })
    }
}}


/** Create a short URL from is.gd, tinyurl, etc. */
function createShortUrl(url) {
  let req;

  try {
    // Get shortening service from prefs.
    browser.storage.local.get('prefs').then(ret => {
      let prefs = ret['prefs'] || {};
      let service;
      if (prefs['service'] === 'custom') {
        service = { url: prefs.custom_url };
      } else {
        service = serviceUrls[prefs['service'] || default_service];
      }

      if (service.request) {
        req = service.request(url);
      } else {
        let _uri = service.url.replace('%URL%', encodeURIComponent(url));
        req = fetch(_uri);
      }

      req.then(response => {
        if (response.ok) {
          let result = service.result ? service.result(response) : response.text();
          return result;
        } else {
          throw new Error(_('shorten_error'));
        }
      }).then(result => {
        finalizeUrl(url, result);
      }).catch(err => {
        notify(err.message);
      });

    }, err => {
      throw new Error(_('shorten_error'));
    });

  } catch (e) {
{'fraction_non_alphanumeric': 0.15544472152950956, 'fraction_numerical': 0.0016625103906899418, 'mean_word_length': 2.170619235836627, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 20, 'https://': 8, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1737603', 'n_tokens_mistral': 1483, 'n_tokens_neox': 1455, 'n_words': 326}