jappixmini: autosubscribe only when contacts list changed
[friendica-addons.git/.git] / jappixmini / lib.js
1 function jappixmini_addon_xor(str1, str2) {
2     if (str1.length != str2.length) throw "not same length";
3
4     encoded = "";
5
6     for (i=0; i<str1.length;i++) {
7         var a = str1.charCodeAt(i);
8         var b = str2.charCodeAt(i);
9         var c = a ^ b;
10
11         encoded += String.fromCharCode(c);
12     }
13
14     return encoded;
15 }
16
17 function jappixmini_addon_set_client_secret(password) {
18         if (!password) return;
19
20         salt1 = "h8doCRekWto0njyQohKpdx6BN0UTyC6N";
21         salt2 = "jdX8OwFC1kWAq3s9uOyAcE8g3UNNO5t3";
22
23         client_secret1 = str_sha1(salt1+password);
24         client_secret2 = str_sha1(salt2+password);
25         client_secret = client_secret1 + client_secret2;
26
27         setPersistent('jappix-mini', 'client-secret', client_secret);
28         console.log("client secret set");
29 }
30
31 function jappixmini_addon_get_client_secret(callback) {
32         client_secret = getPersistent('jappix-mini', 'client-secret');
33         if (client_secret===null) {
34                 div = document.getElementById("#jappixmini-password-query-div");
35
36                 if (!div) {
37                         div = $('<div id="jappixmini-password-query-div" style="position:fixed;padding:1em;background-color:#F00;color:#fff;top:50px;left:50px;">Retype your Friendica password for chatting:<br></div>');
38
39                         input = $('<input type="password" id="jappixmini-password-query-input">')
40                         div.append(input);
41
42                         button = $('<input type="button" value="OK" id="jappixmini-password-query-button">');
43                         div.append(button);
44
45                         $("body").append(div);
46                 }
47
48                 button.click(function(){
49                         password = $("#jappixmini-password-query-input").val();
50                         jappixmini_addon_set_client_secret(password);
51                         div.remove();
52
53                         client_secret = getPersistent('jappix-mini', 'client-secret');
54                         callback(client_secret);
55                 });
56         }
57         else {
58                 callback(client_secret);
59         }
60 }
61
62 function jappixmini_addon_encrypt_password(password, callback) {
63         jappixmini_addon_get_client_secret(function(client_secret){
64                 // add \0 to password until it has the same length as secret
65                 if (password.length>client_secret.length-1) throw "password too long";
66                 while (password.length<client_secret.length) {
67                         password += "\0";
68                 }
69
70                 // xor password with secret
71                 encrypted_password = jappixmini_addon_xor(client_secret, password);
72
73                 encrypted_password = encodeURI(encrypted_password)
74                 callback(encrypted_password);
75         });
76 }
77
78 function jappixmini_addon_decrypt_password(encrypted_password, callback) {
79         encrypted_password = decodeURI(encrypted_password);
80
81         jappixmini_addon_get_client_secret(function(client_secret){
82                 // xor password with secret
83                 password = jappixmini_addon_xor(client_secret, encrypted_password);
84
85                 // remove \0
86                 first_null = password.indexOf("\0")
87                 if (first_null==-1) throw "Decrypted password does not contain \\0";
88                 password = password.substr(0, first_null);
89
90                 callback(password);
91         });
92 }
93
94 function jappixmini_manage_roster(contacts, contacts_hash, autoapprove, autosubscribe) {
95         // listen for subscriptions
96         con.registerHandler('presence',function(presence){
97                 var type = presence.getType();
98                 if (type != "subscribe") return;
99
100                 var from = fullXID(getStanzaFrom(presence));
101                 var xid = bareXID(from);
102                 var pstatus = presence.getStatus();
103
104                 if (autoapprove && contacts[xid]!==undefined) {
105                         // approve known address
106                         approve = true;
107                         console.log("Approve known Friendica contact "+xid+".");
108                 }
109                 else if (autoapprove && pstatus && pstatus.indexOf("Friendica")!=-1) {
110                         // Unknown address claims to be a Friendica contact.
111                         // This is probably because the other side knows our
112                         // address, but we do not know the other side yet.
113                         // But it's only a matter of time, so wait - do not
114                         // approve yet and do not annoy the user by asking.
115                         approve = false;
116                         console.log("Do not approve unknown Friendica contact "+xid+" - wait instead.");
117                 }
118                 else {
119                         // In all other cases, ask the user.
120                         message = "Accept "+xid+" for chat?";
121                         if (pstatus) message += "\n\nStatus:\n"+pstatus;
122                         approve = confirm(message);
123
124                         // do not ask any more
125                         if (!approve) sendSubscribe(xid, "unsubscribed");
126                 }
127
128                 if (approve) {
129                         name = contacts[xid];
130                         if (!name) name = xid;
131
132                         acceptSubscribe(xid, contacts[xid]);
133                         console.log("Accepted "+xid+" for chat.");
134                 }
135         });
136
137         // autosubscribe
138         if (!autosubscribe) return;
139
140         stored_hash = getPersistent("jappix-mini", "contacts-hash");
141         contacts_changed = (stored_hash != contacts_hash); // stored_hash gets updated later if everything was successful
142         if (!contacts_changed) return;
143
144         console.log("Start autosubscribe.");
145
146         var get_roster = new JSJaCIQ();
147         get_roster.setType('get');
148         get_roster.setQuery(NS_ROSTER);
149
150         con.send(get_roster, function(iq){
151                 var handleXML = iq.getQuery();
152
153                 // filter out contacts that are already in the roster
154                 $(handleXML).find('item').each(function() {
155                         xid = $(this).attr("jid");
156                         name = $(this).attr("name");
157                         subscription = $(this).attr("subscription");
158
159                         // ignore accounts not in the list
160                         if (contacts[xid]===undefined) return;
161
162                         // add to Friendica group if necessary
163                         groups = [];
164                         $(this).find('group').each(function() {
165                                 var group_text = $(this).text();
166                                 if(group_text) groups.push(group_text);
167                         });
168
169                         if ($.inArray("Friendica", groups)==-1) {
170                                 groups.push("Friendica");
171                                 sendRoster(xid, null, null, groups);
172                                 console.log("Added "+xid+" to Friendica group.");
173                         }
174
175                         // authorize if necessary
176                         if (subscription=="to") {
177                                 sendSubscribe(xid, 'subscribed');
178                                 console.log("Authorized "+xid+" automatically.");
179                         }
180
181                         // remove from list
182                         delete contacts[xid];
183                 });
184
185                 // go through remaining contacts
186                 for (var xid in contacts) {if(!contacts.hasOwnProperty(xid)) continue;
187                         // subscribe
188                         var presence = new JSJaCPresence();
189                         presence.setTo(xid);
190                         presence.setType("subscribe");
191
192                         // must contain the word "~Friendica" so the other side knows
193                         // how to handle this
194                         presence.setStatus("I'm "+MINI_NICKNAME+" from ~Friendica.\n[machine-generated message]");
195
196                         con.send(presence);
197                         console.log("Subscribed to "+xid+" automatically.");
198
199                         // add to roster
200                         var iq = new JSJaCIQ();
201                         iq.setType('set');
202                         var iqQuery = iq.setQuery(NS_ROSTER);
203                         var item = iqQuery.appendChild(iq.buildNode('item', {'xmlns': NS_ROSTER, 'jid': xid}));
204                         item.setAttribute('name', contacts[xid]);
205                         item.appendChild(iq.buildNode('group', {'xmlns': NS_ROSTER}, "Friendica"));
206                         con.send(iq);
207                         console.log("Added "+xid+" to roster.");
208                 }
209
210                 setPersistent("jappix-mini", "contacts-hash", contacts_hash);
211                 console.log("Autosubscribe done.");
212         });
213
214 }
215
216 function jappixmini_addon_subscribe() {
217         if (!window.con) {
218                 alert("Not connected.");
219                 return;
220         }
221
222         xid = prompt("Jabber address");
223         sendSubscribe(xid, "subscribe");
224 }
225
226 function jappixmini_addon_start(server, username, proxy, bosh, encrypted, password, nickname, contacts, contacts_hash, autoapprove, autosubscribe) {
227     handler = function(password){
228         // check if settings have changed, reinitialize jappix mini if this is the case
229         settings_identifier = str_sha1(server);
230         settings_identifier += str_sha1(username);
231         settings_identifier += str_sha1(proxy);
232         settings_identifier += str_sha1(bosh);
233         settings_identifier += str_sha1(password);
234         settings_identifier += str_sha1(nickname);
235
236         saved_identifier = getDB("jappix-mini", "settings-identifier");
237         if (saved_identifier != settings_identifier) {
238             disconnectMini();
239             removeDB('jappix-mini', 'dom');
240             removePersistent("jappix-mini", "contacts-hash");
241         }
242         setDB("jappix-mini", "settings-identifier", settings_identifier);
243
244        // set HOST_BOSH
245        if (proxy)
246            HOST_BOSH = proxy+"?host_bosh="+encodeURI(bosh);
247        else
248            HOST_BOSH = bosh;
249
250         // start jappix mini
251         MINI_NICKNAME = nickname;
252         LOCK_HOST = "off";
253         launchMini(true, false, server, username, password);
254
255         // increase priority over other Jabber clients - does not seem to work?
256         priority = 101;
257         presenceMini(null,null,priority);
258
259         jappixmini_manage_roster(contacts, contacts_hash, autoapprove, autosubscribe)
260     }
261
262     // decrypt password if necessary
263     if (encrypted)
264         jappixmini_addon_decrypt_password(password, handler);
265     else
266         handler(password);
267 }