notification.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. // SPDX-FileCopyrightText: GSConnect Developers https://github.com/GSConnect
  2. //
  3. // SPDX-License-Identifier: GPL-2.0-or-later
  4. import Gio from 'gi://Gio';
  5. import GLib from 'gi://GLib';
  6. import GObject from 'gi://GObject';
  7. import St from 'gi://St';
  8. import * as Main from 'resource:///org/gnome/shell/ui/main.js';
  9. import * as MessageTray from 'resource:///org/gnome/shell/ui/messageTray.js';
  10. import * as NotificationDaemon from 'resource:///org/gnome/shell/ui/notificationDaemon.js';
  11. import {gettext as _} from 'resource:///org/gnome/shell/extensions/extension.js';
  12. import {HAS_MESSAGELIST_NOTIFICATIONMESSAGE, getIcon} from './utils.js';
  13. const {NotificationMessage} = HAS_MESSAGELIST_NOTIFICATIONMESSAGE
  14. ? await import('resource:///org/gnome/shell/ui/messageList.js') // GNOME 48
  15. : await import('resource:///org/gnome/shell/ui/calendar.js'); // GNOME 46/47
  16. const APP_ID = 'org.gnome.Shell.Extensions.GSConnect';
  17. const APP_PATH = '/org/gnome/Shell/Extensions/GSConnect';
  18. // deviceId Pattern (<device-id>|<remote-id>)
  19. const DEVICE_REGEX = new RegExp(/^([^|]+)\|([\s\S]+)$/);
  20. // requestReplyId Pattern (<device-id>|<remote-id>)|<reply-id>)
  21. const REPLY_REGEX = new RegExp(/^([^|]+)\|([\s\S]+)\|([0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})$/, 'i');
  22. /**
  23. * Extracted from notificationDaemon.js, as it's no longer exported
  24. * https://gitlab.gnome.org/GNOME/gnome-shell/-/blob/main/js/ui/notificationDaemon.js#L556
  25. *
  26. * @returns {{ 'desktop-startup-id': string }} Object with ID containing current time
  27. */
  28. function getPlatformData() {
  29. const startupId = GLib.Variant.new('s', `_TIME${global.get_current_time()}`);
  30. return {'desktop-startup-id': startupId};
  31. }
  32. // This is no longer directly exported, so we do this instead for now
  33. const GtkNotificationDaemon = Main.notificationDaemon._gtkNotificationDaemon.constructor;
  34. /**
  35. * A slightly modified Notification Banner with an entry field
  36. */
  37. const NotificationBanner = GObject.registerClass({
  38. GTypeName: 'GSConnectNotificationBanner',
  39. }, class NotificationBanner extends NotificationMessage {
  40. constructor(notification) {
  41. super(notification);
  42. if (notification.requestReplyId !== undefined)
  43. this._addReplyAction();
  44. }
  45. _addReplyAction() {
  46. if (!this._buttonBox) {
  47. this._buttonBox = new St.BoxLayout({
  48. style_class: 'notification-buttons-bin',
  49. x_expand: true,
  50. });
  51. this.setActionArea(this._buttonBox);
  52. global.focus_manager.add_group(this._buttonBox);
  53. }
  54. // Reply Button
  55. const button = new St.Button({
  56. style_class: 'notification-button',
  57. label: _('Reply'),
  58. x_expand: true,
  59. can_focus: true,
  60. });
  61. button.connect(
  62. 'clicked',
  63. this._onEntryRequested.bind(this)
  64. );
  65. this._buttonBox.add_child(button);
  66. // Reply Entry
  67. this._replyEntry = new St.Entry({
  68. can_focus: true,
  69. hint_text: _('Type a message'),
  70. style_class: 'chat-response',
  71. x_expand: true,
  72. visible: false,
  73. });
  74. this._buttonBox.add_child(this._replyEntry);
  75. }
  76. _onEntryRequested(button) {
  77. this.focused = true;
  78. for (const child of this._buttonBox.get_children())
  79. child.visible = (child === this._replyEntry);
  80. // Release the notification focus with the entry focus
  81. this._replyEntry.connect(
  82. 'key-focus-out',
  83. this._onEntryDismissed.bind(this)
  84. );
  85. this._replyEntry.clutter_text.connect(
  86. 'activate',
  87. this._onEntryActivated.bind(this)
  88. );
  89. this._replyEntry.grab_key_focus();
  90. }
  91. _onEntryDismissed(entry) {
  92. this.focused = false;
  93. this.emit('unfocused');
  94. }
  95. _onEntryActivated(clutter_text) {
  96. // Refuse to send empty replies
  97. if (clutter_text.text === '')
  98. return;
  99. // Copy the text, then clear the entry
  100. const text = clutter_text.text;
  101. clutter_text.text = '';
  102. const {deviceId, requestReplyId} = this.notification;
  103. const target = new GLib.Variant('(ssbv)', [
  104. deviceId,
  105. 'replyNotification',
  106. true,
  107. new GLib.Variant('(ssa{ss})', [requestReplyId, text, {}]),
  108. ]);
  109. const platformData = getPlatformData();
  110. Gio.DBus.session.call(
  111. APP_ID,
  112. APP_PATH,
  113. 'org.freedesktop.Application',
  114. 'ActivateAction',
  115. GLib.Variant.new('(sava{sv})', ['device', [target], platformData]),
  116. null,
  117. Gio.DBusCallFlags.NO_AUTO_START,
  118. -1,
  119. null,
  120. (connection, res) => {
  121. try {
  122. connection.call_finish(res);
  123. } catch {
  124. // Silence errors
  125. }
  126. }
  127. );
  128. this.close();
  129. }
  130. });
  131. /**
  132. * A custom notification source for spawning notifications and closing device
  133. * notifications. This source isn't actually used, but it's methods are patched
  134. * into existing sources.
  135. */
  136. const Source = GObject.registerClass({
  137. GTypeName: 'GSConnectNotificationSource',
  138. }, class Source extends NotificationDaemon.GtkNotificationDaemonAppSource {
  139. _closeGSConnectNotification(notification, reason) {
  140. if (reason !== MessageTray.NotificationDestroyedReason.DISMISSED)
  141. return;
  142. // Avoid sending the request multiple times
  143. if (notification._remoteClosed || notification.remoteId === undefined)
  144. return;
  145. notification._remoteClosed = true;
  146. const target = new GLib.Variant('(ssbv)', [
  147. notification.deviceId,
  148. 'closeNotification',
  149. true,
  150. new GLib.Variant('s', notification.remoteId),
  151. ]);
  152. const platformData = getPlatformData();
  153. Gio.DBus.session.call(
  154. APP_ID,
  155. APP_PATH,
  156. 'org.freedesktop.Application',
  157. 'ActivateAction',
  158. GLib.Variant.new('(sava{sv})', ['device', [target], platformData]),
  159. null,
  160. Gio.DBusCallFlags.NO_AUTO_START,
  161. -1,
  162. null,
  163. (connection, res) => {
  164. try {
  165. connection.call_finish(res);
  166. } catch {
  167. // If we fail, reset in case we can try again
  168. notification._remoteClosed = false;
  169. }
  170. }
  171. );
  172. }
  173. /*
  174. * Parse the id to determine if it's a repliable notification, device
  175. * notification or a regular local notification
  176. */
  177. _parseNotificationId(notificationId) {
  178. let idMatch, deviceId, requestReplyId, remoteId, localId;
  179. if ((idMatch = REPLY_REGEX.exec(notificationId))) {
  180. [, deviceId, remoteId, requestReplyId] = idMatch;
  181. localId = `${deviceId}|${remoteId}`;
  182. } else if ((idMatch = DEVICE_REGEX.exec(notificationId))) {
  183. [, deviceId, remoteId] = idMatch;
  184. localId = `${deviceId}|${remoteId}`;
  185. } else {
  186. localId = notificationId;
  187. }
  188. return [idMatch, deviceId, requestReplyId, remoteId, localId];
  189. }
  190. /*
  191. * Add notification to source or update existing notification with extra
  192. * GsConnect information
  193. */
  194. _createNotification(notification) {
  195. const [idMatch, deviceId, requestReplyId, remoteId, localId] = this._parseNotificationId(notification.id);
  196. const cachedNotification = this._notifications[localId];
  197. // Check if this is a repeat
  198. if (cachedNotification) {
  199. cachedNotification.requestReplyId = requestReplyId;
  200. const title = notification.title;
  201. const body = notification.body
  202. ? notification.body
  203. : null;
  204. // Bail early If @notification represents an exact repeat
  205. if (cachedNotification.title === title &&
  206. cachedNotification.body === body)
  207. return cachedNotification;
  208. // If the details have changed, flag as an update
  209. cachedNotification.title = title;
  210. cachedNotification.body = body;
  211. cachedNotification.acknowledged = false;
  212. return cachedNotification;
  213. }
  214. // Device Notification
  215. if (idMatch) {
  216. notification.deviceId = deviceId;
  217. notification.remoteId = remoteId;
  218. notification.requestReplyId = requestReplyId;
  219. notification.connect('destroy', (notification, reason) => {
  220. this._closeGSConnectNotification(notification, reason);
  221. delete this._notifications[localId];
  222. });
  223. // Service Notification
  224. } else {
  225. notification.connect('destroy', (notification, reason) => {
  226. delete this._notifications[localId];
  227. });
  228. }
  229. this._notifications[localId] = notification;
  230. return notification;
  231. }
  232. /*
  233. * Override to control notification spawning
  234. */
  235. addNotification(notification) {
  236. this._notificationPending = true;
  237. // Fix themed icons
  238. if (notification.icon) {
  239. let gicon = notification.icon;
  240. if (gicon instanceof Gio.ThemedIcon) {
  241. gicon = getIcon(gicon.names[0]);
  242. notification.icon = gicon.serialize();
  243. }
  244. }
  245. const createdNotification = this._createNotification(notification);
  246. this._addNotificationToMessageTray(createdNotification);
  247. this._notificationPending = false;
  248. }
  249. /*
  250. * Reimplementation of MessageTray.addNotification to raise the usual
  251. * notification limit (3)
  252. */
  253. _addNotificationToMessageTray(notification) {
  254. if (this.notifications.includes(notification))
  255. return;
  256. while (this.notifications.length >= 10) {
  257. const [oldest] = this.notifications;
  258. oldest.destroy(MessageTray.NotificationDestroyedReason.EXPIRED);
  259. }
  260. notification.connect('destroy', this._onNotificationDestroy.bind(this));
  261. notification.connect('notify::acknowledged', () => {
  262. this.countUpdated();
  263. // If acknowledged was set to false try to show the notification again
  264. if (!notification.acknowledged)
  265. this.emit('notification-request-banner', notification);
  266. });
  267. this.notifications.push(notification);
  268. this.emit('notification-added', notification);
  269. this.emit('notification-request-banner', notification);
  270. }
  271. createBanner(notification) {
  272. return new NotificationBanner(notification);
  273. }
  274. });
  275. /**
  276. * If there is an active GtkNotificationDaemonAppSource for GSConnect when the
  277. * extension is loaded, it has to be patched in place.
  278. */
  279. export function patchGSConnectNotificationSource() {
  280. const source = Main.notificationDaemon._gtkNotificationDaemon._sources[APP_ID];
  281. if (source !== undefined) {
  282. // Patch in the subclassed methods
  283. source._closeGSConnectNotification = Source.prototype._closeGSConnectNotification;
  284. source._parseNotificationId = Source.prototype._parseNotificationId;
  285. source._createNotification = Source.prototype._createNotification;
  286. source.addNotification = Source.prototype.addNotification;
  287. source._addNotificationToMessageTray = Source.prototype._addNotificationToMessageTray;
  288. source.createBanner = Source.prototype.createBanner;
  289. // Connect to existing notifications
  290. for (const notification of Object.values(source._notifications)) {
  291. const _id = notification.connect('destroy', (notification, reason) => {
  292. source._closeGSConnectNotification(notification, reason);
  293. notification.disconnect(_id);
  294. });
  295. }
  296. }
  297. }
  298. /**
  299. * Wrap GtkNotificationDaemon._ensureAppSource() to patch GSConnect's app source
  300. * https://gitlab.gnome.org/GNOME/gnome-shell/blob/master/js/ui/notificationDaemon.js#L742-755
  301. */
  302. const __ensureAppSource = GtkNotificationDaemon.prototype._ensureAppSource;
  303. // eslint-disable-next-line func-style
  304. const _ensureAppSource = function (appId) {
  305. const source = __ensureAppSource.call(this, appId);
  306. if (source._appId === APP_ID) {
  307. source._closeGSConnectNotification = Source.prototype._closeGSConnectNotification;
  308. source._parseNotificationId = Source.prototype._parseNotificationId;
  309. source._createNotification = Source.prototype._createNotification;
  310. source.addNotification = Source.prototype.addNotification;
  311. source._addNotificationToMessageTray = Source.prototype._addNotificationToMessageTray;
  312. source.createBanner = Source.prototype.createBanner;
  313. }
  314. return source;
  315. };
  316. /**
  317. * Update the prototype for {@link GtkNotificationDaemon}.
  318. */
  319. export function patchGtkNotificationDaemon() {
  320. GtkNotificationDaemon.prototype._ensureAppSource = _ensureAppSource;
  321. }
  322. /**
  323. * Restore the prototype for {@link GtkNotificationDaemon}.
  324. */
  325. export function unpatchGtkNotificationDaemon() {
  326. GtkNotificationDaemon.prototype._ensureAppSource = __ensureAppSource;
  327. }
  328. /**
  329. * We patch other Gtk notification sources so we can notify remote devices when
  330. * notifications have been closed locally.
  331. */
  332. const _addNotification = NotificationDaemon.GtkNotificationDaemonAppSource.prototype.addNotification;
  333. /**
  334. * Update the prototype for {@link NotificationDaemon.GtkNotificationDaemonAppSource}.
  335. */
  336. export function patchGtkNotificationSources() {
  337. // eslint-disable-next-line func-style
  338. const _withdrawGSConnectNotification = function (id, notification, reason) {
  339. if (reason !== MessageTray.NotificationDestroyedReason.DISMISSED)
  340. return;
  341. // Avoid sending the request multiple times
  342. if (notification._remoteWithdrawn)
  343. return;
  344. notification._remoteWithdrawn = true;
  345. // Recreate the notification id as it would've been sent
  346. const target = new GLib.Variant('(ssbv)', [
  347. '*',
  348. 'withdrawNotification',
  349. true,
  350. new GLib.Variant('s', `gtk|${this._appId}|${id}`),
  351. ]);
  352. const platformData = getPlatformData();
  353. Gio.DBus.session.call(
  354. APP_ID,
  355. APP_PATH,
  356. 'org.freedesktop.Application',
  357. 'ActivateAction',
  358. GLib.Variant.new('(sava{sv})', ['device', [target], platformData]),
  359. null,
  360. Gio.DBusCallFlags.NO_AUTO_START,
  361. -1,
  362. null,
  363. (connection, res) => {
  364. try {
  365. connection.call_finish(res);
  366. } catch {
  367. // If we fail, reset in case we can try again
  368. notification._remoteWithdrawn = false;
  369. }
  370. }
  371. );
  372. };
  373. NotificationDaemon.GtkNotificationDaemonAppSource.prototype._withdrawGSConnectNotification = _withdrawGSConnectNotification;
  374. }
  375. /**
  376. * Restore the prototype for {@link NotificationDaemon.GtkNotificationDaemonAppSource}.
  377. */
  378. export function unpatchGtkNotificationSources() {
  379. NotificationDaemon.GtkNotificationDaemonAppSource.prototype.addNotification = _addNotification;
  380. delete NotificationDaemon.GtkNotificationDaemonAppSource.prototype._withdrawGSConnectNotification;
  381. }