aboutsummaryrefslogtreecommitdiffstats
path: root/retweet.js
blob: 09d4d3e5e34d8b1250debd82b8803c6dd2d50aed (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
// PLUGIN_INFO//{{{
var PLUGIN_INFO =
<VimperatorPlugin>
  <name>retweet</name>
  <description>ReTweet This Page.</description>
  <description lang="ja">開いているTweetをReTweetします</description>
  <author mail="from.kyushu.island@gmail.com" homepage="http://iddy.jp/profile/from_kyushu">from_kyushu</author>
  <version>0.3</version>
  <license>GPL</license>
  <minVersion>1.2</minVersion>
  <maxVersion>2.1</maxVersion>
  <updateURL>https://github.com/vimpr/vimperator-plugins/raw/master/retweet.js</updateURL>
  <require type="plugin">_libly.js</require>
  <detail><![CDATA[

== Command ==
Usage:
  :rtt
    ReTweet This Post.

  ]]></detail>
</VimperatorPlugin>;
//}}}
//
(
  function()
  {
    var password;
    var username;
    var passwordManager = Cc["@mozilla.org/login-manager;1"].getService(Ci.nsILoginManager);
    var $U = liberator.plugins.libly.$U;

    function getBody()
    {
      var body = $U.getFirstNodeFromXPath("//span[@class='entry-content']").innerHTML;
      //return body.replace(/<[^>]*>/g, "");
      var tags = body.match(/<[^>]*>/g);
      for(var tag in tags)
      {
        body = body.replace(tags[tag],"");
      }
      return body;
    }

    function getUserName()
    {
      return $U.getFirstNodeFromXPath('//a[contains(concat(" ",normalize-space(@class)," "),"screen-name")]').innerHTML;
    }

    function getShortenUrl(longUrl)
    {
      var xhr = new XMLHttpRequest();
      var req = "http://bit.ly/api?url=" + encodeURIComponent(longUrl);
      xhr.open('GET',req, false);
      xhr.send(null);
      if(xhr.status != 200)
      {
        return longUrl;
      }
      return xhr.responseText;
    }

    function sendTwitter(url,name,body,comment)
    {
      var xhr = new XMLHttpRequest();
      var statusText = (comment ? comment + " " : "") + "RT @" + name + " [" + url +"]: " + body;
      return liberator.echo(statusText);
      xhr.open("POST", "https://twitter.com/statuses/update.json", false, username, password);
      xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      xhr.send("status=" + encodeURIComponent(statusText) + "&source=Vimperator");

      liberator.echo("[RT] Your post was sent.");
    }

    commands.addUserCommand(
      ['retweet[This]','rtt'],
      'ReTweet This.',
      function(args)
      {
        try
        {
          var logins = passwordManager.findLogins({}, "http://twitter.com","https://twitter.com",null);
          var body = getBody();
          var name = getUserName();
          var url = getShortenUrl(buffer.URL);
          if(logins.length)
          {
            username = logins[0].username;
            password = logins[0].password;
            sendTwitter(url,name,body,args.literalArg);
          }
          else if(liberator.globalVariables.twitter_username && liberator.globalVariables.twitter_password)
          {
            username = liberator.globalVariables.twitter_username;
            password = liberator.globalVariables.twitter_password;
            sendTwitter(url,name,body,args.literalArg);
          }
          else
          {
            throw "Accont not found";
          }
        }
        catch(e)
        {
          liberator.echoerr(e);
        }
      },
      {
        literal: 0
      },
      true
    );
  }
)();
>() for (var i=0, max=dictionaries.length ; i<max ; ++i) { if (dictionaries[i] === dict) { this.engine.dictionary = dict; return dict; } } return null; }, /** * @param {Boolean} isBeginningWith */ setBeginningWith: function (isBeginningWith) { this.isBeginningWith = isBeginningWith; }, /** * @param {String} spell * @return {Boolean} */ check: function (spell) { return this.engine.check(spell); }, /** * @param {String} spell * @return {Array} */ suggest: function (spell) { var suggestions = {}; this.engine.suggest(spell, suggestions, {}); suggestions = suggestions.value; if (this.isBeginningWith) { suggestions = suggestions.filter( function (cand) { return (cand.toLowerCase().indexOf(spell) === 0); }); } return suggestions; }, }; var spellChecker = buildSpellChecker(); SITE_DEFINITION.forEach(function(dictionary){ liberator.commands.addUserCommand( dictionary.names, dictionary.shortHelp, function(arg,special){ var sel = (window.content.window.getSelection) ? window.content.window.getSelection().toString() : null; if (special && sel) arg = sel; if (!arg) return; var url; if (dictionary.encode){ var ttbu = Components.classes['@mozilla.org/intl/texttosuburi;1'] .getService( Components.interfaces.nsITextToSubURI); url = dictionary.url.replace(/%s/g, ttbu.ConvertAndEscape(dictionary.encode, arg)); } else { url = dictionary.url.replace(/%s/g,encodeURI(arg)); } //liberator.log('URL: ' +url); var result; getHTML(url, function(str){ var doc = createHTMLDocument(str); var result = getNodeFromXPath(dictionary.xpath, doc, dictionary.multi); if (!result){ liberator.echoerr('Nothing to show...'); } var xs = new XMLSerializer(); liberator.echo('<base href="' + url + '"/>' + xs.serializeToString( result ), true); }, dictionary.encode ? dictionary.encode : 'UTF-8'); }, { completer: function (arg) { if (!spellChecker || !dictionary.dictionary || !spellChecker.setDictionary(dictionary.dictionary)) return [0, []]; var suggestions = spellChecker.suggest(arg); var candidates = []; for (var i=0, max=suggestions.length ; i<max ; ++i) { candidates.push([suggestions[i], 'suggest']); } if (!spellChecker.check(arg)) { candidates.unshift(['', 'not exist']); } return [0, candidates]; }, bang: true } ); }); liberator.commands.addUserCommand( ['availabledictionaries'], 'display available dictionaries', function () { liberator.echo('available dictionaries: ' + spellChecker.getDictionaryList()); }, {} ); /** * @param {String} url * @param {Function} callback * @param {String} charset */ function getHTML(url, callback, charset){ var xhr= new XMLHttpRequest(); xhr.onreadystatechange = function(){ if (xhr.readyState == 4){ if (xhr.status == 200){ callback.call(this,xhr.responseText); } else { throw new Error(xhr.statusText); } } }; xhr.open('GET',url,true); xhr.overrideMimeType('text/html; charset=' + charset); xhr.send(null); } /** * @param {String} str * @return {DOMDocument} */ function createHTMLDocument(str){ str = str.replace(/^[\s\S]*?<html(?:\s[^>]+?)?>|<\/html\s*>[\S\s]*$/ig,'').replace(/[\r\n]+/g,' '); var htmlFragment = document.implementation.createDocument(null,'html',null); var range = document.createRange(); range.setStartAfter(window.content.document.body); htmlFragment.documentElement.appendChild(htmlFragment.importNode(range.createContextualFragment(str),true)); return htmlFragment; } /** * @param {String} xpath XPath Expression * @param {DOMDocument} doc * @param {Boolean} isMulti * @return {Element} */ function getNodeFromXPath(xpath,doc,isMulti){ if (!xpath || !doc) return; var result; if (isMulti){ var nodesSnapshot = doc.evaluate(xpath,doc.documentElement,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null); if (nodesSnapshot.snapshotLength == 0) return; result = document.createElementNS(null,'div'); for (var i=0; i<nodesSnapshot.snapshotLength; result.appendChild(nodesSnapshot.snapshotItem(i++))); } else { var node = doc.evaluate(xpath,doc.documentElement,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null); if (!node.singleNodeValue) return; result = node.singleNodeValue; } return result; } /** * @return {Object} */ function buildSpellChecker() { var enable = liberator.globalVariables.lookupDictionary_enableSuggestion; enable = (enable === undefined) ? true : !!parseInt(enable, 10); if (!enable) return; var spellChecker = new SpellChecker(); var isBeginningWith = liberator.globalVariables.lookupDictionary_beginningWith isBeginningWith = (isBeginningWith === undefined) ? false : !!parseInt(isBeginningWith, 10); spellChecker.setBeginningWith(isBeginningWith); return spellChecker; } })(); // vim: fdm=marker sw=4 ts=4 et: