-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathextension.js
More file actions
550 lines (480 loc) · 16.4 KB
/
extension.js
File metadata and controls
550 lines (480 loc) · 16.4 KB
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
import St from "gi://St";
import Gio from "gi://Gio";
import GLib from "gi://GLib";
import Soup from "gi://Soup";
import * as Main from "resource:///org/gnome/shell/ui/main.js";
import * as PanelMenu from "resource:///org/gnome/shell/ui/panelMenu.js";
import {
Extension,
gettext as _,
} from "resource:///org/gnome/shell/extensions/extension.js";
import { GitHubApi } from "./githubApi.js";
import { GitHubTrayUI } from "./ui.js";
import { NotificationManager } from "./notificationManager.js";
import { WorkflowManager } from "./workflowManager.js";
import { RefreshManager } from "./refreshManager.js";
import { ChangeDetector, sendNotification } from "./changeDetector.js";
export default class GitHubTrayExtension extends Extension {
enable() {
this._settings = this.getSettings();
this._httpSession = new Soup.Session();
this._lastRepos = null;
this._lastFollowers = null;
this._isLoading = false;
this._pendingUpdate = null;
this._pendingDetectChanges = null;
this._createIndicator();
this._initManagers();
this._waitForNetworkAndLoad();
this._refreshManager.setupAutoRefresh();
this._refreshManager.setupNotificationRefresh();
this._refreshManager.setupMonitoredWorkflowRefresh();
this._setupSettingsListener();
}
disable() {
this._cleanupTimers();
this._disconnectSignals();
this._destroyIndicator();
this._cleanupState();
}
// -------------------------------------------------------------------------
// Initialization
// -------------------------------------------------------------------------
_createIndicator() {
this._indicator = new PanelMenu.Button(0.0, "GitHub Tray");
// GitHub icon
const iconPath = `${this.path}/ui/icons/github-symbolic.svg`;
const gicon = Gio.Icon.new_for_string(iconPath);
this._icon = new St.Icon({
gicon: gicon,
style_class: "system-status-icon",
});
const iconBox = new St.BoxLayout({
style: "spacing: 0px; padding: 0 2px;",
});
iconBox.add_child(this._icon);
this._indicator.add_child(iconBox);
// Build UI
this._ui = new GitHubTrayUI(
this._indicator,
this._settings,
this._httpSession,
this.path,
);
this._ui.setBadgeWidget(null);
this._ui.buildMenu(
() => {
this._loadRepositories(true);
this._notificationManager.load();
},
() => {
this.openPreferences();
this._indicator.menu.close();
},
() => this._onDebugClick(),
(repo, callback) => this._fetchRepoIssues(repo, callback),
(notification, callback) =>
this._notificationManager.markRead(notification, callback),
(workflowRun, callback) =>
this._workflowManager.rerun(workflowRun, callback),
(repo, callback) => this._workflowManager.fetchForRepo(repo, callback),
() => this._notificationManager.load(),
);
// Menu open-state handler
this._menuOpenChangedId = this._indicator.menu.connect(
"open-state-changed",
(_menu, open) => {
if (!open) {
this._handleMenuClose();
}
},
);
// Add to panel
const panelBox = this._settings.get_string("panel-box") || "right";
Main.panel.addToStatusArea("github-tray", this._indicator, 0, panelBox);
}
_initManagers() {
const isMenuOpen = () =>
!!(this._indicator && this._indicator.menu.isOpen);
this._notificationManager = new NotificationManager({
httpSession: this._httpSession,
settings: this._settings,
sendNotification: (summary, body, url) => sendNotification(summary, body, url),
ui: this._ui,
});
this._workflowManager = new WorkflowManager({
httpSession: this._httpSession,
settings: this._settings,
sendNotification: (summary, body, url) => sendNotification(summary, body, url),
getMonitoredRepos: () => this._getMonitoredRepos(),
isMenuOpen,
});
this._changeDetector = new ChangeDetector({ isMenuOpen });
this._refreshManager = new RefreshManager({
settings: this._settings,
loadRepositories: () => this._loadRepositories(),
loadNotifications: () => this._notificationManager.load(),
loadMonitoredWorkflowRuns: () => this._workflowManager.loadMonitored(),
});
}
// -------------------------------------------------------------------------
// Data Loading
// -------------------------------------------------------------------------
async _loadRepositories(manualRefresh = false) {
if (this._isLoading || !this._indicator) return;
const token = this._settings?.get_string("github-token");
const username = this._settings?.get_string("github-username");
if (!token || !username) {
this._ui.showMessage(_("Configure token and username in Settings"));
return;
}
this._isLoading = true;
const wasOpen = this._indicator.menu.isOpen;
const isFirstLoad = !this._lastRepos;
if (!this._indicator.menu.isOpen) {
this._ui.showMessage(_("Loading repositories..."));
}
try {
const api = new GitHubApi(this._httpSession, this._settings.get_string("github-enterprise-url"));
const promises = [
api.fetchRepositories(token, username, this._settings),
api.fetchUserInfo(token, username),
api.fetchFollowers(token),
];
// On first load, fetch notifications concurrently so everything appears together
if (isFirstLoad && this._settings.get_boolean("show-notifications")) {
promises.push(this._notificationManager.load());
}
const [repos, userInfo, followers] = await Promise.all(promises);
if (!this._indicator) return;
api.sortRepositories(repos, this._settings);
const oldRepos = this._lastRepos;
const oldFollowers = this._lastFollowers;
this._lastRepos = repos;
this._lastFollowers = followers;
this._handleRepoUpdate(repos, username, userInfo, wasOpen, manualRefresh);
// Load workflow runs for monitored repos on first load
if (!oldRepos) {
this._workflowManager.loadMonitored();
}
if (oldRepos) {
this._changeDetector.schedule(repos, oldRepos, followers, oldFollowers);
}
} catch (error) {
console.error(error, "GitHubTray");
if (this._indicator) {
this._ui.showMessage(_("Error loading repositories"));
Main.notifyError(
_("GitHub Tray"),
_("Failed to fetch repositories: %s").format(error.message),
);
}
} finally {
this._isLoading = false;
}
}
async _fetchRepoIssues(repo, callback) {
const token = this._settings?.get_string("github-token");
if (!token) {
callback([]);
return;
}
try {
const api = new GitHubApi(this._httpSession, this._settings.get_string("github-enterprise-url"));
const [owner, repoName] = repo.full_name.split("/");
const issues = await api.fetchRepoIssues(token, owner, repoName);
callback(issues);
} catch (error) {
console.error(error, "GitHubTray:fetchIssues");
callback([]);
}
}
// -------------------------------------------------------------------------
// Helpers
// -------------------------------------------------------------------------
_getLocalPath(repoFullName) {
try {
const localProjectsJson = this._settings.get_string("local-projects");
const localProjects = JSON.parse(localProjectsJson);
return localProjects[repoFullName] || null;
} catch (e) {
return null;
}
}
_getMonitoredRepos() {
if (!this._lastRepos) return [];
return this._lastRepos.filter(
(repo) => this._getLocalPath(repo.full_name) !== null,
);
}
// -------------------------------------------------------------------------
// Event Handlers
// -------------------------------------------------------------------------
_handleRepoUpdate(repos, username, userInfo, wasOpen, manualRefresh) {
const notifications = this._notificationManager.lastNotifications;
if (manualRefresh && wasOpen) {
this._pendingUpdate = { repos, username, userInfo, notifications };
this._indicator.menu.close();
if (this._menuReopenTimeout) {
GLib.source_remove(this._menuReopenTimeout);
this._menuReopenTimeout = null;
}
this._menuReopenTimeout = GLib.timeout_add(
GLib.PRIORITY_DEFAULT,
400,
() => {
this._menuReopenTimeout = null;
if (this._indicator) {
this._indicator.menu.open();
}
return GLib.SOURCE_REMOVE;
},
);
} else if (!this._indicator.menu.isOpen) {
this._ui.updateMenu(repos, username, userInfo, notifications);
} else {
this._pendingUpdate = { repos, username, userInfo, notifications };
}
}
_onDebugClick() {
if (this._lastRepos && this._lastRepos.length >= 1) {
const oldRepos = this._lastRepos;
const oldFollowers = this._lastFollowers || [];
const username = this._settings.get_string("github-username");
const modifiedRepos = this._lastRepos.map((r, i) => {
if (i < 3 && i < this._lastRepos.length) {
const clone = { ...r };
if (Math.random() > 0.5) {
clone.stargazers_count += Math.floor(Math.random() * 5) + 1;
}
if (Math.random() > 0.7) {
clone.open_issues_count += Math.floor(Math.random() * 3) + 1;
}
if (Math.random() > 0.8) {
clone.forks_count += Math.floor(Math.random() * 2) + 1;
}
return clone;
}
return r;
});
// Add mock new followers for testing
const newFollowers = [...oldFollowers];
const numNewFollowers =
Math.random() > 0.5 ? 1 : Math.floor(Math.random() * 3) + 2;
for (let i = 0; i < numNewFollowers; i++) {
newFollowers.push({
id: Date.now() + i,
login: `test_follower_${Date.now() + i}`,
});
}
this._lastRepos = modifiedRepos;
this._lastFollowers = newFollowers;
this._pendingUpdate = {
repos: modifiedRepos,
username,
userInfo: null,
};
this._pendingDetectChanges = {
newRepos: modifiedRepos,
oldRepos,
newFollowers,
oldFollowers,
};
this._indicator.menu.close();
} else {
this._indicator.menu.close();
}
}
_handleMenuClose() {
if (this._pendingUpdate || this._pendingDetectChanges) {
if (this._menuCloseTimeout) {
GLib.source_remove(this._menuCloseTimeout);
this._menuCloseTimeout = null;
}
this._menuCloseTimeout = GLib.timeout_add(
GLib.PRIORITY_DEFAULT,
300,
() => {
this._menuCloseTimeout = null;
if (!this._indicator) return GLib.SOURCE_REMOVE;
if (this._pendingUpdate) {
const { repos, username, userInfo, notifications } =
this._pendingUpdate;
this._pendingUpdate = null;
this._ui.updateMenu(
repos,
username,
userInfo,
notifications || this._notificationManager.lastNotifications,
);
}
if (this._pendingDetectChanges) {
const { newRepos, oldRepos, newFollowers, oldFollowers } =
this._pendingDetectChanges;
this._pendingDetectChanges = null;
this._changeDetector.schedule(
newRepos,
oldRepos,
newFollowers,
oldFollowers,
);
}
return GLib.SOURCE_REMOVE;
},
);
}
}
// -------------------------------------------------------------------------
// Settings
// -------------------------------------------------------------------------
_setupSettingsListener() {
this._settingsDebounceId = null;
this._settingsChangedId = this._settings.connect(
"changed",
(_settings, key) => {
if (key === "debug-mode" && this._ui) {
this._ui.updateDebugButtonVisibility();
return;
}
if (key === "panel-box") {
this._updatePanelPosition();
return;
}
if (key === "show-notifications" && this._ui) {
// Rebuild the menu immediately to reflect the new setting
if (this._lastRepos) {
const username = this._settings.get_string("github-username");
const notifications =
this._notificationManager?.lastNotifications ?? [];
this._ui.updateMenu(
this._lastRepos,
username,
this._ui._cachedUserInfo,
notifications,
);
}
// Start or stop the notification refresh timer accordingly
this._refreshManager?.restartNotificationRefresh();
return;
}
if (
![
"github-token",
"github-username",
"github-enterprise-url",
"max-repos",
"sort-by",
"sort-order",
].includes(key)
)
return;
if (this._settingsDebounceId) {
GLib.source_remove(this._settingsDebounceId);
this._settingsDebounceId = null;
}
this._settingsDebounceId = GLib.timeout_add(
GLib.PRIORITY_DEFAULT,
1500,
() => {
this._settingsDebounceId = null;
this._loadRepositories();
return GLib.SOURCE_REMOVE;
},
);
},
);
}
_updatePanelPosition() {
if (!this._indicator) return;
const container = this._indicator.get_parent();
if (container) {
container.remove_child(this._indicator);
}
const panelBox = this._settings.get_string("panel-box") || "right";
Main.panel.addToStatusArea("github-tray", this._indicator, 0, panelBox);
}
// -------------------------------------------------------------------------
// Network
// -------------------------------------------------------------------------
_waitForNetworkAndLoad() {
const networkMonitor = Gio.NetworkMonitor.get_default();
if (networkMonitor.get_connectivity() === Gio.NetworkConnectivity.FULL) {
this._loadRepositories();
} else {
this._ui.showMessage(_("Waiting for network connection..."));
this._networkChangedId = networkMonitor.connect(
"network-changed",
(monitor) => {
if (
monitor.get_connectivity() === Gio.NetworkConnectivity.FULL &&
this._indicator
) {
this._loadRepositories();
if (this._networkChangedId) {
monitor.disconnect(this._networkChangedId);
this._networkChangedId = null;
}
}
},
);
}
}
// -------------------------------------------------------------------------
// Cleanup
// -------------------------------------------------------------------------
_cleanupTimers() {
this._refreshManager?.cleanup();
this._changeDetector?.cleanup();
if (this._settingsDebounceId) {
GLib.source_remove(this._settingsDebounceId);
this._settingsDebounceId = null;
}
if (this._menuReopenTimeout) {
GLib.source_remove(this._menuReopenTimeout);
this._menuReopenTimeout = null;
}
if (this._menuCloseTimeout) {
GLib.source_remove(this._menuCloseTimeout);
this._menuCloseTimeout = null;
}
}
_disconnectSignals() {
if (this._settingsChangedId) {
this._settings.disconnect(this._settingsChangedId);
this._settingsChangedId = null;
}
if (this._menuOpenChangedId) {
this._indicator.menu.disconnect(this._menuOpenChangedId);
this._menuOpenChangedId = null;
}
if (this._networkChangedId) {
const networkMonitor = Gio.NetworkMonitor.get_default();
networkMonitor.disconnect(this._networkChangedId);
this._networkChangedId = null;
}
}
_destroyIndicator() {
if (this._indicator) {
this._indicator.destroy();
this._indicator = null;
}
}
_cleanupState() {
this._notificationManager?.destroy();
this._notificationManager = null;
this._workflowManager?.destroy();
this._workflowManager = null;
this._refreshManager?.destroy();
this._refreshManager = null;
this._changeDetector?.destroy();
this._changeDetector = null;
this._httpSession.abort();
this._httpSession = null;
this._settings = null;
this._lastRepos = null;
this._lastFollowers = null;
this._pendingUpdate = null;
this._pendingDetectChanges = null;
this._ui = null;
}
}