Skip to content

Commit

Permalink
work on #291
Browse files Browse the repository at this point in the history
add alarm permission
refactor create local backup with alarm events
create cloud sync with alarm events
  • Loading branch information
drive4ik committed Jul 4, 2024
1 parent f1d3faf commit 02d996d
Show file tree
Hide file tree
Showing 14 changed files with 161 additions and 164 deletions.
4 changes: 4 additions & 0 deletions addon/src/_locales/en/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -1233,6 +1233,10 @@
"message": "File name",
"description": "File name"
},
"dontUploadToCloud": {
"message": "Don't upload to the cloud",
"description": "Don't upload to the cloud, leave it local only"
},
"helpTitle": {
"message": "Help",
"description": "Help"
Expand Down
9 changes: 9 additions & 0 deletions addon/src/components/edit-group.vue
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,15 @@
</div>
</div>
<div class="field">
<div class="control">
<label class="checkbox">
<input type="checkbox" v-model="group.dontUploadToCloud" />
<span v-text="lang('dontUploadToCloud')"></span>
</label>
</div>
</div>
<div class="field">
<div class="control">
<label class="checkbox">
Expand Down
33 changes: 0 additions & 33 deletions addon/src/js/cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -98,35 +98,6 @@ export async function removeTabGroup(tabId) {
return browser.sessions.removeTabValue(tabId, 'groupId').catch(() => {});
}

// syncId
async function loadSyncId(tabId) {
if (tabs[tabId]) {
if (tabs[tabId].syncId) {
return tabs[tabId].syncId;
}

return tabs[tabId].syncId = await browser.sessions.getTabValue(tabId, 'syncId');
}
}

// export async function setSyncId(tabId, syncId) {
// if (syncId) {
// if (tabs[tabId]) {
// tabs[tabId].syncId = syncId;
// } else {
// tabs[tabId] = {syncId};
// }

// return browser.sessions.setTabValue(tabId, 'syncId', syncId);
// }
// }

export async function removeSyncId(tabId) {
delete tabs[tabId]?.syncId;
return browser.sessions.removeTabValue(tabId, 'syncId').catch(() => {});
}


// favIconUrl
async function loadTabFavIcon(tabId) {
if (tabs[tabId]) {
Expand Down Expand Up @@ -205,7 +176,6 @@ export async function loadTabSession(tab, includeFavIconUrl = true, includeThumb

await Promise.all([
loadTabGroup(tab.id),
loadSyncId(tab.id),
includeFavIconUrl ? loadTabFavIcon(tab.id) : null,
includeThumbnail ? loadTabThumbnail(tab.id) : null,
]);
Expand All @@ -216,7 +186,6 @@ export async function loadTabSession(tab, includeFavIconUrl = true, includeThumb
export async function setTabSession(tab) {
await Promise.all([
setTabGroup(tab.id, tab.groupId),
loadSyncId(tab.id, tab.syncId),
setTabFavIcon(tab.id, tab.favIconUrl),
setTabThumbnail(tab.id, tab.thumbnail),
]);
Expand All @@ -226,7 +195,6 @@ export async function setTabSession(tab) {

export function applySession(toObj, fromObj) {
fromObj.groupId && (toObj.groupId = fromObj.groupId);
fromObj.syncId && (toObj.syncId = fromObj.syncId);
fromObj.favIconUrl && (toObj.favIconUrl = fromObj.favIconUrl);
fromObj.thumbnail && (toObj.thumbnail = fromObj.thumbnail);

Expand All @@ -240,7 +208,6 @@ export function applyTabSession(tab) {
export async function removeTabSession(tabId) {
return Promise.all([
removeTabGroup(tabId),
removeSyncId(tabId),
removeTabFavIcon(tabId),
removeTabThumbnail(tabId),
]);
Expand Down
15 changes: 5 additions & 10 deletions addon/src/js/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export const DEFAULT_COOKIE_STORE_ID = 'firefox-default';

export const CONTEXT_MENU_PREFIX_UNDO_REMOVE_GROUP = 'stg-undo-remove-group-id-';

export const AUTO_BACKUP_INTERVAL_KEY = Object.freeze({
export const INTERVAL_KEY = Object.freeze({
minutes: 'minutes',
hours: 'hours',
days: 'days',
Expand Down Expand Up @@ -329,20 +329,19 @@ export const DEFAULT_OPTIONS = Object.freeze({
],

autoBackupEnable: true,
autoBackupLastBackupTimeStamp: 1,
autoBackupIntervalKey: AUTO_BACKUP_INTERVAL_KEY.days, // minutes, hours, days
autoBackupIntervalKey: INTERVAL_KEY.days, // minutes, hours, days
autoBackupIntervalValue: 1,
autoBackupIncludeTabThumbnails: true,
autoBackupIncludeTabFavIcons: true,
autoBackupFolderName: '',
autoBackupByDayIndex: true,

syncEnable: true,
syncEnable: false,
syncOptionsLocation: IS_AVAILABLE_SYNC_STORAGE ? SYNC_STORAGE_FSYNC : SYNC_STORAGE_LOCAL,
syncId: 1,
syncIntervalKey: AUTO_BACKUP_INTERVAL_KEY.days, // minutes, hours, days
syncIntervalKey: INTERVAL_KEY.days, // hours, days
syncIntervalValue: 1,
syncTabFavIcons: true,
syncTabFavIcons: false,

theme: 'auto', // auto, light, dark

Expand All @@ -363,10 +362,6 @@ export const ONLY_BOOL_OPTION_KEYS = Object.freeze(Object.keys(DEFAULT_OPTIONS).

export const ALL_OPTIONS_KEYS = Object.freeze(Object.keys(DEFAULT_OPTIONS).filter(key => !['version', 'groups', 'lastCreatedGroupPosition'].includes(key)));

export const MINUTE_SEC = 60;
export const HOUR_SEC = 60 * MINUTE_SEC;
export const DAY_SEC = 24 * HOUR_SEC;

export const ON_UPDATED_TAB_PROPERTIES = browser.tabs ? Object.freeze([ // browser.tabs not defined into web page scripts
browser.tabs.UpdatePropertyName.TITLE, // for cache
browser.tabs.UpdatePropertyName.STATUS, // for check update url and thumbnail
Expand Down
1 change: 1 addition & 0 deletions addon/src/js/groups.js
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ export function create(id, title, defaultGroupProps = {}) {
discardTabsAfterHide: false,
discardExcludeAudioTabs: false,
prependTitleToWindow: false,
dontUploadToCloud: false,
exportToBookmarksWhenAutoBackup: true,
leaveBookmarksOfClosedTabs: false,
newTabContainer: Constants.DEFAULT_COOKIE_STORE_ID,
Expand Down
2 changes: 1 addition & 1 deletion addon/src/js/logger.js
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ function setLoggerFuncs() {
return this;
}.bind(this);

this.runError = function(message, error) {
this.runError = function(message, error) { // TODO rename to logError
this.onError(message, false)(error);
return this;
}.bind(this);
Expand Down
9 changes: 7 additions & 2 deletions addon/src/js/mixins/sync-cloud.mixin.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ import Messages from '/js/messages.js';

const logger = new Logger('sync.cloud-mixin');

let instance;
let instance,
clearProgressTimer;

const {disconnect} = Messages.connectToBackground('sync-progress-mixin', [
'sync-start',
Expand All @@ -19,17 +20,21 @@ const {disconnect} = Messages.connectToBackground('sync-progress-mixin', [
return;
}

clearTimeout(clearProgressTimer);

if (action === 'sync-start') {
instance.synchronisationError = '';
instance.synchronisationInProgress = true;
} if (action === 'sync-progress') {
instance.synchronisationProgress = progress;
instance.synchronisationInProgress = true;
} else if (action === 'sync-end') {
instance.synchronisationError = '';
// instance.synchronisationError = '';
instance.synchronisationInProgress = false;
} else if (action === 'sync-error') {
instance.synchronisationError = message;
instance.synchronisationInProgress = false;
clearProgressTimer = setTimeout(() => instance.synchronisationProgress = 0, 5000);
}
});

Expand Down
33 changes: 7 additions & 26 deletions addon/src/js/sync/cloud/cloud.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ export async function sync(progressFunc = null) {
});

progressFunc?.(45);

// throw Error('aaa');
const syncResult = await syncData(localData, cloudData);

progressFunc?.(50);
Expand Down Expand Up @@ -162,9 +162,6 @@ export async function sync(progressFunc = null) {
// log.debug('changes.cloud:', syncResult.changes.cloud, syncResult.cloudData.syncId);
// log.debug('changes.local:', syncResult.changes.local, syncResult.localData.syncId);

// TODO syncData for all tabs: Date.now() + tab.url
// await Promise.all(allTabIds.map(tabId => Cache.setSyncId(tabId, syncId)));

if (progressFunc) {
GithubGistCloud.progressFunc = cloudProgressFunc.bind(null, 55, 35);
}
Expand All @@ -174,8 +171,6 @@ export async function sync(progressFunc = null) {
try {
await GithubGistCloud.updateGist(syncResult.cloudData);
} catch (e) {
// GithubGistCloud.progressFunc = null;
// log.error(String(e));
log.stopError(e);
throw new CloudError('githubCantUploadBackupToGist');
}
Expand All @@ -186,21 +181,20 @@ export async function sync(progressFunc = null) {
const result = await GithubGistCloud.createGist(syncResult.cloudData, description);
await saveNewGistId(result.id);
} catch (e) {
// GithubGistCloud.progressFunc = null;
log.stopError(e);
throw new CloudError('githubCantCreateBackupIntoGist');
}
}

// GithubGistCloud.progressFunc = null;

progressFunc?.(95);

if (syncResult.changes.local) {
// TODO normal save options
await Storage.set(syncResult.localData);
}

window.localStorage.autoSyncLastTimeStamp = Utils.unixNow();

progressFunc?.(100);

log.stop();
Expand Down Expand Up @@ -252,26 +246,14 @@ async function syncData(localData, cloudData = null) {
}

async function syncGroups(localData, cloudData, sourceOfTruth, changes) {
const log = logger.start('syncGroups', {sourceOfTruth});
const log = logger.start('syncGroups', {sourceOfTruth, syncTabFavIcons: localData.syncTabFavIcons});

const localGroups = localData.groups;
const cloudGroups = cloudData.groups;

const resultLocalGroups = [];
const resultCloudGroups = [];

// tab.sync == String(options.syncId + tab.url)
// if tabs was synced -
// tab.sync.id === options.syncId
// AND
// tab.sync.url === tab.url
// else - it's new tab or not synced tab or old synced tab

// check real exist tab or archive tab
// const isLocalTabSynced = localTab => localTab.noSync ? false : Tabs.isSynced(localData.syncId, localTab);

// const START_TIME = +self.localStorage.START_TIME;

function prepareForSaveTab(tab, includeLastAccessed) {
// include includeLastAccessed, tab id and openerId only for local tabs
const includeId = includeLastAccessed;
Expand All @@ -287,7 +269,7 @@ async function syncGroups(localData, cloudData, sourceOfTruth, changes) {
const resultLocalGroup = localGroup;
const resultCloudGroup = {...localGroup}; // unlink tabs key

if (resultLocalGroup.dontUploadToCloud) { // TODO check & do this on all code
if (resultLocalGroup.dontUploadToCloud) {
resultLocalGroups.push(resultLocalGroup);
} else {
resultCloudGroup.tabs = prepareForSave(resultLocalGroup.tabs, false);
Expand Down Expand Up @@ -324,7 +306,7 @@ async function syncGroups(localData, cloudData, sourceOfTruth, changes) {
localGroup = localGroups.find(localGroup => localGroup.id === cloudGroup.id);
}

if (localGroup?.dontUploadToCloud) { // TODO check & do this on all code
if (localGroup?.dontUploadToCloud) {
resultLocalGroups.push(localGroup); // leave group in local
resultCloudGroups.push(cloudGroup); // leave in cloud, beacause other comp. can sync with this group
return;
Expand Down Expand Up @@ -411,8 +393,7 @@ async function syncGroups(localData, cloudData, sourceOfTruth, changes) {
resultCloudGroup.tabs = resultCloudTabs;
}

/* TODO
убрать всякие noSync и syncId у вкладок, и переделать по системе:
/*
если lastAccessed у вкладки меньше чем cloudData.syncId - тогда удаляем эти вкладки,
если больше оставляем их. будет проблема с активной вкладкой, её lastAccessed всегда текущее время, поэтому оставляем её, синкаем как новую вкладку. если пользователь захочет узалить её из облака вообще - удаляет локально и тут же нажимает синк. на другом компе её уже нет, и удалять нечего.
*/
Expand Down
12 changes: 0 additions & 12 deletions addon/src/js/tabs.js
Original file line number Diff line number Diff line change
Expand Up @@ -840,15 +840,3 @@ export function getTitle({id, index, title, url, discarded, windowId, lastAccess

return sliceLength ? Utils.sliceText(title, sliceLength) : title;
}

export function isSynced(optionsSyncId, tab) { // TODO remove this function
return tab.sync === `${optionsSyncId}${tab.url}`;
}

// const TIMESTAMP_LENGTH = 13;
// export function getTabSync(tab) {
// return {
// id: Number(tab.sync?.slice(0, TIMESTAMP_LENGTH)) || null,
// url: tab.sync?.slice(TIMESTAMP_LENGTH) || null,
// };
// }
4 changes: 4 additions & 0 deletions addon/src/js/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,10 @@ export function getRandomInt(min = 1, max = Number.MAX_SAFE_INTEGER, step = 1) {
return result;
}

export function minMaxRange(value, min = 0, max = 999) {
return Math.min(Math.max(value, min), max);
}

export function randomColor() {
return 'hsl(' + getRandomInt(0, 360, 10) + ', 100%, 50%)';
}
Expand Down
1 change: 1 addition & 0 deletions addon/src/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"contextualIdentities",
"cookies",
"sessions",
"alarms",
"downloads",
"management",
"webRequest",
Expand Down
Loading

0 comments on commit 02d996d

Please sign in to comment.