File: extension.js

package info (click to toggle)
gnome-shell-mailnag 3.28.0-0.1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 140 kB
  • sloc: xml: 50; makefile: 46
file content (382 lines) | stat: -rw-r--r-- 10,543 bytes parent folder | download
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
/* Mailnag - GNOME-Shell extension frontend
*
* Copyright 2013 - 2016 Patrick Ulbrich <zulu99@gmx.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/

const Main = imports.ui.main;
const Gio = imports.gi.Gio;
const GLib = imports.gi.GLib;
const Lang = imports.lang;
const ExtensionUtils = imports.misc.extensionUtils;
const Me = ExtensionUtils.getCurrentExtension();
const Convenience = Me.imports.convenience;
const Indicator = Me.imports.indicator;
const Opts = Me.imports.opts;

const AVATAR_ICON_SIZE = 38;

const SHOW_AVATARS_KEY					= 'show-avatars';
const MAX_VISIBLE_MAILS_KEY				= 'max-visible-mails';
const SHOW_DATES_KEY					= 'show-dates';
const SHOW_MARK_ALL_AS_READ_BUTTON_KEY	= 'show-mark-all-as-read-button';
const SHOW_CHECK_FOR_MAIL_BUTTON_KEY	= 'show-check-for-mail-button';
const SHOW_SETTINGS_BUTTON_KEY			= 'show-settings-button';
const SHOW_QUIT_BUTTON_KEY				= 'show-quit-button';
const GROUP_BY_ACCOUNT_KEY				= 'group-by-account';
const REMOVE_INDICATOR_KEY				= 'remove-indicator';

const KeyActionMap = new Map([
	[ SHOW_MARK_ALL_AS_READ_BUTTON_KEY,	Opts.ACTION_FLAGS.MARK_ALL_AS_READ ],
	[ SHOW_CHECK_FOR_MAIL_BUTTON_KEY,	Opts.ACTION_FLAGS.CHECK_FOR_MAIL ],
	[ SHOW_SETTINGS_BUTTON_KEY,			Opts.ACTION_FLAGS.SETTINGS ],
	[ SHOW_QUIT_BUTTON_KEY,				Opts.ACTION_FLAGS.QUIT ]
]);

const MailnagIface =
'<node>\
	<interface name="mailnag.MailnagService">\
		<method name="GetMails">\
			<arg type="aa{sv}" direction="out" />\
		</method>\
		<method name="GetMailCount">\
			<arg type="u" direction="out" />\
		</method>\
		<method name="Shutdown" />\
		<method name="CheckForMails" />\
		<method name="MarkMailAsRead">\
			<arg type="s" direction="in" />\
		</method>\
		<signal name="MailsAdded">\
			<arg type="aa{sv}" />\
			<arg type="aa{sv}" />\
		</signal>\
		<signal name="MailsRemoved">\
			<arg type="aa{sv}" />\
		</signal>\
	</interface>\
</node>';

const MailnagDbus = Gio.DBusProxy.makeProxyWrapper(MailnagIface);

const MailnagExtension = new Lang.Class({
	Name: 'MailnagExtension',
	
	_init: function(options) {
		
		this._mails = [];
		this._opts = options;
		this._indicator = null;
		
		this._proxy = new MailnagDbus(Gio.DBus.session,
			'mailnag.MailnagService', '/mailnag/MailnagService');
			
		this._onMailsAddedId = this._proxy.connectSignal('MailsAdded',
			Lang.bind(this, this._onMailsAdded));
		
		this._onMailsRemovedId = this._proxy.connectSignal('MailsRemoved',
			Lang.bind(this, this._onMailsRemoved));
		
		// TODO : what if Mailnag sends a MailsAdded signal here or after GetMailsRemote()
		// (should happen *extremely* rarely)?
		// Is it possible to prevent the extension from notifying twice?
		
		// Mailnag possibly fired a 'MailsAdded' signal before this extension was started,
		// so check if Mailnag fetched mails already and pull them manually.
		this._proxy.GetMailsRemote(Lang.bind(this,
			function([mails], error) {
				if (!error) {
					if ((mails.length > 0) || !this._opts.removeIndicator) {
						this._handle_new_mails(mails, mails);
					}
				}
			}));
	},
	
	_onMailsAdded: function(proxy, sender, [new_mails, all_mails]) {
		this._handle_new_mails(new_mails, all_mails);
	},
	
	_onMailsRemoved: function(proxy, sender, [remaining_mails]) {
		// TODO : not only support removal of *all* mails
		if (remaining_mails.length == 0) {
			this._mails = [];
			
			if (this._indicator != null) {
				if ((this._mails.length == 0) && this._opts.removeIndicator) {
					this._destroyIndicator();
				} else {
					this._indicator.setMails(this._mails);
				}
			}
		}
	},
	
	_handle_new_mails: function(new_mails, all_mails) {
		this._mails = all_mails;
		
		if (this._indicator == null) {
			this._createIndicator();
		} else {
			this._indicator.setMails(all_mails);
		}
	},
	
	_createIndicator: function() {
		this._indicator = new Indicator.MailnagIndicator(this._opts, this);
		this._indicator.setMails(this._mails);
		Main.panel.addToStatusArea('mailnag-indicator', this._indicator, 0);
	},
	
	_destroyIndicator: function() {
		if (this._indicator != null) {
			this._indicator.destroy();
			this._indicator = null;
		}
	},
	
	markMailAsRead: function(mail_id) {
		// Find the mail object with the specified mail_id
		let idx = -1;
		for (let i = 0; i < this._mails.length; i++) {
			[id, size] = this._mails[i]['id'].get_string();
			if (id == mail_id) {
				idx = i;
				break;
			}
		}
		
		// There is no mail object with the specified mail_id -> return
		if (idx == -1)
			return;
		
		// Remove mail from local mail list
		this._mails.splice(idx, 1);
		
		// Notify the Mailnag daemon to mark the mail as read
		this._proxy.MarkMailAsReadRemote(mail_id, function(result, error) {
			if (error) {
				log("Error: markMailAsReadRemote() failed.");
			}
		});
		
		// Update Panel Indicator		
		if ((this._mails.length == 0) && this._opts.removeIndicator) {
			this._destroyIndicator();
		} else {
			if (this._indicator != null)
				this._indicator.setMails(this._mails);
		}
	},
	
	markAllMailsAsRead: function() {
		// TODO: add a markAllMailsAsRead() method to the DBus interface
		for (let i = 0; i < this._mails.length; i++) {
			[id, size] = this._mails[i]['id'].get_string();
		
			// Notify the Mailnag daemon to mark the mail as read
			this._proxy.MarkMailAsReadRemote(id, function(result, error) {
				if (error) {
					log("Error: markMailAsReadRemote() failed.");
				}
			});
		}
		
		this._mails = [];
		
		if (this._opts.removeIndicator) {
			this._destroyIndicator();
		} else {
			if (this._indicator != null)
				this._indicator.setMails(this._mails);
		}
	},
	
	checkForMails: function() {
		this._proxy.CheckForMailsRemote(function(result, error) {
			if (error) {
				log("Error: checkForMailsRemote() failed.");
			}
		});
	},
	
	shutdown: function() {
		this._proxy.ShutdownRemote(function(result, error) {
			if (error) {
				log("Error: shutdownRemote() failed.");
			}
		});
	},
	
	dispose: function() {
		if (this._onMailsAddedId > -1) {
			this._proxy.disconnectSignal(this._onMailsAddedId);
			this._onMailsAddedId = -1;
		}
		
		if (this._onMailsRemovedId > -1) {
			this._proxy.disconnectSignal(this._onMailsRemovedId);
			this._onMailsRemovedId = -1;
		}
		
		this._destroyIndicator();
	}
});

function aggregateAvatarsAsync(completedCallback) {
	let aggregator = "aggregate-avatars";
	let result = null;
	let avatars = {};

	try {
		result = GLib.spawn_async_with_pipes(
			null, [aggregator], 
			null, GLib.SpawnFlags.SEARCH_PATH | 
					GLib.SpawnFlags.DO_NOT_REAP_CHILD, null);
	} catch (ex) {
		try {
			result = GLib.spawn_async_with_pipes(
				Me.path, [aggregator], 
				null, GLib.SpawnFlags.DO_NOT_REAP_CHILD, null);
		} catch (ex) {
			logError(ex, "Failed to spawn '%s'".format(aggregator));
		}
	}

	if (result == null) {
		completedCallback(avatars);
	} else {
		let [res, pid, stdin_fd, stdout_fd, stderr_fd] = result;		
		let stdout = new Gio.DataInputStream({ 
				base_stream: new Gio.UnixInputStream({ fd: stdout_fd, close_fd: true })});

		GLib.close(stdin_fd);
		GLib.close(stderr_fd);

		let childWatch = GLib.child_watch_add(GLib.PRIORITY_DEFAULT, pid, 
			function(pid, status, requestObject) {
				let [out, size] = stdout.read_line(null);

				if (size > 0) {
					let lst = out.toString().split(";");
					for (let i = 0; i < lst.length; i += 2) {
						let email = lst[i].toLowerCase();
						let avatarFile = lst[i + 1];
						avatars[email] = avatarFile;
					}
				}

				stdout.close(null);
				GLib.source_remove(childWatch);
				completedCallback(avatars);
			});
	}
}

function createExt(s, avatars) {
	
	let opts = new Opts.Options();
	
	opts.maxVisibleMails 		= s.get_int(MAX_VISIBLE_MAILS_KEY);
	opts.showDates				= s.get_boolean(SHOW_DATES_KEY);
	opts.groupMailsByAccount	= s.get_boolean(GROUP_BY_ACCOUNT_KEY);
	opts.removeIndicator		= s.get_boolean(REMOVE_INDICATOR_KEY);
	opts.avatars				= avatars;
	opts.avatarSize				= AVATAR_ICON_SIZE;
	opts.menuActions			= Opts.ACTION_FLAGS.NONE;
	
	for ([k, v] of KeyActionMap) {
		if (s.get_boolean(k))
			opts.menuActions |= v;
	}
	
	return new MailnagExtension(opts);
}

let ext = null;
let watch_id = -1;
let settings = null;
let cachedAvatars = null;
let reloadInProgress = false;

function init() {
}

function enable() {	
	settings = Convenience.getSettings();
	
	// Register changed handler for gsettings.
	// (Restarts the extension if settings
	// have been changed, e.g. via prefs.js)
	settings.connect('changed', function(settings, key) {
		if ((ext != null) && !reloadInProgress) {
			ext.dispose();

			if ((cachedAvatars == null) && (key == SHOW_AVATARS_KEY) && settings.get_boolean(key)) {
				reloadInProgress = true;
				aggregateAvatarsAsync(function(avatars) {
						cachedAvatars = avatars;
						ext = createExt(settings, avatars);
						reloadInProgress = false;
					});
			} else {							
				ext = createExt(settings, settings.get_boolean(SHOW_AVATARS_KEY) ? cachedAvatars : {});
			}
		}
	});

	// Register dbus watch handlers - create the extension 
	// if the Mailnag daemon is running / remove it if the daemon is gone.
	watch_id = Gio.DBus.session.watch_name('mailnag.MailnagService', Gio.BusNameWatcherFlags.NONE,
		function (owner) {
			if (settings.get_boolean(SHOW_AVATARS_KEY)) {
				aggregateAvatarsAsync(function(avatars) {
						cachedAvatars = avatars;
						ext = createExt(settings, avatars);
					});
			} else {
				ext = createExt(settings, {});
			}
		},
		function (owner) {
			if (ext != null) {
				ext.dispose();
				ext = null;
			}
		});
}

function disable() {
	if (watch_id > -1) {
		// TODO : test: does this call the function (owner) callback, so ext.dispose() is called twice?
		Gio.DBus.session.unwatch_name(watch_id);
		watch_id = -1;
	}
	
	cachedAvatars = null;
	reloadInProgress = false;
	
	if (settings != null) {
		settings.run_dispose();
		settings = null;
	}
	
	if (ext != null) {
		ext.dispose();
		ext = null;
	}
}