]> gitweb @ CieloNegro.org - sugar.git/blob - dot-files/_vimperator/plugin/bitly_js
Auto commit by The Sugar System.
[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: (function () {
94               let e = content.document.querySelector('#bitly_api_key');
95               return e ? e.value : ''
96             })()
97           }
98         );
99       }
100     );
101   }
102
103   function shorten (url, domain, command, callback) {
104     function fixResponseText (s)
105       s.trim();
106
107     liberator.log(arguments);
108     function get () {
109       let req = new XMLHttpRequest();
110       req.onreadystatechange = function () {
111         if (req.readyState != 4)
112           return;
113         if (req.status == 200)
114           return callback && callback(fixResponseText(req.responseText), req);
115         else
116           return liberator.echoerr(req.statusText);
117       };
118       let requestUri =
119         ApiUrl + '/' + (command || 'shorten') + '?' +
120         'apiKey=' + auth.password + '&' +
121         'login=' + auth.username + '&' +
122         (command !== 'expand' ? 'uri=' : 'shortUrl=') + encodeURIComponent(url) + '&' +
123         'domain=' + (domain || 'bit.ly') + '&' +
124         'format=txt';
125       req.open('GET', requestUri, callback);
126       req.send(null);
127       return !callback && fixResponseText(req.responseText);
128     }
129
130     if (!url)
131       url = buffer.URL;
132
133     let auth = getAuth();
134
135     if (auth)
136       return get();
137
138     if (callback) {
139       let args = Array.slice(arguments);
140       setupAuth(function () shorten.apply(this, args));
141     } else {
142       liberator.echoerr('Not found API Key!! Try :bitly command, before use.');
143     }
144   }
145
146   [
147     ['jmp', 'j.mp'],
148     ['bitly', 'bit.ly'],
149   ].forEach(function ([name, domain]) {
150     commands.addUserCommand(
151       [name],
152       'Copy ' + domain + ' url',
153       function (args) {
154         let url = args.literalArg ? util.stringToURLArray(args.literalArg)[0] : buffer.URL;
155         let cmd = args['-expand'] ? 'expand' : 'shorten';
156
157         shorten(url, domain, cmd, function (short) {
158           util.copyToClipboard(short);
159           liberator.echo(short + ' <= ' + url);
160         });
161       },
162       {
163         literal: 0,
164         options: [
165           [['-expand', '-e'], commands.OPTION_NOARG]
166         ],
167         completer: function (context) {
168           context.completions = [
169             [buffer.URL, 'Current URL']
170           ];
171           context.fork('URL', 0, context, completion.url);
172         }
173       },
174       true
175     );
176     __context__[name] = function (url, cmd, callback) shorten(url, domain, cmd, callback);
177   });
178
179   __context__.get = shorten;
180 })();