Skip to content

Commit

Permalink
refactor background task initialization
Browse files Browse the repository at this point in the history
  • Loading branch information
Serghei Paduret committed Jul 7, 2021
1 parent c738245 commit 500f1ef
Show file tree
Hide file tree
Showing 8 changed files with 76 additions and 73 deletions.
8 changes: 1 addition & 7 deletions angular.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,13 +52,7 @@
"with": "src/environments/environment.prod.ts"
}
],
"outputHashing": "all",
"buildOptimizer": true,
"optimization": true,
"vendorChunk": false,
"extractLicenses": true,
"sourceMap": true,
"namedChunks": true
"outputHashing": "all"
},
"development": {
"buildOptimizer": false,
Expand Down
52 changes: 2 additions & 50 deletions src/app/components/background-page/background-page.component.ts
Original file line number Diff line number Diff line change
@@ -1,64 +1,16 @@
import {Component, OnInit} from '@angular/core';
import {BackgroundService} from '../../services/background.service';
// @ts-ignore
import Alarm = chrome.alarms.Alarm;
import {DataService} from '../../services/data.service';

// @ts-ignore
let chr: any = chrome;

@Component({
selector: 'app-background-service',
templateUrl: './background-page.component.html',
styleUrls: ['./background-page.component.css']
})
export class BackgroundPageComponent implements OnInit {

constructor(private service: BackgroundService, private dataService: DataService) {
constructor(private service: BackgroundService) {
}

ngOnInit(): void {
chr.alarms.clearAll((wasCleared: boolean) => {
if (wasCleared) {
console.debug('alarms cleared');
}

if (chr.alarms.onAlarm.hasListeners()) {
console.error('alarm listener is already defined');
this.showError('alarm listener is already defined');
} else {
chr.alarms.create({periodInMinutes: 1});
console.debug('alarm created');

this.addAlarmListener();

if (chr.alarms.onAlarm.hasListeners()) {
console.debug('alarm listener has been added');
} else {
console.error('alarm listener was not added');
this.showError('alarm listener was not added');
}
}
});
}

addAlarmListener() {
chr.alarms.onAlarm.addListener((alarm: Alarm) => {
this.service.doWork();

const settings = this.dataService.getExtensionSettings();
const newInterval = settings.refreshIntervalInMinutes;
if (settings.refreshIntervalInMinutes !== alarm.periodInMinutes) {
console.log(`interval changed from ${alarm.periodInMinutes} to ${newInterval}, restarting alarm...`);

chr.alarms.create({periodInMinutes: settings.refreshIntervalInMinutes});
console.debug('alarm created');
}
});
}

showError(message: string) {
chr.browserAction.setBadgeBackgroundColor({color: 'red'});
chr.browserAction.setBadgeText({text: message});
this.service.setupAlarms();
}
}
8 changes: 7 additions & 1 deletion src/app/components/options/options.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {forkJoin, of, throwError} from 'rxjs';
import {catchError, tap} from 'rxjs/operators';
import {Component, OnInit} from '@angular/core';
import {SlackClient} from '../../services/slackClient';
import {BackgroundService} from '../../services/background.service';

@Component({
selector: 'app-options',
Expand All @@ -23,7 +24,8 @@ export class OptionsComponent implements OnInit {

constructor(
private settingsService: DataService,
private bitbucketService: BitbucketService) {
private bitbucketService: BitbucketService,
private backgroundService: BackgroundService) {
this.settings = settingsService.getExtensionSettings();

this.enableSlackNotifications = !!this.settings.notifications.slack;
Expand Down Expand Up @@ -70,6 +72,10 @@ export class OptionsComponent implements OnInit {
? this.slackSettings
: undefined;
this.settingsService.saveExtensionSettings(this.settings);

// fetch data
this.backgroundService.doWork();

this.showMessage('saved!');
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export class SnoozeNotificationComponent implements OnInit {
}

onSnoozeToggle() {
// todo: add snooze ttl 1/2/3/5/8 hours or disable
let settings = this.dataService.getNotificationSnoozeSettings();
if (this.snoozed) {
this.dataService.saveNotificationSnoozeSettings(settings.filter(id => id !== this.id));
Expand Down
49 changes: 49 additions & 0 deletions src/app/services/background.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ import {BitbucketCommentAction, PullRequestAction, PullRequestActivityAction, Pu
import {ExtensionSettings, PullRequest} from '../models/models';
import {DataService} from './data.service';
import {NotificationService} from './notification.service';
import Alarm = chrome.alarms.Alarm;

// @ts-ignore
let chr: any = chrome;

@Injectable()
export class BackgroundService {
Expand All @@ -22,6 +26,51 @@ export class BackgroundService {
this.interval = settings.refreshIntervalInMinutes;
}

setupAlarms() {
chr.alarms.clearAll((wasCleared: boolean) => {
if (wasCleared) {
console.debug('alarms cleared');
}

if (chr.alarms.onAlarm.hasListeners()) {
console.error('alarm listener is already defined');
this.showError('alarm listener is already defined');
} else {
chr.alarms.create({periodInMinutes: 1});
console.debug('alarm created');

this.addAlarmListener();

if (chr.alarms.onAlarm.hasListeners()) {
console.debug('alarm listener has been added');
} else {
console.error('alarm listener was not added');
this.showError('alarm listener was not added');
}
}
});
}

private addAlarmListener() {
chr.alarms.onAlarm.addListener((alarm: Alarm) => {
this.doWork();

const settings = this.dataService.getExtensionSettings();
const newInterval = settings.refreshIntervalInMinutes;
if (settings.refreshIntervalInMinutes !== alarm.periodInMinutes) {
console.log(`interval changed from ${alarm.periodInMinutes} to ${newInterval}, restarting alarm...`);

chr.alarms.create({periodInMinutes: settings.refreshIntervalInMinutes});
console.debug('alarm created');
}
});
}

private showError(message: string) {
chr.browserAction.setBadgeBackgroundColor({color: 'red'});
chr.browserAction.setBadgeText({text: message});
}

doWork() {
let runningTime = Date.now();
this.settings = this.dataService.getExtensionSettings();
Expand Down
16 changes: 8 additions & 8 deletions src/app/services/data.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,38 +13,38 @@ export class DataService {
};

getExtensionSettings(): ExtensionSettings {
let settings = JSON.parse(window.localStorage.getItem(this.keys.settings) as string);
let settings = JSON.parse(localStorage.getItem(this.keys.settings) as string);

return new ExtensionSettings(settings);
}

saveExtensionSettings(settings: ExtensionSettings) {
window.localStorage.setItem(this.keys.settings, JSON.stringify(settings));
localStorage.setItem(this.keys.settings, JSON.stringify(settings));
}

getPullRequests(role: PullRequestRole): PullRequest[] {
return JSON.parse(window.localStorage.getItem(`${this.keys.pullRequests}.${role}`) as string) || [];
return JSON.parse(localStorage.getItem(`${this.keys.pullRequests}.${role}`) as string) || [];
}

savePullRequests(role: PullRequestRole, values: PullRequest[]) {
window.localStorage.setItem(`${this.keys.pullRequests}.${role}`, JSON.stringify(values));
localStorage.setItem(`${this.keys.pullRequests}.${role}`, JSON.stringify(values));
}

getLastRunningTimestamp(): number {
// return now - 1h, if last running time is not available
return JSON.parse(window.localStorage.getItem(this.keys.lastRunningTime) as string) || (Date.now() - 60 * 60 * 1000);
return JSON.parse(localStorage.getItem(this.keys.lastRunningTime) as string) || (Date.now() - 60 * 60 * 1000);
}

saveLastRunningTimestamp(timestamp: number) {
return window.localStorage.setItem(this.keys.lastRunningTime, JSON.stringify(timestamp));
return localStorage.setItem(this.keys.lastRunningTime, JSON.stringify(timestamp));
}

getNotificationSnoozeSettings(): number[] {
return JSON.parse(window.localStorage.getItem(this.keys.snoozeSettings) as string) || [];
return JSON.parse(localStorage.getItem(this.keys.snoozeSettings) as string) || [];
}

saveNotificationSnoozeSettings(settings: number[]) {
return window.localStorage.setItem(this.keys.snoozeSettings, JSON.stringify(settings));
return localStorage.setItem(this.keys.snoozeSettings, JSON.stringify(settings));
}
}

12 changes: 6 additions & 6 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
import {enableProdMode} from '@angular/core';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {AppModule} from './app/app.module';
import {environment} from './environments/environment';

if (environment.production) {
enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule)
platformBrowserDynamic()
.bootstrapModule(AppModule)
.catch(err => console.error(err));
3 changes: 2 additions & 1 deletion src/manifest.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"manifest_version": 2,
"name": "Bitbucket Notifications",
"version": "1.0",
"version": "0.1",
"description": "Bitbucket Notifications",
"browser_action": {
"default_icon": "/bitbucket512_rounded.png",
Expand All @@ -17,6 +17,7 @@
},
"permissions": [
"background",
"clipboardWrite",
"alarms",
"notifications",
"https://*/*",
Expand Down

0 comments on commit 500f1ef

Please sign in to comment.