sms.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. // SPDX-FileCopyrightText: GSConnect Developers https://github.com/GSConnect
  2. //
  3. // SPDX-License-Identifier: GPL-2.0-or-later
  4. 'use strict';
  5. const Gio = imports.gi.Gio;
  6. const GLib = imports.gi.GLib;
  7. const GObject = imports.gi.GObject;
  8. const PluginBase = imports.service.plugin;
  9. const LegacyMessaging = imports.service.ui.legacyMessaging;
  10. const Messaging = imports.service.ui.messaging;
  11. const URI = imports.service.utils.uri;
  12. var Metadata = {
  13. label: _('SMS'),
  14. description: _('Send and read SMS of the paired device and be notified of new SMS'),
  15. id: 'org.gnome.Shell.Extensions.GSConnect.Plugin.SMS',
  16. incomingCapabilities: [
  17. 'kdeconnect.sms.messages',
  18. ],
  19. outgoingCapabilities: [
  20. 'kdeconnect.sms.request',
  21. 'kdeconnect.sms.request_conversation',
  22. 'kdeconnect.sms.request_conversations',
  23. ],
  24. actions: {
  25. // SMS Actions
  26. sms: {
  27. label: _('Messaging'),
  28. icon_name: 'sms-symbolic',
  29. parameter_type: null,
  30. incoming: [],
  31. outgoing: ['kdeconnect.sms.request'],
  32. },
  33. uriSms: {
  34. label: _('New SMS (URI)'),
  35. icon_name: 'sms-symbolic',
  36. parameter_type: new GLib.VariantType('s'),
  37. incoming: [],
  38. outgoing: ['kdeconnect.sms.request'],
  39. },
  40. replySms: {
  41. label: _('Reply SMS'),
  42. icon_name: 'sms-symbolic',
  43. parameter_type: new GLib.VariantType('s'),
  44. incoming: [],
  45. outgoing: ['kdeconnect.sms.request'],
  46. },
  47. sendMessage: {
  48. label: _('Send Message'),
  49. icon_name: 'sms-send',
  50. parameter_type: new GLib.VariantType('(aa{sv})'),
  51. incoming: [],
  52. outgoing: ['kdeconnect.sms.request'],
  53. },
  54. sendSms: {
  55. label: _('Send SMS'),
  56. icon_name: 'sms-send',
  57. parameter_type: new GLib.VariantType('(ss)'),
  58. incoming: [],
  59. outgoing: ['kdeconnect.sms.request'],
  60. },
  61. shareSms: {
  62. label: _('Share SMS'),
  63. icon_name: 'sms-send',
  64. parameter_type: new GLib.VariantType('s'),
  65. incoming: [],
  66. outgoing: ['kdeconnect.sms.request'],
  67. },
  68. },
  69. };
  70. /**
  71. * SMS Message event type. Currently all events are TEXT_MESSAGE.
  72. *
  73. * TEXT_MESSAGE: Has a "body" field which contains pure, human-readable text
  74. */
  75. var MessageEventType = {
  76. TEXT_MESSAGE: 0x1,
  77. };
  78. /**
  79. * SMS Message status. READ/UNREAD match the 'read' field from the Android App
  80. * message packet.
  81. *
  82. * UNREAD: A message not marked as read
  83. * READ: A message marked as read
  84. */
  85. var MessageStatus = {
  86. UNREAD: 0,
  87. READ: 1,
  88. };
  89. /**
  90. * SMS Message type, set from the 'type' field in the Android App
  91. * message packet.
  92. *
  93. * See: https://developer.android.com/reference/android/provider/Telephony.TextBasedSmsColumns.html
  94. *
  95. * ALL: all messages
  96. * INBOX: Received messages
  97. * SENT: Sent messages
  98. * DRAFT: Message drafts
  99. * OUTBOX: Outgoing messages
  100. * FAILED: Failed outgoing messages
  101. * QUEUED: Messages queued to send later
  102. */
  103. var MessageBox = {
  104. ALL: 0,
  105. INBOX: 1,
  106. SENT: 2,
  107. DRAFT: 3,
  108. OUTBOX: 4,
  109. FAILED: 5,
  110. QUEUED: 6,
  111. };
  112. /**
  113. * SMS Plugin
  114. * https://github.com/KDE/kdeconnect-kde/tree/master/plugins/sms
  115. * https://github.com/KDE/kdeconnect-android/tree/master/src/org/kde/kdeconnect/Plugins/SMSPlugin/
  116. */
  117. var Plugin = GObject.registerClass({
  118. GTypeName: 'GSConnectSMSPlugin',
  119. Properties: {
  120. 'threads': GObject.param_spec_variant(
  121. 'threads',
  122. 'Conversation List',
  123. 'A list of threads',
  124. new GLib.VariantType('aa{sv}'),
  125. null,
  126. GObject.ParamFlags.READABLE
  127. ),
  128. },
  129. }, class Plugin extends PluginBase.Plugin {
  130. _init(device) {
  131. super._init(device, 'sms');
  132. this.cacheProperties(['_threads']);
  133. }
  134. get threads() {
  135. if (this._threads === undefined)
  136. this._threads = {};
  137. return this._threads;
  138. }
  139. get window() {
  140. if (this.settings.get_boolean('legacy-sms')) {
  141. return new LegacyMessaging.Dialog({
  142. device: this.device,
  143. plugin: this,
  144. });
  145. }
  146. if (this._window === undefined) {
  147. this._window = new Messaging.Window({
  148. application: Gio.Application.get_default(),
  149. device: this.device,
  150. plugin: this,
  151. });
  152. this._window.connect('destroy', () => {
  153. this._window = undefined;
  154. });
  155. }
  156. return this._window;
  157. }
  158. clearCache() {
  159. this._threads = {};
  160. this.notify('threads');
  161. }
  162. cacheLoaded() {
  163. this.notify('threads');
  164. }
  165. connected() {
  166. super.connected();
  167. this._requestConversations();
  168. }
  169. handlePacket(packet) {
  170. switch (packet.type) {
  171. case 'kdeconnect.sms.messages':
  172. this._handleMessages(packet.body.messages);
  173. break;
  174. }
  175. }
  176. /**
  177. * Handle a digest of threads.
  178. *
  179. * @param {Object[]} messages - A list of message objects
  180. * @param {string[]} thread_ids - A list of thread IDs as strings
  181. */
  182. _handleDigest(messages, thread_ids) {
  183. // Prune threads
  184. for (const thread_id of Object.keys(this.threads)) {
  185. if (!thread_ids.includes(thread_id))
  186. delete this.threads[thread_id];
  187. }
  188. // Request each new or newer thread
  189. for (let i = 0, len = messages.length; i < len; i++) {
  190. const message = messages[i];
  191. const cache = this.threads[message.thread_id];
  192. if (cache === undefined) {
  193. this._requestConversation(message.thread_id);
  194. continue;
  195. }
  196. // If this message is marked read, mark the rest as read
  197. if (message.read === MessageStatus.READ) {
  198. for (const msg of cache)
  199. msg.read = MessageStatus.READ;
  200. }
  201. // If we don't have a thread for this message or it's newer
  202. // than the last message in the cache, request the thread
  203. if (!cache.length || cache[cache.length - 1].date < message.date)
  204. this._requestConversation(message.thread_id);
  205. }
  206. this.notify('threads');
  207. }
  208. /**
  209. * Handle a new single message
  210. *
  211. * @param {Object} message - A message object
  212. */
  213. _handleMessage(message) {
  214. let conversation = null;
  215. // If the window is open, try and find an active conversation
  216. if (this._window)
  217. conversation = this._window.getConversationForMessage(message);
  218. // If there's an active conversation, we should log the message now
  219. if (conversation)
  220. conversation.logNext(message);
  221. }
  222. /**
  223. * Parse a conversation (thread of messages) and sort them
  224. *
  225. * @param {Object[]} thread - A list of sms message objects from a thread
  226. */
  227. _handleThread(thread) {
  228. // If there are no addresses this will cause major problems...
  229. if (!thread[0].addresses || !thread[0].addresses[0])
  230. return;
  231. const thread_id = thread[0].thread_id;
  232. const cache = this.threads[thread_id] || [];
  233. // Handle each message
  234. for (let i = 0, len = thread.length; i < len; i++) {
  235. const message = thread[i];
  236. // TODO: We only cache messages of a known MessageBox since we
  237. // have no reliable way to determine its direction, let alone
  238. // what to do with it.
  239. if (message.type < 0 || message.type > 6)
  240. continue;
  241. // If the message exists, just update it
  242. const cacheMessage = cache.find(m => m.date === message.date);
  243. if (cacheMessage) {
  244. Object.assign(cacheMessage, message);
  245. } else {
  246. cache.push(message);
  247. this._handleMessage(message);
  248. }
  249. }
  250. // Sort the thread by ascending date and notify
  251. this.threads[thread_id] = cache.sort((a, b) => a.date - b.date);
  252. this.notify('threads');
  253. }
  254. /**
  255. * Handle a response to telephony.request_conversation(s)
  256. *
  257. * @param {Object[]} messages - A list of sms message objects
  258. */
  259. _handleMessages(messages) {
  260. try {
  261. // If messages is empty there's nothing to do...
  262. if (messages.length === 0)
  263. return;
  264. const thread_ids = [];
  265. // Perform some modification of the messages
  266. for (let i = 0, len = messages.length; i < len; i++) {
  267. const message = messages[i];
  268. // COERCION: thread_id's to strings
  269. message.thread_id = `${message.thread_id}`;
  270. thread_ids.push(message.thread_id);
  271. // TODO: Remove bogus `insert-address-token` entries
  272. let a = message.addresses.length;
  273. while (a--) {
  274. if (message.addresses[a].address === undefined ||
  275. message.addresses[a].address === 'insert-address-token')
  276. message.addresses.splice(a, 1);
  277. }
  278. }
  279. // If there's multiple thread_id's it's a summary of threads
  280. if (thread_ids.some(id => id !== thread_ids[0]))
  281. this._handleDigest(messages, thread_ids);
  282. // Otherwise this is single thread or new message
  283. else
  284. this._handleThread(messages);
  285. } catch (e) {
  286. debug(e, this.device.name);
  287. }
  288. }
  289. /**
  290. * Request a list of messages from a single thread.
  291. *
  292. * @param {number} thread_id - The id of the thread to request
  293. */
  294. _requestConversation(thread_id) {
  295. this.device.sendPacket({
  296. type: 'kdeconnect.sms.request_conversation',
  297. body: {
  298. threadID: thread_id,
  299. },
  300. });
  301. }
  302. /**
  303. * Request a list of the last message in each unarchived thread.
  304. */
  305. _requestConversations() {
  306. this.device.sendPacket({
  307. type: 'kdeconnect.sms.request_conversations',
  308. });
  309. }
  310. /**
  311. * A notification action for replying to SMS messages (or missed calls).
  312. *
  313. * @param {string} hint - Could be either a contact name or phone number
  314. */
  315. replySms(hint) {
  316. this.window.present();
  317. // FIXME: causes problems now that non-numeric addresses are allowed
  318. // this.window.address = hint.toPhoneNumber();
  319. }
  320. /**
  321. * Send an SMS message
  322. *
  323. * @param {string} phoneNumber - The phone number to send the message to
  324. * @param {string} messageBody - The message to send
  325. */
  326. sendSms(phoneNumber, messageBody) {
  327. this.device.sendPacket({
  328. type: 'kdeconnect.sms.request',
  329. body: {
  330. sendSms: true,
  331. phoneNumber: phoneNumber,
  332. messageBody: messageBody,
  333. },
  334. });
  335. }
  336. /**
  337. * Send a message
  338. *
  339. * @param {Object[]} addresses - A list of address objects
  340. * @param {string} messageBody - The message text
  341. * @param {number} [event] - An event bitmask
  342. * @param {boolean} [forceSms] - Whether to force SMS
  343. * @param {number} [subId] - The SIM card to use
  344. */
  345. sendMessage(addresses, messageBody, event = 1, forceSms = false, subId = undefined) {
  346. // TODO: waiting on support in kdeconnect-android
  347. // if (this._version === 1) {
  348. this.device.sendPacket({
  349. type: 'kdeconnect.sms.request',
  350. body: {
  351. sendSms: true,
  352. phoneNumber: addresses[0].address,
  353. messageBody: messageBody,
  354. },
  355. });
  356. // } else if (this._version === 2) {
  357. // this.device.sendPacket({
  358. // type: 'kdeconnect.sms.request',
  359. // body: {
  360. // version: 2,
  361. // addresses: addresses,
  362. // messageBody: messageBody,
  363. // forceSms: forceSms,
  364. // sub_id: subId
  365. // }
  366. // });
  367. // }
  368. }
  369. /**
  370. * Share a text content by SMS message. This is used by the WebExtension to
  371. * share URLs from the browser, but could be used to initiate sharing of any
  372. * text content.
  373. *
  374. * @param {string} url - The link to be shared
  375. */
  376. shareSms(url) {
  377. // Legacy Mode
  378. if (this.settings.get_boolean('legacy-sms')) {
  379. const window = this.window;
  380. window.present();
  381. window.setMessage(url);
  382. // If there are active threads, show the chooser dialog
  383. } else if (Object.values(this.threads).length > 0) {
  384. const window = new Messaging.ConversationChooser({
  385. application: Gio.Application.get_default(),
  386. device: this.device,
  387. message: url,
  388. plugin: this,
  389. });
  390. window.present();
  391. // Otherwise show the window and wait for a contact to be chosen
  392. } else {
  393. this.window.present();
  394. this.window.setMessage(url, true);
  395. }
  396. }
  397. /**
  398. * Open and present the messaging window
  399. */
  400. sms() {
  401. this.window.present();
  402. }
  403. /**
  404. * This is the sms: URI scheme handler
  405. *
  406. * @param {string} uri - The URI the handle (sms:|sms://|sms:///)
  407. */
  408. uriSms(uri) {
  409. try {
  410. uri = new URI.SmsURI(uri);
  411. // Lookup contacts
  412. const addresses = uri.recipients.map(number => {
  413. return {address: number.toPhoneNumber()};
  414. });
  415. const contacts = this.device.contacts.lookupAddresses(addresses);
  416. // Present the window and show the conversation
  417. const window = this.window;
  418. window.present();
  419. window.setContacts(contacts);
  420. // Set the outgoing message if the uri has a body variable
  421. if (uri.body)
  422. window.setMessage(uri.body);
  423. } catch (e) {
  424. debug(e, `${this.device.name}: "${uri}"`);
  425. }
  426. }
  427. _threadHasAddress(thread, addressObj) {
  428. const number = addressObj.address.toPhoneNumber();
  429. for (const taddressObj of thread[0].addresses) {
  430. const tnumber = taddressObj.address.toPhoneNumber();
  431. if (number.endsWith(tnumber) || tnumber.endsWith(number))
  432. return true;
  433. }
  434. return false;
  435. }
  436. /**
  437. * Try to find a thread_id in @smsPlugin for @addresses.
  438. *
  439. * @param {Object[]} addresses - a list of address objects
  440. * @return {string|null} a thread ID
  441. */
  442. getThreadIdForAddresses(addresses = []) {
  443. const threads = Object.values(this.threads);
  444. for (const thread of threads) {
  445. if (addresses.length !== thread[0].addresses.length)
  446. continue;
  447. if (addresses.every(addressObj => this._threadHasAddress(thread, addressObj)))
  448. return thread[0].thread_id;
  449. }
  450. return null;
  451. }
  452. destroy() {
  453. if (this._window !== undefined)
  454. this._window.destroy();
  455. super.destroy();
  456. }
  457. });