Skip to content

Commit

Permalink
feat: allow user to delete a saved space
Browse files Browse the repository at this point in the history
closes #45
  • Loading branch information
juancarlosfarah committed May 1, 2019
1 parent 3eaee98 commit 37bc8c4
Show file tree
Hide file tree
Showing 9 changed files with 81 additions and 116 deletions.
119 changes: 32 additions & 87 deletions app/electron.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,30 +12,36 @@ const isDev = require('electron-is-dev');
const fs = require('fs');
const isOnline = require('is-online');
const electronDl = require('electron-dl');
const rimraf = require('rimraf');
// const fse = require('fs-extra');
// const extract = require('extract-zip');
// const archiver = require('archiver');
// const { ncp } = require('ncp');
const { autoUpdater } = require('electron-updater');
const Sentry = require('@sentry/electron');
const {
// DELETE_SPACE_CHANNEL,
// DELETED_SPACE_CHANNEL,
// EXPORT_SPACE_CHANNEL,
// EXPORTED_SPACE_CHANNEL,
// LOAD_SPACE_CHANNEL,
// LOADED_SPACE_CHANNEL,
DELETE_SPACE_CHANNEL,
DELETED_SPACE_CHANNEL,
GET_SPACE_CHANNEL,
MESSAGE_DIALOG_RESPOND_CHANNEL,
GET_SPACES_CHANNEL,
SAVE_DIALOG_PATH_SELECTED_CHANNEL,
SHOW_MESSAGE_DIALOG_CHANNEL,
RESPOND_DELETE_SPACE_PROMPT_CHANNEL,
SHOW_DELETE_SPACE_PROMPT_CHANNEL,
SHOW_SAVE_DIALOG_CHANNEL,
SHOW_OPEN_DIALOG_CHANNEL,
OPEN_DIALOG_PATHS_SELECTED_CHANNEL,
SAVE_SPACE_CHANNEL,
} = require('../src/config/channels');
const { getExtension, isDownloadable, generateHash } = require('./utilities');
const {
getExtension,
isDownloadable,
generateHash,
createSpaceDirectory,
} = require('./utilities');
const {
ensureDatabaseExists,
bootstrapDatabase,
Expand All @@ -44,6 +50,7 @@ const {
const {
ERROR_SPACE_ALREADY_AVAILABLE,
ERROR_DOWNLOADING_FILE,
ERROR_GENERAL,
} = require('../src/config/errors');
const logger = require('./logger');

Expand Down Expand Up @@ -232,6 +239,9 @@ app.on('ready', async () => {
);
}

// create directory where resources will be stored
createSpaceDirectory({ id });

const { phases } = spaceToSave;
// eslint-disable-next-line no-restricted-syntax
for (const phase of phases) {
Expand All @@ -245,7 +255,8 @@ app.on('ready', async () => {
const hash = generateHash(resource);
const ext = getExtension(resource);
const fileName = `${hash}.${ext}`;
const filePath = `${VAR_FOLDER}/${fileName}`;
const spacePath = `${VAR_FOLDER}/${id}`;
const filePath = `${spacePath}/${fileName}`;
phase.items[i].hash = hash;

// eslint-disable-next-line no-await-in-loop
Expand All @@ -260,7 +271,7 @@ app.on('ready', async () => {
if (isConnected) {
// eslint-disable-next-line no-await-in-loop
const dl = await download(mainWindow, url, {
directory: VAR_FOLDER,
directory: spacePath,
filename: fileName,
});
phase.items[i].asset = dl.getSavePath();
Expand Down Expand Up @@ -310,84 +321,18 @@ app.on('ready', async () => {
}
});

// ipcMain.on(DELETE_SPACE_CHANNEL, async (event, { id }) => {
// try {
// let spaces = [];
// let spaceImageUrl = '';
// const spacesPath = `${savedSpacesPath}/${spacesFileName}`;
// fs.readFile(spacesPath, 'utf8', async (err, data) => {
// if (err) {
// mainWindow.webContents.send(DELETED_SPACE_CHANNEL, ERROR_GENERAL);
// } else {
// spaces = JSON.parse(data);
// const allResources = [];
// const spaceResources = [];
//
// // eslint-disable-next-line no-restricted-syntax
// for (const space of spaces) {
// const { phases, id: spaceId, image: imageUrl } = space;
// if (spaceId === id) {
// // to get the extension of the background image for the space to be deleted
// spaceImageUrl = imageUrl;
// }
// // eslint-disable-next-line no-restricted-syntax
// for (const phase of phases) {
// const { items = [] } = phase;
// for (let i = 0; i < items.length; i += 1) {
// const { resource } = items[i];
// if (resource) {
// const { hash, type } = resource;
// const fileName = `${hash}.${type}`;
// const filePath = `${savedSpacesPath}/${fileName}`;
// // eslint-disable-next-line no-await-in-loop
// const fileAvailable = await isFileAvailable(filePath);
// if (fileAvailable) {
// if (spaceId === id) {
// spaceResources.push(filePath);
// } else {
// allResources.push(filePath);
// }
// }
// }
// }
// }
// }
// // resources in the space but not used by other spaces
// const allResourcesSet = new Set(allResources);
// const spaceDistinctResources = new Set(
// [...spaceResources].filter(
// filePath => !allResourcesSet.has(filePath)
// )
// );
// const extension = spaceImageUrl.match(/[^\\]*\.(\w+)$/)[1];
// const backgroundImagePath = `${savedSpacesPath}/background-${id}.${extension}`;
// const backgroundImageExists = await isFileAvailable(
// backgroundImagePath
// );
// if (backgroundImageExists) {
// spaceDistinctResources.add(backgroundImagePath);
// }
// // delete all resources used by the space to be deleted only
// [...spaceDistinctResources].forEach(filePath =>
// fs.unlink(filePath, error => {
// if (error) {
// logger.error(error);
// }
// })
// );
// const newSpaces = spaces.filter(el => Number(el.id) !== Number(id));
// const spacesString = JSON.stringify(newSpaces);
// await fsPromises.writeFile(
// `${savedSpacesPath}/${spacesFileName}`,
// spacesString
// );
// mainWindow.webContents.send(DELETED_SPACE_CHANNEL);
// }
// });
// } catch {
// mainWindow.webContents.send(DELETED_SPACE_CHANNEL, ERROR_GENERAL);
// }
// });
// called when deleting a space
ipcMain.on(DELETE_SPACE_CHANNEL, async (event, { id }) => {
try {
db.get(SPACES_COLLECTION)
.remove({ id })
.write();
rimraf.sync(`${VAR_FOLDER}/${id}`);
mainWindow.webContents.send(DELETED_SPACE_CHANNEL);
} catch (err) {
mainWindow.webContents.send(DELETED_SPACE_CHANNEL, ERROR_GENERAL);
}
});

// ipcMain.on(LOAD_SPACE_CHANNEL, async (event, { fileLocation }) => {
// try {
Expand Down Expand Up @@ -576,7 +521,7 @@ app.on('ready', async () => {
mainWindow.webContents.send(SAVE_DIALOG_PATH_SELECTED_CHANNEL, filePath);
});
});
ipcMain.on(SHOW_MESSAGE_DIALOG_CHANNEL, () => {
ipcMain.on(SHOW_DELETE_SPACE_PROMPT_CHANNEL, () => {
const options = {
type: 'warning',
buttons: ['Cancel', 'Delete'],
Expand All @@ -585,7 +530,7 @@ app.on('ready', async () => {
message: 'Are you sure you want to delete this space?',
};
dialog.showMessageBox(null, options, respond => {
mainWindow.webContents.send(MESSAGE_DIALOG_RESPOND_CHANNEL, respond);
mainWindow.webContents.send(RESPOND_DELETE_SPACE_PROMPT_CHANNEL, respond);
});
});
});
Expand Down
19 changes: 18 additions & 1 deletion app/utilities.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
const mkdirp = require('mkdirp');
const mime = require('mime-types');
const md5 = require('md5');
const logger = require('./logger');
const {
DOWNLOADABLE_MIME_TYPES,
APPLICATION,
RESOURCE,
VAR_FOLDER,
} = require('./config/config');

const getExtension = ({ url, mimeType }) => {
Expand Down Expand Up @@ -42,4 +45,18 @@ const generateHash = resource => {
return md5(url);
};

module.exports = { getExtension, isDownloadable, generateHash };
// create space directory
const createSpaceDirectory = async ({ id }) => {
try {
mkdirp.sync(`${VAR_FOLDER}/${id}`);
} catch (err) {
logger.error(err);
}
};

module.exports = {
getExtension,
isDownloadable,
generateHash,
createSpaceDirectory,
};
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@
"redux-devtools-extension": "2.13.8",
"redux-promise": "0.6.0",
"redux-thunk": "2.3.0",
"rimraf": "2.6.3",
"wait-on": "3.2.0"
},
"devDependencies": {
Expand Down
44 changes: 22 additions & 22 deletions src/actions/space/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
GET_SPACE_SUCCEEDED,
FLAG_EXPORTING_SPACE,
FLAG_DELETING_SPACE,
ON_SPACE_DELETED,
DELETE_SPACE_SUCCESS,
FLAG_SAVING_SPACE,
SAVE_SPACE_SUCCEEDED,
} from '../../types';
Expand All @@ -29,9 +29,9 @@ import {
GET_SPACES_CHANNEL,
LOAD_SPACE_CHANNEL,
LOADED_SPACE_CHANNEL,
MESSAGE_DIALOG_RESPOND_CHANNEL,
RESPOND_DELETE_SPACE_PROMPT_CHANNEL,
SAVE_DIALOG_PATH_SELECTED_CHANNEL,
SHOW_MESSAGE_DIALOG_CHANNEL,
SHOW_DELETE_SPACE_PROMPT_CHANNEL,
SHOW_SAVE_DIALOG_CHANNEL,
SAVE_SPACE_CHANNEL,
} from '../../config/channels';
Expand Down Expand Up @@ -262,26 +262,26 @@ const exportSpace = (id, spaces, spaceName) => dispatch => {
};

const deleteSpace = ({ id }) => dispatch => {
dispatch(flagDeletingSpace(true));
window.ipcRenderer.send(SHOW_MESSAGE_DIALOG_CHANNEL);
window.ipcRenderer.once(MESSAGE_DIALOG_RESPOND_CHANNEL, (event, respond) => {
if (respond === 1) {
window.ipcRenderer.send(DELETE_SPACE_CHANNEL, { id });
} else {
dispatch(flagExportingSpace(false));
// show confirmation prompt
window.ipcRenderer.send(SHOW_DELETE_SPACE_PROMPT_CHANNEL);
window.ipcRenderer.once(
RESPOND_DELETE_SPACE_PROMPT_CHANNEL,
(event, response) => {
if (response === 1) {
dispatch(flagDeletingSpace(true));
window.ipcRenderer.send(DELETE_SPACE_CHANNEL, { id });
}
}
});
window.ipcRenderer.once(DELETED_SPACE_CHANNEL, (event, deletedReply) => {
switch (deletedReply) {
case ERROR_GENERAL:
toastr.error('Error', ERROR_DELETING_MESSAGE);
break;
default:
toastr.success('Success', SUCCESS_DELETING_MESSAGE);
dispatch({
type: ON_SPACE_DELETED,
payload: true,
});
);
window.ipcRenderer.once(DELETED_SPACE_CHANNEL, (event, response) => {
if (response === ERROR_GENERAL) {
toastr.error('Error', ERROR_DELETING_MESSAGE);
} else {
toastr.success('Success', SUCCESS_DELETING_MESSAGE);
dispatch({
type: DELETE_SPACE_SUCCESS,
payload: true,
});
}
dispatch(flagDeletingSpace(false));
});
Expand Down
3 changes: 2 additions & 1 deletion src/components/space/SpaceNotFound.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@ import React from 'react';
import PropTypes from 'prop-types';
import { withRouter } from 'react-router';
import Button from '@material-ui/core//Button';
import { HOME_PATH } from '../../config/paths';

const SpaceNotFound = ({ history: { replace } }) => {
return (
<div>
Space not found.
<Button onClick={() => replace('/')}>Home</Button>
<Button onClick={() => replace(HOME_PATH)}>Home</Button>
</div>
);
};
Expand Down
1 change: 1 addition & 0 deletions src/components/space/SpaceScreen.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ class SpaceScreen extends Component {
deleted,
history: { replace },
} = this.props;
// redirect to home if space is deleted
if (deleted) {
replace(HOME_PATH);
}
Expand Down
4 changes: 2 additions & 2 deletions src/config/channels.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ module.exports = {
SHOW_OPEN_DIALOG_CHANNEL: 'show-open-dialog',
SHOW_SAVE_DIALOG_CHANNEL: 'show-save-dialog',
OPEN_DIALOG_PATHS_SELECTED_CHANNEL: 'open-dialog-paths-selected',
SHOW_MESSAGE_DIALOG_CHANNEL: 'show-message-dialog',
SAVE_DIALOG_PATH_SELECTED_CHANNEL: 'save-dialog-path-selected',
MESSAGE_DIALOG_RESPOND_CHANNEL: 'message-dialog-respond',
SHOW_DELETE_SPACE_PROMPT_CHANNEL: 'prompt:space:delete:show',
RESPOND_DELETE_SPACE_PROMPT_CHANNEL: 'prompt:space:delete:respond',
};
4 changes: 2 additions & 2 deletions src/reducers/SpaceReducer.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
FLAG_GETTING_SPACES,
FLAG_LOADING_SPACE,
FLAG_EXPORTING_SPACE,
ON_SPACE_DELETED,
DELETE_SPACE_SUCCESS,
SAVE_SPACE_SUCCEEDED,
} from '../types';

Expand Down Expand Up @@ -44,7 +44,7 @@ export default (state = INITIAL_STATE, { type, payload }) => {
return state.setIn(['current', 'activity'], payload);
case FLAG_DELETING_SPACE:
return state.setIn(['current', 'activity'], payload);
case ON_SPACE_DELETED:
case DELETE_SPACE_SUCCESS:
return state.setIn(['current', 'deleted'], payload);
case GET_SPACES:
return state.setIn(['saved'], payload);
Expand Down
2 changes: 1 addition & 1 deletion src/types/space/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export const FLAG_EXPORTING_SPACE = 'FLAG_EXPORTING_SPACES';
export const TOGGLE_SPACE_MENU = 'TOGGLE_SPACE_MENU';
export const CLEAR_SPACE = 'CLEAR_SPACE';
export const GET_SPACE_SUCCEEDED = 'GET_SPACE_SUCCEEDED';
export const ON_SPACE_DELETED = 'ON_SPACE_DELETED';
export const DELETE_SPACE_SUCCESS = 'DELETE_SPACE_SUCCESS';
export const SAVE_SPACE = 'SAVE_SPACE';
export const FLAG_SAVING_SPACE = 'FLAG_SAVING_SPACE';
export const SAVE_SPACE_SUCCEEDED = 'SAVE_SPACE_SUCCEEDED';

0 comments on commit 37bc8c4

Please sign in to comment.