Skip to content

Commit

Permalink
Merge pull request #498 from internxt/feat/retry-sync-post-logout
Browse files Browse the repository at this point in the history
[PB-1393]: Feat/add modal to force sync.
  • Loading branch information
miguelsw authored Apr 30, 2024
2 parents 356f723 + 1f4086f commit bb969e5
Show file tree
Hide file tree
Showing 17 changed files with 341 additions and 68 deletions.
4 changes: 2 additions & 2 deletions src/apps/main/auth/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,14 @@ import {
} from './service';

let isLoggedIn: boolean;
setIsLoggedIn(!!getUser());

export function setIsLoggedIn(value: boolean) {
isLoggedIn = value;

getWidget()?.webContents.send('user-logged-in-changed', value);
}

setIsLoggedIn(!!getUser());

export function getIsLoggedIn() {
return isLoggedIn;
}
Expand Down
61 changes: 32 additions & 29 deletions src/apps/main/auth/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,27 @@ export function encryptToken() {
ConfigStore.set('bearerTokenEncrypted', true);
}

export function obtainToken(tokenName: TokenKey): string {
const token = ConfigStore.get(tokenName);
const isEncrypted = ConfigStore.get<EncryptedTokenKey>(
`${tokenName}Encrypted`
);

if (!isEncrypted) {
return token;
}

if (!safeStorage.isEncryptionAvailable()) {
throw new Error(
'[AUTH] Safe Storage was not available when decrypting encrypted token'
);
}

const buffer = Buffer.from(token, TOKEN_ENCODING);

return safeStorage.decryptString(buffer);
}

function ecnryptToken(token: string): string {
const buffer = safeStorage.encryptString(token);

Expand Down Expand Up @@ -125,26 +146,6 @@ export function getUser(): User | null {
return user && Object.keys(user).length ? user : null;
}

export function obtainToken(tokenName: TokenKey): string {
const token = ConfigStore.get(tokenName);
const isEncrypted = ConfigStore.get<EncryptedTokenKey>(
`${tokenName}Encrypted`
);

if (!isEncrypted) {
return token;
}

if (!safeStorage.isEncryptionAvailable()) {
throw new Error(
'[AUTH] Safe Storage was not available when decrypting encrypted token'
);
}

const buffer = Buffer.from(token, TOKEN_ENCODING);

return safeStorage.decryptString(buffer);
}

export function obtainTokens(): Array<string> {
return tokensKeys.map(obtainToken);
Expand Down Expand Up @@ -179,14 +180,6 @@ export function canHisConfigBeRestored(uuid: string) {
return true;
}

export function logout() {
Logger.info('Loggin out');
saveConfig();
resetConfig();
resetCredentials();
Logger.info('[AUTH] User logged out');
}

function saveConfig() {
const user = getUser();
if (!user) {
Expand All @@ -197,7 +190,7 @@ function saveConfig() {

const savedConfigs = ConfigStore.get('savedConfigs');

const configToSave: any = {};
const configToSave: Record<string, unknown> = {};

for (const field of fieldsToSave) {
const value = ConfigStore.get(field);
Expand All @@ -219,3 +212,13 @@ function resetConfig() {
}
}
}

export function logout() {
Logger.info('Loggin out');
saveConfig();
resetConfig();
resetCredentials();
Logger.info('[AUTH] User logged out');
}


15 changes: 7 additions & 8 deletions src/apps/main/background-processes/process-issues.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,13 @@ import {
let processIssues: ProcessIssue[] = [];
let generalIssues: GeneralIssue[] = [];

export function getGeneralIssues() {
return generalIssues;
}
function getProcessIssues() {
return processIssues;
}

ipcMain.handle('get-process-issues', getProcessIssues);
ipcMain.handle('get-general-issues', getGeneralIssues);

Expand All @@ -22,18 +29,10 @@ function onGeneralIssuesChanged() {
broadcastToWindows('general-issues-changed', generalIssues);
}

function getProcessIssues() {
return processIssues;
}

export function getSyncIssues() {
return processIssues.filter((issue) => issue.process === 'SYNC');
}

export function getGeneralIssues() {
return generalIssues;
}

export function clearSyncIssues() {
processIssues = processIssues.filter((issue) => issue.process === 'BACKUPS');
onProcessIssuesChanged();
Expand Down
15 changes: 13 additions & 2 deletions src/apps/main/background-processes/sync-engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ async function stopAndClearSyncEngineWatcher() {

export function updateSyncEngine() {
try {
if ( worker && worker?.webContents && !worker.isDestroyed() ) {
if (worker?.webContents && !worker?.isDestroyed()) {
worker?.webContents.send('UPDATE_SYNC_ENGINE_PROCESS');
}
} catch (err) {
Expand All @@ -244,13 +244,24 @@ export function updateSyncEngine() {

export function fallbackSyncEngine() {
try {
if ( worker && worker?.webContents && !worker.isDestroyed() ) {
if (worker?.webContents && !worker?.isDestroyed()) {
worker?.webContents.send('FALLBACK_SYNC_ENGINE_PROCESS');
}
} catch (err) {
Logger.error(err);
}
}
export async function sendUpdateFilesInSyncPending(): Promise<string[]> {
try {
if (worker?.webContents && !worker?.isDestroyed()) {
worker?.webContents.send('UPDATE_UNSYNC_FILE_IN_SYNC_ENGINE_PROCESS');
}
return [];
} catch (err) {
Logger.error(err);
return [];
}
}

eventBus.on('USER_LOGGED_OUT', stopAndClearSyncEngineWatcher);
eventBus.on('USER_WAS_UNAUTHORIZED', stopAndClearSyncEngineWatcher);
Expand Down
2 changes: 2 additions & 0 deletions src/apps/main/preload.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,5 +169,7 @@ declare interface Window {
getPreferredAppLanguage: () => Promise<Array<string>>;
syncManually: () => Promise<void>;
getRecentlywasSyncing: () => Promise<boolean>;
getUnsycFileInSyncEngine: () => Promise<string[]>;
updateUnsycFileInSyncEngine: () => Promise<void>;
};
}
8 changes: 7 additions & 1 deletion src/apps/main/preload.js
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,13 @@ contextBridge.exposeInMainWorld('electron', {
syncManually() {
return ipcRenderer.invoke('SYNC_MANUALLY');
},
getRecentlywasSyncing() {
getUnsycFileInSyncEngine() {
return ipcRenderer.invoke('GET_UNSYNC_FILE_IN_SYNC_ENGINE');
},
updateUnsycFileInSyncEngine() {
return ipcRenderer.invoke('SEND_UPDATE_UNSYNC_FILE_IN_SYNC_ENGINE');
},
getRecentlywasSyncing() {
const FIVE_SECONDS = 5000;
return ipcRenderer.invoke('CHECK_SYNC_IN_PROGRESS', FIVE_SECONDS);
},
Expand Down
21 changes: 18 additions & 3 deletions src/apps/main/remote-sync/RemoteSyncManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
RemoteSyncedFolder,
RemoteSyncedFile,
SyncConfig,
SYNC_OFFSET_MS,
SIX_HOURS_IN_MILLISECONDS,
rewind,
WAITING_AFTER_SYNCING_DEFAULT
Expand All @@ -25,6 +26,7 @@ export class RemoteSyncManager {
(newStatus: RemoteSyncStatus) => void
> = [];
private totalFilesSynced = 0;
private totalFilesUnsynced: string[] = [];
private totalFoldersSynced = 0;
private lastSyncingFinishedTimestamp: Date | null = null;
private _isProcessRunning = false;
Expand Down Expand Up @@ -57,6 +59,14 @@ export class RemoteSyncManager {
return this.status;
}

getUnSyncFiles(): string[] {
return this.totalFilesUnsynced;
}

setUnsyncFiles(files: string[]): void {
this.totalFilesUnsynced = files;
}

private getLastSyncingFinishedTimestamp() {
return this.lastSyncingFinishedTimestamp;
}
Expand All @@ -76,9 +86,11 @@ export class RemoteSyncManager {
* @returns False if the RemoteSyncManager was not syncing recently
* @param milliseconds Time in milliseconds to check if the RemoteSyncManager was syncing
*/
recentlyWasSyncing( milliseconds: number) {
const passedTime = Date.now() - ( this.getLastSyncingFinishedTimestamp()?.getTime() ?? Date.now() );
return passedTime < ( milliseconds ?? WAITING_AFTER_SYNCING_DEFAULT );
recentlyWasSyncing(milliseconds: number) {
const passedTime =
Date.now() -
(this.getLastSyncingFinishedTimestamp()?.getTime() ?? Date.now());
return passedTime < (milliseconds ?? WAITING_AFTER_SYNCING_DEFAULT);
}

resetRemoteSync() {
Expand All @@ -88,6 +100,7 @@ export class RemoteSyncManager {
this._placeholdersStatus = 'IDLE';
this.lastSyncingFinishedTimestamp = null;
this.totalFilesSynced = 0;
this.totalFilesUnsynced = [];
this.totalFoldersSynced = 0;
}
/**
Expand All @@ -107,6 +120,7 @@ export class RemoteSyncManager {
return;
}
this.totalFilesSynced = 0;
this.totalFilesUnsynced = [];
this.totalFoldersSynced = 0;
await this.db.files.connect();
await this.db.folders.connect();
Expand All @@ -133,6 +147,7 @@ export class RemoteSyncManager {
reportError(error as Error);
} finally {
Logger.info('Total synced files: ', this.totalFilesSynced);
Logger.info('Total unsynced files: ', this.totalFilesUnsynced);
Logger.info('Total synced folders: ', this.totalFoldersSynced);
}
}
Expand Down
38 changes: 35 additions & 3 deletions src/apps/main/remote-sync/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,16 @@ import { ipcMain } from 'electron';
import { reportError } from '../bug-report/service';
import { sleep } from '../util';
import { broadcastToWindows } from '../windows';
import { updateSyncEngine,fallbackSyncEngine} from '../background-processes/sync-engine';
import {
updateSyncEngine,
fallbackSyncEngine,
sendUpdateFilesInSyncPending,
} from '../background-processes/sync-engine';
import { debounce } from 'lodash';

const SYNC_DEBOUNCE_DELAY = 3_000;


let initialSyncReady = false;
const driveFilesCollection = new DriveFilesCollection();
const driveFoldersCollection = new DriveFoldersCollection();
Expand Down Expand Up @@ -110,6 +115,25 @@ ipcMain.handle('SYNC_MANUALLY', async () => {
await fallbackRemoteSync();
});

ipcMain.handle('GET_UNSYNC_FILE_IN_SYNC_ENGINE', async () => {
Logger.info('[Get UnSync] Received Get UnSync File event');
Logger.info(remoteSyncManager.getUnSyncFiles());
return remoteSyncManager.getUnSyncFiles();
});

ipcMain.handle('SEND_UPDATE_UNSYNC_FILE_IN_SYNC_ENGINE', async () => {
Logger.info('[UPDATE UnSync] Received update UnSync File event');
await sendUpdateFilesInSyncPending();
});

ipcMain.on(
'UPDATE_UNSYNC_FILE_IN_SYNC_ENGINE',
async (_, filesPath: string[]) => {
Logger.info('[SYNC ENGINE] update unSync files', filesPath);
remoteSyncManager.setUnsyncFiles(filesPath);
}
);

const debouncedSynchronization = debounce(async () => {
await updateRemoteSync();
}, SYNC_DEBOUNCE_DELAY);
Expand Down Expand Up @@ -146,6 +170,14 @@ ipcMain.on('CHECK_SYNC_CHANGE_STATUS', async (_, placeholderStates) => {
remoteSyncManager.placeholderStatus = placeholderStates;
});

ipcMain.handle('CHECK_SYNC_IN_PROGRESS', async (_, milliSeconds : number) => {
return checkSyncEngineInProcess(milliSeconds);
export async function checkSyncInProgress(milliSeconds: number) {
const syncingStatus: RemoteSyncStatus = 'SYNCING';
const isSyncing = remoteSyncManager.getSyncStatus() === syncingStatus;
const recentlySyncing = remoteSyncManager.recentlyWasSyncing(milliSeconds);
return isSyncing || recentlySyncing; // syncing or recently was syncing
}

ipcMain.handle('CHECK_SYNC_IN_PROGRESS', async (_, milliSeconds: number) => {
return await checkSyncInProgress(milliSeconds);
});

16 changes: 15 additions & 1 deletion src/apps/renderer/localize/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,21 @@
"send-feedback": "Send feedback",
"support": "Support",
"logout": "Log out",
"quit": "Quit"
"quit": "Quit",
"logout-confirmation": {
"no-sync-pending": {
"title": "Log out from this device?",
"message": "Internxt Drive will not show up without an account logged in.",
"confirm": "Log out",
"cancel": "Cancel"
},
"sync-pending": {
"title": "Some items are not synced",
"message": "If you log out now, these files won’t be synced and will be moved to a folder on the desktop.",
"confirm": "Log out",
"cancel": "Force sync"
}
}
}
},
"body": {
Expand Down
16 changes: 15 additions & 1 deletion src/apps/renderer/localize/locales/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,21 @@
"send-feedback": "Enviar feedback",
"support": "Ayuda",
"logout": "Cerrar sesión",
"quit": "Salir"
"quit": "Salir",
"logout-confirmation": {
"no-sync-pending": {
"title": "¿Cerrar sesión en este dispositivo?",
"message": "Internxt Drive no se mostrará sin una cuenta iniciada.",
"confirm": "Cerrar sesión",
"cancel": "Cancelar"
},
"sync-pending": {
"title": "Algunos elementos no están sincronizados",
"message": "Si cierras sesión ahora, estos archivos no se sincronizarán y se moverán a una carpeta en el escritorio.",
"confirm": "Cerrar sesión",
"cancel": "Forzar sincronización"
}
}
}
},
"body": {
Expand Down
Loading

0 comments on commit bb969e5

Please sign in to comment.