Skip to content

Commit

Permalink
Merge pull request #496 from internxt/feat/2-0-8-features
Browse files Browse the repository at this point in the history
[_]: Feat/2.0.8-features
  • Loading branch information
ArceDanielShok authored May 1, 2024
2 parents 4ea607a + bb969e5 commit d74c236
Show file tree
Hide file tree
Showing 37 changed files with 712 additions and 221 deletions.
2 changes: 0 additions & 2 deletions src/apps/main/analytics/user-handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import {
userSignin,
userSigninFailed,
} from './service';
import { clearRemoteSyncStore } from '../remote-sync/helpers';
import { clearTempFolder } from '../app-info/helpers';

eventBus.on('USER_LOGGED_IN', () => {
Expand All @@ -16,7 +15,6 @@ eventBus.on('USER_LOGGED_IN', () => {

eventBus.on('USER_LOGGED_OUT', () => {
userLogout();
clearRemoteSyncStore();
clearTempFolder();
});

Expand Down
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
64 changes: 50 additions & 14 deletions src/apps/main/background-processes/sync-engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,30 @@ import Logger from 'electron-log';
import eventBus from '../event-bus';
import nodeSchedule from 'node-schedule';
import * as Sentry from '@sentry/electron/main';
import { checkSyncEngineInProcess } from '../remote-sync/handlers';

let worker: BrowserWindow | null = null;
let workerIsRunning = false;
let startingWorker = false;
let healthCheckSchedule: nodeSchedule.Job | null = null;
let attemptsAlreadyStarting = 0;

ipcMain.once('SYNC_ENGINE_PROCESS_SETUP_SUCCESSFUL', () => {
Logger.debug('[MAIN] SYNC ENGINE RUNNING');
workerIsRunning = true;
startingWorker = false;
});

ipcMain.on('SYNC_ENGINE_PROCESS_SETUP_FAILED', () => {
Logger.debug('[MAIN] SYNC ENGINE FAILED');
workerIsRunning = false;
startingWorker = false;
});

async function healthCheck() {
const responsePromise = new Promise<void>((resolve, reject) => {
ipcMain.once('SYNC_ENGINE:PONG', () => {
Logger.debug('Health check PONG resolved');
resolve();
});

Expand Down Expand Up @@ -48,17 +63,27 @@ function scheduleHeathCheck() {
Sentry.captureMessage(warning);
workerIsRunning = false;
worker?.destroy();
if (attemptsAlreadyStarting >= 3) {
attemptsAlreadyStarting = 0;
startingWorker = false;
return;
}
spawnSyncEngineWorker();
});

healthCheckSchedule = nodeSchedule.scheduleJob('*/30 * * * * *', async () => {
await relaunchOnFail();
const workerIsPending = checkSyncEngineInProcess(5_000);
Logger.debug('Health check', workerIsPending ? 'Worker is pending' : 'Worker is running');
if(!workerIsPending) {
await relaunchOnFail();
}
});
}

function spawnSyncEngineWorker() {
if (startingWorker) {
Logger.info('[MAIN] Worker is already starting');
attemptsAlreadyStarting++;
return;
}
if (workerIsRunning) {
Expand Down Expand Up @@ -100,18 +125,6 @@ function spawnSyncEngineWorker() {
spawnSyncEngineWorker();
}
});

ipcMain.once('SYNC_ENGINE_PROCESS_SETUP_SUCCESSFUL', () => {
Logger.debug('[MAIN] SYNC ENGINE RUNNING');
workerIsRunning = true;
startingWorker = false;
});

ipcMain.on('SYNC_ENGINE_PROCESS_SETUP_FAILED', () => {
Logger.debug('[MAIN] SYNC ENGINE NOT RUNNING');
workerIsRunning = false;
startingWorker = false;
});
}

export async function stopSyncEngineWatcher() {
Expand Down Expand Up @@ -219,14 +232,37 @@ async function stopAndClearSyncEngineWatcher() {

export function updateSyncEngine() {
try {
worker?.webContents.send('UPDATE_SYNC_ENGINE_PROCESS');
if (worker?.webContents && !worker?.isDestroyed()) {
worker?.webContents.send('UPDATE_SYNC_ENGINE_PROCESS');
}
} catch (err) {
// TODO: handle error
Logger.error(err);
Sentry.captureException(err);
}
}

export function fallbackSyncEngine() {
try {
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);
eventBus.on('INITIAL_SYNC_READY', spawnSyncEngineWorker);
5 changes: 5 additions & 0 deletions src/apps/main/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ export interface AppStore {
preferedLanguage?: string;
preferedTheme?: string;
virtualdriveWindowsLetter: string;
dataIntegrityMaintenance?: boolean;
}

const schema: Schema<AppStore> = {
Expand Down Expand Up @@ -103,6 +104,9 @@ const schema: Schema<AppStore> = {
virtualdriveWindowsLetter: {
type: 'string',
},
dataIntegrityMaintenance: {
type: 'boolean',
},
} as const;

export const defaults: AppStore = {
Expand All @@ -127,6 +131,7 @@ export const defaults: AppStore = {
preferedLanguage: '',
preferedTheme: 'system',
virtualdriveWindowsLetter: 'I',
dataIntegrityMaintenance: false,
};

const configStore = new Store({ schema, defaults });
Expand Down
17 changes: 11 additions & 6 deletions src/apps/main/database/adapters/base.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
export abstract class DatabaseCollectionAdapter<DatabaseItemType> {
export interface DatabaseCollectionAdapter<DatabaseItemType> {
/**
* Used to initialize the database adapter
*/
abstract connect(): Promise<{ success: boolean }>;
connect(): Promise<{ success: boolean }>;

/**
* Gets an item from the database
*/
abstract get(
get(
itemId: string
): Promise<{ success: boolean; result: DatabaseItemType | null }>;

/**
* Updates an item in the database
*/
abstract update(
update(
itemId: string,
updatePayload: Partial<DatabaseItemType>
): Promise<{
Expand All @@ -25,15 +25,20 @@ export abstract class DatabaseCollectionAdapter<DatabaseItemType> {
/**
* Creates an item in the database
*/
abstract create(creationPayload: DatabaseItemType): Promise<{
create(creationPayload: DatabaseItemType): Promise<{
success: boolean;
result: DatabaseItemType | null;
}>;

/**
* Removes an item from the database
*/
abstract remove(itemId: string): Promise<{
remove(itemId: string): Promise<{
success: boolean;
}>;

getLastUpdated(): Promise<{
success: boolean;
result: DatabaseItemType | null;
}>;
}
27 changes: 27 additions & 0 deletions src/apps/main/database/collections/DriveFileCollection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ import { DatabaseCollectionAdapter } from '../adapters/base';
import { AppDataSource } from '../data-source';
import { DriveFile } from '../entities/DriveFile';
import { Repository } from 'typeorm';
import * as Sentry from '@sentry/electron/main';
import Logger from 'electron-log';

export class DriveFilesCollection
implements DatabaseCollectionAdapter<DriveFile>
{
Expand Down Expand Up @@ -67,4 +70,28 @@ export class DriveFilesCollection
success: result.affected ? true : false,
};
}

async getLastUpdated(): Promise<{
success: boolean;
result: DriveFile | null;
}> {
try {
const queryResult = await this.repository
.createQueryBuilder('drive_file')
.orderBy('datetime(drive_file.updatedAt)', 'DESC')
.getOne();

return {
success: true,
result: queryResult,
};
} catch (error) {
Sentry.captureException(error);
Logger.error('Error fetching newest drive file:', error);
return {
success: false,
result: null,
};
}
}
}
Loading

0 comments on commit d74c236

Please sign in to comment.