Merge remote-tracking branch 'upstream/master' into ELECTRON-249

# Conflicts:
#	js/mainApiMgr.js
This commit is contained in:
kiranniranjan 2018-01-18 16:34:56 +05:30
commit cef30ff128
8 changed files with 159 additions and 85 deletions

View File

@ -16,6 +16,7 @@ const cmds = keyMirror({
registerProtocolHandler: null,
registerActivityDetection: null,
showNotificationSettings: null,
sanitize: null
});
module.exports = {

View File

@ -14,6 +14,8 @@ const badgeCount = require('./badgeCount.js');
const protocolHandler = require('./protocolHandler');
const configureNotification = require('./notify/settings/configure-notification-position');
const { bringToFront } = require('./bringToFront.js');
const eventEmitter = require('./eventEmitter');
const { isMac } = require('./utils/misc');
const apiEnums = require('./enums/api.js');
const apiCmds = apiEnums.cmds;
@ -48,6 +50,24 @@ function isValidWindow(event) {
return result;
}
/**
* Method that is invoked when the application is reloaded/navigated
* window.addEventListener('beforeunload')
* @param windowName
*/
function sanitize(windowName) {
// To make sure the reload event is from the main window
if (windowMgr.getMainWindow() && windowName === windowMgr.getMainWindow().winName) {
// reset the badge count whenever an user refreshes the electron client
badgeCount.show(0);
// Terminates the screen snippet process on reload
if (!isMac) {
eventEmitter.emit('killScreenSnippet');
}
}
}
/**
* Handle API related ipc messages from renderers. Only messages from windows
* we have created are allowed.
@ -61,54 +81,62 @@ electron.ipcMain.on(apiName, (event, arg) => {
return;
}
if (arg.cmd === apiCmds.isOnline && typeof arg.isOnline === 'boolean') {
windowMgr.setIsOnline(arg.isOnline);
return;
switch(arg.cmd) {
case apiCmds.isOnline:
if (typeof arg.isOnline === 'boolean') {
windowMgr.setIsOnline(arg.isOnline);
}
break;
case apiCmds.setBadgeCount:
if (typeof arg.count === 'number') {
badgeCount.show(arg.count);
}
break;
case apiCmds.registerProtocolHandler:
protocolHandler.setProtocolWindow(event.sender);
protocolHandler.checkProtocolAction();
break;
case apiCmds.badgeDataUrl:
if (typeof arg.dataUrl === 'string' && typeof arg.count === 'number') {
badgeCount.setDataUrl(arg.dataUrl, arg.count);
}
break;
case apiCmds.activate:
if (typeof arg.windowName === 'string') {
// validates the user bring to front config and activates the wrapper
if (typeof arg.reason === 'string' && arg.reason === 'bringToFront') {
bringToFront(arg.windowName);
return;
}
windowMgr.activate(arg.windowName);
}
break;
case apiCmds.registerBoundsChange:
windowMgr.setBoundsChangeWindow(event.sender);
break;
case apiCmds.registerLogger:
// renderer window that has a registered logger from JS.
log.setLogWindow(event.sender);
break;
case apiCmds.registerActivityDetection:
if (typeof arg.period === 'number') {
// renderer window that has a registered activity detection from JS.
activityDetection.setActivityWindow(arg.period, event.sender);
}
break;
case apiCmds.showNotificationSettings:
if (typeof arg.windowName === 'string') {
configureNotification.openConfigurationWindow(arg.windowName);
}
break;
case apiCmds.sanitize:
if (typeof arg.windowName === 'string') {
sanitize(arg.windowName);
}
break;
default:
}
if (arg.cmd === apiCmds.setBadgeCount && typeof arg.count === 'number') {
badgeCount.show(arg.count);
return;
}
if (arg.cmd === apiCmds.registerProtocolHandler) {
protocolHandler.setProtocolWindow(event.sender);
protocolHandler.checkProtocolAction();
}
if (arg.cmd === apiCmds.badgeDataUrl && typeof arg.dataUrl === 'string' &&
typeof arg.count === 'number') {
badgeCount.setDataUrl(arg.dataUrl, arg.count);
return;
}
if (arg.cmd === apiCmds.activate && typeof arg.windowName === 'string') {
// validates the user bring to front config and activates the wrapper
if (typeof arg.reason === 'string' && arg.reason === 'bringToFront') {
bringToFront(arg.windowName);
return;
}
windowMgr.activate(arg.windowName);
return;
}
if (arg.cmd === apiCmds.registerBoundsChange) {
windowMgr.setBoundsChangeWindow(event.sender);
}
if (arg.cmd === apiCmds.registerLogger) {
// renderer window that has a registered logger from JS.
log.setLogWindow(event.sender);
}
if (arg.cmd === apiCmds.registerActivityDetection) {
// renderer window that has a registered activity detection from JS.
activityDetection.setActivityWindow(arg.period, event.sender);
}
if (arg.cmd === apiCmds.showNotificationSettings && typeof arg.windowName === 'string') {
configureNotification.openConfigurationWindow(arg.windowName);
}
});
// expose these methods primarily for testing...

View File

@ -369,17 +369,17 @@ function createAPI() {
});
}
// reset the badge count whenever an user refreshes the electron client
function resetBadgeCount() {
// Invoked whenever the app is reloaded/navigated
function sanitize() {
local.ipcRenderer.send(apiName, {
cmd: apiCmds.setBadgeCount,
count: 0
cmd: apiCmds.sanitize,
windowName: window.name
});
}
window.addEventListener('offline', updateOnlineStatus, false);
window.addEventListener('online', updateOnlineStatus, false);
window.addEventListener('beforeunload', resetBadgeCount, false);
window.addEventListener('beforeunload', sanitize, false);
updateOnlineStatus();
}

View File

@ -181,6 +181,14 @@ function createWarn(msg) {
}
/* eslint-enable class-methods-use-this */
// terminates the screen snippet process wherever the
// main window is reloaded/navigated
eventEmitter.on('killScreenSnippet', function () {
if (child) {
child.kill();
}
});
module.exports = {
ScreenSnippet: ScreenSnippet,
// note: readResult only exposed for testing purposes

View File

@ -52,6 +52,7 @@ const searchConfig = {
MINIMUM_DATE: '0000000000000',
MAXIMUM_DATE: '9999999999999',
SORT_BY_SCORE: 0,
INDEX_VERSION: 'v1',
BATCH_RANDOM_INDEX_PATH_LENGTH: 20,
LIBRARY_CONSTANTS: libraryPaths,
FOLDERS_CONSTANTS: folderPaths,

View File

@ -21,7 +21,11 @@ class SearchUtils {
checkFreeSpace() {
return new Promise((resolve, reject) => {
if (!isMac) {
this.path = this.path.substring(0, 2);
try {
this.path = this.path.substring(0, 2);
} catch (e) {
reject(new Error('Invalid Path : ' + e));
}
}
checkDiskSpace(this.path, resolve, reject);
});
@ -65,7 +69,7 @@ function readFile(userId, resolve, reject) {
if (err) {
return reject(new Error('Error reading the '))
}
let usersConfig = [];
let usersConfig = {};
try {
usersConfig = JSON.parse(data);
} catch (e) {
@ -111,12 +115,16 @@ function createUser(userId, oldConfig) {
* @param data
*/
function createUserConfigFile(userId, data) {
let userData = data;
let createStream = fs.createWriteStream(searchConfig.FOLDERS_CONSTANTS.USER_CONFIG_FILE);
if (data) {
let jsonData;
if (userData) {
if (!userData.indexVersion) {
userData.indexVersion = searchConfig.INDEX_VERSION;
}
try {
jsonData = JSON.stringify(data);
createStream.write(`{"${userId}": ${jsonData}}`);
userData = JSON.stringify(userData);
createStream.write(`{"${userId}": ${userData}}`);
} catch (e) {
createStream.write(`{"${userId}": {}}`);
}
@ -135,9 +143,15 @@ function createUserConfigFile(userId, data) {
* @returns {*}
*/
function updateConfig(userId, data, resolve, reject) {
let userData = data;
if (userData && !userData.indexVersion) {
userData.indexVersion = searchConfig.INDEX_VERSION;
}
let configPath = searchConfig.FOLDERS_CONSTANTS.USER_CONFIG_FILE;
if (!fs.existsSync(configPath)) {
createUserConfigFile(userId, data);
createUserConfigFile(userId, userData);
return reject(null);
}

View File

@ -1,6 +1,7 @@
const childProcess = require('child_process');
const path = require('path');
const fs = require('fs');
const { isMac } = require('../js/utils/misc.js');
let executionPath = null;
let userConfigDir = null;
@ -45,6 +46,9 @@ describe('Tests for Search', function() {
key = 'jjjehdnctsjyieoalskcjdhsnahsadndfnusdfsdfsd=';
executionPath = path.join(__dirname, 'library');
if (!isMac) {
executionPath = path.join(__dirname, '..', 'library');
}
userConfigDir = path.join(__dirname, '..');
searchConfig = require('../js/search/searchConfig.js');
@ -53,7 +57,7 @@ describe('Tests for Search', function() {
realTimeIndexPath = path.join(userConfigDir, 'data', 'temp_realtime_index');
tempBatchPath = path.join(userConfigDir, 'data', 'temp_batch_indexes');
dataFolderPath = path.join(searchConfig.FOLDERS_CONSTANTS.EXEC_PATH, '..', 'data');
dataFolderPath = path.join(userConfigDir, 'data');
if (fs.existsSync(dataFolderPath)) {
fs.unlinkSync(dataFolderPath)
}
@ -65,7 +69,7 @@ describe('Tests for Search', function() {
setTimeout(function () {
deleteIndexFolders(dataFolderPath);
let root = path.join(searchConfig.FOLDERS_CONSTANTS.EXEC_PATH, '..', `${searchConfig.FOLDERS_CONSTANTS.PREFIX_NAME}_${userId}.enc`);
let root = path.join(userConfigDir, `${searchConfig.FOLDERS_CONSTANTS.PREFIX_NAME}_${userId}.enc`);
if (fs.existsSync(root)) {
fs.unlinkSync(root);
}
@ -77,7 +81,7 @@ describe('Tests for Search', function() {
function deleteIndexFolders(location) {
if (fs.existsSync(location)) {
fs.readdirSync(location).forEach(function(file) {
let curPath = location + "/" + file;
let curPath = path.join(location, file);
if (fs.lstatSync(curPath).isDirectory()) {
deleteIndexFolders(curPath);
} else {
@ -421,11 +425,10 @@ describe('Tests for Search', function() {
});
it('should not get the latest timestamp', function (done) {
SearchApi.indexFolderName = '';
const getLatestMessageTimestamp = jest.spyOn(SearchApi, 'getLatestMessageTimestamp');
deleteIndexFolders(dataFolderPath);
SearchApi.getLatestMessageTimestamp().catch(function (err) {
expect(err).toEqual(new Error('Index folder does not exist.'));
SearchApi.indexFolderName = `${dataFolderPath}/${searchConfig.FOLDERS_CONSTANTS.PREFIX_NAME}_${userId}`;
expect(getLatestMessageTimestamp).toHaveBeenCalled();
expect(getLatestMessageTimestamp).toHaveBeenCalledTimes(3);
done();
@ -435,11 +438,13 @@ describe('Tests for Search', function() {
describe('Test to decrypt the index', function () {
it('should decrypt the index', function () {
deleteIndexFolders(dataFolderPath);
const decryptAndInit = jest.spyOn(SearchApi, 'decryptAndInit');
SearchApi.decryptAndInit();
expect(decryptAndInit).toHaveBeenCalled();
it('should decrypt the index', function (done) {
setTimeout(function () {
const decryptAndInit = jest.spyOn(SearchApi, 'decryptAndInit');
SearchApi.decryptAndInit();
expect(decryptAndInit).toHaveBeenCalled();
done();
}, 3000);
});
it('should get message from the decrypted index', function (done) {
@ -480,17 +485,19 @@ describe('Tests for Search', function() {
});
it('should search fails index folder not fund', function (done) {
const searchQuery = jest.spyOn(SearchApi, 'searchQuery');
deleteIndexFolders(dataFolderPath);
SearchApi.searchQuery('it works', [], [], '', '', '', 25, 0, 0).catch(function (err) {
expect(err).toEqual(new Error('Index folder does not exist.'));
expect(searchQuery).toHaveBeenCalledTimes(8);
expect(searchQuery).toHaveBeenCalled();
SearchApi = undefined;
const { Search } = require('../js/search/search.js');
SearchApi = new Search(userId, key);
done();
});
setTimeout(function () {
const searchQuery = jest.spyOn(SearchApi, 'searchQuery');
SearchApi.searchQuery('it works', [], [], '', '', '', 25, 0, 0).catch(function (err) {
expect(err).toEqual(new Error('Index folder does not exist.'));
expect(searchQuery).toHaveBeenCalledTimes(8);
expect(searchQuery).toHaveBeenCalled();
SearchApi = undefined;
const { Search } = require('../js/search/search.js');
SearchApi = new Search(userId, key);
done();
})
}, 3000);
});
it('should search fails query is undefined', function (done) {

View File

@ -1,5 +1,6 @@
const fs = require('fs');
const path = require('path');
const { isMac } = require('../js/utils/misc.js');
let executionPath = null;
let userConfigDir = null;
@ -60,20 +61,32 @@ describe('Tests for Search Utils', function() {
it('should return error', function (done) {
const checkFreeSpace = jest.spyOn(SearchUtilsAPI, 'checkFreeSpace');
SearchUtilsAPI.path = undefined;
SearchUtilsAPI.checkFreeSpace().catch(function (err) {
expect(err).toEqual(new Error("Please provide path"));
expect(checkFreeSpace).toHaveBeenCalled();
done();
});
if (isMac) {
SearchUtilsAPI.path = undefined;
SearchUtilsAPI.checkFreeSpace().catch(function (err) {
expect(err).toEqual(new Error("Please provide path"));
expect(checkFreeSpace).toHaveBeenCalled();
done();
});
} else {
SearchUtilsAPI.path = undefined;
SearchUtilsAPI.checkFreeSpace().catch(function (err) {
expect(err).toBeTruthy();
expect(checkFreeSpace).toHaveBeenCalled();
done();
});
}
});
it('should return error invalid path', function (done) {
const checkFreeSpace = jest.spyOn(SearchUtilsAPI, 'checkFreeSpace');
SearchUtilsAPI.path = './tp';
if (!isMac) {
SearchUtilsAPI.path = 'A://test';
}
SearchUtilsAPI.checkFreeSpace().catch(function (err) {
expect(checkFreeSpace).toHaveBeenCalled();
expect(err).toEqual(err);
expect(err).toBeTruthy();
done();
});
});
@ -111,6 +124,7 @@ describe('Tests for Search Utils', function() {
language: 'en'
};
SearchUtilsAPI.updateUserConfig(1234567891011, data).then(function (res) {
data.indexVersion = 'v1';
expect(res).toEqual(data);
done();
})
@ -124,6 +138,7 @@ describe('Tests for Search Utils', function() {
};
SearchUtilsAPI.updateUserConfig(1234567891011, data).then(function (res) {
expect(res.rotationId).toEqual(1);
expect(res.indexVersion).toEqual('v1');
done();
})
});