This repository has been archived by the owner on Mar 11, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 20
/
sms.js
789 lines (653 loc) · 25.6 KB
/
sms.js
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
/**
* sms.js - A simple dialog for sending SMS messages with MConnect/KDE Connect
* with (optional) Google Contacts auto-completion via Gnome Online Accounts.
*
* A great deal of credit and appreciation is owed to the indicator-kdeconnect
* developers for the sister Python script 'Sms.py':
*
* https://github.com/Bajoja/indicator-kdeconnect/blob/master/src/sms/Sms.py
*/
const Lang = imports.lang;
const System = imports.system;
const Gettext = imports.gettext.domain("gnome-shell-extension-mconnect");
const _ = Gettext.gettext;
const GdkPixbuf = imports.gi.GdkPixbuf;
const Gio = imports.gi.Gio;
const GLib = imports.gi.GLib;
const GObject = imports.gi.GObject;
const Gtk = imports.gi.Gtk;
try {
var GData = imports.gi.GData;
var Goa = imports.gi.Goa;
} catch (e) {
var GData = undefined;
var Goa = undefined;
}
const SUPPORTED_NUMBER_TYPES = [
// GData: https://developers.google.com/gdata/docs/2.0/elements#rel-values_71
"http://schemas.google.com/g/2005#home",
"http://schemas.google.com/g/2005#main",
"http://schemas.google.com/g/2005#mobile",
"http://schemas.google.com/g/2005#other",
"http://schemas.google.com/g/2005#pager",
"http://schemas.google.com/g/2005#work",
"http://schemas.google.com/g/2005#work_mobile",
"http://schemas.google.com/g/2005#work_pager",
// Folks: http://www.ietf.org/rfc/rfc2426.txt
"home",
"cell", // Equal to GData->mobile
"pager",
"pref", // Equal to GData->main
"work",
"voice" // Sometimes mapped from GData#work
];
// Local Imports
function getPath() {
// Diced from: https://github.com/optimisme/gjs-examples/
let m = new RegExp("@(.+):\\d+").exec((new Error()).stack.split("\n")[1]);
return Gio.File.new_for_path(m[1]).get_parent().get_path();
}
imports.searchPath.push(getPath());
const KDEConnect = imports.kdeconnect;
const MConnect = imports.mconnect;
const { initTranslations, Me, Resources, Settings } = imports.lib;
var ServiceProvider = {
MCONNECT: 0,
KDECONNECT: 1
};
initTranslations();
/** Phone Number types that support receiving texts */
/** A Gtk.EntryCompletion subclass for Google Contacts */
var ContactCompletion = new Lang.Class({
Name: "ContactCompletion",
Extends: Gtk.EntryCompletion,
Properties: {
"provider": GObject.ParamSpec.string(
"provider",
"ContactsProvider",
"The provider for contacts",
GObject.ParamFlags.READWRITE,
"none"
)
},
_init: function () {
this.parent();
// Track suggested completions
this._matched = [];
this._last = null;
// Phone number icons
let theme = Gtk.IconTheme.get_default()
this.phone_number_default = theme.load_icon("phone-number-default", 0, 0);
this.phone_number_home = theme.load_icon("phone-number-home", 0, 0);
this.phone_number_mobile = theme.load_icon("phone-number-mobile", 0, 0);
this.phone_number_work = theme.load_icon("phone-number-work", 0, 0);
// Define a completion model
let listStore = new Gtk.ListStore();
listStore.set_column_types([
GObject.TYPE_STRING, // Title ("Name <Phone Number>")
GObject.TYPE_STRING, // Name
GObject.TYPE_STRING, // Phone Number
GdkPixbuf.Pixbuf // Type Icon
]);
listStore.set_sort_column_id(0, Gtk.SortType.ASCENDING);
listStore.set_sort_func(1, this._levenshtein, null, null);
this.set_model(listStore);
// Title
this.set_text_column(0);
// Type Icon
let typeCell = new Gtk.CellRendererPixbuf();
this.pack_start(typeCell, false);
this.add_attribute(typeCell, "pixbuf", 3);
this.set_match_func(Lang.bind(this, this._match), null, null);
this.connect("match-selected", Lang.bind(this, this._select));
this._get_contacts();
},
/** Spawn folks.py */
_get_contacts: function () {
let envp = GLib.get_environ();
envp.push("FOLKS_BACKENDS_DISABLED=telepathy")
let [res, pid, in_fd, out_fd, err_fd] = GLib.spawn_async_with_pipes(
null, // working dir
["python3", Me.path + "/folks.py"], // argv
envp, // envp
GLib.SpawnFlags.SEARCH_PATH, // enables PATH
null // child_setup (func)
);
this._check_folks(err_fd, out_fd);
},
/** Check spawned folks.py for errors on stderr */
_check_folks: function (err_fd, out_fd) {
let errstream = new Gio.DataInputStream({
base_stream: new Gio.UnixInputStream({ fd: err_fd })
});
errstream.read_line_async(GLib.PRIORITY_LOW, null, (source, res) => {
let [errline, length] = source.read_line_finish(res);
if (errline === null) {
let stream = new Gio.DataInputStream({
base_stream: new Gio.UnixInputStream({ fd: out_fd })
});
this.provider = "avatar-default-symbolic";
this.notify("provider");
this._read_folk(stream)
} else {
log("Folks: " + errline);
try {
for (let account in this._get_google_accounts()) {
this._get_google_contacts(account);
this.provider = "goa-account-google";
this.notify("provider");
}
} catch (e) {
log("Google: " + e.message);
}
}
});
},
/** Read a folk from folks.py output */
_read_folk: function (stream) {
stream.read_line_async(GLib.PRIORITY_LOW, null, (source, res) => {
let [contact, length] = source.read_line_finish(res);
if (contact !== null) {
let [name, number, type] = contact.toString().split("\t");
this._add_contact(name, number, type);
this._read_folk(stream);
}
});
},
/** Get all google accounts in Goa */
_get_google_accounts: function () {
let goaClient = Goa.Client.new_sync(null, null);
let goaAccounts = goaClient.get_accounts();
for (let goaAccount in goaAccounts) {
let acct = goaAccounts[goaAccount].get_account();
if (acct.provider_type === "google") {
yield new GData.ContactsService({
authorizer: new GData.GoaAuthorizer({
goa_object: goaClient.lookup_by_id(acct.id)
})
})
}
}
},
/** Query google contacts via GData */
_get_google_contacts: function (account) {
let query = new GData.Query({ q: "" });
let count = 0;
while (true) {
let feed = account.query_contacts(
query, // query,
null, // cancellable
(contact) => {
for (let phoneNumber of contact.get_phone_numbers()) {
this._add_contact(
contact.title,
phoneNumber.number,
phoneNumber.relation_type
);
}
},
null
);
count += feed.items_per_page;
query.start_index = count;
if (count > feed.total_results) { break; }
}
},
/** Add contact */
_add_contact: function (name, number, type) {
// Only include types that could possibly support SMS
if (SUPPORTED_NUMBER_TYPES.indexOf(type) < 0) { return; }
// Append the number to the title column
let title = name + " <" + number + ">";
// Phone Type Icon
if (type.indexOf("home") > -1) {
type = this.phone_number_home;
} else if (type.indexOf("cell") > -1 || type.indexOf("mobile") > -1) {
type = this.phone_number_mobile;
} else if (type.indexOf("work") > -1 || type.indexOf("voice") > -1) {
type = this.phone_number_work;
} else {
type = this.phone_number_default;
}
this.model.set(
this.model.append(),
[0, 1, 2, 3],
[title, name, number, type]
);
},
/** Multi-recipient capable match function */
_match: function (completion, key, tree_iter) {
let model = completion.get_model();
let title = model.get_value(tree_iter, 0).toLowerCase();
let name = model.get_value(tree_iter, 1).toLowerCase();
let number = model.get_value(tree_iter, 2);
let currentContacts = key.split(";").slice(0, -1);
// Set key to the last or only search item, trimmed of whitespace
if (key.indexOf(";") > -1) { key = key.split(";").pop().trim(); }
// Return if the possible match is in the current list
if (currentContacts.indexOf(title) > -1) { return false; }
// Clear current matches, reset last key and return if the key is empty
if (!key.length) {
this._matched = [];
this._last = null;
return;
// Clear current matches and reset last key if the key has changed
} else if (key !== this._last) {
this._matched = [];
this._last = key;
}
if (this._matched.length >= 20) { return false; }
// Match name or number
if (name.indexOf(key) > -1 || number.indexOf(key) > -1) {
this._matched.push(model.get_string_from_iter(tree_iter));
return true;
}
},
/** Add selected auto-complete entry to list of contacts in the entry */
_select: function (completion, model, tree_iter) {
let entry = completion.get_entry();
let currentContacts = entry.text.split(";").slice(0, -1);
let selectedContact = model.get_value(tree_iter, 0);
// Return if this contact is already in the current list
if (currentContacts.indexOf(selectedContact) > -1) { return; }
entry.set_text(
currentContacts.join("; ")
+ ((currentContacts.length) ? "; " : "")
+ selectedContact + "; "
);
entry.set_position(-1);
this._matched = [];
return true;
},
/**
* A levenshtein sort function
* See: https://gist.github.com/andrei-m/982927#gistcomment-2059365
*/
_levenshtein: function (model, a, b, user_data) {
var tmp;
if (a.length === 0) { return b.length; }
if (b.length === 0) { return a.length; }
if (a.length > b.length) { tmp = a; a = b; b = tmp; }
var i, j, res, alen = a.length, blen = b.length, row = Array(alen);
for (i = 0; i <= alen; i++) { row[i] = i; }
for (i = 1; i <= blen; i++) {
res = i;
for (j = 1; j <= alen; j++) {
tmp = row[j - 1];
row[j - 1] = res;
res = b[i - 1] === a[j - 1] ? tmp : Math.min(tmp + 1, Math.min(res + 1, row[j] + 1));
}
}
return res;
}
});
/** A Gtk.Entry subclass for contact names and phone numbers */
var ContactEntry = new Lang.Class({
Name: "ContactEntry",
Extends: Gtk.SearchEntry,
_init: function () {
this.parent({
hexpand: true,
placeholder_text: _("Type a phone number"),
primary_icon_name: "call-start-symbolic",
primary_icon_activatable: false,
primary_icon_sensitive: true,
input_purpose: Gtk.InputPurpose.PHONE,
completion: new ContactCompletion()
});
this.completion.connect("notify::provider", (completion) => {
this.placeholder_text = _("Type a phone number or name");
this.primary_icon_name = this.completion.provider;
this.input_purpose = Gtk.InputPurpose.FREE_FORM;
});
// Select the first completion suggestion on "activate"
this.connect("activate", () => { this._select(this); });
// Workaround for empty searches not calling CompletionMatchFunc
this.connect("changed", (entry) => {
let styleContext = entry.get_style_context();
if (entry.text === "") {
let completion = entry.get_completion();
completion._matched = [];
completion._last = null;
} else if (styleContext.has_class("error")) {
styleContext.remove_class("error");
}
});
},
_select: function (entry) {
let completion = entry.get_completion();
if (completion._matched.length > 0) {
let iter_path = completion._matched["0"];
let [b, iter] = completion.model.get_iter_from_string(iter_path);
let oldContacts = entry.text.split(";").slice(0, -1);
let newContact = completion.model.get_value(iter, 0);
// Ignore duplicate selections
if (oldContacts.indexOf(newContact) > -1) { return; }
entry.set_text(
oldContacts.join("; ")
+ ((oldContacts.length) ? "; " : "")
+ newContact + "; "
);
entry.set_position(-1);
completion._matched = [];
}
}
});
/** SMS Window */
var ApplicationWindow = new Lang.Class({
Name: "ApplicationWindow",
Extends: Gtk.ApplicationWindow,
_init: function(application, device) {
this.parent({
application: application,
title: "MConnect",
default_width: 300,
default_height: 300,
icon_name: "phone"
});
this.device = device;
// Contact Entry
this.contactEntry = new ContactEntry();
this.device.bind_property(
"reachable",
this.contactEntry,
"sensitive",
GObject.BindingFlags.DEFAULT
);
// HeaderBar
this.set_titlebar(
new Gtk.HeaderBar({
custom_title: this.contactEntry,
show_close_button: true
})
);
// Content
this.layout = new Gtk.Box({
orientation: Gtk.Orientation.VERTICAL,
margin: 6,
spacing: 6
});
this.add(this.layout);
// InfoBar
this.infoBar = new Gtk.InfoBar({
message_type: Gtk.MessageType.WARNING
});
this.infoBar.get_content_area().add(
new Gtk.Image({ icon_name: "dialog-warning-symbolic" })
);
this.infoBar.get_content_area().add(
new Gtk.Label({ label: _("Device is offline") })
);
// Content -> Conversation View
// TODO: intercept notifications to fake a two-way conversation
let scrolledWindow = new Gtk.ScrolledWindow({
can_focus: false,
hexpand: true,
vexpand: true
});
this.layout.add(scrolledWindow);
let conversationFrame = new Gtk.Frame();
scrolledWindow.add(conversationFrame);
this.conversationBuffer = new Gtk.TextBuffer();
let conversationView = new Gtk.TextView({
hexpand: true,
vexpand: true,
cursor_visible: false,
editable: false,
wrap_mode: Gtk.WrapMode.WORD,
buffer: this.conversationBuffer
});
this.device.bind_property(
"reachable",
conversationView,
"sensitive",
GObject.BindingFlags.DEFAULT
);
conversationFrame.add(conversationView);
// Content -> Message Entry
this.messageEntry = new Gtk.Entry({
hexpand: true,
placeholder_text: _("Type an SMS message"),
secondary_icon_name: "sms-send",
secondary_icon_activatable: true,
secondary_icon_sensitive: false
});
this.messageEntry.connect("changed", (entry, signal_id, data) => {
entry.secondary_icon_sensitive = (entry.text.length) ? true : false;
});
this.messageEntry.connect("activate", (entry, signal_id, data) => {
this.send(entry, signal_id, data);
});
this.messageEntry.connect("icon-release", (entry, signal_id, data) => {
this.send(entry, signal_id, data);
});
this.device.bind_property(
"reachable",
this.messageEntry,
"sensitive",
GObject.BindingFlags.DEFAULT
);
this.layout.add(this.messageEntry);
// Device Status
// See: https://bugzilla.gnome.org/show_bug.cgi?id=710888
this.device.connect("notify::reachable", () => {
if (!this.device.reachable) {
this.layout.add(this.infoBar);
this.layout.reorder_child(this.infoBar, 0);
this.infoBar.show_all();
} else if (this.device.reachable) {
this.infoBar.hide();
this.layout.remove(this.infoBar);
}
});
// Connect to notifications
if (this.device.hasOwnProperty("notifications")) {
this.device.notifications.connect(
"notification::posted",
Lang.bind(this, this._catch_notification)
);
}
// Finish initing
this.show_all();
this.has_focus = true;
},
_catch_notification: function (plugin, nid) {
let note;
if (Settings.get_enum("service-provider") === ServiceProvider.MCONNECT) {
// TODO: two-way sms not supported for MConnect, yet
return;
} else {
note = new KDEConnect.Notification(
this.device.gObjectPath + "/notifications/" + nid
);
}
log("Notification DBus ID: " + nid);
log("Notification App Name: \"" + note.name + "\"");
log("Notification ID: \"" + note.id + "\"");
log("Notification: \"" + note.content + "\"");
if (note.id.indexOf(":sms:") > -1) {
let recipients = this._get_recipients();
// string between sender and message:
// bin: 00100000 10000000010000 00100000
// hex: 20201020
// url: %20%E2%80%90%20
let [sender, message] = note.content.split(" ‐ ");
log("SMS Sender: \"" + sender + "\"");
log("SMS Message: \"" + message + "\"");
// Check for a verbatim match
if (recipients.has(sender)) {
log("Matched incoming sender");
this._log_message(sender, message);
this.urgency_hint = true;
note.dismiss();
// Might be just a number, strip both and check
} else {
for (let [name, number] of recipients.entries()) {
let local_num = number.replace(/\D/g, "");
let remote_num = sender.replace(/\D/g, "");
log("Local Number: \"" + local_num + "\"");
log("Incoming Number: \"" + remote_num + "\"");
if (local_num === remote_num) {
log("Matched incoming number");
this._log_message(name, message);
this.urgency_hint = true;
note.dismiss();
}
}
}
}
note.destroy();
},
_get_recipients: function () {
let contactItems = this.contactEntry.text.split(";").filter((s) => {
return /\S/.test(s);
});
let recipients = new Map();
let model = this.contactEntry.get_completion().get_model();
for (let item of contactItems) {
item = item.trim();
let contact = false;
// Search the completion for a matching
model.foreach((model, path, tree_iter) => {
if (item === model.get_value(tree_iter, 0)) {
contact = [
model.get_value(tree_iter, 1),
model.get_value(tree_iter, 2)
];
log("found recipient (name): \"" + contact[0] + "\"");
log("found recipient (num): \"" + contact[1] + "\"");
return true;
}
contact = false;
});
if (contact) {
recipients.set(contact[0], contact[1]);
} else {
recipients.set(item, item);
}
}
return recipients;
},
_get_numbers: function () {
let contactItems = this.contactEntry.text.split(";").filter((s) => {
return /\S/.test(s);
});
let numbers = [];
let model = this.contactEntry.get_completion().get_model();
for (let item of contactItems) {
item = item.trim();
let number = false;
// Search the completion for an exact contact match
model.foreach((model, path, tree_iter) => {
if (item === model.get_value(tree_iter, 0)) {
number = model.get_value(tree_iter, 2);
return true;
}
number = false;
});
// Found a matching Contact
if (number) {
numbers.push(number);
// Anything else can be handled by the device (libphonenumber)
} else {
numbers.push(item);
}
}
return numbers;
},
_log_message: function (name, message) {
let item = "<b>" + name + ":</b> " + message + "\n";
this.conversationBuffer.insert_markup(
this.conversationBuffer.get_end_iter(),
item,
item.length
);
},
/** Return a list of phone numbers that the SMS will be sent to */
send: function (entry, signal_id, event) {
let numbers = this._get_numbers();
// Check a number/contact has been provided
if (!numbers.length) {
this.contactEntry.has_focus = true;
this.contactEntry.secondary_icon_name = "dialog-error-symbolic";
let styleContext = this.contactEntry.get_style_context();
if (!styleContext.has_class("error")) {
styleContext.add_class("error");
}
return false;
}
// Send to each number
for (let number of numbers) {
this.device.sms(number, entry.text);
}
// Log the sent message in the Conversation View and clear the entry
this._log_message(_("You"), entry.text);
entry.text = "";
}
});
var Application = new Lang.Class({
Name: "Application",
Extends: Gtk.Application,
_init: function() {
this.parent({
application_id: "org.gnome.shell.extensions.mconnect.sms",
flags: Gio.ApplicationFlags.FLAGS_NONE
});
let application_name = _("MConnect SMS");
GLib.set_prgname(application_name);
GLib.set_application_name(application_name);
this._id = null;
// Options
this.add_main_option(
"device",
"d".charCodeAt(0),
GLib.OptionFlags.NONE,
GLib.OptionArg.STRING,
"Device ID",
"<device-id>"
);
},
vfunc_startup: function() {
this.parent();
Gtk.IconTheme.get_default().add_resource_path("/icons");
if (Settings.get_enum("service-provider") === ServiceProvider.MCONNECT) {
this.manager = new MConnect.DeviceManager();
} else {
this.manager = new KDEConnect.DeviceManager();
}
},
vfunc_activate: function() {
let device;
for (let dev of this.manager.devices.values()) {
if (dev.id === this._id && dev.hasOwnProperty("telephony")) {
device = dev;
}
}
if (device === undefined) {
throw Error("Device is unreachable or doesn't support sending SMS");
}
let windows = this.get_windows();
let window = false;
for (let index_ in windows) {
if (device.id === windows[index_].device.id) {
window = windows[index_];
}
}
if (!window) { window = new ApplicationWindow(this, device); }
window.present();
},
vfunc_handle_local_options: function(options) {
if (options.contains("device")) {
this._id = options.lookup_value("device", null).deep_unpack();
return -1;
}
throw Error("Device ID not specified");
return 1;
},
vfunc_shutdown: function() {
this.parent();
this.manager.destroy();
delete this.manager;
}
});
(new Application()).run([System.programInvocationName].concat(ARGV));