]> gitweb @ CieloNegro.org - sugar.git/blob - dot-files/_vimperator/plugin/bitly_js
5d4af2dbddd17f285ec77994b3b9e9d23bfec708
[sugar.git] / dot-files / _vimperator / plugin / bitly_js
1 /* NEW BSD LICENSE {{{
2 Copyright (c) 2008-2010, anekos.
3 All rights reserved.
4
5 Redistribution and use in source and binary forms, with or without modification,
6 are permitted provided that the following conditions are met:
7
8     1. Redistributions of source code must retain the above copyright notice,
9        this list of conditions and the following disclaimer.
10     2. Redistributions in binary form must reproduce the above copyright notice,
11        this list of conditions and the following disclaimer in the documentation
12        and/or other materials provided with the distribution.
13     3. The names of the authors may not be used to endorse or promote products
14        derived from this software without specific prior written permission.
15
16 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
17 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19 IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
20 INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
23 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
25 THE POSSIBILITY OF SUCH DAMAGE.
26
27
28 ###################################################################################
29 # http://sourceforge.jp/projects/opensource/wiki/licenses%2Fnew_BSD_license       #
30 # に参考になる日本語訳がありますが、有効なのは上記英文となります。                #
31 ###################################################################################
32
33 }}} */
34
35 // PLUGIN_INFO {{{
36 let PLUGIN_INFO = xml`
37 <VimperatorPlugin>
38   <name>bit.ly</name>
39   <description>Get short alias by bit.ly and j.mp</description>
40   <description lang="ja">bit.ly や j.mp で短縮URLを得る</description>
41   <version>2.1.2</version>
42   <author mail="anekos@snca.net" homepage="http://d.hatena.ne.jp/nokturnalmortum/">anekos</author>
43   <license>new BSD License (Please read the source code comments of this plugin)</license>
44   <license lang="ja">修正BSDライセンス (ソースコードのコメントを参照してください)</license>
45   <updateURL>https://github.com/vimpr/vimperator-plugins/raw/master/bitly.js</updateURL>
46   <minVersion>2.0pre</minVersion>
47   <detail><![CDATA[
48     == Commands ==
49       :bitly [<URL>]
50         Copy to clipboard.
51       :jmp [<URL>]
52         Copy to clipboard.
53     == Require ==
54       bit.ly API Key
55   ]]></detail>
56 </VimperatorPlugin>`;
57 // }}}
58
59
60 (function () {
61
62   const Realm = 'API Key for bit.ly (bitly.js)';
63   const HostName = 'http://api.bit.ly';
64   const ApiUrl = 'http://api.bit.ly/v3';
65   const PasswordManager = Cc['@mozilla.org/login-manager;1'].getService(Ci.nsILoginManager);
66   const LoginInfo =
67     new Components.Constructor(
68       '@mozilla.org/login-manager/loginInfo;1',
69       Ci.nsILoginInfo,
70       'init'
71     );
72
73   function getAuth () {
74     let count = {};
75     let logins = PasswordManager.findLogins(count, HostName, null, Realm);
76     if (logins.length)
77       return logins[0];
78   }
79
80   function setupAuth (callback) {
81     liberator.open('http://bit.ly/a/your_api_key', liberator.NEW_TAB);
82     commandline.input(
83       'Login name for bit.ly: ',
84       function (username) {
85         commandline.input(
86           'API Key: ',
87           function (apiKey) {
88             let login = LoginInfo(HostName, null, Realm, username, apiKey, '', '');
89             PasswordManager.addLogin(login);
90             callback();
91           },
92           {
93             default: let (e = content.document.querySelector('#bitly_api_key')) (e ? e.value : '')
94           }
95         );
96       }
97     );
98   }
99
100   function shorten (url, domain, command, callback) {
101     function fixResponseText (s)
102       s.trim();
103
104     liberator.log(arguments);
105     function get () {
106       let req = new XMLHttpRequest();
107       req.onreadystatechange = function () {
108         if (req.readyState != 4)
109           return;
110         if (req.status == 200)
111           return callback && callback(fixResponseText(req.responseText), req);
112         else
113           return liberator.echoerr(req.statusText);
114       };
115       let requestUri =
116         ApiUrl + '/' + (command || 'shorten') + '?' +
117         'apiKey=' + auth.password + '&' +
118         'login=' + auth.username + '&' +
119         (command !== 'expand' ? 'uri=' : 'shortUrl=') + encodeURIComponent(url) + '&' +
120         'domain=' + (domain || 'bit.ly') + '&' +
121         'format=txt';
122       req.open('GET', requestUri, callback);
123       req.send(null);
124       return !callback && fixResponseText(req.responseText);
125     }
126
127     if (!url)
128       url = buffer.URL;
129
130     let auth = getAuth();
131
132     if (auth)
133       return get();
134
135     if (callback) {
136       let args = Array.slice(arguments);
137       setupAuth(function () shorten.apply(this, args));
138     } else {
139       liberator.echoerr('Not found API Key!! Try :bitly command, before use.');
140     }
141   }
142
143   [
144     ['jmp', 'j.mp'],
145     ['bitly', 'bit.ly'],
146   ].forEach(function ([name, domain]) {
147     commands.addUserCommand(
148       [name],
149       'Copy ' + domain + ' url',
150       function (args) {
151         let url = args.literalArg ? util.stringToURLArray(args.literalArg)[0] : buffer.URL;
152         let cmd = args['-expand'] ? 'expand' : 'shorten';
153
154         shorten(url, domain, cmd, function (short) {
155           util.copyToClipboard(short);
156           liberator.echo(short + ' <= ' + url);
157         });
158       },
159       {
160         literal: 0,
161         options: [
162           [['-expand', '-e'], commands.OPTION_NOARG]
163         ],
164         completer: function (context) {
165           context.completions = [
166             [buffer.URL, 'Current URL']
167           ];
168           context.fork('URL', 0, context, completion.url);
169         }
170       },
171       true
172     );
173     __context__[name] = function (url, cmd, callback) shorten(url, domain, cmd, callback);
174   });
175
176   __context__.get = shorten;
177 })();