Skip to content

Commit 05842e0

Browse files
committed
Cache settings
1 parent a4a9e4d commit 05842e0

File tree

11 files changed

+187
-134
lines changed

11 files changed

+187
-134
lines changed

src/background.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,21 @@ import Browser from 'webextension-polyfill';
22
import { initTracker } from './tracker';
33
import { logger } from './compositions/logger';
44
import { scheduleJobs } from './jobs/sheduler';
5+
import { Settings } from './compositions/settings';
6+
import { StorageParams } from './storage/storage-params';
57

68
logger.log('Start background script');
79

810
Browser.runtime.onInstalled.addListener(details => {
911
logger.log('Extension installed:', details);
1012
});
1113

14+
Browser.storage.onChanged.addListener((changes, namespace) => {
15+
for (var key in changes) {
16+
if (Object.values(StorageParams).includes(key as StorageParams))
17+
Settings.getInstance().reloadSetting(key as StorageParams);
18+
}
19+
});
20+
1221
scheduleJobs();
1322
initTracker();

src/compositions/black-list.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,10 @@
1-
import { injecStorage } from '../storage/inject-storage';
21
import { StorageParams } from '../storage/storage-params';
32
import { isDomainEquals } from '../utils/common';
43
import { extractHostname } from './extract-hostname';
4+
import { Settings } from './settings';
55

66
export async function isInBlackList(url: string): Promise<boolean> {
7-
const storage = injecStorage();
8-
const blackList = (await storage.getValue(StorageParams.BLACK_LIST)) as string[];
7+
const blackList = (await Settings.getInstance().getSetting(StorageParams.BLACK_LIST)) as string[];
98
return (
109
blackList?.find(x => isDomainEquals(extractHostname(x), extractHostname(url))) !== undefined
1110
);
Lines changed: 36 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,41 @@
1-
import { TimeInterval } from "../entity/time-interval";
2-
import { injecStorage } from "../storage/inject-storage";
3-
import { StorageDeserializeParam, StorageParams } from "../storage/storage-params";
4-
import { todayLocalDate } from "../utils/today";
1+
import { TimeInterval } from '../entity/time-interval';
2+
import { injecStorage } from '../storage/inject-storage';
3+
import { StorageDeserializeParam, StorageParams } from '../storage/storage-params';
4+
import { todayLocalDate } from '../utils/today';
55

6-
export async function closeInterval(domain:string | null): Promise<void>{
7-
if (domain == null) return;
8-
const storage = injecStorage();
9-
const timeIntervalList = await storage.getDeserializeList(StorageDeserializeParam.TIMEINTERVAL_LIST) as TimeInterval[];
10-
const item = timeIntervalList?.find(x => x.domain === domain && x.day == todayLocalDate());
11-
item?.closeInterval();
12-
await storage.saveValue(StorageParams.TIMEINTERVAL_LIST, timeIntervalList);
6+
export async function closeInterval(domain: string | null): Promise<void> {
7+
if (domain == null) return;
8+
const storage = injecStorage();
9+
const timeIntervalList = (await storage.getDeserializeList(
10+
StorageDeserializeParam.TIMEINTERVAL_LIST,
11+
)) as TimeInterval[];
12+
const item = timeIntervalList?.find(x => x.domain === domain && x.day == todayLocalDate());
13+
item?.closeInterval();
14+
await storage.saveIntervalList(timeIntervalList);
1315
}
1416

15-
export async function addInterval(domain:string | null): Promise<void>{
16-
if (domain == null) return;
17+
export async function addInterval(domain: string | null): Promise<void> {
18+
if (domain == null) return;
1719

18-
const storage = injecStorage();
19-
let timeIntervalList = await storage.getDeserializeList(StorageDeserializeParam.TIMEINTERVAL_LIST) as TimeInterval[];
20-
if (timeIntervalList == undefined)
21-
timeIntervalList = [];
22-
const item = timeIntervalList?.find(x => x.domain === domain && x.day == todayLocalDate());
23-
if (item != undefined) {
24-
if (item.day == todayLocalDate())
25-
item.addInterval();
26-
else {
27-
const newInterval = new TimeInterval();
28-
newInterval.init(todayLocalDate(), domain);
29-
newInterval.addInterval();
30-
timeIntervalList.push(newInterval);
31-
}
32-
} else {
33-
const newInterval = new TimeInterval();
34-
newInterval.init(todayLocalDate(), domain);
35-
newInterval.addInterval();
36-
timeIntervalList.push(newInterval);
20+
const storage = injecStorage();
21+
let timeIntervalList = (await storage.getDeserializeList(
22+
StorageDeserializeParam.TIMEINTERVAL_LIST,
23+
)) as TimeInterval[];
24+
if (timeIntervalList == undefined) timeIntervalList = [];
25+
const item = timeIntervalList?.find(x => x.domain === domain && x.day == todayLocalDate());
26+
if (item != undefined) {
27+
if (item.day == todayLocalDate()) item.addInterval();
28+
else {
29+
const newInterval = new TimeInterval();
30+
newInterval.init(todayLocalDate(), domain);
31+
newInterval.addInterval();
32+
timeIntervalList.push(newInterval);
3733
}
38-
await storage.saveValue(StorageParams.TIMEINTERVAL_LIST, timeIntervalList);
39-
}
34+
} else {
35+
const newInterval = new TimeInterval();
36+
newInterval.init(todayLocalDate(), domain);
37+
newInterval.addInterval();
38+
timeIntervalList.push(newInterval);
39+
}
40+
await storage.saveIntervalList(timeIntervalList);
41+
}

src/compositions/limit-list.ts

Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,20 @@
1-
import { Restriction } from "../entity/restriction";
2-
import { Tab } from "../entity/tab";
3-
import { injecStorage } from "../storage/inject-storage";
4-
import { StorageParams } from "../storage/storage-params";
5-
import { todayLocalDate } from "../utils/today";
1+
import { Restriction } from '../entity/restriction';
2+
import { Tab } from '../entity/tab';
3+
import { StorageParams } from '../storage/storage-params';
4+
import { todayLocalDate } from '../utils/today';
5+
import { Settings } from './settings';
66

7-
export async function isLimitExceeded(url: string, tab: Tab): Promise<boolean>{
8-
const storage = injecStorage();
9-
const limitList = await storage.getValue(StorageParams.RESTRICTION_LIST) as Restriction[];
10-
const item = limitList?.find(x => x.domain == url);
11-
if (item != undefined){
12-
const date = tab.days.find(x => x.date == todayLocalDate());
13-
if (date != undefined){
14-
return date.summary >= item.time;
15-
}
7+
export async function isLimitExceeded(url: string, tab: Tab): Promise<boolean> {
8+
const limitList = (await Settings.getInstance().getSetting(
9+
StorageParams.RESTRICTION_LIST,
10+
)) as Restriction[];
11+
const item = limitList?.find(x => x.domain == url);
12+
if (item != undefined) {
13+
const date = tab.days.find(x => x.date == todayLocalDate());
14+
if (date != undefined) {
15+
return date.summary >= item.time;
1616
}
17+
}
1718

18-
return false;
19-
}
19+
return false;
20+
}

src/compositions/settings.ts

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import { injecStorage } from '../storage/inject-storage';
2+
import { StorageParams, getDefaultValue } from '../storage/storage-params';
3+
4+
export class Settings {
5+
private static instance: Settings;
6+
private _settings = new Map();
7+
8+
constructor() {
9+
if (Settings.instance) {
10+
throw new Error('Error - use Settings.getInstance()');
11+
}
12+
}
13+
14+
static getInstance(): Settings {
15+
Settings.instance = Settings.instance || new Settings();
16+
return Settings.instance;
17+
}
18+
19+
async getSetting(param: StorageParams) {
20+
if (this._settings.has(param)) return this._settings.get(param);
21+
else return await this.getValue(param);
22+
}
23+
24+
async reloadSetting(param: StorageParams) {
25+
await this.getValue(param);
26+
}
27+
28+
private async getValue(param: StorageParams) {
29+
const storage = injecStorage();
30+
const value = await storage.getValue(param, getDefaultValue(param));
31+
this._settings.set(param, value);
32+
return value;
33+
}
34+
}

src/jobs/sheduler.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import Browser, { Alarms } from 'webextension-polyfill';
22
import { logger } from '../compositions/logger';
33
import { StorageParams } from '../storage/storage-params';
4-
import { injecStorage } from '../storage/inject-storage';
54
import { DAY_MINUTES, getNextTimeOfDay } from '../utils/time';
5+
import { Settings } from '../compositions/settings';
66

77
export enum JobId {
88
DailySummaryNotification = '@alarm/daily-summary-notification',
@@ -24,8 +24,7 @@ export function scheduleJobs(): void {
2424
}
2525

2626
async function rescheduleJobs(): Promise<void> {
27-
const storage = injecStorage();
28-
const dailySummaryNotificationTime = (await storage.getValue(
27+
const dailySummaryNotificationTime = (await Settings.getInstance().getSetting(
2928
StorageParams.DAILY_SUMMARY_NOTIFICATION_TIME,
3029
)) as number;
3130
await Browser.alarms.clear(JobId.DailySummaryNotification);

src/storage/inject-storage.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
import { LocalStorage } from "./local-storage";
2-
import { IStorage } from "./storage-interface";
1+
import { LocalStorage } from './local-storage';
2+
import { IStorage } from './storage-interface';
33

44
export function injecStorage(): IStorage {
5-
return new LocalStorage();
6-
}
5+
return new LocalStorage();
6+
}

src/storage/local-storage.ts

Lines changed: 44 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,51 @@
1-
import { IStorage } from "./storage-interface";
2-
import { StorageDeserializeParam, StorageDeserializeType, StorageParams, createDeserializeParambject } from "./storage-params";
3-
import { Tab } from "../entity/tab";
1+
import { IStorage } from './storage-interface';
2+
import {
3+
StorageDeserializeParam,
4+
StorageDeserializeType,
5+
StorageParams,
6+
createDeserializeParambject,
7+
} from './storage-params';
8+
import { Tab } from '../entity/tab';
49
import Browser from 'webextension-polyfill';
5-
import { isEmpty } from "../utils/common";
10+
import { isEmpty } from '../utils/common';
11+
import { TimeInterval } from '../entity/time-interval';
612

713
export class LocalStorage implements IStorage {
8-
async getDeserializeList(param: StorageDeserializeParam): Promise<StorageDeserializeType[]> {
9-
return new Promise(async resolve => {
10-
const obj = await Browser.storage.local.get(param);
11-
const list = obj[param];
12-
if (list != undefined){
13-
let tempList:StorageDeserializeType[] = [];
14-
for (let i = 0; i < list.length; i++) {
15-
const obj = createDeserializeParambject(param);
16-
tempList.push(obj.deserialize(list[i]));
17-
}
18-
return resolve(tempList);
19-
}
20-
else resolve([]);
21-
});
22-
}
14+
async getDeserializeList(param: StorageDeserializeParam): Promise<StorageDeserializeType[]> {
15+
return new Promise(async resolve => {
16+
const obj = await Browser.storage.local.get(param);
17+
const list = obj[param];
18+
if (list != undefined) {
19+
let tempList: StorageDeserializeType[] = [];
20+
for (let i = 0; i < list.length; i++) {
21+
const obj = createDeserializeParambject(param);
22+
tempList.push(obj.deserialize(list[i]));
23+
}
24+
return resolve(tempList);
25+
} else resolve([]);
26+
});
27+
}
2328

24-
async saveTabs(value: Tab[]): Promise<void> {
25-
return await Browser.storage.local.set({ tabs: value });
26-
}
29+
async saveTabs(value: Tab[]): Promise<void> {
30+
return await Browser.storage.local.set({ [StorageDeserializeParam.TABS]: value });
31+
}
2732

28-
async saveValue(name: StorageParams, value: any): Promise<void> {
29-
return await Browser.storage.local.set({
30-
[name]: value
31-
});
32-
}
33+
async saveIntervalList(value: TimeInterval[]): Promise<void> {
34+
return await Browser.storage.local.set({ [StorageDeserializeParam.TIMEINTERVAL_LIST]: value });
35+
}
3336

34-
async getValue(name: StorageParams, defaultValue?: any): Promise<any> {
35-
let value = await Browser.storage.local.get(name);
36-
if (isEmpty(value) && defaultValue != undefined){
37-
await this.saveValue(name, defaultValue);
38-
return defaultValue;
39-
}
40-
return value[name];
37+
async saveValue(name: StorageParams, value: any): Promise<void> {
38+
return await Browser.storage.local.set({
39+
[name]: value,
40+
});
41+
}
42+
43+
async getValue(name: StorageParams, defaultValue?: any): Promise<any> {
44+
let value = await Browser.storage.local.get(name);
45+
if (isEmpty(value) && defaultValue != undefined) {
46+
await this.saveValue(name, defaultValue);
47+
return defaultValue;
4148
}
42-
}
49+
return value[name];
50+
}
51+
}

src/storage/storage-interface.ts

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
1-
import { StorageDeserializeParam, StorageDeserializeType, StorageParams } from "./storage-params";
2-
import { Tab } from "../entity/tab";
1+
import { StorageDeserializeParam, StorageDeserializeType, StorageParams } from './storage-params';
2+
import { Tab } from '../entity/tab';
3+
import { TimeInterval } from '../entity/time-interval';
34

45
export interface IStorage {
5-
getDeserializeList(param: StorageDeserializeParam): Promise<StorageDeserializeType[]>;
6-
saveTabs(value:Tab[]): Promise<void>;
7-
saveValue(name:StorageParams, value: any): Promise<void>;
8-
getValue(name:StorageParams, defaultValue?: any): Promise<any>;
9-
}
6+
getDeserializeList(param: StorageDeserializeParam): Promise<StorageDeserializeType[]>;
7+
saveTabs(value: Tab[]): Promise<void>;
8+
saveIntervalList(value: TimeInterval[]): Promise<void>;
9+
saveValue(name: StorageParams, value: any): Promise<void>;
10+
getValue(name: StorageParams, defaultValue?: any): Promise<any>;
11+
}

src/storage/storage-params.ts

Lines changed: 25 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -2,19 +2,14 @@ import { Tab } from '../entity/tab';
22
import { TimeInterval } from '../entity/time-interval';
33

44
export enum StorageParams {
5-
TABS = 'tabs',
65
BLACK_LIST = 'black_list',
76
RESTRICTION_LIST = 'restriction_list',
87
NOTIFICATION_LIST = 'notification_list',
98
NOTIFICATION_MESSAGE = 'notification_message',
10-
TIMEINTERVAL_LIST = 'time_interval',
119
INTERVAL_INACTIVITY = 'inactivity_interval',
12-
INTERVAL_SAVE_STORAGE = 'interval_save_in_storage',
13-
INTERVAL_RANGE = 'range_days',
1410
DARK_MODE = 'night_mode',
1511
VIEW_TIME_IN_BADGE = 'view_time_in_badge',
1612
BLOCK_DEFERRAL = 'view_block_deferral',
17-
SHOW_HINT = 'show_hint',
1813
DAILY_SUMMARY_NOTIFICATION_TIME = 'dailySummaryNotificationTime',
1914
}
2015

@@ -47,23 +42,35 @@ export enum InactivityInterval {
4742
Min_30 = 1800,
4843
}
4944

50-
export enum RangeForDays {
51-
Days_2 = 'days2',
52-
Days_3 = 'days3',
53-
Days_4 = 'days4',
54-
Days_5 = 'days5',
55-
Days_6 = 'days6',
56-
Days_7 = 'days7',
57-
Month_1 = 'month1',
58-
Month_2 = 'month2',
59-
Month_3 = 'month3',
60-
}
61-
6245
export const NOTIFICATION_MESSAGE_DEFAULT = 'You have spent a lot of time on this site';
6346
export const INTERVAL_INACTIVITY_DEFAULT = InactivityInterval.Seconds_30;
6447
export const INTERVAL_SAVE_STORAGE_DEFAULT = 5000;
65-
export const INTERVAL_RANGE_DEFAULT = RangeForDays.Days_7;
6648
export const DARK_MODE_DEFAULT = false;
6749
export const VIEW_TIME_IN_BADGE_DEFAULT = true;
6850
export const BLOCK_DEFERRAL_DEFAULT = true;
6951
export const SHOW_HINT_DEFAULT = true;
52+
// default time is 20:00, time in miliseconds
53+
export const DAILY_SUMMARY_NOTIFICATION_TIME_DEFAULT = 20 * 60 * 60 * 1000;
54+
55+
export function getDefaultValue(param: StorageParams) {
56+
switch (param) {
57+
case StorageParams.BLACK_LIST:
58+
return [];
59+
case StorageParams.RESTRICTION_LIST:
60+
return [];
61+
case StorageParams.NOTIFICATION_LIST:
62+
return [];
63+
case StorageParams.NOTIFICATION_MESSAGE:
64+
return NOTIFICATION_MESSAGE_DEFAULT;
65+
case StorageParams.INTERVAL_INACTIVITY:
66+
return INTERVAL_INACTIVITY_DEFAULT;
67+
case StorageParams.DARK_MODE:
68+
return DARK_MODE_DEFAULT;
69+
case StorageParams.VIEW_TIME_IN_BADGE:
70+
return VIEW_TIME_IN_BADGE_DEFAULT;
71+
case StorageParams.BLOCK_DEFERRAL:
72+
return BLOCK_DEFERRAL_DEFAULT;
73+
case StorageParams.DAILY_SUMMARY_NOTIFICATION_TIME:
74+
return DAILY_SUMMARY_NOTIFICATION_TIME_DEFAULT;
75+
}
76+
}

0 commit comments

Comments
 (0)