// max of 140 chars is recommended, but it really allows 160
const TWEET_MAXLEN = 140;
const TWEET_SHORT_URL_MAX_LENGTH = 17;

CmdUtils.CreateCommand({
  name: "tweet",
  icon: "http://assets3.twitter.com/images/favicon.ico",
  takes: {status: noun_arb_text},
  modifiers: {},
  description: "Sets your Twitter status to a message of at most 160 characters.",
  help: "You'll need a Twitter account, obviously.  If you're not already logged in" +
        " you'll be asked to log in.",
  preview: function(previewBlock, directObj) {
    var statusText = directObj.text;
    var statusLength = statusText.length;

    var usesUrlShortener = statusText.indexOf('isgd') != -1;
    if (usesUrlShortener) statusLength += TWEET_SHORT_URL_MAX_LENGTH - 4;

    var previewData = {
      status: statusText,
      chars: TWEET_MAXLEN - statusLength
    };

    var previewTemplate = "Updates your Twitter status to: 
${status}

Characters remaining: ${chars}"; var truncateTemplate = "
The last ${truncate} characters will be truncated!"; var urlWillBeShortenedText = "
The text 'isgd' will be replaced with an http://is.gd/ link to the current page." var previewHTML = CmdUtils.renderTemplate(previewTemplate, previewData); if (usesUrlShortener) previewHTML += urlWillBeShortenedText; if(previewData.chars < 0) { var truncateData = { truncate: 0 - previewData.chars }; previewHTML += CmdUtils.renderTemplate(truncateTemplate, truncateData); } previewBlock.innerHTML = previewHTML; }, execute: function(directObj) { var statusText = directObj.text; if(statusText.length < 1) { displayMessage("Twitter requires a status to be entered"); return; } var usesUrlShortener = statusText.indexOf('isgd') != -1; var postUpdate = function( shortURL ) { var finalStatusText = statusText.replace('isgd', shortURL); var updateUrl = "https://twitter.com/statuses/update.json"; var updateParams = { source: "ubiquity", status: statusText }; jQuery.ajax({ type: "POST", url: updateUrl, data: updateParams, dataType: "json", error: function() { displayMessage("Twitter error - status not updated"); }, success: function() { displayMessage("Twitter status updated"); } }); } if (usesUrlShortener) { var urlToShorten = Application.activeWindow.activeTab.document.location.href; jQuery.get( 'http://is.gd/api.php', { 'longurl' : urlToShorten }, postUpdate); } else { postUpdate(''); } } });