Use of async/await

This commit is contained in:
Benoit Schweblin 2018-05-13 13:27:33 +00:00
parent e971082768
commit 597c747b00
69 changed files with 4194 additions and 4208 deletions

View File

@ -92,20 +92,19 @@ export default {
return !!this.$store.getters['modal/config']; return !!this.$store.getters['modal/config'];
}, },
}, },
created() { async created() {
syncSvc.init() try {
.then(() => { await syncSvc.init();
networkSvc.init(); await networkSvc.init();
sponsorSvc.init(); await sponsorSvc.init();
this.ready = true; this.ready = true;
tempFileSvc.setReady(); tempFileSvc.setReady();
}) } catch (err) {
.catch((err) => { if (err && err.message !== 'reload') {
if (err && err.message !== 'reload') { console.error(err); // eslint-disable-line no-console
console.error(err); // eslint-disable-line no-console this.$store.dispatch('notification/error', err);
this.$store.dispatch('notification/error', err); }
} }
});
}, },
}; };
</script> </script>

View File

@ -97,29 +97,36 @@ export default {
} }
return true; return true;
}, },
submitNewChild(cancel) { async submitNewChild(cancel) {
const { newChildNode } = this.$store.state.explorer; const { newChildNode } = this.$store.state.explorer;
if (!cancel && !newChildNode.isNil && newChildNode.item.name) { if (!cancel && !newChildNode.isNil && newChildNode.item.name) {
if (newChildNode.isFolder) { try {
fileSvc.storeItem(newChildNode.item) if (newChildNode.isFolder) {
.then(item => this.select(item.id), () => { /* cancel */ }); const item = await fileSvc.storeItem(newChildNode.item);
} else { this.select(item.id);
fileSvc.createFile(newChildNode.item) } else {
.then(item => this.select(item.id), () => { /* cancel */ }); const item = await fileSvc.createFile(newChildNode.item);
this.select(item.id);
}
} catch (e) {
// Cancel
} }
} }
this.$store.commit('explorer/setNewItem', null); this.$store.commit('explorer/setNewItem', null);
}, },
submitEdit(cancel) { async submitEdit(cancel) {
const { item } = this.$store.getters['explorer/editingNode']; const { item } = this.$store.getters['explorer/editingNode'];
const value = this.editingValue; const value = this.editingValue;
this.setEditingId(null); this.setEditingId(null);
if (!cancel && item.id && value) { if (!cancel && item.id && value) {
fileSvc.storeItem({ try {
...item, await fileSvc.storeItem({
name: value, ...item,
}) name: value,
.catch(() => { /* cancel */ }); });
} catch (e) {
// Cancel
}
} }
}, },
setDragSourceId(evt) { setDragSourceId(evt) {
@ -140,22 +147,17 @@ export default {
&& !targetNode.isNil && !targetNode.isNil
&& sourceNode.item.id !== targetNode.item.id && sourceNode.item.id !== targetNode.item.id
) { ) {
const patch = { fileSvc.storeItem({
id: sourceNode.item.id, ...sourceNode.item,
parentId: targetNode.item.id, parentId: targetNode.item.id,
}; });
if (sourceNode.isFolder) {
this.$store.commit('folder/patchItem', patch);
} else {
this.$store.commit('file/patchItem', patch);
}
} }
}, },
onContextMenu(evt) { async onContextMenu(evt) {
if (this.select(undefined, false)) { if (this.select(undefined, false)) {
evt.preventDefault(); evt.preventDefault();
evt.stopPropagation(); evt.stopPropagation();
this.$store.dispatch('contextMenu/open', { const item = await this.$store.dispatch('contextMenu/open', {
coordinates: { coordinates: {
left: evt.clientX, left: evt.clientX,
top: evt.clientY, top: evt.clientY,
@ -178,8 +180,8 @@ export default {
name: 'Delete', name: 'Delete',
perform: () => explorerSvc.deleteItem(), perform: () => explorerSvc.deleteItem(),
}], }],
}) });
.then(item => item.perform()); item.perform();
} }
}, },
}, },

View File

@ -175,10 +175,6 @@ export default {
background-color: rgba(160, 160, 160, 0.5); background-color: rgba(160, 160, 160, 0.5);
overflow: auto; overflow: auto;
hr {
margin: 0.5em 0;
}
p { p {
line-height: 1.5; line-height: 1.5;
} }

View File

@ -192,7 +192,7 @@ export default {
editorSvc.pagedownEditor.uiManager.doClick(name); editorSvc.pagedownEditor.uiManager.doClick(name);
} }
}, },
editTitle(toggle) { async editTitle(toggle) {
this.titleFocus = toggle; this.titleFocus = toggle;
if (toggle) { if (toggle) {
this.titleInputElt.setSelectionRange(0, this.titleInputElt.value.length); this.titleInputElt.setSelectionRange(0, this.titleInputElt.value.length);
@ -200,11 +200,14 @@ export default {
const title = this.title.trim(); const title = this.title.trim();
this.title = this.$store.getters['file/current'].name; this.title = this.$store.getters['file/current'].name;
if (title) { if (title) {
fileSvc.storeItem({ try {
...this.$store.getters['file/current'], await fileSvc.storeItem({
name: title, ...this.$store.getters['file/current'],
}) name: title,
.catch(() => { /* Cancel */ }); });
} catch (e) {
// Cancel
}
} }
} }
}, },

View File

@ -47,12 +47,13 @@ export default {
...mapMutations('discussion', [ ...mapMutations('discussion', [
'setIsCommenting', 'setIsCommenting',
]), ]),
removeComment() { async removeComment() {
this.$store.dispatch('modal/commentDeletion') try {
.then( await this.$store.dispatch('modal/commentDeletion');
() => this.$store.dispatch('discussion/cleanCurrentFile', { filterComment: this.comment }), this.$store.dispatch('discussion/cleanCurrentFile', { filterComment: this.comment });
() => { /* Cancel */ }, } catch (e) {
); // Cancel
}
}, },
}, },
mounted() { mounted() {

View File

@ -93,14 +93,15 @@ export default {
.start(); .start();
} }
}, },
removeDiscussion() { async removeDiscussion() {
this.$store.dispatch('modal/discussionDeletion') try {
.then( await this.$store.dispatch('modal/discussionDeletion');
() => this.$store.dispatch('discussion/cleanCurrentFile', { this.$store.dispatch('discussion/cleanCurrentFile', {
filterDiscussion: this.currentDiscussion, filterDiscussion: this.currentDiscussion,
}), });
() => { /* Cancel */ }, } catch (e) {
); // Cancel
}
}, },
}, },
}; };

View File

@ -96,12 +96,13 @@ export default {
...mapMutations('content', [ ...mapMutations('content', [
'setRevisionContent', 'setRevisionContent',
]), ]),
signin() { async signin() {
return googleHelper.signin() try {
.then( await googleHelper.signin();
() => syncSvc.requestSync(), syncSvc.requestSync();
() => { /* Cancel */ }, } catch (e) {
); // Cancel
}
}, },
close() { close() {
this.$store.dispatch('data/setSideBarPanel', 'menu'); this.$store.dispatch('data/setSideBarPanel', 'menu');
@ -117,10 +118,15 @@ export default {
const currentFile = this.$store.getters['file/current']; const currentFile = this.$store.getters['file/current'];
this.$store.dispatch( this.$store.dispatch(
'queue/enqueue', 'queue/enqueue',
() => Promise.resolve() async () => {
.then(() => this.workspaceProvider try {
.getRevisionContent(syncToken, currentFile.id, revision.id)) const content = await this.workspaceProvider
.then(resolve, reject), .getRevisionContent(syncToken, currentFile.id, revision.id);
resolve(content);
} catch (e) {
reject(e);
}
},
); );
}); });
revisionContentPromises[revision.id] = revisionContentPromise; revisionContentPromises[revision.id] = revisionContentPromise;
@ -181,9 +187,15 @@ export default {
revisionsPromise = new Promise((resolve, reject) => { revisionsPromise = new Promise((resolve, reject) => {
this.$store.dispatch( this.$store.dispatch(
'queue/enqueue', 'queue/enqueue',
() => Promise.resolve() async () => {
.then(() => this.workspaceProvider.listRevisions(syncToken, currentFile.id)) try {
.then(resolve, reject), const revisions = await this.workspaceProvider
.listRevisions(syncToken, currentFile.id);
resolve(revisions);
} catch (e) {
reject(e);
}
},
); );
}) })
.catch(() => { .catch(() => {

View File

@ -104,16 +104,20 @@ export default {
...mapActions('data', { ...mapActions('data', {
setPanel: 'setSideBarPanel', setPanel: 'setSideBarPanel',
}), }),
signin() { async signin() {
return googleHelper.signin() try {
.then( await googleHelper.signin();
() => syncSvc.requestSync(), syncSvc.requestSync();
() => { /* Cancel */ }, } catch (e) {
); // Cancel
}
}, },
fileProperties() { async fileProperties() {
return this.$store.dispatch('modal/open', 'fileProperties') try {
.catch(() => { /* Cancel */ }); await this.$store.dispatch('modal/open', 'fileProperties');
} catch (e) {
// Cancel
}
}, },
print() { print() {
window.print(); window.print();

View File

@ -78,29 +78,33 @@ export default {
document.body.removeChild(iframeElt); document.body.removeChild(iframeElt);
}, 60000); }, 60000);
}, },
settings() { async settings() {
return this.$store.dispatch('modal/open', 'settings') try {
.then( const settings = await this.$store.dispatch('modal/open', 'settings');
settings => this.$store.dispatch('data/setSettings', settings), this.$store.dispatch('data/setSettings', settings);
() => { /* Cancel */ }, } catch (e) {
); // Cancel
}
}, },
templates() { async templates() {
return this.$store.dispatch('modal/open', 'templates') try {
.then( const { templates } = await this.$store.dispatch('modal/open', 'templates');
({ templates }) => this.$store.dispatch('data/setTemplates', templates), this.$store.dispatch('data/setTemplates', templates);
() => { /* Cancel */ }, } catch (e) {
); // Cancel
}
}, },
reset() { async reset() {
return this.$store.dispatch('modal/reset') try {
.then(() => { await this.$store.dispatch('modal/reset');
window.location.href = '#reset=true'; window.location.href = '#reset=true';
window.location.reload(); window.location.reload();
}); } catch (e) {
// Cancel
}
}, },
about() { about() {
return this.$store.dispatch('modal/open', 'about'); this.$store.dispatch('modal/open', 'about');
}, },
}, },
}; };

View File

@ -118,12 +118,15 @@ const tokensToArray = (tokens, filter = () => true) => Object.keys(tokens)
.filter(token => filter(token)) .filter(token => filter(token))
.sort((token1, token2) => token1.name.localeCompare(token2.name)); .sort((token1, token2) => token1.name.localeCompare(token2.name));
const openPublishModal = (token, type) => store.dispatch('modal/open', { const publishModalOpener = type => async (token) => {
type, try {
token, const publishLocation = await store.dispatch('modal/open', {
}).then(publishLocation => publishSvc.createPublishLocation(publishLocation)); type,
token,
const onCancel = () => {}; });
publishSvc.createPublishLocation(publishLocation);
} catch (e) { /* cancel */ }
};
export default { export default {
components: { components: {
@ -178,74 +181,48 @@ export default {
managePublish() { managePublish() {
return this.$store.dispatch('modal/open', 'publishManagement'); return this.$store.dispatch('modal/open', 'publishManagement');
}, },
addGoogleDriveAccount() { async addGoogleDriveAccount() {
return this.$store.dispatch('modal/open', { try {
type: 'googleDriveAccount', await this.$store.dispatch('modal/open', { type: 'googleDriveAccount' });
onResolve: () => googleHelper.addDriveAccount(!store.getters['data/localSettings'].googleDriveRestrictedAccess), await googleHelper.addDriveAccount(!store.getters['data/localSettings'].googleDriveRestrictedAccess);
}) } catch (e) { /* cancel */ }
.catch(onCancel);
}, },
addDropboxAccount() { async addDropboxAccount() {
return this.$store.dispatch('modal/open', { try {
type: 'dropboxAccount', await this.$store.dispatch('modal/open', { type: 'dropboxAccount' });
onResolve: () => dropboxHelper.addAccount(!store.getters['data/localSettings'].dropboxRestrictedAccess), await dropboxHelper.addAccount(!store.getters['data/localSettings'].dropboxRestrictedAccess);
}) } catch (e) { /* cancel */ }
.catch(onCancel);
}, },
addGithubAccount() { async addGithubAccount() {
return this.$store.dispatch('modal/open', { try {
type: 'githubAccount', await this.$store.dispatch('modal/open', { type: 'githubAccount' });
onResolve: () => githubHelper.addAccount(store.getters['data/localSettings'].githubRepoFullAccess), await githubHelper.addAccount(store.getters['data/localSettings'].githubRepoFullAccess);
}) } catch (e) { /* cancel */ }
.catch(onCancel);
}, },
addWordpressAccount() { async addWordpressAccount() {
return wordpressHelper.addAccount() try {
.catch(onCancel); await wordpressHelper.addAccount();
} catch (e) { /* cancel */ }
}, },
addBloggerAccount() { async addBloggerAccount() {
return googleHelper.addBloggerAccount() try {
.catch(onCancel); await googleHelper.addBloggerAccount();
} catch (e) { /* cancel */ }
}, },
addZendeskAccount() { async addZendeskAccount() {
return this.$store.dispatch('modal/open', { try {
type: 'zendeskAccount', const { subdomain, clientId } = await this.$store.dispatch('modal/open', { type: 'zendeskAccount' });
onResolve: ({ subdomain, clientId }) => zendeskHelper.addAccount(subdomain, clientId), await zendeskHelper.addAccount(subdomain, clientId);
}) } catch (e) { /* cancel */ }
.catch(onCancel);
},
publishGoogleDrive(token) {
return openPublishModal(token, 'googleDrivePublish')
.catch(onCancel);
},
publishDropbox(token) {
return openPublishModal(token, 'dropboxPublish')
.catch(onCancel);
},
publishGithub(token) {
return openPublishModal(token, 'githubPublish')
.catch(onCancel);
},
publishGist(token) {
return openPublishModal(token, 'gistPublish')
.catch(onCancel);
},
publishWordpress(token) {
return openPublishModal(token, 'wordpressPublish')
.catch(onCancel);
},
publishBlogger(token) {
return openPublishModal(token, 'bloggerPublish')
.catch(onCancel);
},
publishBloggerPage(token) {
return openPublishModal(token, 'bloggerPagePublish')
.catch(onCancel);
},
publishZendesk(token) {
return openPublishModal(token, 'zendeskPublish')
.catch(onCancel);
}, },
publishGoogleDrive: publishModalOpener('googleDrivePublish'),
publishDropbox: publishModalOpener('dropboxPublish'),
publishGithub: publishModalOpener('githubPublish'),
publishGist: publishModalOpener('gistPublish'),
publishWordpress: publishModalOpener('wordpressPublish'),
publishBlogger: publishModalOpener('bloggerPublish'),
publishBloggerPage: publishModalOpener('bloggerPagePublish'),
publishZendesk: publishModalOpener('zendeskPublish'),
}, },
}; };
</script> </script>

View File

@ -101,8 +101,6 @@ const openSyncModal = (token, type) => store.dispatch('modal/open', {
token, token,
}).then(syncLocation => syncSvc.createSyncLocation(syncLocation)); }).then(syncLocation => syncSvc.createSyncLocation(syncLocation));
const onCancel = () => {};
export default { export default {
components: { components: {
MenuEntry, MenuEntry,
@ -147,66 +145,79 @@ export default {
manageSync() { manageSync() {
return this.$store.dispatch('modal/open', 'syncManagement'); return this.$store.dispatch('modal/open', 'syncManagement');
}, },
addGoogleDriveAccount() { async addGoogleDriveAccount() {
return this.$store.dispatch('modal/open', { try {
type: 'googleDriveAccount', await this.$store.dispatch('modal/open', { type: 'googleDriveAccount' });
onResolve: () => googleHelper.addDriveAccount(!store.getters['data/localSettings'].googleDriveRestrictedAccess), await googleHelper.addDriveAccount(!store.getters['data/localSettings'].googleDriveRestrictedAccess);
}) } catch (e) { /* cancel */ }
.catch(onCancel);
}, },
addDropboxAccount() { async addDropboxAccount() {
return this.$store.dispatch('modal/open', { try {
type: 'dropboxAccount', await this.$store.dispatch('modal/open', { type: 'dropboxAccount' });
onResolve: () => dropboxHelper.addAccount(!store.getters['data/localSettings'].dropboxRestrictedAccess), await dropboxHelper.addAccount(!store.getters['data/localSettings'].dropboxRestrictedAccess);
}) } catch (e) { /* cancel */ }
.catch(onCancel);
}, },
addGithubAccount() { async addGithubAccount() {
return this.$store.dispatch('modal/open', { try {
type: 'githubAccount', await this.$store.dispatch('modal/open', { type: 'githubAccount' });
onResolve: () => githubHelper.addAccount(store.getters['data/localSettings'].githubRepoFullAccess), await githubHelper.addAccount(store.getters['data/localSettings'].githubRepoFullAccess);
}) } catch (e) { /* cancel */ }
.catch(onCancel);
}, },
openGoogleDrive(token) { async openGoogleDrive(token) {
return googleHelper.openPicker(token, 'doc') const files = await googleHelper.openPicker(token, 'doc');
.then(files => this.$store.dispatch( this.$store.dispatch(
'queue/enqueue', 'queue/enqueue',
() => googleDriveProvider.openFiles(token, files), () => googleDriveProvider.openFiles(token, files),
)); );
}, },
openDropbox(token) { async openDropbox(token) {
return dropboxHelper.openChooser(token) const paths = await dropboxHelper.openChooser(token);
.then(paths => this.$store.dispatch( this.$store.dispatch(
'queue/enqueue', 'queue/enqueue',
() => dropboxProvider.openFiles(token, paths), () => dropboxProvider.openFiles(token, paths),
)); );
}, },
saveGoogleDrive(token) { async saveGoogleDrive(token) {
return openSyncModal(token, 'googleDriveSave') try {
.catch(onCancel); await openSyncModal(token, 'googleDriveSave');
} catch (e) {
// Cancel
}
}, },
saveDropbox(token) { async saveDropbox(token) {
return openSyncModal(token, 'dropboxSave') try {
.catch(onCancel); await openSyncModal(token, 'dropboxSave');
} catch (e) {
// Cancel
}
}, },
openGithub(token) { async openGithub(token) {
return store.dispatch('modal/open', { try {
type: 'githubOpen', const syncLocation = await store.dispatch('modal/open', {
token, type: 'githubOpen',
}) token,
.then(syncLocation => this.$store.dispatch( });
this.$store.dispatch(
'queue/enqueue', 'queue/enqueue',
() => githubProvider.openFile(token, syncLocation), () => githubProvider.openFile(token, syncLocation),
)); );
} catch (e) {
// Cancel
}
}, },
saveGithub(token) { async saveGithub(token) {
return openSyncModal(token, 'githubSave') try {
.catch(onCancel); await openSyncModal(token, 'githubSave');
} catch (e) {
// Cancel
}
}, },
saveGist(token) { async saveGist(token) {
return openSyncModal(token, 'gistSync') try {
.catch(onCancel); await openSyncModal(token, 'gistSync');
} catch (e) {
// Cancel
}
}, },
}, },
}; };

View File

@ -31,8 +31,6 @@ import { mapGetters } from 'vuex';
import MenuEntry from './common/MenuEntry'; import MenuEntry from './common/MenuEntry';
import googleHelper from '../../services/providers/helpers/googleHelper'; import googleHelper from '../../services/providers/helpers/googleHelper';
const onCancel = () => {};
export default { export default {
components: { components: {
MenuEntry, MenuEntry,
@ -46,28 +44,37 @@ export default {
]), ]),
}, },
methods: { methods: {
addCouchdbWorkspace() { async addCouchdbWorkspace() {
return this.$store.dispatch('modal/open', { try {
type: 'couchdbWorkspace', this.$store.dispatch('modal/open', {
}) type: 'couchdbWorkspace',
.catch(onCancel); });
} catch (e) {
// Cancel
}
}, },
addGithubWorkspace() { async addGithubWorkspace() {
return this.$store.dispatch('modal/open', { try {
type: 'githubWorkspace', this.$store.dispatch('modal/open', {
}) type: 'githubWorkspace',
.catch(onCancel); });
} catch (e) {
// Cancel
}
}, },
addGoogleDriveWorkspace() { async addGoogleDriveWorkspace() {
return googleHelper.addDriveAccount(true) try {
.then(token => this.$store.dispatch('modal/open', { const token = await googleHelper.addDriveAccount(true);
this.$store.dispatch('modal/open', {
type: 'googleDriveWorkspace', type: 'googleDriveWorkspace',
token, token,
})) });
.catch(onCancel); } catch (e) {
// Cancel
}
}, },
manageWorkspaces() { manageWorkspaces() {
return this.$store.dispatch('modal/open', 'workspaceManagement'); this.$store.dispatch('modal/open', 'workspaceManagement');
}, },
}, },
}; };

View File

@ -2,7 +2,7 @@
<modal-inner class="modal__inner-1--about-modal" aria-label="About"> <modal-inner class="modal__inner-1--about-modal" aria-label="About">
<div class="modal__content"> <div class="modal__content">
<div class="logo-background"></div> <div class="logo-background"></div>
<small>v{{version}}<br>© 2013-2018 Dock5 Software</small> <small>© 2013-2018 Dock5 Software<br>v{{version}}</small>
<hr> <hr>
StackEdit on <a target="_blank" href="https://github.com/benweet/stackedit/">GitHub</a> StackEdit on <a target="_blank" href="https://github.com/benweet/stackedit/">GitHub</a>
<br> <br>
@ -59,11 +59,12 @@ export default {
.logo-background { .logo-background {
height: 75px; height: 75px;
margin: 0.5rem 0; margin: 0;
} }
small { small {
display: block; display: block;
font-size: 0.75em;
} }
hr { hr {

View File

@ -41,6 +41,9 @@
</form-entry> </form-entry>
<form-entry label="Status"> <form-entry label="Status">
<input slot="field" class="textfield" type="text" v-model.trim="status" @keydown.enter="resolve()"> <input slot="field" class="textfield" type="text" v-model.trim="status" @keydown.enter="resolve()">
<div class="form-entry__info">
<b>Example:</b> draft
</div>
</form-entry> </form-entry>
<form-entry label="Date" info="YYYY-MM-DD"> <form-entry label="Date" info="YYYY-MM-DD">
<input slot="field" class="textfield" type="text" v-model.trim="date" @keydown.enter="resolve()"> <input slot="field" class="textfield" type="text" v-model.trim="date" @keydown.enter="resolve()">

View File

@ -37,12 +37,13 @@ export default modalTemplate({
let timeoutId; let timeoutId;
this.$watch('selectedTemplate', (selectedTemplate) => { this.$watch('selectedTemplate', (selectedTemplate) => {
clearTimeout(timeoutId); clearTimeout(timeoutId);
timeoutId = setTimeout(() => { timeoutId = setTimeout(async () => {
const currentFile = this.$store.getters['file/current']; const currentFile = this.$store.getters['file/current'];
exportSvc.applyTemplate(currentFile.id, this.allTemplates[selectedTemplate]) const html = await exportSvc.applyTemplate(
.then((html) => { currentFile.id,
this.result = html; this.allTemplates[selectedTemplate],
}); );
this.result = html;
}, 10); }, 10);
}, { }, {
immediate: true, immediate: true,

View File

@ -61,15 +61,17 @@ export default modalTemplate({
addGooglePhotosAccount() { addGooglePhotosAccount() {
return googleHelper.addPhotosAccount(); return googleHelper.addPhotosAccount();
}, },
openGooglePhotos(token) { async openGooglePhotos(token) {
const { callback } = this.config; const { callback } = this.config;
this.config.reject(); this.config.reject();
googleHelper.openPicker(token, 'img') const res = await googleHelper.openPicker(token, 'img');
.then(res => res[0] && this.$store.dispatch('modal/open', { if (res[0]) {
this.$store.dispatch('modal/open', {
type: 'googlePhoto', type: 'googlePhoto',
url: res[0].url, url: res[0].url,
callback, callback,
})); });
}
}, },
}, },
}); });

View File

@ -38,19 +38,20 @@ export default modalTemplate({
selectedFormat: 'pandocExportFormat', selectedFormat: 'pandocExportFormat',
}, },
methods: { methods: {
resolve() { async resolve() {
this.config.resolve(); this.config.resolve();
const currentFile = this.$store.getters['file/current']; const currentFile = this.$store.getters['file/current'];
const currentContent = this.$store.getters['content/current']; const currentContent = this.$store.getters['content/current'];
const { selectedFormat } = this; const { selectedFormat } = this;
this.$store.dispatch('queue/enqueue', () => Promise.all([ const [sponsorToken, token] = await this.$store.dispatch('queue/enqueue', () => Promise.all([
Promise.resolve().then(() => { Promise.resolve().then(() => {
const sponsorToken = this.$store.getters['workspace/sponsorToken']; const tokenToRefresh = this.$store.getters['workspace/sponsorToken'];
return sponsorToken && googleHelper.refreshToken(sponsorToken); return tokenToRefresh && googleHelper.refreshToken(tokenToRefresh);
}), }),
sponsorSvc.getToken(), sponsorSvc.getToken(),
]) ]));
.then(([sponsorToken, token]) => networkSvc.request({ try {
const { body } = await networkSvc.request({
method: 'POST', method: 'POST',
url: 'pandocExport', url: 'pandocExport',
params: { params: {
@ -63,20 +64,16 @@ export default modalTemplate({
body: JSON.stringify(editorSvc.getPandocAst()), body: JSON.stringify(editorSvc.getPandocAst()),
blob: true, blob: true,
timeout: 60000, timeout: 60000,
}) });
.then((res) => { FileSaver.saveAs(body, `${currentFile.name}.${selectedFormat}`);
FileSaver.saveAs(res.body, `${currentFile.name}.${selectedFormat}`); } catch (err) {
}, (err) => { if (err.status === 401) {
if (err.status !== 401) { this.$store.dispatch('modal/sponsorOnly');
throw err; } else {
}
this.$store.dispatch('modal/sponsorOnly')
.catch(() => { /* Cancel */ });
}))
.catch((err) => {
console.error(err); // eslint-disable-line no-console console.error(err); // eslint-disable-line no-console
this.$store.dispatch('notification/error', err); this.$store.dispatch('notification/error', err);
})); }
}
}, },
}, },
}); });

View File

@ -33,22 +33,24 @@ export default modalTemplate({
selectedTemplate: 'pdfExportTemplate', selectedTemplate: 'pdfExportTemplate',
}, },
methods: { methods: {
resolve() { async resolve() {
this.config.resolve(); this.config.resolve();
const currentFile = this.$store.getters['file/current']; const currentFile = this.$store.getters['file/current'];
this.$store.dispatch('queue/enqueue', () => Promise.all([ const [sponsorToken, token, html] = await this.$store
Promise.resolve().then(() => { .dispatch('queue/enqueue', () => Promise.all([
const sponsorToken = this.$store.getters['workspace/sponsorToken']; Promise.resolve().then(() => {
return sponsorToken && googleHelper.refreshToken(sponsorToken); const tokenToRefresh = this.$store.getters['workspace/sponsorToken'];
}), return tokenToRefresh && googleHelper.refreshToken(tokenToRefresh);
sponsorSvc.getToken(), }),
exportSvc.applyTemplate( sponsorSvc.getToken(),
currentFile.id, exportSvc.applyTemplate(
this.allTemplates[this.selectedTemplate], currentFile.id,
true, this.allTemplates[this.selectedTemplate],
), true,
]) ),
.then(([sponsorToken, token, html]) => networkSvc.request({ ]));
try {
const { body } = await networkSvc.request({
method: 'POST', method: 'POST',
url: 'pdfExport', url: 'pdfExport',
params: { params: {
@ -59,20 +61,16 @@ export default modalTemplate({
body: html, body: html,
blob: true, blob: true,
timeout: 60000, timeout: 60000,
}) });
.then((res) => { FileSaver.saveAs(body, `${currentFile.name}.pdf`);
FileSaver.saveAs(res.body, `${currentFile.name}.pdf`); } catch (err) {
}, (err) => { if (err.status === 401) {
if (err.status !== 401) { this.$store.dispatch('modal/sponsorOnly');
throw err; } else {
}
this.$store.dispatch('modal/sponsorOnly')
.catch(() => { /* Cancel */ });
}))
.catch((err) => {
console.error(err); // eslint-disable-line no-console console.error(err); // eslint-disable-line no-console
this.$store.dispatch('notification/error', err); this.$store.dispatch('notification/error', err);
})); }
}
}, },
}, },
}); });

View File

@ -75,12 +75,13 @@ export default {
} }
this.editedId = null; this.editedId = null;
}, },
remove(id) { async remove(id) {
return this.$store.dispatch('modal/removeWorkspace') try {
.then( await this.$store.dispatch('modal/removeWorkspace');
() => localDbSvc.removeWorkspace(id), localDbSvc.removeWorkspace(id);
() => { /* Cancel */ }, } catch (e) {
); // Cancel
}
}, },
}, },
}; };

View File

@ -29,20 +29,18 @@ export default {
}, },
}, },
methods: { methods: {
sponsor() { async sponsor() {
Promise.resolve() try {
.then(() => !this.$store.getters['workspace/sponsorToken'] && if (!this.$store.getters['workspace/sponsorToken']) {
// If user has to sign in // User has to sign in
this.$store.dispatch('modal/signInForSponsorship', { await this.$store.dispatch('modal/signInForSponsorship');
onResolve: () => googleHelper.signin() await googleHelper.signin();
.then(() => syncSvc.requestSync()), syncSvc.requestSync();
})) }
.then(() => { if (!this.$store.getters.isSponsor) {
if (!this.$store.getters.isSponsor) { await this.$store.dispatch('modal/open', 'sponsor');
this.$store.dispatch('modal/open', 'sponsor'); }
} } catch (e) { /* cancel */ }
})
.catch(() => { /* Cancel */ });
}, },
}, },
}; };

View File

@ -63,17 +63,15 @@ export default (desc) => {
return sortedTemplates; return sortedTemplates;
}; };
// Make use of `function` to have `this` bound to the component // Make use of `function` to have `this` bound to the component
component.methods.configureTemplates = function () { // eslint-disable-line func-names component.methods.configureTemplates = async function () { // eslint-disable-line func-names
store.dispatch('modal/open', { const { templates, selectedId } = await store.dispatch('modal/open', {
type: 'templates', type: 'templates',
selectedId: this.selectedTemplate, selectedId: this.selectedTemplate,
}) });
.then(({ templates, selectedId }) => { store.dispatch('data/setTemplates', templates);
store.dispatch('data/setTemplates', templates); store.dispatch('data/patchLocalSettings', {
store.dispatch('data/patchLocalSettings', { [id]: selectedId,
[id]: selectedId, });
});
});
}; };
} }
}); });

View File

@ -18,14 +18,12 @@ OfflinePluginRuntime.install({
// Tells to new SW to take control immediately // Tells to new SW to take control immediately
OfflinePluginRuntime.applyUpdate(); OfflinePluginRuntime.applyUpdate();
}, },
onUpdated: () => { onUpdated: async () => {
if (!store.state.light) { if (!store.state.light) {
localDbSvc.sync() await localDbSvc.sync();
.then(() => { localStorage.updated = true;
localStorage.updated = true; // Reload the webpage to load into the new version
// Reload the webpage to load into the new version window.location.reload();
window.location.reload();
});
} }
}, },
}); });

View File

@ -49,20 +49,26 @@ export default {
} }
}); });
await utils.awaitSequence(Object.keys(folderNameMap), async externalId => fileSvc.storeItem({ await utils.awaitSequence(
id: folderIdMap[externalId], Object.keys(folderNameMap),
type: 'folder', async externalId => fileSvc.setOrPatchItem({
name: folderNameMap[externalId], id: folderIdMap[externalId],
parentId: folderIdMap[parentIdMap[externalId]], type: 'folder',
}, true)); name: folderNameMap[externalId],
parentId: folderIdMap[parentIdMap[externalId]],
}),
);
await utils.awaitSequence(Object.keys(fileNameMap), async externalId => fileSvc.createFile({ await utils.awaitSequence(
name: fileNameMap[externalId], Object.keys(fileNameMap),
parentId: folderIdMap[parentIdMap[externalId]], async externalId => fileSvc.createFile({
text: textMap[externalId], name: fileNameMap[externalId],
properties: propertiesMap[externalId], parentId: folderIdMap[parentIdMap[externalId]],
discussions: discussionsMap[externalId], text: textMap[externalId],
comments: commentsMap[externalId], properties: propertiesMap[externalId],
}, true)); discussions: discussionsMap[externalId],
comments: commentsMap[externalId],
}, true),
);
}, },
}; };

View File

@ -120,7 +120,7 @@ const editorSvc = Object.assign(new Vue(), editorSvcDiscussions, editorSvcUtils,
/** /**
* Refresh the preview with the result of `convert()` * Refresh the preview with the result of `convert()`
*/ */
refreshPreview() { async refreshPreview() {
const sectionDescList = []; const sectionDescList = [];
let sectionPreviewElt; let sectionPreviewElt;
let sectionTocElt; let sectionTocElt;
@ -222,10 +222,10 @@ const editorSvc = Object.assign(new Vue(), editorSvcDiscussions, editorSvcUtils,
img.onerror = resolve; img.onerror = resolve;
img.src = imgElt.src; img.src = imgElt.src;
})); }));
await Promise.all(loadedPromises);
Promise.all(loadedPromises) // Debounce if sections have already been measured
// Debounce if sections have already been measured this.measureSectionDimensions(!!this.previewCtxMeasured);
.then(() => this.measureSectionDimensions(!!this.previewCtxMeasured));
}, },
/** /**

View File

@ -15,71 +15,74 @@ export default {
parentId, parentId,
}); });
}, },
deleteItem() { async deleteItem() {
const selectedNode = store.getters['explorer/selectedNode']; const selectedNode = store.getters['explorer/selectedNode'];
if (selectedNode.isNil) { if (selectedNode.isNil) {
return Promise.resolve(); return;
} }
if (selectedNode.isTrash || selectedNode.item.parentId === 'trash') { if (selectedNode.isTrash || selectedNode.item.parentId === 'trash') {
return store.dispatch('modal/trashDeletion').catch(() => { /* Cancel */ }); try {
await store.dispatch('modal/trashDeletion');
} catch (e) {
// Cancel
}
return;
} }
// See if we have a dialog to show // See if we have a confirmation dialog to show
let modalAction;
let moveToTrash = true; let moveToTrash = true;
if (selectedNode.isTemp) { try {
modalAction = 'modal/tempFolderDeletion'; if (selectedNode.isTemp) {
moveToTrash = false; await store.dispatch('modal/tempFolderDeletion', selectedNode.item);
} else if (selectedNode.item.parentId === 'temp') { moveToTrash = false;
modalAction = 'modal/tempFileDeletion'; } else if (selectedNode.item.parentId === 'temp') {
moveToTrash = false; await store.dispatch('modal/tempFileDeletion', selectedNode.item);
} else if (selectedNode.isFolder) { moveToTrash = false;
modalAction = 'modal/folderDeletion'; } else if (selectedNode.isFolder) {
await store.dispatch('modal/folderDeletion', selectedNode.item);
}
} catch (e) {
return; // cancel
} }
return (modalAction const deleteFile = (id) => {
? store.dispatch(modalAction, selectedNode.item) if (moveToTrash) {
: Promise.resolve()) store.commit('file/patchItem', {
.then(() => { id,
const deleteFile = (id) => { parentId: 'trash',
if (moveToTrash) { });
store.commit('file/patchItem', { } else {
id, fileSvc.deleteFile(id);
parentId: 'trash', }
}); };
} else {
fileSvc.deleteFile(id);
}
};
if (selectedNode === store.getters['explorer/selectedNode']) { if (selectedNode === store.getters['explorer/selectedNode']) {
const currentFileId = store.getters['file/current'].id; const currentFileId = store.getters['file/current'].id;
let doClose = selectedNode.item.id === currentFileId; let doClose = selectedNode.item.id === currentFileId;
if (selectedNode.isFolder) { if (selectedNode.isFolder) {
const recursiveDelete = (folderNode) => { const recursiveDelete = (folderNode) => {
folderNode.folders.forEach(recursiveDelete); folderNode.folders.forEach(recursiveDelete);
folderNode.files.forEach((fileNode) => { folderNode.files.forEach((fileNode) => {
doClose = doClose || fileNode.item.id === currentFileId; doClose = doClose || fileNode.item.id === currentFileId;
deleteFile(fileNode.item.id); deleteFile(fileNode.item.id);
}); });
store.commit('folder/deleteItem', folderNode.item.id); store.commit('folder/deleteItem', folderNode.item.id);
}; };
recursiveDelete(selectedNode); recursiveDelete(selectedNode);
} else { } else {
deleteFile(selectedNode.item.id); deleteFile(selectedNode.item.id);
}
if (doClose) {
// Close the current file by opening the last opened, not deleted one
store.getters['data/lastOpenedIds'].some((id) => {
const file = store.state.file.itemMap[id];
if (file.parentId === 'trash') {
return false;
} }
if (doClose) { store.commit('file/setCurrentId', id);
// Close the current file by opening the last opened, not deleted one return true;
store.getters['data/lastOpenedIds'].some((id) => { });
const file = store.state.file.itemMap[id]; }
if (file.parentId === 'trash') { }
return false;
}
store.commit('file/setCurrentId', id);
return true;
});
}
}
}, () => { /* Cancel */ });
}, },
}; };

View File

@ -42,86 +42,83 @@ export default {
/** /**
* Apply the template to the file content * Apply the template to the file content
*/ */
applyTemplate(fileId, template = { async applyTemplate(fileId, template = {
value: '{{{files.0.content.text}}}', value: '{{{files.0.content.text}}}',
helpers: '', helpers: '',
}, pdf = false) { }, pdf = false) {
const file = store.state.file.itemMap[fileId]; const file = store.state.file.itemMap[fileId];
return localDbSvc.loadItem(`${fileId}/content`) const content = await localDbSvc.loadItem(`${fileId}/content`);
.then((content) => { const properties = utils.computeProperties(content.properties);
const properties = utils.computeProperties(content.properties); const options = extensionSvc.getOptions(properties);
const options = extensionSvc.getOptions(properties); const converter = markdownConversionSvc.createConverter(options, true);
const converter = markdownConversionSvc.createConverter(options, true); const parsingCtx = markdownConversionSvc.parseSections(converter, content.text);
const parsingCtx = markdownConversionSvc.parseSections(converter, content.text); const conversionCtx = markdownConversionSvc.convert(parsingCtx);
const conversionCtx = markdownConversionSvc.convert(parsingCtx); const html = conversionCtx.htmlSectionList.map(htmlSanitizer.sanitizeHtml).join('');
const html = conversionCtx.htmlSectionList.map(htmlSanitizer.sanitizeHtml).join(''); containerElt.innerHTML = html;
containerElt.innerHTML = html; extensionSvc.sectionPreview(containerElt, options);
extensionSvc.sectionPreview(containerElt, options);
// Unwrap tables // Unwrap tables
containerElt.querySelectorAll('.table-wrapper').cl_each((wrapperElt) => { containerElt.querySelectorAll('.table-wrapper').cl_each((wrapperElt) => {
while (wrapperElt.firstChild) { while (wrapperElt.firstChild) {
wrapperElt.parentNode.insertBefore(wrapperElt.firstChild, wrapperElt.nextSibling); wrapperElt.parentNode.insertBefore(wrapperElt.firstChild, wrapperElt.nextSibling);
} }
wrapperElt.parentNode.removeChild(wrapperElt); wrapperElt.parentNode.removeChild(wrapperElt);
}); });
// Make TOC // Make TOC
const headings = containerElt.querySelectorAll('h1,h2,h3,h4,h5,h6').cl_map(headingElt => ({ const headings = containerElt.querySelectorAll('h1,h2,h3,h4,h5,h6').cl_map(headingElt => ({
title: headingElt.textContent, title: headingElt.textContent,
anchor: headingElt.id, anchor: headingElt.id,
level: parseInt(headingElt.tagName.slice(1), 10), level: parseInt(headingElt.tagName.slice(1), 10),
children: [], children: [],
})); }));
const toc = groupHeadings(headings); const toc = groupHeadings(headings);
const view = { const view = {
pdf, pdf,
files: [{ files: [{
name: file.name, name: file.name,
content: { content: {
text: content.text, text: content.text,
properties, properties,
yamlProperties: content.properties, yamlProperties: content.properties,
html: containerElt.innerHTML, html: containerElt.innerHTML,
toc, toc,
}, },
}], }],
}; };
containerElt.innerHTML = ''; containerElt.innerHTML = '';
// Run template conversion in a Worker to prevent attacks from helpers // Run template conversion in a Worker to prevent attacks from helpers
const worker = new TemplateWorker(); const worker = new TemplateWorker();
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => { const timeoutId = setTimeout(() => {
worker.terminate(); worker.terminate();
reject(new Error('Template generation timeout.')); reject(new Error('Template generation timeout.'));
}, 10000); }, 10000);
worker.addEventListener('message', (e) => { worker.addEventListener('message', (e) => {
clearTimeout(timeoutId); clearTimeout(timeoutId);
worker.terminate(); worker.terminate();
// e.data can contain unsafe data if helpers attempts to call postMessage // e.data can contain unsafe data if helpers attempts to call postMessage
const [err, result] = e.data; const [err, result] = e.data;
if (err) { if (err) {
reject(new Error(`${err}`)); reject(new Error(`${err}`));
} else { } else {
resolve(`${result}`); resolve(`${result}`);
} }
});
worker.postMessage([template.value, view, template.helpers]);
});
}); });
worker.postMessage([template.value, view, template.helpers]);
});
}, },
/** /**
* Export a file to disk. * Export a file to disk.
*/ */
exportToDisk(fileId, type, template) { async exportToDisk(fileId, type, template) {
const file = store.state.file.itemMap[fileId]; const file = store.state.file.itemMap[fileId];
return this.applyTemplate(fileId, template) const html = await this.applyTemplate(fileId, template);
.then((html) => { const blob = new Blob([html], {
const blob = new Blob([html], { type: 'text/plain;charset=utf-8',
type: 'text/plain;charset=utf-8', });
}); FileSaver.saveAs(blob, `${file.name}.${type}`);
FileSaver.saveAs(blob, `${file.name}.${type}`);
});
}, },
}; };

View File

@ -7,7 +7,7 @@ export default {
/** /**
* Create a file in the store with the specified fields. * Create a file in the store with the specified fields.
*/ */
createFile({ async createFile({
name, name,
parentId, parentId,
text, text,
@ -29,77 +29,99 @@ export default {
discussions: discussions || {}, discussions: discussions || {},
comments: comments || {}, comments: comments || {},
}; };
const nameStripped = file.name !== utils.defaultName && file.name !== name;
// Check if there is a path conflict
const workspaceUniquePaths = store.getters['workspace/hasUniquePaths']; const workspaceUniquePaths = store.getters['workspace/hasUniquePaths'];
let pathConflict;
if (workspaceUniquePaths) { // Show warning dialogs
const parentPath = store.getters.itemPaths[file.parentId] || ''; if (!background) {
const path = parentPath + file.name; // If name is being stripped
pathConflict = !!store.getters.pathItems[path]; if (file.name !== utils.defaultName && file.name !== name) {
await store.dispatch('modal/stripName', name);
}
// Check if there is already a file with that path
if (workspaceUniquePaths) {
const parentPath = store.getters.itemPaths[file.parentId] || '';
const path = parentPath + file.name;
if (store.getters.pathItems[path]) {
await store.dispatch('modal/pathConflict', name);
}
}
} }
// Show warning dialogs and then save in the store // Save file and content in the store
return Promise.resolve() store.commit('content/setItem', content);
.then(() => !background && nameStripped && store.dispatch('modal/stripName', name)) store.commit('file/setItem', file);
.then(() => !background && pathConflict && store.dispatch('modal/pathConflict', name)) if (workspaceUniquePaths) {
.then(() => { this.makePathUnique(id);
store.commit('content/setItem', content); }
store.commit('file/setItem', file);
if (workspaceUniquePaths) { // Return the new file item
this.makePathUnique(id); return store.state.file.itemMap[id];
}
return store.state.file.itemMap[id];
});
}, },
/** /**
* Make sanity checks and then create/update the folder/file in the store. * Make sanity checks and then create/update the folder/file in the store.
*/ */
async storeItem(item, background = false) { async storeItem(item) {
const id = item.id || utils.uid(); const id = item.id || utils.uid();
const sanitizedName = utils.sanitizeName(item.name); const sanitizedName = utils.sanitizeName(item.name);
if (item.type === 'folder' && forbiddenFolderNameMatcher.exec(sanitizedName)) { if (item.type === 'folder' && forbiddenFolderNameMatcher.exec(sanitizedName)) {
if (background) {
return null;
}
await store.dispatch('modal/unauthorizedName', item.name); await store.dispatch('modal/unauthorizedName', item.name);
throw new Error('Unauthorized name.'); throw new Error('Unauthorized name.');
} }
const workspaceUniquePaths = store.getters['workspace/hasUniquePaths'];
// Show warning dialogs // Show warning dialogs
if (!background) { // If name has been stripped
// If name has been stripped if (sanitizedName !== utils.defaultName && sanitizedName !== item.name) {
if (sanitizedName !== utils.defaultName && sanitizedName !== item.name) { await store.dispatch('modal/stripName', item.name);
await store.dispatch('modal/stripName', item.name); }
// Check if there is a path conflict
if (store.getters['workspace/hasUniquePaths']) {
const parentPath = store.getters.itemPaths[item.parentId] || '';
const path = parentPath + sanitizedName;
const pathItems = store.getters.pathItems[path] || [];
if (pathItems.some(itemWithSamePath => itemWithSamePath.id !== id)) {
await store.dispatch('modal/pathConflict', item.name);
} }
// Check if there is a path conflict }
if (workspaceUniquePaths) {
const parentPath = store.getters.itemPaths[item.parentId] || ''; return this.setOrPatchItem({
const path = parentPath + sanitizedName; ...item,
const pathItems = store.getters.pathItems[path] || []; id,
if (pathItems.some(itemWithSamePath => itemWithSamePath.id !== id)) { });
await store.dispatch('modal/pathConflict', item.name); },
}
/**
* Create/update the folder/file in the store and make sure its path is unique.
*/
setOrPatchItem(patch) {
const item = {
...store.getters.allItemMap[patch.id] || patch,
};
if (!item.id) {
return null;
}
if (patch.parentId !== undefined) {
item.parentId = patch.parentId || null;
}
if (patch.name) {
const sanitizedName = utils.sanitizeName(patch.name);
if (item.type !== 'folder' || !forbiddenFolderNameMatcher.exec(sanitizedName)) {
item.name = sanitizedName;
} }
} }
// Save item in the store // Save item in the store
store.commit(`${item.type}/setItem`, { store.commit(`${item.type}/setItem`, item);
id,
parentId: item.parentId || null,
name: sanitizedName,
});
// Ensure path uniqueness // Ensure path uniqueness
if (workspaceUniquePaths) { if (store.getters['workspace/hasUniquePaths']) {
this.makePathUnique(id); this.makePathUnique(item.id);
} }
return store.getters.allItemMap[id];
return store.getters.allItemMap[item.id];
}, },
/** /**

View File

@ -136,7 +136,7 @@ const localDbSvc = {
* localDb will be finished. Effectively, open a transaction, then read and apply all changes * localDb will be finished. Effectively, open a transaction, then read and apply all changes
* from the DB since the previous transaction, then write all the changes from the store. * from the DB since the previous transaction, then write all the changes from the store.
*/ */
sync() { async sync() {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
// Create the DB transaction // Create the DB transaction
this.connection.createTx((tx) => { this.connection.createTx((tx) => {
@ -275,7 +275,7 @@ const localDbSvc = {
/** /**
* Retrieve an item from the DB and put it in the store. * Retrieve an item from the DB and put it in the store.
*/ */
loadItem(id) { async loadItem(id) {
// Check if item is in the store // Check if item is in the store
const itemInStore = store.getters.allItemMap[id]; const itemInStore = store.getters.allItemMap[id];
if (itemInStore) { if (itemInStore) {
@ -307,181 +307,165 @@ const localDbSvc = {
/** /**
* Unload from the store contents that haven't been opened recently * Unload from the store contents that haven't been opened recently
*/ */
unloadContents() { async unloadContents() {
return this.sync() await this.sync();
.then(() => { // Keep only last opened files in memory
// Keep only last opened files in memory const lastOpenedFileIdSet = new Set(store.getters['data/lastOpenedIds']);
const lastOpenedFileIdSet = new Set(store.getters['data/lastOpenedIds']); Object.keys(contentTypes).forEach((type) => {
Object.keys(contentTypes).forEach((type) => { store.getters[`${type}/items`].forEach((item) => {
store.getters[`${type}/items`].forEach((item) => { const [fileId] = item.id.split('/');
const [fileId] = item.id.split('/'); if (!lastOpenedFileIdSet.has(fileId)) {
if (!lastOpenedFileIdSet.has(fileId)) { // Remove item from the store
// Remove item from the store store.commit(`${type}/deleteItem`, item.id);
store.commit(`${type}/deleteItem`, item.id); }
}
});
});
}); });
});
}, },
/** /**
* Drop the database and clean the localStorage for the specified workspaceId. * Drop the database and clean the localStorage for the specified workspaceId.
*/ */
removeWorkspace(id) { async removeWorkspace(id) {
const workspaces = { const workspaces = {
...store.getters['data/workspaces'], ...store.getters['data/workspaces'],
}; };
delete workspaces[id]; delete workspaces[id];
store.dispatch('data/setWorkspaces', workspaces); store.dispatch('data/setWorkspaces', workspaces);
this.syncLocalStorage(); this.syncLocalStorage();
return new Promise((resolve, reject) => { await new Promise((resolve, reject) => {
const dbName = getDbName(id); const dbName = getDbName(id);
const request = indexedDB.deleteDatabase(dbName); const request = indexedDB.deleteDatabase(dbName);
request.onerror = reject; request.onerror = reject;
request.onsuccess = resolve; request.onsuccess = resolve;
}) });
.then(() => { localStorage.removeItem(`${id}/lastSyncActivity`);
localStorage.removeItem(`${id}/lastSyncActivity`); localStorage.removeItem(`${id}/lastWindowFocus`);
localStorage.removeItem(`${id}/lastWindowFocus`);
});
}, },
/** /**
* Create the connection and start syncing. * Create the connection and start syncing.
*/ */
init() { async init() {
return Promise.resolve() // Reset the app if reset flag was passed
.then(() => { if (resetApp) {
// Reset the app if reset flag was passed await Promise.all(Object.keys(store.getters['data/workspaces'])
if (resetApp) { .map(workspaceId => localDbSvc.removeWorkspace(workspaceId)));
return Promise.all(Object.keys(store.getters['data/workspaces']) utils.localStorageDataIds.forEach((id) => {
.map(workspaceId => localDbSvc.removeWorkspace(workspaceId))) // Clean data stored in localStorage
.then(() => utils.localStorageDataIds.forEach((id) => { localStorage.removeItem(`data/${id}`);
// Clean data stored in localStorage });
localStorage.removeItem(`data/${id}`); window.location.reload();
})) throw new Error('reload');
.then(() => { }
window.location.reload();
throw new Error('reload');
});
}
// Create the connection // Create the connection
this.connection = new Connection(); this.connection = new Connection();
// Load the DB // Load the DB
return localDbSvc.sync(); await localDbSvc.sync();
})
.then(() => {
// If exportWorkspace parameter was provided
if (exportWorkspace) {
const backup = JSON.stringify(store.getters.allItemMap);
const blob = new Blob([backup], {
type: 'text/plain;charset=utf-8',
});
FileSaver.saveAs(blob, 'StackEdit workspace.json');
return;
}
// Save welcome file content hash if not done already // If exportWorkspace parameter was provided
const hash = utils.hash(welcomeFile); if (exportWorkspace) {
const { welcomeFileHashes } = store.getters['data/localSettings']; const backup = JSON.stringify(store.getters.allItemMap);
if (!welcomeFileHashes[hash]) { const blob = new Blob([backup], {
store.dispatch('data/patchLocalSettings', { type: 'text/plain;charset=utf-8',
welcomeFileHashes: { });
...welcomeFileHashes, FileSaver.saveAs(blob, 'StackEdit workspace.json');
[hash]: 1, return;
}, }
});
}
// If app was last opened 7 days ago and synchronization is off // Save welcome file content hash if not done already
if (!store.getters['workspace/syncToken'] && const hash = utils.hash(welcomeFile);
(store.state.workspace.lastFocus + utils.cleanTrashAfter < Date.now()) const { welcomeFileHashes } = store.getters['data/localSettings'];
) { if (!welcomeFileHashes[hash]) {
// Clean files store.dispatch('data/patchLocalSettings', {
store.getters['file/items'] welcomeFileHashes: {
.filter(file => file.parentId === 'trash') // If file is in the trash ...welcomeFileHashes,
.forEach(file => fileSvc.deleteFile(file.id)); [hash]: 1,
} },
});
}
// Enable sponsorship // If app was last opened 7 days ago and synchronization is off
if (utils.queryParams.paymentSuccess) { if (!store.getters['workspace/syncToken'] &&
window.location.hash = ''; // PaymentSuccess param is always on its own (store.state.workspace.lastFocus + utils.cleanTrashAfter < Date.now())
store.dispatch('modal/paymentSuccess') ) {
.catch(() => { /* Cancel */ }); // Clean files
const sponsorToken = store.getters['workspace/sponsorToken']; store.getters['file/items']
// Force check sponsorship after a few seconds .filter(file => file.parentId === 'trash') // If file is in the trash
const currentDate = Date.now(); .forEach(file => fileSvc.deleteFile(file.id));
if (sponsorToken && sponsorToken.expiresOn > currentDate - checkSponsorshipAfter) { }
store.dispatch('data/setGoogleToken', {
...sponsorToken, // Enable sponsorship
expiresOn: currentDate - checkSponsorshipAfter, if (utils.queryParams.paymentSuccess) {
}); window.location.hash = ''; // PaymentSuccess param is always on its own
store.dispatch('modal/paymentSuccess')
.catch(() => { /* Cancel */ });
const sponsorToken = store.getters['workspace/sponsorToken'];
// Force check sponsorship after a few seconds
const currentDate = Date.now();
if (sponsorToken && sponsorToken.expiresOn > currentDate - checkSponsorshipAfter) {
store.dispatch('data/setGoogleToken', {
...sponsorToken,
expiresOn: currentDate - checkSponsorshipAfter,
});
}
}
// Sync local DB periodically
utils.setInterval(() => localDbSvc.sync(), 1000);
// watch current file changing
store.watch(
() => store.getters['file/current'].id,
async () => {
// See if currentFile is real, ie it has an ID
const currentFile = store.getters['file/current'];
// If current file has no ID, get the most recent file
if (!currentFile.id) {
const recentFile = store.getters['file/lastOpened'];
// Set it as the current file
if (recentFile.id) {
store.commit('file/setCurrentId', recentFile.id);
} else {
// If still no ID, create a new file
const newFile = await fileSvc.createFile({
name: 'Welcome file',
text: welcomeFile,
}, true);
// Set it as the current file
store.commit('file/setCurrentId', newFile.id);
}
} else {
try {
// Load contentState from DB
await localDbSvc.loadContentState(currentFile.id);
// Load syncedContent from DB
await localDbSvc.loadSyncedContent(currentFile.id);
// Load content from DB
try {
await localDbSvc.loadItem(`${currentFile.id}/content`);
} catch (err) {
// Failure (content is not available), go back to previous file
const lastOpenedFile = store.getters['file/lastOpened'];
store.commit('file/setCurrentId', lastOpenedFile.id);
throw err;
}
// Set last opened file
store.dispatch('data/setLastOpenedId', currentFile.id);
// Cancel new discussion and open the gutter if file contains discussions
store.commit(
'discussion/setCurrentDiscussionId',
store.getters['discussion/nextDiscussionId'],
);
} catch (err) {
console.error(err); // eslint-disable-line no-console
store.dispatch('notification/error', err);
} }
} }
},
// Sync local DB periodically { immediate: true },
utils.setInterval(() => localDbSvc.sync(), 1000); );
// watch current file changing
store.watch(
() => store.getters['file/current'].id,
() => {
// See if currentFile is real, ie it has an ID
const currentFile = store.getters['file/current'];
// If current file has no ID, get the most recent file
if (!currentFile.id) {
const recentFile = store.getters['file/lastOpened'];
// Set it as the current file
if (recentFile.id) {
store.commit('file/setCurrentId', recentFile.id);
} else {
// If still no ID, create a new file
fileSvc.createFile({
name: 'Welcome file',
text: welcomeFile,
}, true)
// Set it as the current file
.then(newFile => store.commit('file/setCurrentId', newFile.id));
}
} else {
Promise.resolve()
// Load contentState from DB
.then(() => localDbSvc.loadContentState(currentFile.id))
// Load syncedContent from DB
.then(() => localDbSvc.loadSyncedContent(currentFile.id))
// Load content from DB
.then(() => localDbSvc.loadItem(`${currentFile.id}/content`))
.then(
() => {
// Set last opened file
store.dispatch('data/setLastOpenedId', currentFile.id);
// Cancel new discussion
store.commit('discussion/setCurrentDiscussionId');
// Open the gutter if file contains discussions
store.commit(
'discussion/setCurrentDiscussionId',
store.getters['discussion/nextDiscussionId'],
);
},
(err) => {
// Failure (content is not available), go back to previous file
const lastOpenedFile = store.getters['file/lastOpened'];
store.commit('file/setCurrentId', lastOpenedFile.id);
throw err;
},
)
.catch((err) => {
console.error(err); // eslint-disable-line no-console
store.dispatch('notification/error', err);
});
}
}, {
immediate: true,
},
);
});
}, },
}; };

View File

@ -7,6 +7,27 @@ const networkTimeout = 30 * 1000; // 30 sec
let isConnectionDown = false; let isConnectionDown = false;
const userInactiveAfter = 2 * 60 * 1000; // 2 minutes const userInactiveAfter = 2 * 60 * 1000; // 2 minutes
function parseHeaders(xhr) {
const pairs = xhr.getAllResponseHeaders().trim().split('\n');
const headers = {};
pairs.forEach((header) => {
const split = header.trim().split(':');
const key = split.shift().trim().toLowerCase();
const value = split.join(':').trim();
headers[key] = value;
});
return headers;
}
function isRetriable(err) {
if (err.status === 403) {
const googleReason = ((((err.body || {}).error || {}).errors || [])[0] || {}).reason;
return googleReason === 'rateLimitExceeded' || googleReason === 'userRateLimitExceeded';
}
return err.status === 429 || (err.status >= 500 && err.status < 600);
}
export default { export default {
init() { init() {
// Keep track of the last user activity // Keep track of the last user activity
@ -31,37 +52,34 @@ export default {
window.addEventListener('focus', setLastFocus); window.addEventListener('focus', setLastFocus);
// Check browser is online periodically // Check browser is online periodically
const checkOffline = () => { const checkOffline = async () => {
const isBrowserOffline = window.navigator.onLine === false; const isBrowserOffline = window.navigator.onLine === false;
if (!isBrowserOffline && if (!isBrowserOffline &&
store.state.lastOfflineCheck + networkTimeout + 5000 < Date.now() && store.state.lastOfflineCheck + networkTimeout + 5000 < Date.now() &&
this.isUserActive() this.isUserActive()
) { ) {
store.commit('updateLastOfflineCheck'); store.commit('updateLastOfflineCheck');
new Promise((resolve, reject) => { const script = document.createElement('script');
const script = document.createElement('script'); let timeout;
let timeout; try {
let clean = (cb) => { await new Promise((resolve, reject) => {
clearTimeout(timeout); script.onload = resolve;
document.head.removeChild(script); script.onerror = reject;
clean = () => {}; // Prevent from cleaning several times script.src = `https://apis.google.com/js/api.js?${Date.now()}`;
cb(); try {
}; document.head.appendChild(script); // This can fail with bad network
script.onload = () => clean(resolve); timeout = setTimeout(reject, networkTimeout);
script.onerror = () => clean(reject); } catch (e) {
script.src = `https://apis.google.com/js/api.js?${Date.now()}`; reject(e);
try { }
document.head.appendChild(script); // This can fail with bad network
timeout = setTimeout(() => clean(reject), networkTimeout);
} catch (e) {
reject(e);
}
})
.then(() => {
isConnectionDown = false;
}, () => {
isConnectionDown = true;
}); });
isConnectionDown = false;
} catch (e) {
isConnectionDown = true;
} finally {
clearTimeout(timeout);
document.head.removeChild(script);
}
} }
const offline = isBrowserOffline || isConnectionDown; const offline = isBrowserOffline || isConnectionDown;
if (store.state.offline !== offline) { if (store.state.offline !== offline) {
@ -88,7 +106,7 @@ export default {
isUserActive() { isUserActive() {
return this.lastActivity > Date.now() - userInactiveAfter && this.isWindowFocused(); return this.lastActivity > Date.now() - userInactiveAfter && this.isWindowFocused();
}, },
loadScript(url) { async loadScript(url) {
if (!scriptLoadingPromises[url]) { if (!scriptLoadingPromises[url]) {
scriptLoadingPromises[url] = new Promise((resolve, reject) => { scriptLoadingPromises[url] = new Promise((resolve, reject) => {
const script = document.createElement('script'); const script = document.createElement('script');
@ -103,7 +121,7 @@ export default {
} }
return scriptLoadingPromises[url]; return scriptLoadingPromises[url];
}, },
startOauth2(url, params = {}, silent = false) { async startOauth2(url, params = {}, silent = false) {
// Build the authorize URL // Build the authorize URL
const state = utils.uid(); const state = utils.uid();
params.state = state; params.state = state;
@ -125,69 +143,66 @@ export default {
} }
} }
return new Promise((resolve, reject) => { let checkClosedInterval;
let checkClosedInterval; let closeTimeout;
let closeTimeout; let msgHandler;
let msgHandler; try {
let clean = () => { return await new Promise((resolve, reject) => {
clearInterval(checkClosedInterval); if (silent) {
if (!silent && !wnd.closed) { iframeElt.onerror = () => {
wnd.close(); reject(new Error('Unknown error.'));
};
closeTimeout = setTimeout(() => {
isConnectionDown = true;
store.commit('setOffline', true);
store.commit('updateLastOfflineCheck');
reject(new Error('You are offline.'));
}, networkTimeout);
} else {
closeTimeout = setTimeout(() => {
reject(new Error('Timeout.'));
}, oauth2AuthorizationTimeout);
} }
if (iframeElt) {
document.body.removeChild(iframeElt);
}
clearTimeout(closeTimeout);
window.removeEventListener('message', msgHandler);
clean = () => Promise.resolve(); // Prevent from cleaning several times
return Promise.resolve();
};
if (silent) { msgHandler = (event) => {
iframeElt.onerror = () => clean() if (event.source === wnd && event.origin === utils.origin) {
.then(() => reject(new Error('Unknown error.'))); const data = utils.parseQueryParams(`${event.data}`.slice(1));
closeTimeout = setTimeout( if (data.error || data.state !== state) {
() => clean() console.error(data); // eslint-disable-line no-console
.then(() => { reject(new Error('Could not get required authorization.'));
isConnectionDown = true; } else {
store.commit('setOffline', true); resolve({
store.commit('updateLastOfflineCheck'); accessToken: data.access_token,
reject(new Error('You are offline.')); code: data.code,
}), idToken: data.id_token,
networkTimeout, expiresIn: data.expires_in,
); });
} else { }
closeTimeout = setTimeout(
() => clean()
.then(() => reject(new Error('Timeout.'))),
oauth2AuthorizationTimeout,
);
}
msgHandler = event => event.source === wnd && event.origin === utils.origin && clean()
.then(() => {
const data = utils.parseQueryParams(`${event.data}`.slice(1));
if (data.error || data.state !== state) {
console.error(data); // eslint-disable-line no-console
reject(new Error('Could not get required authorization.'));
} else {
resolve({
accessToken: data.access_token,
code: data.code,
idToken: data.id_token,
expiresIn: data.expires_in,
});
} }
}); };
window.addEventListener('message', msgHandler); window.addEventListener('message', msgHandler);
if (!silent) { if (!silent) {
checkClosedInterval = setInterval(() => wnd.closed && clean() checkClosedInterval = setInterval(() => {
.then(() => reject(new Error('Authorize window was closed.'))), 250); if (wnd.closed) {
reject(new Error('Authorize window was closed.'));
}
}, 250);
}
});
} finally {
clearInterval(checkClosedInterval);
if (!silent && !wnd.closed) {
wnd.close();
} }
}); if (iframeElt) {
document.body.removeChild(iframeElt);
}
clearTimeout(closeTimeout);
window.removeEventListener('message', msgHandler);
}
}, },
request(configParam, offlineCheck = false) { async request(configParam, offlineCheck = false) {
let retryAfter = 500; // 500 ms let retryAfter = 500; // 500 ms
const maxRetryAfter = 10 * 1000; // 10 sec const maxRetryAfter = 10 * 1000; // 10 sec
const config = Object.assign({}, configParam); const config = Object.assign({}, configParam);
@ -198,101 +213,84 @@ export default {
config.headers['Content-Type'] = 'application/json'; config.headers['Content-Type'] = 'application/json';
} }
function parseHeaders(xhr) { const attempt = async () => {
const pairs = xhr.getAllResponseHeaders().trim().split('\n'); try {
return pairs.reduce((headers, header) => { await new Promise((resolve, reject) => {
const split = header.trim().split(':');
const key = split.shift().trim().toLowerCase();
const value = split.join(':').trim();
headers[key] = value;
return headers;
}, {});
}
function isRetriable(err) {
if (err.status === 403) {
const googleReason = ((((err.body || {}).error || {}).errors || [])[0] || {}).reason;
return googleReason === 'rateLimitExceeded' || googleReason === 'userRateLimitExceeded';
}
return err.status === 429 || (err.status >= 500 && err.status < 600);
}
const attempt =
() => new Promise((resolve, reject) => {
if (offlineCheck) {
store.commit('updateLastOfflineCheck');
}
const xhr = new window.XMLHttpRequest();
xhr.withCredentials = config.withCredentials || false;
let timeoutId;
xhr.onload = () => {
if (offlineCheck) { if (offlineCheck) {
isConnectionDown = false; store.commit('updateLastOfflineCheck');
} }
clearTimeout(timeoutId); const xhr = new window.XMLHttpRequest();
const result = { xhr.withCredentials = config.withCredentials || false;
status: xhr.status, let timeoutId;
headers: parseHeaders(xhr),
body: config.blob ? xhr.response : xhr.responseText, xhr.onload = () => {
}; if (offlineCheck) {
if (!config.raw && !config.blob) { isConnectionDown = false;
try {
result.body = JSON.parse(result.body);
} catch (e) {
// ignore
} }
} clearTimeout(timeoutId);
if (result.status >= 200 && result.status < 300) { const result = {
resolve(result); status: xhr.status,
return; headers: parseHeaders(xhr),
} body: config.blob ? xhr.response : xhr.responseText,
reject(result); };
}; if (!config.raw && !config.blob) {
try {
result.body = JSON.parse(result.body);
} catch (e) {
// ignore
}
}
if (result.status >= 200 && result.status < 300) {
resolve(result);
return;
}
reject(result);
};
xhr.onerror = () => { xhr.onerror = () => {
clearTimeout(timeoutId); clearTimeout(timeoutId);
if (offlineCheck) { if (offlineCheck) {
isConnectionDown = true; isConnectionDown = true;
store.commit('setOffline', true); store.commit('setOffline', true);
reject(new Error('You are offline.')); reject(new Error('You are offline.'));
} else { } else {
reject(new Error('Network request failed.')); reject(new Error('Network request failed.'));
} }
}; };
timeoutId = setTimeout(() => { timeoutId = setTimeout(() => {
xhr.abort(); xhr.abort();
if (offlineCheck) { if (offlineCheck) {
isConnectionDown = true; isConnectionDown = true;
store.commit('setOffline', true); store.commit('setOffline', true);
reject(new Error('You are offline.')); reject(new Error('You are offline.'));
} else { } else {
reject(new Error('Network request timeout.')); reject(new Error('Network request timeout.'));
} }
}, config.timeout); }, config.timeout);
const url = utils.addQueryParams(config.url, config.params); const url = utils.addQueryParams(config.url, config.params);
xhr.open(config.method || 'GET', url); xhr.open(config.method || 'GET', url);
Object.entries(config.headers).forEach(([key, value]) => Object.entries(config.headers).forEach(([key, value]) =>
value && xhr.setRequestHeader(key, `${value}`)); value && xhr.setRequestHeader(key, `${value}`));
if (config.blob) { if (config.blob) {
xhr.responseType = 'blob'; xhr.responseType = 'blob';
}
xhr.send(config.body || null);
})
.catch((err) => {
// Try again later in case of retriable error
if (isRetriable(err) && retryAfter < maxRetryAfter) {
return new Promise((resolve) => {
setTimeout(resolve, retryAfter);
// Exponential backoff
retryAfter *= 2;
})
.then(attempt);
} }
throw err; xhr.send(config.body || null);
}); });
} catch (err) {
// Try again later in case of retriable error
if (isRetriable(err) && retryAfter < maxRetryAfter) {
await new Promise((resolve) => {
setTimeout(resolve, retryAfter);
// Exponential backoff
retryAfter *= 2;
});
attempt();
}
throw err;
}
};
return attempt(); return attempt();
}, },

View File

@ -15,24 +15,21 @@ export default new Provider({
const token = this.getToken(location); const token = this.getToken(location);
return `${location.pageId}${location.blogUrl}${token.name}`; return `${location.pageId}${location.blogUrl}${token.name}`;
}, },
publish(token, html, metadata, publishLocation) { async publish(token, html, metadata, publishLocation) {
return googleHelper.uploadBlogger( const page = await googleHelper.uploadBlogger({
token, token,
publishLocation.blogUrl, blogUrl: publishLocation.blogUrl,
publishLocation.blogId, blogId: publishLocation.blogId,
publishLocation.pageId, postId: publishLocation.pageId,
metadata.title, title: metadata.title,
html, content: html,
null, isPage: true,
null, });
null, return {
true, ...publishLocation,
) blogId: page.blog.id,
.then(page => ({ pageId: page.id,
...publishLocation, };
blogId: page.blog.id,
pageId: page.id,
}));
}, },
makeLocation(token, blogUrl, pageId) { makeLocation(token, blogUrl, pageId) {
const location = { const location = {

View File

@ -15,23 +15,21 @@ export default new Provider({
const token = this.getToken(location); const token = this.getToken(location);
return `${location.postId}${location.blogUrl}${token.name}`; return `${location.postId}${location.blogUrl}${token.name}`;
}, },
publish(token, html, metadata, publishLocation) { async publish(token, html, metadata, publishLocation) {
return googleHelper.uploadBlogger( const post = await googleHelper.uploadBlogger({
...publishLocation,
token, token,
publishLocation.blogUrl, title: metadata.title,
publishLocation.blogId, content: html,
publishLocation.postId, labels: metadata.tags,
metadata.title, isDraft: metadata.status === 'draft',
html, published: metadata.date,
metadata.tags, });
metadata.status === 'draft', return {
metadata.date, ...publishLocation,
) blogId: post.blog.id,
.then(post => ({ postId: post.id,
...publishLocation, };
blogId: post.blog.id,
postId: post.id,
}));
}, },
makeLocation(token, blogUrl, postId) { makeLocation(token, blogUrl, postId) {
const location = { const location = {

View File

@ -2,6 +2,7 @@ import providerRegistry from './providerRegistry';
import emptyContent from '../../../data/emptyContent'; import emptyContent from '../../../data/emptyContent';
import utils from '../../utils'; import utils from '../../utils';
import store from '../../../store'; import store from '../../../store';
import fileSvc from '../../fileSvc';
const dataExtractor = /<!--stackedit_data:([A-Za-z0-9+/=\s]+)-->$/; const dataExtractor = /<!--stackedit_data:([A-Za-z0-9+/=\s]+)-->$/;
@ -66,6 +67,14 @@ export default class Provider {
return utils.addItemHash(result); return utils.addItemHash(result);
} }
static getContentSyncData(fileId) {
const syncData = store.getters['data/syncDataByItemId'][`${fileId}/content`];
if (!syncData) {
throw new Error(); // No need for a proper error message.
}
return syncData;
}
/** /**
* Find and open a file with location that meets the criteria * Find and open a file with location that meets the criteria
*/ */
@ -73,13 +82,13 @@ export default class Provider {
const location = utils.search(allLocations, criteria); const location = utils.search(allLocations, criteria);
if (location) { if (location) {
// Found one, open it if it exists // Found one, open it if it exists
const file = store.state.file.itemMap[location.fileId]; const item = store.state.file.itemMap[location.fileId];
if (file) { if (item) {
store.commit('file/setCurrentId', file.id); store.commit('file/setCurrentId', item.id);
// If file is in the trash, restore it // If file is in the trash, restore it
if (file.parentId === 'trash') { if (item.parentId === 'trash') {
store.commit('file/patchItem', { fileSvc.setOrPatchItem({
...file, ...item,
parentId: null, parentId: null,
}); });
} }

View File

@ -3,13 +3,6 @@ import couchdbHelper from './helpers/couchdbHelper';
import Provider from './common/Provider'; import Provider from './common/Provider';
import utils from '../utils'; import utils from '../utils';
const getSyncData = (fileId) => {
const syncData = store.getters['data/syncDataByItemId'][`${fileId}/content`];
return syncData
? Promise.resolve(syncData)
: Promise.reject(); // No need for a proper error message.
};
let syncLastSeq; let syncLastSeq;
export default new Provider({ export default new Provider({
@ -17,7 +10,7 @@ export default new Provider({
getToken() { getToken() {
return store.getters['workspace/syncToken']; return store.getters['workspace/syncToken'];
}, },
initWorkspace() { async initWorkspace() {
const dbUrl = (utils.queryParams.dbUrl || '').replace(/\/?$/, ''); // Remove trailing / const dbUrl = (utils.queryParams.dbUrl || '').replace(/\/?$/, ''); // Remove trailing /
const workspaceParams = { const workspaceParams = {
providerId: this.id, providerId: this.id,
@ -35,85 +28,85 @@ export default new Provider({
}); });
} }
return Promise.resolve() // Create the workspace
.then(() => getWorkspace() || couchdbHelper.getDb(getToken()) let workspace = getWorkspace();
.then((db) => { if (!workspace) {
store.dispatch('data/patchWorkspaces', { // Make sure the database exists and retrieve its name
[workspaceId]: { let db;
id: workspaceId, try {
name: db.db_name, db = await couchdbHelper.getDb(getToken());
providerId: this.id, } catch (e) {
dbUrl, throw new Error(`${dbUrl} is not accessible. Make sure you have the proper permissions.`);
}, }
}); store.dispatch('data/patchWorkspaces', {
return getWorkspace(); [workspaceId]: {
}, () => { id: workspaceId,
throw new Error(`${dbUrl} is not accessible. Make sure you have the right permissions.`); name: db.db_name,
})) providerId: this.id,
.then((workspace) => { dbUrl,
// Fix the URL hash },
utils.setQueryParams(workspaceParams);
if (workspace.url !== window.location.href) {
store.dispatch('data/patchWorkspaces', {
[workspace.id]: {
...workspace,
url: window.location.href,
},
});
}
return getWorkspace();
}); });
workspace = getWorkspace();
}
// Fix the URL hash
utils.setQueryParams(workspaceParams);
if (workspace.url !== window.location.href) {
store.dispatch('data/patchWorkspaces', {
[workspace.id]: {
...workspace,
url: window.location.href,
},
});
}
return getWorkspace();
}, },
getChanges() { async getChanges() {
const syncToken = store.getters['workspace/syncToken']; const syncToken = store.getters['workspace/syncToken'];
const lastSeq = store.getters['data/localSettings'].syncLastSeq; const lastSeq = store.getters['data/localSettings'].syncLastSeq;
return couchdbHelper.getChanges(syncToken, lastSeq) const result = await couchdbHelper.getChanges(syncToken, lastSeq);
.then((result) => { const changes = result.changes.filter((change) => {
const changes = result.changes.filter((change) => { if (!change.deleted && change.doc) {
if (!change.deleted && change.doc) { change.item = change.doc.item;
change.item = change.doc.item; if (!change.item || !change.item.id || !change.item.type) {
if (!change.item || !change.item.id || !change.item.type) { return false;
return false; }
} // Build sync data
// Build sync data change.syncData = {
change.syncData = { id: change.id,
id: change.id, itemId: change.item.id,
itemId: change.item.id, type: change.item.type,
type: change.item.type, hash: change.item.hash,
hash: change.item.hash, rev: change.doc._rev, // eslint-disable-line no-underscore-dangle
rev: change.doc._rev, // eslint-disable-line no-underscore-dangle };
}; }
} change.syncDataId = change.id;
change.syncDataId = change.id; return true;
return true; });
}); syncLastSeq = result.lastSeq;
syncLastSeq = result.lastSeq; return changes;
return changes;
});
}, },
onChangesApplied() { onChangesApplied() {
store.dispatch('data/patchLocalSettings', { store.dispatch('data/patchLocalSettings', {
syncLastSeq, syncLastSeq,
}); });
}, },
saveSimpleItem(item, syncData) { async saveSimpleItem(item, syncData) {
const syncToken = store.getters['workspace/syncToken']; const syncToken = store.getters['workspace/syncToken'];
return couchdbHelper.uploadDocument( const { id, rev } = couchdbHelper.uploadDocument({
syncToken, token: syncToken,
item, item,
undefined, documentId: syncData && syncData.id,
undefined, rev: syncData && syncData.rev,
syncData && syncData.id, });
syncData && syncData.rev, return {
) // Build sync data
.then(res => ({ id,
// Build sync data itemId: item.id,
id: res.id, type: item.type,
itemId: item.id, hash: item.hash,
type: item.type, rev,
hash: item.hash, };
rev: res.rev,
}));
}, },
removeItem(syncData) { removeItem(syncData) {
const syncToken = store.getters['workspace/syncToken']; const syncToken = store.getters['workspace/syncToken'];
@ -122,65 +115,61 @@ export default new Provider({
downloadContent(token, syncLocation) { downloadContent(token, syncLocation) {
return this.downloadData(`${syncLocation.fileId}/content`); return this.downloadData(`${syncLocation.fileId}/content`);
}, },
downloadData(dataId) { async downloadData(dataId) {
const syncData = store.getters['data/syncDataByItemId'][dataId]; const syncData = store.getters['data/syncDataByItemId'][dataId];
if (!syncData) { if (!syncData) {
return Promise.resolve(); return Promise.resolve();
} }
const syncToken = store.getters['workspace/syncToken']; const syncToken = store.getters['workspace/syncToken'];
return couchdbHelper.retrieveDocumentWithAttachments(syncToken, syncData.id) const body = await couchdbHelper.retrieveDocumentWithAttachments(syncToken, syncData.id);
.then((body) => { let item;
let item; if (body.item.type === 'content') {
if (body.item.type === 'content') { item = Provider.parseContent(body.attachments.data, body.item.id);
item = Provider.parseContent(body.attachments.data, body.item.id);
} else {
item = utils.addItemHash(JSON.parse(body.attachments.data));
}
const rev = body._rev; // eslint-disable-line no-underscore-dangle
if (item.hash !== syncData.hash || rev !== syncData.rev) {
store.dispatch('data/patchSyncData', {
[syncData.id]: {
...syncData,
hash: item.hash,
rev,
},
});
}
return item;
});
},
uploadContent(token, content, syncLocation) {
return this.uploadData(content)
.then(() => syncLocation);
},
uploadData(item) {
const syncData = store.getters['data/syncDataByItemId'][item.id];
if (syncData && syncData.hash === item.hash) {
return Promise.resolve();
}
let data;
let dataType;
if (item.type === 'content') {
data = Provider.serializeContent(item);
dataType = 'text/plain';
} else { } else {
data = JSON.stringify(item); item = utils.addItemHash(JSON.parse(body.attachments.data));
dataType = 'application/json';
} }
const syncToken = store.getters['workspace/syncToken']; const rev = body._rev; // eslint-disable-line no-underscore-dangle
return couchdbHelper.uploadDocument( if (item.hash !== syncData.hash || rev !== syncData.rev) {
syncToken, store.dispatch('data/patchSyncData', {
{ [syncData.id]: {
id: item.id, ...syncData,
type: item.type, hash: item.hash,
hash: item.hash, rev,
}, },
data, });
dataType, }
syncData && syncData.id, return item;
syncData && syncData.rev, },
) async uploadContent(token, content, syncLocation) {
.then(res => store.dispatch('data/patchSyncData', { await this.uploadData(content);
return syncLocation;
},
async uploadData(item) {
const syncData = store.getters['data/syncDataByItemId'][item.id];
if (!syncData || syncData.hash !== item.hash) {
let data;
let dataType;
if (item.type === 'content') {
data = Provider.serializeContent(item);
dataType = 'text/plain';
} else {
data = JSON.stringify(item);
dataType = 'application/json';
}
const syncToken = store.getters['workspace/syncToken'];
const res = await couchdbHelper.uploadDocument({
token: syncToken,
item: {
id: item.id,
type: item.type,
hash: item.hash,
},
data,
dataType,
documentId: syncData && syncData.id,
rev: syncData && syncData.rev,
});
store.dispatch('data/patchSyncData', {
[res.id]: { [res.id]: {
// Build sync data // Build sync data
id: res.id, id: res.id,
@ -189,37 +178,34 @@ export default new Provider({
hash: item.hash, hash: item.hash,
rev: res.rev, rev: res.rev,
}, },
})); });
}
}, },
listRevisions(token, fileId) { async listRevisions(token, fileId) {
return getSyncData(fileId) const syncData = Provider.getContentSyncData(fileId);
.then(syncData => couchdbHelper.retrieveDocumentWithRevisions(token, syncData.id)) const body = await couchdbHelper.retrieveDocumentWithRevisions(token, syncData.id);
.then((body) => { const revisions = [];
const revisions = []; body._revs_info.forEach((revInfo) => { // eslint-disable-line no-underscore-dangle
body._revs_info.forEach((revInfo) => { // eslint-disable-line no-underscore-dangle if (revInfo.status === 'available') {
if (revInfo.status === 'available') { revisions.push({
revisions.push({ id: revInfo.rev,
id: revInfo.rev, sub: null,
sub: null, created: null,
created: null,
});
}
}); });
return revisions; }
}); });
return revisions;
}, },
loadRevision(token, fileId, revision) { async loadRevision(token, fileId, revision) {
return getSyncData(fileId) const syncData = Provider.getContentSyncData(fileId);
.then(syncData => couchdbHelper.retrieveDocument(token, syncData.id, revision.id)) const body = await couchdbHelper.retrieveDocument(token, syncData.id, revision.id);
.then((body) => { revision.sub = body.sub;
revision.sub = body.sub; revision.created = body.time || 1; // Has to be truthy to prevent from loading several times
revision.created = body.time || 1; // Has to be truthy to prevent from loading several times
});
}, },
getRevisionContent(token, fileId, revisionId) { async getRevisionContent(token, fileId, revisionId) {
return getSyncData(fileId) const syncData = Provider.getContentSyncData(fileId);
.then(syncData => couchdbHelper const body = await couchdbHelper
.retrieveDocumentWithAttachments(token, syncData.id, revisionId)) .retrieveDocumentWithAttachments(token, syncData.id, revisionId);
.then(body => Provider.parseContent(body.attachments.data, body.item.id)); return Provider.parseContent(body.attachments.data, body.item.id);
}, },
}); });

View File

@ -34,94 +34,88 @@ export default new Provider({
checkPath(path) { checkPath(path) {
return path && path.match(/^\/[^\\<>:"|?*]+$/); return path && path.match(/^\/[^\\<>:"|?*]+$/);
}, },
downloadContent(token, syncLocation) { async downloadContent(token, syncLocation) {
return dropboxHelper.downloadFile( const { content } = await dropboxHelper.downloadFile({
token, token,
makePathRelative(token, syncLocation.path), path: makePathRelative(token, syncLocation.path),
syncLocation.dropboxFileId, fileId: syncLocation.dropboxFileId,
) });
.then(({ content }) => Provider.parseContent(content, `${syncLocation.fileId}/content`)); return Provider.parseContent(content, `${syncLocation.fileId}/content`);
}, },
uploadContent(token, content, syncLocation) { async uploadContent(token, content, syncLocation) {
return dropboxHelper.uploadFile( const dropboxFile = await dropboxHelper.uploadFile({
token, token,
makePathRelative(token, syncLocation.path), path: makePathRelative(token, syncLocation.path),
Provider.serializeContent(content), content: Provider.serializeContent(content),
syncLocation.dropboxFileId, fileId: syncLocation.dropboxFileId,
) });
.then(dropboxFile => ({ return {
...syncLocation, ...syncLocation,
path: makePathAbsolute(token, dropboxFile.path_display), path: makePathAbsolute(token, dropboxFile.path_display),
dropboxFileId: dropboxFile.id, dropboxFileId: dropboxFile.id,
})); };
}, },
publish(token, html, metadata, publishLocation) { async publish(token, html, metadata, publishLocation) {
return dropboxHelper.uploadFile( const dropboxFile = await dropboxHelper.uploadFile({
token, token,
publishLocation.path, path: publishLocation.path,
html, content: html,
publishLocation.dropboxFileId, fileId: publishLocation.dropboxFileId,
) });
.then(dropboxFile => ({ return {
...publishLocation, ...publishLocation,
path: makePathAbsolute(token, dropboxFile.path_display), path: makePathAbsolute(token, dropboxFile.path_display),
dropboxFileId: dropboxFile.id, dropboxFileId: dropboxFile.id,
})); };
}, },
openFiles(token, paths) { async openFiles(token, paths) {
const openOneFile = () => { await utils.awaitSequence(paths, async (path) => {
const path = paths.pop(); // Check if the file exists and open it
if (!path) { if (!Provider.openFileWithLocation(store.getters['syncLocation/items'], {
return null;
}
if (Provider.openFileWithLocation(store.getters['syncLocation/items'], {
providerId: this.id, providerId: this.id,
path, path,
})) { })) {
// File exists and has just been opened. Next... // Download content from Dropbox
return openOneFile(); const syncLocation = {
} path,
// Download content from Dropbox and create the file providerId: this.id,
const syncLocation = { sub: token.sub,
path, };
providerId: this.id, let content;
sub: token.sub, try {
}; content = await this.downloadContent(token, syncLocation);
return this.downloadContent(token, syncLocation) } catch (e) {
.then((content) => {
let name = path;
const slashPos = name.lastIndexOf('/');
if (slashPos > -1 && slashPos < name.length - 1) {
name = name.slice(slashPos + 1);
}
const dotPos = name.lastIndexOf('.');
if (dotPos > 0 && slashPos < name.length) {
name = name.slice(0, dotPos);
}
return fileSvc.createFile({
name,
parentId: store.getters['file/current'].parentId,
text: content.text,
properties: content.properties,
discussions: content.discussions,
comments: content.comments,
}, true);
})
.then((item) => {
store.commit('file/setCurrentId', item.id);
store.commit('syncLocation/setItem', {
...syncLocation,
id: utils.uid(),
fileId: item.id,
});
store.dispatch('notification/info', `${store.getters['file/current'].name} was imported from Dropbox.`);
})
.catch(() => {
store.dispatch('notification/error', `Could not open file ${path}.`); store.dispatch('notification/error', `Could not open file ${path}.`);
}) return;
.then(() => openOneFile()); }
};
return Promise.resolve(openOneFile()); // Create the file
let name = path;
const slashPos = name.lastIndexOf('/');
if (slashPos > -1 && slashPos < name.length - 1) {
name = name.slice(slashPos + 1);
}
const dotPos = name.lastIndexOf('.');
if (dotPos > 0 && slashPos < name.length) {
name = name.slice(0, dotPos);
}
const item = await fileSvc.createFile({
name,
parentId: store.getters['file/current'].parentId,
text: content.text,
properties: content.properties,
discussions: content.discussions,
comments: content.comments,
}, true);
store.commit('file/setCurrentId', item.id);
store.commit('syncLocation/setItem', {
...syncLocation,
id: utils.uid(),
fileId: item.id,
});
store.dispatch('notification/info', `${store.getters['file/current'].name} was imported from Dropbox.`);
}
});
}, },
makeLocation(token, path) { makeLocation(token, path) {
return { return {

View File

@ -15,39 +15,38 @@ export default new Provider({
const token = this.getToken(location); const token = this.getToken(location);
return `${location.filename}${location.gistId}${token.name}`; return `${location.filename}${location.gistId}${token.name}`;
}, },
downloadContent(token, syncLocation) { async downloadContent(token, syncLocation) {
return githubHelper.downloadGist(token, syncLocation.gistId, syncLocation.filename) const content = await githubHelper.downloadGist({
.then(content => Provider.parseContent(content, `${syncLocation.fileId}/content`)); ...syncLocation,
token,
});
return Provider.parseContent(content, `${syncLocation.fileId}/content`);
}, },
uploadContent(token, content, syncLocation) { async uploadContent(token, content, syncLocation) {
const file = store.state.file.itemMap[syncLocation.fileId]; const file = store.state.file.itemMap[syncLocation.fileId];
const description = utils.sanitizeName(file && file.name); const description = utils.sanitizeName(file && file.name);
return githubHelper.uploadGist( const gist = await githubHelper.uploadGist({
...syncLocation,
token, token,
description, description,
syncLocation.filename, content: Provider.serializeContent(content),
Provider.serializeContent(content), });
syncLocation.isPublic, return {
syncLocation.gistId, ...syncLocation,
) gistId: gist.id,
.then(gist => ({ };
...syncLocation,
gistId: gist.id,
}));
}, },
publish(token, html, metadata, publishLocation) { async publish(token, html, metadata, publishLocation) {
return githubHelper.uploadGist( const gist = await githubHelper.uploadGist({
...publishLocation,
token, token,
metadata.title, description: metadata.title,
publishLocation.filename, content: html,
html, });
publishLocation.isPublic, return {
publishLocation.gistId, ...publishLocation,
) gistId: gist.id,
.then(gist => ({ };
...publishLocation,
gistId: gist.id,
}));
}, },
makeLocation(token, filename, isPublic, gistId) { makeLocation(token, filename, isPublic, gistId) {
return { return {

View File

@ -18,99 +18,83 @@ export default new Provider({
const token = this.getToken(location); const token = this.getToken(location);
return `${location.path}${location.owner}/${location.repo}${token.name}`; return `${location.path}${location.owner}/${location.repo}${token.name}`;
}, },
downloadContent(token, syncLocation) { async downloadContent(token, syncLocation) {
return githubHelper.downloadFile( try {
token, const { sha, content } = await githubHelper.downloadFile({
syncLocation.owner, ...syncLocation,
syncLocation.repo, token,
syncLocation.branch,
syncLocation.path,
)
.then(({ sha, content }) => {
savedSha[syncLocation.id] = sha;
return Provider.parseContent(content, `${syncLocation.fileId}/content`);
})
.catch(() => null); // Ignore error, upload is going to fail anyway
},
uploadContent(token, content, syncLocation) {
let result = Promise.resolve();
if (!savedSha[syncLocation.id]) {
result = this.downloadContent(token, syncLocation); // Get the last sha
}
return result
.then(() => {
const sha = savedSha[syncLocation.id];
delete savedSha[syncLocation.id];
return githubHelper.uploadFile(
token,
syncLocation.owner,
syncLocation.repo,
syncLocation.branch,
syncLocation.path,
Provider.serializeContent(content),
sha,
);
})
.then(() => syncLocation);
},
publish(token, html, metadata, publishLocation) {
return this.downloadContent(token, publishLocation) // Get the last sha
.then(() => {
const sha = savedSha[publishLocation.id];
delete savedSha[publishLocation.id];
return githubHelper.uploadFile(
token,
publishLocation.owner,
publishLocation.repo,
publishLocation.branch,
publishLocation.path,
html,
sha,
);
})
.then(() => publishLocation);
},
openFile(token, syncLocation) {
return Promise.resolve()
.then(() => {
if (Provider.openFileWithLocation(store.getters['syncLocation/items'], syncLocation)) {
// File exists and has just been opened. Next...
return null;
}
// Download content from GitHub and create the file
return this.downloadContent(token, syncLocation)
.then((content) => {
let name = syncLocation.path;
const slashPos = name.lastIndexOf('/');
if (slashPos > -1 && slashPos < name.length - 1) {
name = name.slice(slashPos + 1);
}
const dotPos = name.lastIndexOf('.');
if (dotPos > 0 && slashPos < name.length) {
name = name.slice(0, dotPos);
}
return fileSvc.createFile({
name,
parentId: store.getters['file/current'].parentId,
text: content.text,
properties: content.properties,
discussions: content.discussions,
comments: content.comments,
}, true);
})
.then((item) => {
store.commit('file/setCurrentId', item.id);
store.commit('syncLocation/setItem', {
...syncLocation,
id: utils.uid(),
fileId: item.id,
});
store.dispatch('notification/info', `${store.getters['file/current'].name} was imported from GitHub.`);
})
.catch(() => {
store.dispatch('notification/error', `Could not open file ${syncLocation.path}.`);
});
}); });
savedSha[syncLocation.id] = sha;
return Provider.parseContent(content, `${syncLocation.fileId}/content`);
} catch (e) {
// Ignore error, upload is going to fail anyway
return null;
}
},
async uploadContent(token, content, syncLocation) {
if (!savedSha[syncLocation.id]) {
await this.downloadContent(token, syncLocation); // Get the last sha
}
const sha = savedSha[syncLocation.id];
delete savedSha[syncLocation.id];
await githubHelper.uploadFile({
...syncLocation,
token,
content: Provider.serializeContent(content),
sha,
});
return syncLocation;
},
async publish(token, html, metadata, publishLocation) {
await this.downloadContent(token, publishLocation); // Get the last sha
const sha = savedSha[publishLocation.id];
delete savedSha[publishLocation.id];
await githubHelper.uploadFile({
...publishLocation,
token,
content: html,
sha,
});
return publishLocation;
},
async openFile(token, syncLocation) {
// Check if the file exists and open it
if (!Provider.openFileWithLocation(store.getters['syncLocation/items'], syncLocation)) {
// Download content from GitHub
let content;
try {
content = await this.downloadContent(token, syncLocation);
} catch (e) {
store.dispatch('notification/error', `Could not open file ${syncLocation.path}.`);
return;
}
// Create the file
let name = syncLocation.path;
const slashPos = name.lastIndexOf('/');
if (slashPos > -1 && slashPos < name.length - 1) {
name = name.slice(slashPos + 1);
}
const dotPos = name.lastIndexOf('.');
if (dotPos > 0 && slashPos < name.length) {
name = name.slice(0, dotPos);
}
const item = await fileSvc.createFile({
name,
parentId: store.getters['file/current'].parentId,
text: content.text,
properties: content.properties,
discussions: content.discussions,
comments: content.comments,
}, true);
store.commit('file/setCurrentId', item.id);
store.commit('syncLocation/setItem', {
...syncLocation,
id: utils.uid(),
fileId: item.id,
});
store.dispatch('notification/info', `${store.getters['file/current'].name} was imported from GitHub.`);
}
}, },
parseRepoUrl(url) { parseRepoUrl(url) {
const parsedRepo = url && url.match(/([^/:]+)\/([^/]+?)(?:\.git|\/)?$/); const parsedRepo = url && url.match(/([^/:]+)\/([^/]+?)(?:\.git|\/)?$/);

View File

@ -4,15 +4,8 @@ import Provider from './common/Provider';
import utils from '../utils'; import utils from '../utils';
import userSvc from '../userSvc'; import userSvc from '../userSvc';
const getSyncData = (fileId) => {
const syncData = store.getters['data/syncDataByItemId'][`${fileId}/content`];
return syncData
? Promise.resolve(syncData)
: Promise.reject(); // No need for a proper error message.
};
const getAbsolutePath = syncData => const getAbsolutePath = syncData =>
(store.getters['workspace/currentWorkspace'].path || '') + syncData.id; `${store.getters['workspace/currentWorkspace'].path || ''}${syncData.id}`;
const getWorkspaceWithOwner = () => { const getWorkspaceWithOwner = () => {
const workspace = store.getters['workspace/currentWorkspace']; const workspace = store.getters['workspace/currentWorkspace'];
@ -38,7 +31,7 @@ export default new Provider({
getToken() { getToken() {
return store.getters['workspace/syncToken']; return store.getters['workspace/syncToken'];
}, },
initWorkspace() { async initWorkspace() {
const [owner, repo] = (utils.queryParams.repo || '').split('/'); const [owner, repo] = (utils.queryParams.repo || '').split('/');
const { branch } = utils.queryParams; const { branch } = utils.queryParams;
const workspaceParams = { const workspaceParams = {
@ -55,409 +48,390 @@ export default new Provider({
const workspaceId = utils.makeWorkspaceId(workspaceParams); const workspaceId = utils.makeWorkspaceId(workspaceParams);
let workspace = store.getters['data/sanitizedWorkspaces'][workspaceId]; let workspace = store.getters['data/sanitizedWorkspaces'][workspaceId];
return Promise.resolve() // See if we already have a token
.then(() => { let token;
// See if we already have a token if (workspace) {
if (workspace) { // Token sub is in the workspace
// Token sub is in the workspace token = store.getters['data/githubTokens'][workspace.sub];
const token = store.getters['data/githubTokens'][workspace.sub]; }
if (token) { if (!token) {
return token; await store.dispatch('modal/open', { type: 'githubAccount' });
} token = await githubHelper.addAccount(store.getters['data/localSettings'].githubRepoFullAccess);
} }
// If no token has been found, popup an authorize window and get one
return store.dispatch('modal/open', { if (!workspace) {
type: 'githubAccount', const pathEntries = (path || '').split('/');
onResolve: () => githubHelper.addAccount(store.getters['data/localSettings'].githubRepoFullAccess), const name = pathEntries[pathEntries.length - 2] || repo; // path ends with `/`
}); workspace = {
}) ...workspaceParams,
.then((token) => { id: workspaceId,
if (!workspace) { sub: token.sub,
const pathEntries = (path || '').split('/'); name,
const name = pathEntries[pathEntries.length - 2] || repo; // path ends with `/` };
workspace = { }
...workspaceParams,
id: workspaceId, // Fix the URL hash
sub: token.sub, utils.setQueryParams(workspaceParams);
name, if (workspace.url !== window.location.href) {
}; store.dispatch('data/patchWorkspaces', {
} [workspaceId]: {
// Fix the URL hash ...workspace,
utils.setQueryParams(workspaceParams); url: window.location.href,
if (workspace.url !== window.location.href) { },
store.dispatch('data/patchWorkspaces', {
[workspaceId]: {
...workspace,
url: window.location.href,
},
});
}
return store.getters['data/sanitizedWorkspaces'][workspaceId];
}); });
}
return store.getters['data/sanitizedWorkspaces'][workspaceId];
}, },
getChanges() { async getChanges() {
const syncToken = store.getters['workspace/syncToken']; const syncToken = store.getters['workspace/syncToken'];
const { owner, repo, branch } = getWorkspaceWithOwner(); const { owner, repo, branch } = getWorkspaceWithOwner();
return githubHelper.getHeadTree(syncToken, owner, repo, branch) const tree = await githubHelper.getTree({
.then((tree) => { token: syncToken,
const workspacePath = store.getters['workspace/currentWorkspace'].path || ''; owner,
const syncDataByPath = store.getters['data/syncData']; repo,
const syncDataByItemId = store.getters['data/syncDataByItemId']; branch,
});
const workspacePath = store.getters['workspace/currentWorkspace'].path || '';
const syncDataByPath = store.getters['data/syncData'];
const syncDataByItemId = store.getters['data/syncDataByItemId'];
// Store all blobs sha // Store all blobs sha
treeShaMap = Object.create(null); treeShaMap = Object.create(null);
// Store interesting paths // Store interesting paths
treeFolderMap = Object.create(null); treeFolderMap = Object.create(null);
treeFileMap = Object.create(null); treeFileMap = Object.create(null);
treeDataMap = Object.create(null); treeDataMap = Object.create(null);
treeSyncLocationMap = Object.create(null); treeSyncLocationMap = Object.create(null);
treePublishLocationMap = Object.create(null); treePublishLocationMap = Object.create(null);
tree.filter(({ type, path }) => type === 'blob' && path.indexOf(workspacePath) === 0) tree.filter(({ type, path }) => type === 'blob' && path.indexOf(workspacePath) === 0)
.forEach((blobEntry) => { .forEach((blobEntry) => {
// Make path relative // Make path relative
const path = blobEntry.path.slice(workspacePath.length); const path = blobEntry.path.slice(workspacePath.length);
// Collect blob sha // Collect blob sha
treeShaMap[path] = blobEntry.sha; treeShaMap[path] = blobEntry.sha;
// Collect parents path // Collect parents path
let parentPath = ''; let parentPath = '';
path.split('/').slice(0, -1).forEach((folderName) => { path.split('/').slice(0, -1).forEach((folderName) => {
const folderPath = `${parentPath}${folderName}/`; const folderPath = `${parentPath}${folderName}/`;
treeFolderMap[folderPath] = parentPath; treeFolderMap[folderPath] = parentPath;
parentPath = folderPath; parentPath = folderPath;
});
// Collect file path
if (path.indexOf('.stackedit-data/') === 0) {
treeDataMap[path] = true;
} else if (endsWith(path, '.md')) {
treeFileMap[path] = parentPath;
} else if (endsWith(path, '.sync')) {
treeSyncLocationMap[path] = true;
} else if (endsWith(path, '.publish')) {
treePublishLocationMap[path] = true;
}
});
// Collect changes
const changes = [];
const pathIds = {};
const syncDataToIgnore = Object.create(null);
const getId = (path) => {
const syncData = syncDataByPath[path];
const id = syncData ? syncData.itemId : utils.uid();
pathIds[path] = id;
return id;
};
// Folder creations/updates
// Assume map entries are sorted from top to bottom
Object.entries(treeFolderMap).forEach(([path, parentPath]) => {
const id = getId(path);
const item = utils.addItemHash({
id,
type: 'folder',
name: path.slice(parentPath.length, -1),
parentId: pathIds[parentPath] || null,
});
changes.push({
syncDataId: path,
item,
syncData: {
id: path,
itemId: id,
type: item.type,
hash: item.hash,
},
});
}); });
// Collect file path
// File creations/updates if (path.indexOf('.stackedit-data/') === 0) {
Object.entries(treeFileMap).forEach(([path, parentPath]) => { treeDataMap[path] = true;
const id = getId(path); } else if (endsWith(path, '.md')) {
const item = utils.addItemHash({ treeFileMap[path] = parentPath;
id, } else if (endsWith(path, '.sync')) {
type: 'file', treeSyncLocationMap[path] = true;
name: path.slice(parentPath.length, -'.md'.length), } else if (endsWith(path, '.publish')) {
parentId: pathIds[parentPath] || null, treePublishLocationMap[path] = true;
}); }
changes.push({
syncDataId: path,
item,
syncData: {
id: path,
itemId: id,
type: item.type,
hash: item.hash,
},
});
// Content creations/updates
const contentSyncData = syncDataByItemId[`${id}/content`];
if (contentSyncData) {
syncDataToIgnore[contentSyncData.id] = true;
}
if (!contentSyncData || contentSyncData.sha !== treeShaMap[path]) {
// Use `/` as a prefix to get a unique syncData id
changes.push({
syncDataId: `/${path}`,
item: {
id: `${id}/content`,
type: 'content',
// Need a truthy value to force saving sync data
hash: 1,
},
syncData: {
id: `/${path}`,
itemId: `${id}/content`,
type: 'content',
// Need a truthy value to force downloading the content
hash: 1,
},
});
}
});
// Data creations/updates
Object.keys(treeDataMap).forEach((path) => {
try {
const [, id] = path.match(/^\.stackedit-data\/([\s\S]+)\.json$/);
pathIds[path] = id;
const syncData = syncDataByItemId[id];
if (syncData) {
syncDataToIgnore[syncData.id] = true;
}
if (!syncData || syncData.sha !== treeShaMap[path]) {
changes.push({
syncDataId: path,
item: {
id,
type: 'data',
// Need a truthy value to force saving sync data
hash: 1,
},
syncData: {
id: path,
itemId: id,
type: 'data',
// Need a truthy value to force downloading the content
hash: 1,
},
});
}
} catch (e) {
// Ignore parsing errors
}
});
// Location creations/updates
[{
type: 'syncLocation',
map: treeSyncLocationMap,
pathMatcher: /^([\s\S]+)\.([\w-]+)\.sync$/,
}, {
type: 'publishLocation',
map: treePublishLocationMap,
pathMatcher: /^([\s\S]+)\.([\w-]+)\.publish$/,
}]
.forEach(({ type, map, pathMatcher }) => Object.keys(map).forEach((path) => {
try {
const [, filePath, data] = path.match(pathMatcher);
// If there is a corresponding md file in the tree
const fileId = pathIds[`${filePath}.md`];
if (fileId) {
const id = getId(path);
const item = utils.addItemHash({
...JSON.parse(utils.decodeBase64(data)),
id,
type,
fileId,
});
changes.push({
syncDataId: path,
item,
syncData: {
id: path,
itemId: id,
type: item.type,
hash: item.hash,
},
});
}
} catch (e) {
// Ignore parsing errors
}
}));
// Deletions
Object.keys(syncDataByPath).forEach((path) => {
if (!pathIds[path] && !syncDataToIgnore[path]) {
changes.push({ syncDataId: path });
}
});
return changes;
}); });
},
saveSimpleItem(item) { // Collect changes
const path = store.getters.itemPaths[item.fileId || item.id]; const changes = [];
return Promise.resolve() const pathIds = {};
.then(() => { const syncDataToIgnore = Object.create(null);
const syncToken = store.getters['workspace/syncToken']; const getId = (path) => {
const { owner, repo, branch } = getWorkspaceWithOwner(); const syncData = syncDataByPath[path];
const syncData = { const id = syncData ? syncData.itemId : utils.uid();
itemId: item.id, pathIds[path] = id;
return id;
};
// Folder creations/updates
// Assume map entries are sorted from top to bottom
Object.entries(treeFolderMap).forEach(([path, parentPath]) => {
const id = getId(path);
const item = utils.addItemHash({
id,
type: 'folder',
name: path.slice(parentPath.length, -1),
parentId: pathIds[parentPath] || null,
});
changes.push({
syncDataId: path,
item,
syncData: {
id: path,
itemId: id,
type: item.type, type: item.type,
hash: item.hash, hash: item.hash,
}; },
});
});
if (item.type === 'file') { // File creations/updates
syncData.id = `${path}.md`; Object.entries(treeFileMap).forEach(([path, parentPath]) => {
} else if (item.type === 'folder') { const id = getId(path);
syncData.id = path; const item = utils.addItemHash({
} id,
if (syncData.id) { type: 'file',
return syncData; name: path.slice(parentPath.length, -'.md'.length),
} parentId: pathIds[parentPath] || null,
});
changes.push({
syncDataId: path,
item,
syncData: {
id: path,
itemId: id,
type: item.type,
hash: item.hash,
},
});
// locations are stored as paths, so we upload an empty file // Content creations/updates
const data = utils.encodeBase64(utils.serializeObject({ const contentSyncData = syncDataByItemId[`${id}/content`];
...item, if (contentSyncData) {
id: undefined, syncDataToIgnore[contentSyncData.id] = true;
type: undefined, }
fileId: undefined, if (!contentSyncData || contentSyncData.sha !== treeShaMap[path]) {
}), true); // Use `/` as a prefix to get a unique syncData id
const extension = item.type === 'syncLocation' ? 'sync' : 'publish'; changes.push({
syncData.id = `${path}.${data}.${extension}`; syncDataId: `/${path}`,
return githubHelper.uploadFile( item: {
syncToken, id: `${id}/content`,
owner, type: 'content',
repo, // Need a truthy value to force saving sync data
branch, hash: 1,
getAbsolutePath(syncData), },
'', syncData: {
treeShaMap[syncData.id], id: `/${path}`,
).then(() => syncData); itemId: `${id}/content`,
}); type: 'content',
}, // Need a truthy value to force downloading the content
removeItem(syncData) { hash: 1,
// Ignore content deletion
if (syncData.type === 'content') {
return Promise.resolve();
}
const syncToken = store.getters['workspace/syncToken'];
const { owner, repo, branch } = getWorkspaceWithOwner();
return githubHelper.removeFile(
syncToken,
owner,
repo,
branch,
getAbsolutePath(syncData),
treeShaMap[syncData.id],
);
},
downloadContent(token, syncLocation) {
const syncData = store.getters['data/syncDataByItemId'][syncLocation.fileId];
const contentSyncData = store.getters['data/syncDataByItemId'][`${syncLocation.fileId}/content`];
if (!syncData || !contentSyncData) {
return Promise.resolve();
}
const { owner, repo, branch } = getWorkspaceWithOwner();
return githubHelper.downloadFile(token, owner, repo, branch, getAbsolutePath(syncData))
.then(({ sha, content }) => {
const item = Provider.parseContent(content, `${syncLocation.fileId}/content`);
if (item.hash !== contentSyncData.hash) {
store.dispatch('data/patchSyncData', {
[contentSyncData.id]: {
...contentSyncData,
hash: item.hash,
sha,
},
});
}
return item;
});
},
downloadData(dataId) {
const syncData = store.getters['data/syncDataByItemId'][dataId];
if (!syncData) {
return Promise.resolve();
}
const syncToken = store.getters['workspace/syncToken'];
const { owner, repo, branch } = getWorkspaceWithOwner();
return githubHelper.downloadFile(syncToken, owner, repo, branch, getAbsolutePath(syncData))
.then(({ sha, content }) => {
const item = JSON.parse(content);
if (item.hash !== syncData.hash) {
store.dispatch('data/patchSyncData', {
[syncData.id]: {
...syncData,
hash: item.hash,
sha,
},
});
}
return item;
});
},
uploadContent(token, content, syncLocation) {
const contentSyncData = store.getters['data/syncDataByItemId'][`${syncLocation.fileId}/content`];
if (contentSyncData && contentSyncData.hash === content.hash) {
return Promise.resolve(syncLocation);
}
const syncData = store.getters['data/syncDataByItemId'][syncLocation.fileId];
const { owner, repo, branch } = getWorkspaceWithOwner();
return githubHelper.uploadFile(
token,
owner,
repo,
branch,
getAbsolutePath(syncData),
Provider.serializeContent(content),
treeShaMap[syncData.id],
)
.then((res) => {
const id = `/${syncData.id}`;
store.dispatch('data/patchSyncData', {
[id]: {
// Build sync data
id,
itemId: content.id,
type: content.type,
hash: content.hash,
sha: res.content.sha,
}, },
}); });
return syncLocation; }
}); });
// Data creations/updates
Object.keys(treeDataMap).forEach((path) => {
try {
const [, id] = path.match(/^\.stackedit-data\/([\s\S]+)\.json$/);
pathIds[path] = id;
const syncData = syncDataByItemId[id];
if (syncData) {
syncDataToIgnore[syncData.id] = true;
}
if (!syncData || syncData.sha !== treeShaMap[path]) {
changes.push({
syncDataId: path,
item: {
id,
type: 'data',
// Need a truthy value to force saving sync data
hash: 1,
},
syncData: {
id: path,
itemId: id,
type: 'data',
// Need a truthy value to force downloading the content
hash: 1,
},
});
}
} catch (e) {
// Ignore parsing errors
}
});
// Location creations/updates
[{
type: 'syncLocation',
map: treeSyncLocationMap,
pathMatcher: /^([\s\S]+)\.([\w-]+)\.sync$/,
}, {
type: 'publishLocation',
map: treePublishLocationMap,
pathMatcher: /^([\s\S]+)\.([\w-]+)\.publish$/,
}]
.forEach(({ type, map, pathMatcher }) => Object.keys(map).forEach((path) => {
try {
const [, filePath, data] = path.match(pathMatcher);
// If there is a corresponding md file in the tree
const fileId = pathIds[`${filePath}.md`];
if (fileId) {
const id = getId(path);
const item = utils.addItemHash({
...JSON.parse(utils.decodeBase64(data)),
id,
type,
fileId,
});
changes.push({
syncDataId: path,
item,
syncData: {
id: path,
itemId: id,
type: item.type,
hash: item.hash,
},
});
}
} catch (e) {
// Ignore parsing errors
}
}));
// Deletions
Object.keys(syncDataByPath).forEach((path) => {
if (!pathIds[path] && !syncDataToIgnore[path]) {
changes.push({ syncDataId: path });
}
});
return changes;
}, },
uploadData(item) { async saveSimpleItem(item) {
const oldSyncData = store.getters['data/syncDataByItemId'][item.id]; const path = store.getters.itemPaths[item.fileId || item.id];
if (oldSyncData && oldSyncData.hash === item.hash) { const syncToken = store.getters['workspace/syncToken'];
return Promise.resolve();
}
const syncData = { const syncData = {
id: `.stackedit-data/${item.id}.json`,
itemId: item.id, itemId: item.id,
type: item.type, type: item.type,
hash: item.hash, hash: item.hash,
}; };
if (item.type === 'file') {
syncData.id = `${path}.md`;
return syncData;
}
if (item.type === 'folder') {
syncData.id = path;
return syncData;
}
// locations are stored as paths, so we upload an empty file
const data = utils.encodeBase64(utils.serializeObject({
...item,
id: undefined,
type: undefined,
fileId: undefined,
}), true);
const extension = item.type === 'syncLocation' ? 'sync' : 'publish';
syncData.id = `${path}.${data}.${extension}`;
await githubHelper.uploadFile({
...getWorkspaceWithOwner(),
token: syncToken,
path: getAbsolutePath(syncData),
content: '',
sha: treeShaMap[syncData.id],
});
return syncData;
},
async removeItem(syncData) {
// Ignore content deletion
if (syncData.type !== 'content') {
const syncToken = store.getters['workspace/syncToken'];
await githubHelper.removeFile({
...getWorkspaceWithOwner(),
token: syncToken,
path: getAbsolutePath(syncData),
sha: treeShaMap[syncData.id],
});
}
},
async downloadContent(token, syncLocation) {
const syncData = store.getters['data/syncDataByItemId'][syncLocation.fileId];
const contentSyncData = store.getters['data/syncDataByItemId'][`${syncLocation.fileId}/content`];
if (!syncData || !contentSyncData) {
return null;
}
const { sha, content } = await githubHelper.downloadFile({
...getWorkspaceWithOwner(),
token,
path: getAbsolutePath(syncData),
});
const item = Provider.parseContent(content, `${syncLocation.fileId}/content`);
if (item.hash !== contentSyncData.hash) {
store.dispatch('data/patchSyncData', {
[contentSyncData.id]: {
...contentSyncData,
hash: item.hash,
sha,
},
});
}
return item;
},
async downloadData(dataId) {
const syncData = store.getters['data/syncDataByItemId'][dataId];
if (!syncData) {
return null;
}
const syncToken = store.getters['workspace/syncToken']; const syncToken = store.getters['workspace/syncToken'];
const { owner, repo, branch } = getWorkspaceWithOwner(); const { sha, content } = await githubHelper.downloadFile({
return githubHelper.uploadFile( ...getWorkspaceWithOwner(),
syncToken, token: syncToken,
owner, path: getAbsolutePath(syncData),
repo, });
branch, const item = JSON.parse(content);
getAbsolutePath(syncData), if (item.hash !== syncData.hash) {
JSON.stringify(item), store.dispatch('data/patchSyncData', {
oldSyncData && oldSyncData.sha, [syncData.id]: {
) ...syncData,
.then(res => store.dispatch('data/patchSyncData', { hash: item.hash,
sha,
},
});
}
return item;
},
async uploadContent(token, content, syncLocation) {
const contentSyncData = store.getters['data/syncDataByItemId'][`${syncLocation.fileId}/content`];
if (!contentSyncData || contentSyncData.hash !== content.hash) {
const path = `${store.getters.itemPaths[syncLocation.fileId]}.md`;
const absolutePath = `${store.getters['workspace/currentWorkspace'].path || ''}${path}`;
const id = `/${path}`;
const res = await githubHelper.uploadFile({
...getWorkspaceWithOwner(),
token,
path: absolutePath,
content: Provider.serializeContent(content),
sha: treeShaMap[id],
});
store.dispatch('data/patchSyncData', {
[id]: {
// Build sync data
id,
itemId: content.id,
type: content.type,
hash: content.hash,
sha: res.content.sha,
},
});
}
return syncLocation;
},
async uploadData(item) {
const oldSyncData = store.getters['data/syncDataByItemId'][item.id];
if (!oldSyncData || oldSyncData.hash !== item.hash) {
const syncData = {
id: `.stackedit-data/${item.id}.json`,
itemId: item.id,
type: item.type,
hash: item.hash,
};
const syncToken = store.getters['workspace/syncToken'];
const res = await githubHelper.uploadFile({
...getWorkspaceWithOwner(),
token: syncToken,
path: getAbsolutePath(syncData),
content: JSON.stringify(item),
sha: oldSyncData && oldSyncData.sha,
});
store.dispatch('data/patchSyncData', {
[syncData.id]: { [syncData.id]: {
...syncData, ...syncData,
sha: res.content.sha, sha: res.content.sha,
}, },
})); });
}
}, },
onSyncEnd() { onSyncEnd() {
// Clean up // Clean up
@ -468,34 +442,48 @@ export default new Provider({
treeSyncLocationMap = null; treeSyncLocationMap = null;
treePublishLocationMap = null; treePublishLocationMap = null;
}, },
listRevisions(token, fileId) { async listRevisions(token, fileId) {
const { owner, repo, branch } = getWorkspaceWithOwner(); const { owner, repo, branch } = getWorkspaceWithOwner();
return getSyncData(fileId) const syncData = Provider.getContentSyncData(fileId);
.then(syncData => githubHelper.getCommits(token, owner, repo, branch, syncData.id)) const entries = await githubHelper.getCommits({
.then(entries => entries.map((entry) => { token,
let user; owner,
if (entry.author && entry.author.login) { repo,
user = entry.author; sha: branch,
} else if (entry.committer && entry.committer.login) { path: syncData.id,
user = entry.committer; });
} return entries.map(({
const sub = `gh:${user.id}`; author,
userSvc.addInfo({ id: sub, name: user.login, imageUrl: user.avatar_url }); committer,
const date = (entry.commit.author && entry.commit.author.date) commit,
|| (entry.commit.committer && entry.commit.committer.date); sha,
return { }) => {
id: entry.sha, let user;
sub, if (author && author.login) {
created: date ? new Date(date).getTime() : 1, user = author;
}; } else if (committer && committer.login) {
}) user = committer;
.sort((revision1, revision2) => revision2.created - revision1.created)); }
const sub = `gh:${user.id}`;
userSvc.addInfo({ id: sub, name: user.login, imageUrl: user.avatar_url });
const date = (commit.author && commit.author.date)
|| (commit.committer && commit.committer.date);
return {
id: sha,
sub,
created: date ? new Date(date).getTime() : 1,
};
})
.sort((revision1, revision2) => revision2.created - revision1.created);
}, },
getRevisionContent(token, fileId, revisionId) { async getRevisionContent(token, fileId, revisionId) {
const { owner, repo } = getWorkspaceWithOwner(); const syncData = Provider.getContentSyncData(fileId);
return getSyncData(fileId) const { content } = await githubHelper.downloadFile({
.then(syncData => githubHelper ...getWorkspaceWithOwner(),
.downloadFile(token, owner, repo, revisionId, getAbsolutePath(syncData))) token,
.then(({ content }) => Provider.parseContent(content, `${fileId}/content`)); branch: revisionId,
path: getAbsolutePath(syncData),
});
return Provider.parseContent(content, `${fileId}/content`);
}, },
}); });

View File

@ -10,65 +10,59 @@ export default new Provider({
getToken() { getToken() {
return store.getters['workspace/syncToken']; return store.getters['workspace/syncToken'];
}, },
initWorkspace() { async initWorkspace() {
// Nothing much to do since the main workspace isn't necessarily synchronized // Nothing much to do since the main workspace isn't necessarily synchronized
return Promise.resolve() // Remove the URL hash
.then(() => { utils.setQueryParams();
// Remove the URL hash // Return the main workspace
utils.setQueryParams(); return store.getters['data/workspaces'].main;
// Return the main workspace
return store.getters['data/workspaces'].main;
});
}, },
getChanges() { async getChanges() {
const syncToken = store.getters['workspace/syncToken']; const syncToken = store.getters['workspace/syncToken'];
const startPageToken = store.getters['data/localSettings'].syncStartPageToken; const startPageToken = store.getters['data/localSettings'].syncStartPageToken;
return googleHelper.getChanges(syncToken, startPageToken, true) const result = await googleHelper.getChanges(syncToken, startPageToken, true);
.then((result) => { const changes = result.changes.filter((change) => {
const changes = result.changes.filter((change) => { if (change.file) {
if (change.file) { // Parse item from file name
// Parse item from file name try {
try { change.item = JSON.parse(change.file.name);
change.item = JSON.parse(change.file.name); } catch (e) {
} catch (e) { return false;
return false; }
} // Build sync data
// Build sync data change.syncData = {
change.syncData = { id: change.fileId,
id: change.fileId, itemId: change.item.id,
itemId: change.item.id, type: change.item.type,
type: change.item.type, hash: change.item.hash,
hash: change.item.hash, };
}; }
} change.syncDataId = change.fileId;
change.syncDataId = change.fileId; return true;
return true; });
}); syncStartPageToken = result.startPageToken;
syncStartPageToken = result.startPageToken; return changes;
return changes;
});
}, },
onChangesApplied() { onChangesApplied() {
store.dispatch('data/patchLocalSettings', { store.dispatch('data/patchLocalSettings', {
syncStartPageToken, syncStartPageToken,
}); });
}, },
saveSimpleItem(item, syncData, ifNotTooLate) { async saveSimpleItem(item, syncData, ifNotTooLate) {
const syncToken = store.getters['workspace/syncToken']; const syncToken = store.getters['workspace/syncToken'];
return googleHelper.uploadAppDataFile( const file = await googleHelper.uploadAppDataFile({
syncToken, token: syncToken,
JSON.stringify(item), name: JSON.stringify(item),
undefined, fileId: syncData && syncData.id,
syncData && syncData.id,
ifNotTooLate, ifNotTooLate,
) });
.then(file => ({ // Build sync data
// Build sync data return {
id: file.id, id: file.id,
itemId: item.id, itemId: item.id,
type: item.type, type: item.type,
hash: item.hash, hash: item.hash,
})); };
}, },
removeItem(syncData, ifNotTooLate) { removeItem(syncData, ifNotTooLate) {
const syncToken = store.getters['workspace/syncToken']; const syncToken = store.getters['workspace/syncToken'];
@ -77,48 +71,44 @@ export default new Provider({
downloadContent(token, syncLocation) { downloadContent(token, syncLocation) {
return this.downloadData(`${syncLocation.fileId}/content`); return this.downloadData(`${syncLocation.fileId}/content`);
}, },
downloadData(dataId) { async downloadData(dataId) {
const syncData = store.getters['data/syncDataByItemId'][dataId]; const syncData = store.getters['data/syncDataByItemId'][dataId];
if (!syncData) { if (!syncData) {
return Promise.resolve(); return null;
} }
const syncToken = store.getters['workspace/syncToken']; const syncToken = store.getters['workspace/syncToken'];
return googleHelper.downloadAppDataFile(syncToken, syncData.id) const data = await googleHelper.downloadAppDataFile(syncToken, syncData.id);
.then((data) => { const item = utils.addItemHash(JSON.parse(data));
const item = utils.addItemHash(JSON.parse(data)); if (item.hash !== syncData.hash) {
if (item.hash !== syncData.hash) { store.dispatch('data/patchSyncData', {
store.dispatch('data/patchSyncData', { [syncData.id]: {
[syncData.id]: { ...syncData,
...syncData, hash: item.hash,
hash: item.hash, },
},
});
}
return item;
}); });
},
uploadContent(token, content, syncLocation, ifNotTooLate) {
return this.uploadData(content, ifNotTooLate)
.then(() => syncLocation);
},
uploadData(item, ifNotTooLate) {
const syncData = store.getters['data/syncDataByItemId'][item.id];
if (syncData && syncData.hash === item.hash) {
return Promise.resolve();
} }
const syncToken = store.getters['workspace/syncToken']; return item;
return googleHelper.uploadAppDataFile( },
syncToken, async uploadContent(token, content, syncLocation, ifNotTooLate) {
JSON.stringify({ await this.uploadData(content, ifNotTooLate);
id: item.id, return syncLocation;
type: item.type, },
hash: item.hash, async uploadData(item, ifNotTooLate) {
}), const syncData = store.getters['data/syncDataByItemId'][item.id];
JSON.stringify(item), if (!syncData || syncData.hash !== item.hash) {
syncData && syncData.id, const syncToken = store.getters['workspace/syncToken'];
ifNotTooLate, const file = await googleHelper.uploadAppDataFile({
) token: syncToken,
.then(file => store.dispatch('data/patchSyncData', { name: JSON.stringify({
id: item.id,
type: item.type,
hash: item.hash,
}),
media: JSON.stringify(item),
fileId: syncData && syncData.id,
ifNotTooLate,
});
store.dispatch('data/patchSyncData', {
[file.id]: { [file.id]: {
// Build sync data // Build sync data
id: file.id, id: file.id,
@ -126,27 +116,22 @@ export default new Provider({
type: item.type, type: item.type,
hash: item.hash, hash: item.hash,
}, },
})); });
},
listRevisions(token, fileId) {
const syncData = store.getters['data/syncDataByItemId'][`${fileId}/content`];
if (!syncData) {
return Promise.reject(); // No need for a proper error message.
} }
return googleHelper.getAppDataFileRevisions(token, syncData.id)
.then(revisions => revisions.map(revision => ({
id: revision.id,
sub: revision.lastModifyingUser && `go:${revision.lastModifyingUser.permissionId}`,
created: new Date(revision.modifiedTime).getTime(),
}))
.sort((revision1, revision2) => revision2.created - revision1.created));
}, },
getRevisionContent(token, fileId, revisionId) { async listRevisions(token, fileId) {
const syncData = store.getters['data/syncDataByItemId'][`${fileId}/content`]; const syncData = Provider.getContentSyncData(fileId);
if (!syncData) { const revisions = await googleHelper.getAppDataFileRevisions(token, syncData.id);
return Promise.reject(); // No need for a proper error message. return revisions.map(revision => ({
} id: revision.id,
return googleHelper.downloadAppDataFileRevision(token, syncData.id, revisionId) sub: revision.lastModifyingUser && `go:${revision.lastModifyingUser.permissionId}`,
.then(content => JSON.parse(content)); created: new Date(revision.modifiedTime).getTime(),
}))
.sort((revision1, revision2) => revision2.created - revision1.created);
},
async getRevisionContent(token, fileId, revisionId) {
const syncData = Provider.getContentSyncData(fileId);
const content = await googleHelper.downloadAppDataFileRevision(token, syncData.id, revisionId);
return JSON.parse(content);
}, },
}); });

View File

@ -17,184 +17,167 @@ export default new Provider({
const token = this.getToken(location); const token = this.getToken(location);
return `${location.driveFileId}${token.name}`; return `${location.driveFileId}${token.name}`;
}, },
initAction() { async initAction() {
const state = googleHelper.driveState || {}; const state = googleHelper.driveState || {};
return state.userId && Promise.resolve() if (state.userId) {
.then(() => { // Try to find the token corresponding to the user ID
// Try to find the token corresponding to the user ID let token = store.getters['data/googleTokens'][state.userId];
const token = store.getters['data/googleTokens'][state.userId]; // If not found or not enough permission, popup an OAuth2 window
// If not found or not enough permission, popup an OAuth2 window if (!token || !token.isDrive) {
return token && token.isDrive ? token : store.dispatch('modal/open', { await store.dispatch('modal/open', { type: 'googleDriveAccount' });
type: 'googleDriveAccount', token = await googleHelper.addDriveAccount(
onResolve: () => googleHelper.addDriveAccount( !store.getters['data/localSettings'].googleDriveRestrictedAccess,
!store.getters['data/localSettings'].googleDriveRestrictedAccess, state.userId,
state.userId, );
), }
});
}) const openWorkspaceIfExists = (file) => {
.then((token) => { const folderId = file
const openWorkspaceIfExists = (file) => { && file.appProperties
const folderId = file && file.appProperties.folderId;
&& file.appProperties if (folderId) {
&& file.appProperties.folderId; // See if we have the corresponding workspace
if (folderId) { const workspaceParams = {
// See if we have the corresponding workspace providerId: 'googleDriveWorkspace',
const workspaceParams = { folderId,
providerId: 'googleDriveWorkspace', };
folderId, const workspaceId = utils.makeWorkspaceId(workspaceParams);
}; const workspace = store.getters['data/sanitizedWorkspaces'][workspaceId];
const workspaceId = utils.makeWorkspaceId(workspaceParams); // If we have the workspace, open it by changing the current URL
const workspace = store.getters['data/sanitizedWorkspaces'][workspaceId]; if (workspace) {
// If we have the workspace, open it by changing the current URL utils.setQueryParams(workspaceParams);
if (workspace) { }
utils.setQueryParams(workspaceParams); }
};
switch (state.action) {
case 'create':
default:
// See if folder is part of a workspace we can open
try {
const folder = await googleHelper.getFile(token, state.folderId);
folder.appProperties = folder.appProperties || {};
googleHelper.driveActionFolder = folder;
openWorkspaceIfExists(folder);
} catch (err) {
if (!err || err.status !== 404) {
throw err;
} }
// We received an HTTP 404 meaning we have no permission to read the folder
googleHelper.driveActionFolder = { id: state.folderId };
} }
}; break;
switch (state.action) { case 'open': {
case 'create': await utils.awaitSequence(state.ids || [], async (id) => {
default: const file = await googleHelper.getFile(token, id);
// See if folder is part of a workspace we can open file.appProperties = file.appProperties || {};
return googleHelper.getFile(token, state.folderId) googleHelper.driveActionFiles.push(file);
.then((folder) => { });
folder.appProperties = folder.appProperties || {};
googleHelper.driveActionFolder = folder;
openWorkspaceIfExists(folder);
}, (err) => {
if (!err || err.status !== 404) {
throw err;
}
// We received an HTTP 404 meaning we have no permission to read the folder
googleHelper.driveActionFolder = { id: state.folderId };
});
case 'open': { // Check if first file is part of a workspace
const getOneFile = (ids = state.ids || []) => { openWorkspaceIfExists(googleHelper.driveActionFiles[0]);
const id = ids.shift();
return id && googleHelper.getFile(token, id)
.then((file) => {
file.appProperties = file.appProperties || {};
googleHelper.driveActionFiles.push(file);
return getOneFile(ids);
});
};
return getOneFile()
// Check if first file is part of a workspace
.then(() => openWorkspaceIfExists(googleHelper.driveActionFiles[0]));
}
} }
}); }
}
}, },
performAction() { async performAction() {
return Promise.resolve() const state = googleHelper.driveState || {};
.then(() => { const token = store.getters['data/googleTokens'][state.userId];
const state = googleHelper.driveState || {}; switch (token && state.action) {
const token = store.getters['data/googleTokens'][state.userId]; case 'create': {
switch (token && state.action) { const file = await fileSvc.createFile({}, true);
case 'create': store.commit('file/setCurrentId', file.id);
return fileSvc.createFile({}, true) // Return a new syncLocation
.then((file) => { return this.makeLocation(token, null, googleHelper.driveActionFolder.id);
store.commit('file/setCurrentId', file.id); }
// Return a new syncLocation case 'open':
return this.makeLocation(token, null, googleHelper.driveActionFolder.id); store.dispatch(
}); 'queue/enqueue',
case 'open': () => this.openFiles(token, googleHelper.driveActionFiles),
return store.dispatch( );
'queue/enqueue', return null;
() => this.openFiles(token, googleHelper.driveActionFiles), default:
); return null;
default: }
return null;
}
});
}, },
downloadContent(token, syncLocation) { async downloadContent(token, syncLocation) {
return googleHelper.downloadFile(token, syncLocation.driveFileId) const content = await googleHelper.downloadFile(token, syncLocation.driveFileId);
.then(content => Provider.parseContent(content, `${syncLocation.fileId}/content`)); return Provider.parseContent(content, `${syncLocation.fileId}/content`);
}, },
uploadContent(token, content, syncLocation, ifNotTooLate) { async uploadContent(token, content, syncLocation, ifNotTooLate) {
const file = store.state.file.itemMap[syncLocation.fileId]; const file = store.state.file.itemMap[syncLocation.fileId];
const name = utils.sanitizeName(file && file.name); const name = utils.sanitizeName(file && file.name);
const parents = []; const parents = [];
if (syncLocation.driveParentId) { if (syncLocation.driveParentId) {
parents.push(syncLocation.driveParentId); parents.push(syncLocation.driveParentId);
} }
return googleHelper.uploadFile( const driveFile = await googleHelper.uploadFile({
token, token,
name, name,
parents, parents,
undefined, media: Provider.serializeContent(content),
Provider.serializeContent(content), fileId: syncLocation.driveFileId,
undefined,
syncLocation.driveFileId,
undefined,
ifNotTooLate, ifNotTooLate,
) });
.then(driveFile => ({ return {
...syncLocation, ...syncLocation,
driveFileId: driveFile.id, driveFileId: driveFile.id,
})); };
}, },
publish(token, html, metadata, publishLocation) { async publish(token, html, metadata, publishLocation) {
return googleHelper.uploadFile( const driveFile = await googleHelper.uploadFile({
token, token,
metadata.title, name: metadata.title,
[], parents: [],
undefined, media: html,
html, mediaType: publishLocation.templateId ? 'text/html' : undefined,
publishLocation.templateId ? 'text/html' : undefined, fileId: publishLocation.driveFileId,
publishLocation.driveFileId, });
) return {
.then(driveFile => ({ ...publishLocation,
...publishLocation, driveFileId: driveFile.id,
driveFileId: driveFile.id, };
}));
}, },
openFiles(token, driveFiles) { async openFiles(token, driveFiles) {
const openOneFile = () => { return utils.awaitSequence(driveFiles, async (driveFile) => {
const driveFile = driveFiles.shift(); // Check if the file exists and open it
if (!driveFile) { if (!Provider.openFileWithLocation(store.getters['syncLocation/items'], {
return null;
}
if (Provider.openFileWithLocation(store.getters['syncLocation/items'], {
providerId: this.id, providerId: this.id,
driveFileId: driveFile.id, driveFileId: driveFile.id,
})) { })) {
// File exists and has just been opened. Next... // Download content from Google Drive
return openOneFile(); const syncLocation = {
} driveFileId: driveFile.id,
// Download content from Google Drive and create the file providerId: this.id,
const syncLocation = { sub: token.sub,
driveFileId: driveFile.id, };
providerId: this.id, let content;
sub: token.sub, try {
}; content = await this.downloadContent(token, syncLocation);
return this.downloadContent(token, syncLocation) } catch (e) {
.then(content => fileSvc.createFile({ store.dispatch('notification/error', `Could not open file ${driveFile.id}.`);
return;
}
// Create the file
const item = await fileSvc.createFile({
name: driveFile.name, name: driveFile.name,
parentId: store.getters['file/current'].parentId, parentId: store.getters['file/current'].parentId,
text: content.text, text: content.text,
properties: content.properties, properties: content.properties,
discussions: content.discussions, discussions: content.discussions,
comments: content.comments, comments: content.comments,
}, true)) }, true);
.then((item) => { store.commit('file/setCurrentId', item.id);
store.commit('file/setCurrentId', item.id); store.commit('syncLocation/setItem', {
store.commit('syncLocation/setItem', { ...syncLocation,
...syncLocation, id: utils.uid(),
id: utils.uid(), fileId: item.id,
fileId: item.id, });
}); store.dispatch('notification/info', `${store.getters['file/current'].name} was imported from Google Drive.`);
store.dispatch('notification/info', `${store.getters['file/current'].name} was imported from Google Drive.`); }
}) });
.catch(() => {
store.dispatch('notification/error', `Could not open file ${driveFile.id}.`);
})
.then(() => openOneFile());
};
return Promise.resolve(openOneFile());
}, },
makeLocation(token, fileId, folderId) { makeLocation(token, fileId, folderId) {
const location = { const location = {

View File

@ -4,13 +4,6 @@ import Provider from './common/Provider';
import utils from '../utils'; import utils from '../utils';
import fileSvc from '../fileSvc'; import fileSvc from '../fileSvc';
const getSyncData = (fileId) => {
const syncData = store.getters['data/syncDataByItemId'][`${fileId}/content`];
return syncData
? Promise.resolve(syncData)
: Promise.reject(); // No need for a proper error message.
};
let fileIdToOpen; let fileIdToOpen;
let syncStartPageToken; let syncStartPageToken;
@ -19,7 +12,7 @@ export default new Provider({
getToken() { getToken() {
return store.getters['workspace/syncToken']; return store.getters['workspace/syncToken'];
}, },
initWorkspace() { async initWorkspace() {
const makeWorkspaceParams = folderId => ({ const makeWorkspaceParams = folderId => ({
providerId: this.id, providerId: this.id,
folderId, folderId,
@ -31,489 +24,437 @@ export default new Provider({
const getWorkspace = folderId => const getWorkspace = folderId =>
store.getters['data/sanitizedWorkspaces'][makeWorkspaceId(folderId)]; store.getters['data/sanitizedWorkspaces'][makeWorkspaceId(folderId)];
const initFolder = (token, folder) => Promise.resolve({ const initFolder = async (token, folder) => {
folderId: folder.id, const appProperties = {
dataFolderId: folder.appProperties.dataFolderId, folderId: folder.id,
trashFolderId: folder.appProperties.trashFolderId, dataFolderId: folder.appProperties.dataFolderId,
}) trashFolderId: folder.appProperties.trashFolderId,
.then((properties) => { };
// Make sure data folder exists
if (properties.dataFolderId) {
return properties;
}
return googleHelper.uploadFile(
token,
'.stackedit-data',
[folder.id],
{ folderId: folder.id },
undefined,
googleHelper.folderMimeType,
)
.then(dataFolder => ({
...properties,
dataFolderId: dataFolder.id,
}));
})
.then((properties) => {
// Make sure trash folder exists
if (properties.trashFolderId) {
return properties;
}
return googleHelper.uploadFile(
token,
'.stackedit-trash',
[folder.id],
{ folderId: folder.id },
undefined,
googleHelper.folderMimeType,
)
.then(trashFolder => ({
...properties,
trashFolderId: trashFolder.id,
}));
})
.then((properties) => {
// Update workspace if some properties are missing
if (properties.folderId === folder.appProperties.folderId
&& properties.dataFolderId === folder.appProperties.dataFolderId
&& properties.trashFolderId === folder.appProperties.trashFolderId
) {
return properties;
}
return googleHelper.uploadFile(
token,
undefined,
undefined,
properties,
undefined,
googleHelper.folderMimeType,
folder.id,
)
.then(() => properties);
})
.then((properties) => {
// Update workspace in the store
const workspaceId = makeWorkspaceId(folder.id);
store.dispatch('data/patchWorkspaces', {
[workspaceId]: {
id: workspaceId,
sub: token.sub,
name: folder.name,
providerId: this.id,
url: window.location.href,
folderId: folder.id,
teamDriveId: folder.teamDriveId,
dataFolderId: properties.dataFolderId,
trashFolderId: properties.trashFolderId,
},
});
// Return the workspace // Make sure data folder exists
return store.getters['data/sanitizedWorkspaces'][workspaceId]; if (!appProperties.dataFolderId) {
}); appProperties.dataFolderId = (await googleHelper.uploadFile({
return Promise.resolve()
.then(() => {
const workspace = getWorkspace(utils.queryParams.folderId);
// See if we already have a token
const googleTokens = store.getters['data/googleTokens'];
// Token sub is in the workspace or in the url if workspace is about to be created
const token = workspace ? googleTokens[workspace.sub] : googleTokens[utils.queryParams.sub];
if (token && token.isDrive && token.driveFullAccess) {
return token;
}
// If no token has been found, popup an authorize window and get one
return store.dispatch('modal/workspaceGoogleRedirection', {
onResolve: () => googleHelper.addDriveAccount(true, utils.queryParams.sub),
});
})
.then(token => Promise.resolve()
// If no folderId is provided, create one
.then(() => utils.queryParams.folderId || googleHelper.uploadFile(
token, token,
'StackEdit workspace', name: '.stackedit-data',
[], parents: [folder.id],
undefined, appProperties: { folderId: folder.id },
undefined, mediaType: googleHelper.folderMimeType,
googleHelper.folderMimeType, })).id;
) }
.then(folder => initFolder(token, {
...folder, // Make sure trash folder exists
appProperties: {}, if (!appProperties.trashFolderId) {
}) appProperties.trashFolderId = (await googleHelper.uploadFile({
.then(() => folder.id))) token,
// If workspace does not exist, initialize one name: '.stackedit-trash',
.then(folderId => getWorkspace(folderId) || googleHelper.getFile(token, folderId) parents: [folder.id],
.then((folder) => { appProperties: { folderId: folder.id },
folder.appProperties = folder.appProperties || {}; mediaType: googleHelper.folderMimeType,
const folderIdProperty = folder.appProperties.folderId; })).id;
if (folderIdProperty && folderIdProperty !== folderId) { }
throw new Error(`Folder ${folderId} is part of another workspace.`);
} // Update workspace if some properties are missing
return initFolder(token, folder); if (appProperties.folderId !== folder.appProperties.folderId
}, () => { || appProperties.dataFolderId !== folder.appProperties.dataFolderId
throw new Error(`Folder ${folderId} is not accessible. Make sure you have the right permissions.`); || appProperties.trashFolderId !== folder.appProperties.trashFolderId
})) ) {
.then((workspace) => { await googleHelper.uploadFile({
// Fix the URL hash token,
utils.setQueryParams(makeWorkspaceParams(workspace.folderId)); appProperties,
if (workspace.url !== window.location.href) { mediaType: googleHelper.folderMimeType,
store.dispatch('data/patchWorkspaces', { fileId: folder.id,
[workspace.id]: { });
...workspace, }
url: window.location.href,
}, // Update workspace in the store
}); const workspaceId = makeWorkspaceId(folder.id);
} store.dispatch('data/patchWorkspaces', {
return store.getters['data/sanitizedWorkspaces'][workspace.id]; [workspaceId]: {
})); id: workspaceId,
}, sub: token.sub,
performAction() { name: folder.name,
return Promise.resolve() providerId: this.id,
.then(() => { url: window.location.href,
const state = googleHelper.driveState || {}; folderId: folder.id,
const token = this.getToken(); teamDriveId: folder.teamDriveId,
switch (token && state.action) { dataFolderId: appProperties.dataFolderId,
case 'create': trashFolderId: appProperties.trashFolderId,
return Promise.resolve() },
.then(() => {
const driveFolder = googleHelper.driveActionFolder;
let syncData = store.getters['data/syncData'][driveFolder.id];
if (!syncData && driveFolder.appProperties.id) {
// Create folder if not already synced
store.commit('folder/setItem', {
id: driveFolder.appProperties.id,
name: driveFolder.name,
});
const item = store.state.folder.itemMap[driveFolder.appProperties.id];
syncData = {
id: driveFolder.id,
itemId: item.id,
type: item.type,
hash: item.hash,
};
store.dispatch('data/patchSyncData', {
[syncData.id]: syncData,
});
}
return fileSvc.createFile({
parentId: syncData && syncData.itemId,
}, true)
.then((file) => {
store.commit('file/setCurrentId', file.id);
// File will be created on next workspace sync
});
});
case 'open':
return Promise.resolve()
.then(() => {
// open first file only
const firstFile = googleHelper.driveActionFiles[0];
const syncData = store.getters['data/syncData'][firstFile.id];
if (!syncData) {
fileIdToOpen = firstFile.id;
} else {
store.commit('file/setCurrentId', syncData.itemId);
}
});
default:
return null;
}
}); });
};
// Token sub is in the workspace or in the url if workspace is about to be created
const { sub } = getWorkspace(utils.queryParams.folderId) || utils.queryParams;
// See if we already have a token
let token = store.getters['data/googleTokens'][sub];
// If no token has been found, popup an authorize window and get one
if (!token || !token.isDrive || !token.driveFullAccess) {
await store.dispatch('modal/workspaceGoogleRedirection');
token = await googleHelper.addDriveAccount(true, utils.queryParams.sub);
}
let { folderId } = utils.queryParams;
// If no folderId is provided, create one
if (!folderId) {
const folder = await googleHelper.uploadFile({
token,
name: 'StackEdit workspace',
parents: [],
mediaType: googleHelper.folderMimeType,
});
await initFolder(token, {
...folder,
appProperties: {},
});
folderId = folder.id;
}
// Init workspace
let workspace = getWorkspace(folderId);
if (!workspace) {
let folder;
try {
folder = googleHelper.getFile(token, folderId);
} catch (err) {
throw new Error(`Folder ${folderId} is not accessible. Make sure you have the right permissions.`);
}
folder.appProperties = folder.appProperties || {};
const folderIdProperty = folder.appProperties.folderId;
if (folderIdProperty && folderIdProperty !== folderId) {
throw new Error(`Folder ${folderId} is part of another workspace.`);
}
await initFolder(token, folder);
workspace = getWorkspace(folderId);
}
// Fix the URL hash
utils.setQueryParams(makeWorkspaceParams(workspace.folderId));
if (workspace.url !== window.location.href) {
store.dispatch('data/patchWorkspaces', {
[workspace.id]: {
...workspace,
url: window.location.href,
},
});
}
return store.getters['data/sanitizedWorkspaces'][workspace.id];
}, },
getChanges() { async performAction() {
const state = googleHelper.driveState || {};
const token = this.getToken();
switch (token && state.action) {
case 'create': {
const driveFolder = googleHelper.driveActionFolder;
let syncData = store.getters['data/syncData'][driveFolder.id];
if (!syncData && driveFolder.appProperties.id) {
// Create folder if not already synced
store.commit('folder/setItem', {
id: driveFolder.appProperties.id,
name: driveFolder.name,
});
const item = store.state.folder.itemMap[driveFolder.appProperties.id];
syncData = {
id: driveFolder.id,
itemId: item.id,
type: item.type,
hash: item.hash,
};
store.dispatch('data/patchSyncData', {
[syncData.id]: syncData,
});
}
const file = await fileSvc.createFile({
parentId: syncData && syncData.itemId,
}, true);
store.commit('file/setCurrentId', file.id);
// File will be created on next workspace sync
break;
}
case 'open': {
// open first file only
const firstFile = googleHelper.driveActionFiles[0];
const syncData = store.getters['data/syncData'][firstFile.id];
if (!syncData) {
fileIdToOpen = firstFile.id;
} else {
store.commit('file/setCurrentId', syncData.itemId);
}
break;
}
default:
}
},
async getChanges() {
const workspace = store.getters['workspace/currentWorkspace']; const workspace = store.getters['workspace/currentWorkspace'];
const syncToken = store.getters['workspace/syncToken']; const syncToken = store.getters['workspace/syncToken'];
const startPageToken = store.getters['data/localSettings'].syncStartPageToken; const lastStartPageToken = store.getters['data/localSettings'].syncStartPageToken;
return googleHelper.getChanges(syncToken, startPageToken, false, workspace.teamDriveId) const { changes, startPageToken } = await googleHelper
.then((result) => { .getChanges(syncToken, lastStartPageToken, false, workspace.teamDriveId);
// Collect possible parent IDs
const parentIds = {};
Object.entries(store.getters['data/syncDataByItemId']).forEach(([id, syncData]) => {
parentIds[syncData.id] = id;
});
result.changes.forEach((change) => {
const { id } = (change.file || {}).appProperties || {};
if (id) {
parentIds[change.fileId] = id;
}
});
// Collect changes // Collect possible parent IDs
const changes = []; const parentIds = {};
result.changes.forEach((change) => { Object.entries(store.getters['data/syncDataByItemId']).forEach(([id, syncData]) => {
// Ignore changes on StackEdit own folders parentIds[syncData.id] = id;
if (change.fileId === workspace.folderId });
|| change.fileId === workspace.dataFolderId changes.forEach((change) => {
|| change.fileId === workspace.trashFolderId const { id } = (change.file || {}).appProperties || {};
) { if (id) {
parentIds[change.fileId] = id;
}
});
// Collect changes
const result = [];
changes.forEach((change) => {
// Ignore changes on StackEdit own folders
if (change.fileId === workspace.folderId
|| change.fileId === workspace.dataFolderId
|| change.fileId === workspace.trashFolderId
) {
return;
}
let contentChange;
if (change.file) {
// Ignore changes in files that are not in the workspace
const { appProperties } = change.file;
if (!appProperties || appProperties.folderId !== workspace.folderId
) {
return;
}
// If change is on a data item
if (change.file.parents[0] === workspace.dataFolderId) {
// Data item has a JSON filename
try {
change.item = JSON.parse(change.file.name);
} catch (e) {
return; return;
} }
} else {
// Change on a file or folder
const type = change.file.mimeType === googleHelper.folderMimeType
? 'folder'
: 'file';
const item = {
id: appProperties.id,
type,
name: change.file.name,
parentId: null,
};
let contentChange; // Fill parentId
if (change.file) { if (change.file.parents.some(parentId => parentId === workspace.trashFolderId)) {
// Ignore changes in files that are not in the workspace item.parentId = 'trash';
const { appProperties } = change.file;
if (!appProperties || appProperties.folderId !== workspace.folderId
) {
return;
}
// If change is on a data item
if (change.file.parents[0] === workspace.dataFolderId) {
// Data item has a JSON filename
try {
change.item = JSON.parse(change.file.name);
} catch (e) {
return;
}
} else {
// Change on a file or folder
const type = change.file.mimeType === googleHelper.folderMimeType
? 'folder'
: 'file';
const item = {
id: appProperties.id,
type,
name: change.file.name,
parentId: null,
};
// Fill parentId
if (change.file.parents.some(parentId => parentId === workspace.trashFolderId)) {
item.parentId = 'trash';
} else {
change.file.parents.some((parentId) => {
if (!parentIds[parentId]) {
return false;
}
item.parentId = parentIds[parentId];
return true;
});
}
change.item = utils.addItemHash(item);
if (type === 'file') {
// create a fake change as a file content change
contentChange = {
item: {
id: `${appProperties.id}/content`,
type: 'content',
// Need a truthy value to force saving sync data
hash: 1,
},
syncData: {
id: `${change.fileId}/content`,
itemId: `${appProperties.id}/content`,
type: 'content',
// Need a truthy value to force downloading the content
hash: 1,
},
syncDataId: `${change.fileId}/content`,
};
}
}
// Build sync data
change.syncData = {
id: change.fileId,
parentIds: change.file.parents,
itemId: change.item.id,
type: change.item.type,
hash: change.item.hash,
};
} else { } else {
// Item was removed change.file.parents.some((parentId) => {
const syncData = store.getters['data/syncData'][change.fileId]; if (!parentIds[parentId]) {
if (syncData && syncData.type === 'file') { return false;
// create a fake change as a file content change }
contentChange = { item.parentId = parentIds[parentId];
syncDataId: `${change.fileId}/content`, return true;
}; });
}
} }
change.item = utils.addItemHash(item);
// Push change if (type === 'file') {
change.syncDataId = change.fileId; // create a fake change as a file content change
changes.push(change); contentChange = {
if (contentChange) { item: {
changes.push(contentChange); id: `${appProperties.id}/content`,
type: 'content',
// Need a truthy value to force saving sync data
hash: 1,
},
syncData: {
id: `${change.fileId}/content`,
itemId: `${appProperties.id}/content`,
type: 'content',
// Need a truthy value to force downloading the content
hash: 1,
},
syncDataId: `${change.fileId}/content`,
};
} }
}); }
syncStartPageToken = result.startPageToken;
return changes; // Build sync data
}); change.syncData = {
id: change.fileId,
parentIds: change.file.parents,
itemId: change.item.id,
type: change.item.type,
hash: change.item.hash,
};
} else {
// Item was removed
const syncData = store.getters['data/syncData'][change.fileId];
if (syncData && syncData.type === 'file') {
// create a fake change as a file content change
contentChange = {
syncDataId: `${change.fileId}/content`,
};
}
}
// Push change
change.syncDataId = change.fileId;
result.push(change);
if (contentChange) {
result.push(contentChange);
}
});
syncStartPageToken = startPageToken;
return result;
}, },
onChangesApplied() { onChangesApplied() {
store.dispatch('data/patchLocalSettings', { store.dispatch('data/patchLocalSettings', {
syncStartPageToken, syncStartPageToken,
}); });
}, },
saveSimpleItem(item, syncData, ifNotTooLate) { async saveSimpleItem(item, syncData, ifNotTooLate) {
return Promise.resolve() const workspace = store.getters['workspace/currentWorkspace'];
.then(() => {
const workspace = store.getters['workspace/currentWorkspace'];
const syncToken = store.getters['workspace/syncToken'];
if (item.type !== 'file' && item.type !== 'folder') {
return googleHelper.uploadFile(
syncToken,
JSON.stringify(item),
[workspace.dataFolderId],
{
folderId: workspace.folderId,
},
undefined,
undefined,
syncData && syncData.id,
syncData && syncData.parentIds,
ifNotTooLate,
);
}
// For type `file` or `folder`
const parentSyncData = store.getters['data/syncDataByItemId'][item.parentId];
let parentId;
if (item.parentId === 'trash') {
parentId = workspace.trashFolderId;
} else if (parentSyncData) {
parentId = parentSyncData.id;
} else {
parentId = workspace.folderId;
}
return googleHelper.uploadFile(
syncToken,
item.name,
[parentId],
{
id: item.id,
folderId: workspace.folderId,
},
undefined,
item.type === 'folder' ? googleHelper.folderMimeType : undefined,
syncData && syncData.id,
syncData && syncData.parentIds,
ifNotTooLate,
);
})
.then(file => ({
// Build sync data
id: file.id,
itemId: item.id,
type: item.type,
hash: item.hash,
}));
},
removeItem(syncData, ifNotTooLate) {
// Ignore content deletion
if (syncData.type === 'content') {
return Promise.resolve();
}
const syncToken = store.getters['workspace/syncToken']; const syncToken = store.getters['workspace/syncToken'];
return googleHelper.removeFile(syncToken, syncData.id, ifNotTooLate); let file;
if (item.type !== 'file' && item.type !== 'folder') {
// For sync/publish locations, store item as filename
file = await googleHelper.uploadFile({
token: syncToken,
name: JSON.stringify(item),
parents: [workspace.dataFolderId],
appProperties: {
folderId: workspace.folderId,
},
fileId: syncData && syncData.id,
oldParents: syncData && syncData.parentIds,
ifNotTooLate,
});
} else {
// For type `file` or `folder`
const parentSyncData = store.getters['data/syncDataByItemId'][item.parentId];
let parentId;
if (item.parentId === 'trash') {
parentId = workspace.trashFolderId;
} else if (parentSyncData) {
parentId = parentSyncData.id;
} else {
parentId = workspace.folderId;
}
file = await googleHelper.uploadFile({
token: syncToken,
name: item.name,
parents: [parentId],
appProperties: {
id: item.id,
folderId: workspace.folderId,
},
mediaType: item.type === 'folder' ? googleHelper.folderMimeType : undefined,
fileId: syncData && syncData.id,
oldParents: syncData && syncData.parentIds,
ifNotTooLate,
});
}
// Build sync data
return {
id: file.id,
itemId: item.id,
type: item.type,
hash: item.hash,
};
}, },
downloadContent(token, syncLocation) { async removeItem(syncData, ifNotTooLate) {
// Ignore content deletion
if (syncData.type !== 'content') {
const syncToken = store.getters['workspace/syncToken'];
await googleHelper.removeFile(syncToken, syncData.id, ifNotTooLate);
}
},
async downloadContent(token, syncLocation) {
const syncData = store.getters['data/syncDataByItemId'][syncLocation.fileId]; const syncData = store.getters['data/syncDataByItemId'][syncLocation.fileId];
const contentSyncData = store.getters['data/syncDataByItemId'][`${syncLocation.fileId}/content`]; const contentSyncData = store.getters['data/syncDataByItemId'][`${syncLocation.fileId}/content`];
if (!syncData || !contentSyncData) { if (!syncData || !contentSyncData) {
return Promise.resolve(); return null;
} }
return googleHelper.downloadFile(token, syncData.id) const content = await googleHelper.downloadFile(token, syncData.id);
.then((content) => { const item = Provider.parseContent(content, `${syncLocation.fileId}/content`);
const item = Provider.parseContent(content, `${syncLocation.fileId}/content`); if (item.hash !== contentSyncData.hash) {
if (item.hash !== contentSyncData.hash) { store.dispatch('data/patchSyncData', {
store.dispatch('data/patchSyncData', { [contentSyncData.id]: {
[contentSyncData.id]: { ...contentSyncData,
...contentSyncData, hash: item.hash,
hash: item.hash, },
},
});
}
// Open the file requested by action if it wasn't synced yet
if (fileIdToOpen && fileIdToOpen === syncData.id) {
fileIdToOpen = null;
// Open the file once downloaded content has been stored
setTimeout(() => {
store.commit('file/setCurrentId', syncData.itemId);
}, 10);
}
return item;
}); });
}
// Open the file requested by action if it wasn't synced yet
if (fileIdToOpen && fileIdToOpen === syncData.id) {
fileIdToOpen = null;
// Open the file once downloaded content has been stored
setTimeout(() => {
store.commit('file/setCurrentId', syncData.itemId);
}, 10);
}
return item;
}, },
downloadData(dataId) { async downloadData(dataId) {
const syncData = store.getters['data/syncDataByItemId'][dataId]; const syncData = store.getters['data/syncDataByItemId'][dataId];
if (!syncData) { if (!syncData) {
return Promise.resolve(); return null;
} }
const syncToken = store.getters['workspace/syncToken']; const syncToken = store.getters['workspace/syncToken'];
return googleHelper.downloadFile(syncToken, syncData.id) const content = await googleHelper.downloadFile(syncToken, syncData.id);
.then((content) => { const item = JSON.parse(content);
const item = JSON.parse(content); if (item.hash !== syncData.hash) {
if (item.hash !== syncData.hash) { store.dispatch('data/patchSyncData', {
store.dispatch('data/patchSyncData', { [syncData.id]: {
[syncData.id]: { ...syncData,
...syncData, hash: item.hash,
hash: item.hash, },
},
});
}
return item;
}); });
},
uploadContent(token, content, syncLocation, ifNotTooLate) {
const contentSyncData = store.getters['data/syncDataByItemId'][`${syncLocation.fileId}/content`];
if (contentSyncData && contentSyncData.hash === content.hash) {
return Promise.resolve(syncLocation);
} }
return Promise.resolve() return item;
.then(() => { },
const syncData = store.getters['data/syncDataByItemId'][syncLocation.fileId]; async uploadContent(token, content, syncLocation, ifNotTooLate) {
if (syncData) { const contentSyncData = store.getters['data/syncDataByItemId'][`${syncLocation.fileId}/content`];
// Only update file media if (!contentSyncData || contentSyncData.hash !== content.hash) {
return googleHelper.uploadFile( const syncData = store.getters['data/syncDataByItemId'][syncLocation.fileId];
token, let file;
undefined, if (syncData) {
undefined, // Only update file media
undefined, file = await googleHelper.uploadFile({
Provider.serializeContent(content), token,
undefined, media: Provider.serializeContent(content),
syncData.id, fileId: syncData.id,
undefined, ifNotTooLate,
ifNotTooLate, });
); } else {
}
// Create file with media // Create file with media
const workspace = store.getters['workspace/currentWorkspace']; const workspace = store.getters['workspace/currentWorkspace'];
// Use deepCopy to freeze objects // Use deepCopy to freeze objects
const item = utils.deepCopy(store.state.file.itemMap[syncLocation.fileId]); const item = utils.deepCopy(store.state.file.itemMap[syncLocation.fileId]);
const parentSyncData = store.getters['data/syncDataByItemId'][item.parentId]; const parentSyncData = store.getters['data/syncDataByItemId'][item.parentId];
return googleHelper.uploadFile( file = await googleHelper.uploadFile({
token, token,
item.name, name: item.name,
[parentSyncData ? parentSyncData.id : workspace.folderId], parents: [parentSyncData ? parentSyncData.id : workspace.folderId],
{ appProperties: {
id: item.id, id: item.id,
folderId: workspace.folderId, folderId: workspace.folderId,
}, },
Provider.serializeContent(content), media: Provider.serializeContent(content),
undefined,
undefined,
undefined,
ifNotTooLate, ifNotTooLate,
) });
.then((file) => { store.dispatch('data/patchSyncData', {
store.dispatch('data/patchSyncData', { [file.id]: {
[file.id]: { id: file.id,
id: file.id, itemId: item.id,
itemId: item.id, type: item.type,
type: item.type, hash: item.hash,
hash: item.hash, },
}, });
}); }
return file; store.dispatch('data/patchSyncData', {
});
})
.then(file => store.dispatch('data/patchSyncData', {
[`${file.id}/content`]: { [`${file.id}/content`]: {
// Build sync data // Build sync data
id: `${file.id}/content`, id: `${file.id}/content`,
@ -521,34 +462,32 @@ export default new Provider({
type: content.type, type: content.type,
hash: content.hash, hash: content.hash,
}, },
})) });
.then(() => syncLocation);
},
uploadData(item, ifNotTooLate) {
const syncData = store.getters['data/syncDataByItemId'][item.id];
if (syncData && syncData.hash === item.hash) {
return Promise.resolve();
} }
const workspace = store.getters['workspace/currentWorkspace']; return syncLocation;
const syncToken = store.getters['workspace/syncToken']; },
return googleHelper.uploadFile( async uploadData(item, ifNotTooLate) {
syncToken, const syncData = store.getters['data/syncDataByItemId'][item.id];
JSON.stringify({ if (!syncData || syncData.hash !== item.hash) {
id: item.id, const workspace = store.getters['workspace/currentWorkspace'];
type: item.type, const syncToken = store.getters['workspace/syncToken'];
hash: item.hash, const file = await googleHelper.uploadFile({
}), token: syncToken,
[workspace.dataFolderId], name: JSON.stringify({
{ id: item.id,
folderId: workspace.folderId, type: item.type,
}, hash: item.hash,
JSON.stringify(item), }),
undefined, parents: [workspace.dataFolderId],
syncData && syncData.id, appProperties: {
syncData && syncData.parentIds, folderId: workspace.folderId,
ifNotTooLate, },
) media: JSON.stringify(item),
.then(file => store.dispatch('data/patchSyncData', { fileId: syncData && syncData.id,
oldParents: syncData && syncData.parentIds,
ifNotTooLate,
});
store.dispatch('data/patchSyncData', {
[file.id]: { [file.id]: {
// Build sync data // Build sync data
id: file.id, id: file.id,
@ -556,21 +495,22 @@ export default new Provider({
type: item.type, type: item.type,
hash: item.hash, hash: item.hash,
}, },
})); });
}
}, },
listRevisions(token, fileId) { async listRevisions(token, fileId) {
return getSyncData(fileId) const syncData = Provider.getContentSyncData(fileId);
.then(syncData => googleHelper.getFileRevisions(token, syncData.id)) const revisions = await googleHelper.getFileRevisions(token, syncData.id);
.then(revisions => revisions.map(revision => ({ return revisions.map(revision => ({
id: revision.id, id: revision.id,
sub: revision.lastModifyingUser && revision.lastModifyingUser.permissionId, sub: revision.lastModifyingUser && revision.lastModifyingUser.permissionId,
created: new Date(revision.modifiedTime).getTime(), created: new Date(revision.modifiedTime).getTime(),
})) }))
.sort((revision1, revision2) => revision2.created - revision1.created)); .sort((revision1, revision2) => revision2.created - revision1.created);
}, },
getRevisionContent(token, fileId, revisionId) { async getRevisionContent(token, fileId, revisionId) {
return getSyncData(fileId) const syncData = Provider.getContentSyncData(fileId);
.then(syncData => googleHelper.downloadFileRevision(token, syncData.id, revisionId)) const content = await googleHelper.downloadFileRevision(token, syncData.id, revisionId);
.then(content => Provider.parseContent(content, `${fileId}/content`)); return Provider.parseContent(content, `${fileId}/content`);
}, },
}); });

View File

@ -2,31 +2,37 @@ import networkSvc from '../../networkSvc';
import utils from '../../utils'; import utils from '../../utils';
import store from '../../../store'; import store from '../../../store';
const request = (token, options = {}) => { const request = async (token, options = {}) => {
const baseUrl = `${token.dbUrl}/`; const baseUrl = `${token.dbUrl}/`;
const getLastToken = () => store.getters['data/couchdbTokens'][token.sub]; const getLastToken = () => store.getters['data/couchdbTokens'][token.sub];
const ifUnauthorized = cb => (err) => { const assertUnauthorized = (err) => {
if (err.status !== 401) { if (err.status !== 401) {
throw err; throw err;
} }
return cb(err);
}; };
const onUnauthorized = () => networkSvc.request({ const onUnauthorized = async () => {
method: 'POST', try {
url: utils.resolveUrl(baseUrl, '../_session'), const { name, password } = getLastToken();
withCredentials: true, await networkSvc.request({
body: { method: 'POST',
name: getLastToken().name, url: utils.resolveUrl(baseUrl, '../_session'),
password: getLastToken().password, withCredentials: true,
}, body: {
}) name,
.catch(ifUnauthorized(() => store.dispatch('modal/open', { password,
type: 'couchdbCredentials', },
token: getLastToken(), });
}) } catch (err) {
.then(onUnauthorized))); assertUnauthorized(err);
await store.dispatch('modal/open', {
type: 'couchdbCredentials',
token: getLastToken(),
});
await onUnauthorized();
}
};
const config = { const config = {
...options, ...options,
@ -38,55 +44,75 @@ const request = (token, options = {}) => {
withCredentials: true, withCredentials: true,
}; };
return networkSvc.request(config) try {
.catch(ifUnauthorized(() => onUnauthorized() let res;
.then(() => networkSvc.request(config)))) try {
.then(res => res.body) res = await networkSvc.request(config);
.catch((err) => { } catch (err) {
if (err.status === 409) { assertUnauthorized(err);
throw new Error('TOO_LATE'); await onUnauthorized();
} res = await networkSvc.request(config);
throw err; }
}); return res.body;
} catch (err) {
if (err.status === 409) {
throw new Error('TOO_LATE');
}
throw err;
}
}; };
export default { export default {
/**
* http://docs.couchdb.org/en/2.1.1/api/database/common.html#db
*/
getDb(token) { getDb(token) {
return request(token); return request(token);
}, },
getChanges(token, lastSeq) {
/**
* http://docs.couchdb.org/en/2.1.1/api/database/changes.html#db-changes
*/
async getChanges(token, lastSeq) {
const result = { const result = {
changes: [], changes: [],
lastSeq,
}; };
const getPage = (since = 0) => request(token, { const getPage = async () => {
method: 'GET', const body = await request(token, {
path: '_changes', method: 'GET',
params: { path: '_changes',
since, params: {
include_docs: true, since: result.lastSeq || 0,
limit: 1000, include_docs: true,
}, limit: 1000,
}) },
.then((body) => {
result.changes = result.changes.concat(body.results);
if (body.pending) {
return getPage(body.last_seq);
}
result.lastSeq = body.last_seq;
return result;
}); });
result.changes = [...result.changes, ...body.results];
result.lastSeq = body.last_seq;
if (body.pending) {
return getPage();
}
return result;
};
return getPage(lastSeq); return getPage();
}, },
uploadDocument(
/**
* http://docs.couchdb.org/en/2.1.1/api/database/common.html#post--db
* http://docs.couchdb.org/en/2.1.1/api/document/common.html#put--db-docid
*/
async uploadDocument({
token, token,
item, item,
data = null, data = null,
dataType = null, dataType = null,
documentId = null, documentId = null,
rev = null, rev = null,
) { }) {
const options = { const options = {
method: 'POST', method: 'POST',
body: { item, time: Date.now() }, body: { item, time: Date.now() },
@ -110,34 +136,48 @@ export default {
} }
return request(token, options); return request(token, options);
}, },
removeDocument(token, documentId, rev) {
/**
* http://docs.couchdb.org/en/2.1.1/api/document/common.html#delete--db-docid
*/
async removeDocument(token, documentId, rev) {
return request(token, { return request(token, {
method: 'DELETE', method: 'DELETE',
path: documentId, path: documentId,
params: { rev }, params: { rev },
}); });
}, },
retrieveDocument(token, documentId, rev) {
/**
* http://docs.couchdb.org/en/2.1.1/api/document/common.html#get--db-docid
*/
async retrieveDocument(token, documentId, rev) {
return request(token, { return request(token, {
path: documentId, path: documentId,
params: { rev }, params: { rev },
}); });
}, },
retrieveDocumentWithAttachments(token, documentId, rev) {
return request(token, { /**
* http://docs.couchdb.org/en/2.1.1/api/document/common.html#get--db-docid
*/
async retrieveDocumentWithAttachments(token, documentId, rev) {
const body = await request(token, {
path: documentId, path: documentId,
params: { attachments: true, rev }, params: { attachments: true, rev },
}) });
.then((body) => { body.attachments = {};
body.attachments = {}; // eslint-disable-next-line no-underscore-dangle
// eslint-disable-next-line no-underscore-dangle Object.entries(body._attachments).forEach(([name, attachment]) => {
Object.entries(body._attachments).forEach(([name, attachment]) => { body.attachments[name] = utils.decodeBase64(attachment.data);
body.attachments[name] = utils.decodeBase64(attachment.data); });
}); return body;
return body;
});
}, },
retrieveDocumentWithRevisions(token, documentId) {
/**
* http://docs.couchdb.org/en/2.1.1/api/document/common.html#get--db-docid
*/
async retrieveDocumentWithRevisions(token, documentId) {
return request(token, { return request(token, {
path: documentId, path: documentId,
params: { params: {

View File

@ -1,8 +1,6 @@
import networkSvc from '../../networkSvc'; import networkSvc from '../../networkSvc';
import store from '../../../store'; import store from '../../../store';
let Dropbox;
const getAppKey = (fullAccess) => { const getAppKey = (fullAccess) => {
if (fullAccess) { if (fullAccess) {
return 'lq6mwopab8wskas'; return 'lq6mwopab8wskas';
@ -22,89 +20,105 @@ const request = (token, options, args) => networkSvc.request({
}); });
export default { export default {
startOauth2(fullAccess, sub = null, silent = false) {
return networkSvc.startOauth2( /**
* https://www.dropbox.com/developers/documentation/http/documentation#oauth2-authorize
*/
async startOauth2(fullAccess, sub = null, silent = false) {
const { accessToken } = await networkSvc.startOauth2(
'https://www.dropbox.com/oauth2/authorize', 'https://www.dropbox.com/oauth2/authorize',
{ {
client_id: getAppKey(fullAccess), client_id: getAppKey(fullAccess),
response_type: 'token', response_type: 'token',
}, },
silent, silent,
) );
// Call the user info endpoint
.then(({ accessToken }) => request({ accessToken }, { // Call the user info endpoint
method: 'POST', const { body } = await request({ accessToken }, {
url: 'https://api.dropboxapi.com/2/users/get_current_account', method: 'POST',
}) url: 'https://api.dropboxapi.com/2/users/get_current_account',
.then((res) => { });
// Check the returned sub consistency
if (sub && `${res.body.account_id}` !== sub) { // Check the returned sub consistency
throw new Error('Dropbox account ID not expected.'); if (sub && `${body.account_id}` !== sub) {
} throw new Error('Dropbox account ID not expected.');
// Build token object including scopes and sub
const token = {
accessToken,
name: res.body.name.display_name,
sub: `${res.body.account_id}`,
fullAccess,
};
// Add token to dropboxTokens
store.dispatch('data/setDropboxToken', token);
return token;
}));
},
loadClientScript() {
if (Dropbox) {
return Promise.resolve();
} }
return networkSvc.loadScript('https://www.dropbox.com/static/api/2/dropins.js')
.then(() => { // Build token object including scopes and sub
({ Dropbox } = window); const token = {
}); accessToken,
name: body.name.display_name,
sub: `${body.account_id}`,
fullAccess,
};
// Add token to dropboxTokens
store.dispatch('data/setDropboxToken', token);
return token;
}, },
addAccount(fullAccess = false) { addAccount(fullAccess = false) {
return this.startOauth2(fullAccess); return this.startOauth2(fullAccess);
}, },
uploadFile(token, path, content, fileId) {
return request(token, { /**
* https://www.dropbox.com/developers/documentation/http/documentation#files-upload
*/
async uploadFile({
token,
path,
content,
fileId,
}) {
return (await request(token, {
method: 'POST', method: 'POST',
url: 'https://content.dropboxapi.com/2/files/upload', url: 'https://content.dropboxapi.com/2/files/upload',
body: content, body: content,
}, { }, {
path: fileId || path, path: fileId || path,
mode: 'overwrite', mode: 'overwrite',
}) })).body;
.then(res => res.body);
}, },
downloadFile(token, path, fileId) {
return request(token, { /**
* https://www.dropbox.com/developers/documentation/http/documentation#files-download
*/
async downloadFile({
token,
path,
fileId,
}) {
const res = await request(token, {
method: 'POST', method: 'POST',
url: 'https://content.dropboxapi.com/2/files/download', url: 'https://content.dropboxapi.com/2/files/download',
raw: true, raw: true,
}, { }, {
path: fileId || path, path: fileId || path,
}) });
.then(res => ({ return {
id: JSON.parse(res.headers['dropbox-api-result']).id, id: JSON.parse(res.headers['dropbox-api-result']).id,
content: res.body, content: res.body,
})); };
}, },
openChooser(token) {
return this.loadClientScript() /**
.then(() => new Promise((resolve) => { * https://www.dropbox.com/developers/chooser
Dropbox.appKey = getAppKey(token.fullAccess); */
Dropbox.choose({ async openChooser(token) {
multiselect: true, if (!window.Dropbox) {
linkType: 'direct', await networkSvc.loadScript('https://www.dropbox.com/static/api/2/dropins.js');
success: (files) => { }
const paths = files.map((file) => { return new Promise((resolve) => {
const path = file.link.replace(/.*\/view\/[^/]*/, ''); window.Dropbox.appKey = getAppKey(token.fullAccess);
return decodeURI(path); window.Dropbox.choose({
}); multiselect: true,
resolve(paths); linkType: 'direct',
}, success: files => resolve(files.map((file) => {
cancel: () => resolve([]), const path = file.link.replace(/.*\/view\/[^/]*/, '');
}); return decodeURI(path);
})); })),
cancel: () => resolve([]),
});
});
}, },
}; };

View File

@ -20,7 +20,8 @@ const request = (token, options) => networkSvc.request({
const repoRequest = (token, owner, repo, options) => request(token, { const repoRequest = (token, owner, repo, options) => request(token, {
...options, ...options,
url: `https://api.github.com/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/${options.url}`, url: `https://api.github.com/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/${options.url}`,
}); })
.then(res => res.body);
const getCommitMessage = (name, path) => { const getCommitMessage = (name, path) => {
const message = store.getters['data/computedSettings'].github[name]; const message = store.getters['data/computedSettings'].github[name];
@ -28,95 +29,131 @@ const getCommitMessage = (name, path) => {
}; };
export default { export default {
startOauth2(scopes, sub = null, silent = false) {
return networkSvc.startOauth2( /**
* https://developer.github.com/apps/building-oauth-apps/authorization-options-for-oauth-apps/
*/
async startOauth2(scopes, sub = null, silent = false) {
const { code } = await networkSvc.startOauth2(
'https://github.com/login/oauth/authorize', 'https://github.com/login/oauth/authorize',
{ {
client_id: clientId, client_id: clientId,
scope: scopes.join(' '), scope: scopes.join(' '),
}, },
silent, silent,
) );
// Exchange code with token
.then(data => networkSvc.request({ // Exchange code with token
method: 'GET', const accessToken = (await networkSvc.request({
url: 'oauth2/githubToken', method: 'GET',
params: { url: 'oauth2/githubToken',
clientId, params: {
code: data.code, clientId,
}, code,
}) },
.then(res => res.body)) })).body;
// Call the user info endpoint
.then(accessToken => networkSvc.request({ // Call the user info endpoint
method: 'GET', const user = (await networkSvc.request({
url: 'https://api.github.com/user', method: 'GET',
params: { url: 'https://api.github.com/user',
access_token: accessToken, params: {
}, access_token: accessToken,
}) },
.then((res) => { })).body;
// Check the returned sub consistency
if (sub && `${res.body.id}` !== sub) { // Check the returned sub consistency
throw new Error('GitHub account ID not expected.'); if (sub && `${user.id}` !== sub) {
} throw new Error('GitHub account ID not expected.');
// Build token object including scopes and sub }
const token = {
scopes, // Build token object including scopes and sub
accessToken, const token = {
name: res.body.login, scopes,
sub: `${res.body.id}`, accessToken,
repoFullAccess: scopes.indexOf('repo') !== -1, name: user.login,
}; sub: `${user.id}`,
// Add token to githubTokens repoFullAccess: scopes.indexOf('repo') !== -1,
store.dispatch('data/setGithubToken', token); };
return token;
})); // Add token to githubTokens
store.dispatch('data/setGithubToken', token);
return token;
}, },
addAccount(repoFullAccess = false) { async addAccount(repoFullAccess = false) {
return this.startOauth2(getScopes({ repoFullAccess })); return this.startOauth2(getScopes({ repoFullAccess }));
}, },
getUser(userId) {
return networkSvc.request({ /**
* Getting a user from its userId is not feasible with API v3.
* Using an undocumented endpoint...
*/
async getUser(userId) {
const user = (await networkSvc.request({
url: `https://api.github.com/user/${userId}`, url: `https://api.github.com/user/${userId}`,
params: { params: {
t: Date.now(), // Prevent from caching t: Date.now(), // Prevent from caching
}, },
}) })).body;
.then((res) => { store.commit('userInfo/addItem', {
store.commit('userInfo/addItem', { id: `gh:${user.id}`,
id: `gh:${res.body.id}`, name: user.login,
name: res.body.login, imageUrl: user.avatar_url || '',
imageUrl: res.body.avatar_url || '', });
}); return user;
return res.body;
});
}, },
getTree(token, owner, repo, sha) {
return repoRequest(token, owner, repo, { /**
url: `git/trees/${encodeURIComponent(sha)}?recursive=1`, * https://developer.github.com/v3/repos/commits/#get-a-single-commit
}) * https://developer.github.com/v3/git/trees/#get-a-tree
.then((res) => { */
if (res.body.truncated) { async getTree({
throw new Error('Git tree too big. Please remove some files in the repository.'); token,
} owner,
return res.body.tree; repo,
}); branch,
}, }) {
getHeadTree(token, owner, repo, branch) { const { commit } = (await repoRequest(token, owner, repo, {
return repoRequest(token, owner, repo, {
url: `commits/${encodeURIComponent(branch)}`, url: `commits/${encodeURIComponent(branch)}`,
}) })).body;
.then(res => this.getTree(token, owner, repo, res.body.commit.tree.sha)); const { tree, truncated } = (await repoRequest(token, owner, repo, {
url: `git/trees/${encodeURIComponent(commit.tree.sha)}?recursive=1`,
})).body;
if (truncated) {
throw new Error('Git tree too big. Please remove some files in the repository.');
}
return tree;
}, },
getCommits(token, owner, repo, sha, path) {
/**
* https://developer.github.com/v3/repos/commits/#list-commits-on-a-repository
*/
async getCommits({
token,
owner,
repo,
sha,
path,
}) {
return repoRequest(token, owner, repo, { return repoRequest(token, owner, repo, {
url: 'commits', url: 'commits',
params: { sha, path }, params: { sha, path },
}) });
.then(res => res.body);
}, },
uploadFile(token, owner, repo, branch, path, content, sha) {
/**
* https://developer.github.com/v3/repos/contents/#create-a-file
* https://developer.github.com/v3/repos/contents/#update-a-file
*/
async uploadFile({
token,
owner,
repo,
branch,
path,
content,
sha,
}) {
return repoRequest(token, owner, repo, { return repoRequest(token, owner, repo, {
method: 'PUT', method: 'PUT',
url: `contents/${encodeURIComponent(path)}`, url: `contents/${encodeURIComponent(path)}`,
@ -126,10 +163,20 @@ export default {
sha, sha,
branch, branch,
}, },
}) });
.then(res => res.body);
}, },
removeFile(token, owner, repo, branch, path, sha) {
/**
* https://developer.github.com/v3/repos/contents/#delete-a-file
*/
async removeFile({
token,
owner,
repo,
branch,
path,
sha,
}) {
return repoRequest(token, owner, repo, { return repoRequest(token, owner, repo, {
method: 'DELETE', method: 'DELETE',
url: `contents/${encodeURIComponent(path)}`, url: `contents/${encodeURIComponent(path)}`,
@ -138,21 +185,42 @@ export default {
sha, sha,
branch, branch,
}, },
}) });
.then(res => res.body);
}, },
downloadFile(token, owner, repo, branch, path) {
return repoRequest(token, owner, repo, { /**
* https://developer.github.com/v3/repos/contents/#get-contents
*/
async downloadFile({
token,
owner,
repo,
branch,
path,
}) {
const body = await repoRequest(token, owner, repo, {
url: `contents/${encodeURIComponent(path)}`, url: `contents/${encodeURIComponent(path)}`,
params: { ref: branch }, params: { ref: branch },
}) });
.then(res => ({ return {
sha: res.body.sha, sha: body.sha,
content: utils.decodeBase64(res.body.content), content: utils.decodeBase64(body.content),
})); };
}, },
uploadGist(token, description, filename, content, isPublic, gistId) {
return request(token, gistId ? { /**
* https://developer.github.com/v3/gists/#create-a-gist
* https://developer.github.com/v3/gists/#edit-a-gist
*/
async uploadGist({
token,
description,
filename,
content,
isPublic,
gistId,
}) {
const { body } = await request(token, gistId ? {
method: 'PATCH', method: 'PATCH',
url: `https://api.github.com/gists/${gistId}`, url: `https://api.github.com/gists/${gistId}`,
body: { body: {
@ -175,19 +243,24 @@ export default {
}, },
public: isPublic, public: isPublic,
}, },
}) });
.then(res => res.body); return body;
}, },
downloadGist(token, gistId, filename) {
return request(token, { /**
* https://developer.github.com/v3/gists/#get-a-single-gist
*/
async downloadGist({
token,
gistId,
filename,
}) {
const result = (await request(token, {
url: `https://api.github.com/gists/${gistId}`, url: `https://api.github.com/gists/${gistId}`,
}) })).body.files[filename];
.then((res) => { if (!result) {
const result = res.body.files[filename]; throw new Error('Gist file not found.');
if (!result) { }
throw new Error('Gist file not found.'); return result.content;
}
return result.content;
});
}, },
}; };

File diff suppressed because it is too large Load Diff

View File

@ -10,11 +10,15 @@ const request = (token, options) => networkSvc.request({
...options.headers || {}, ...options.headers || {},
Authorization: `Bearer ${token.accessToken}`, Authorization: `Bearer ${token.accessToken}`,
}, },
}); })
.then(res => res.body);
export default { export default {
startOauth2(sub = null, silent = false) { /**
return networkSvc.startOauth2( * https://developer.wordpress.com/docs/oauth2/
*/
async startOauth2(sub = null, silent = false) {
const { accessToken, expiresIn } = await networkSvc.startOauth2(
'https://public-api.wordpress.com/oauth2/authorize', 'https://public-api.wordpress.com/oauth2/authorize',
{ {
client_id: clientId, client_id: clientId,
@ -22,49 +26,49 @@ export default {
scope: 'global', scope: 'global',
}, },
silent, silent,
) );
// Call the user info endpoint
.then(data => request({ accessToken: data.accessToken }, { // Call the user info endpoint
url: 'https://public-api.wordpress.com/rest/v1.1/me', const body = await request({ accessToken }, {
}) url: 'https://public-api.wordpress.com/rest/v1.1/me',
.then((res) => { });
// Check the returned sub consistency
if (sub && `${res.body.ID}` !== sub) { // Check the returned sub consistency
throw new Error('WordPress account ID not expected.'); if (sub && `${body.ID}` !== sub) {
} throw new Error('WordPress account ID not expected.');
// Build token object including scopes and sub }
const token = { // Build token object including scopes and sub
accessToken: data.accessToken, const token = {
expiresOn: Date.now() + (data.expiresIn * 1000), accessToken,
name: res.body.display_name, expiresOn: Date.now() + (expiresIn * 1000),
sub: `${res.body.ID}`, name: body.display_name,
}; sub: `${body.ID}`,
// Add token to wordpressTokens };
store.dispatch('data/setWordpressToken', token); // Add token to wordpressTokens
return token; store.dispatch('data/setWordpressToken', token);
})); return token;
}, },
refreshToken(token) { async refreshToken(token) {
const { sub } = token; const { sub } = token;
const lastToken = store.getters['data/wordpressTokens'][sub]; const lastToken = store.getters['data/wordpressTokens'][sub];
return Promise.resolve() if (lastToken.expiresOn > Date.now() + tokenExpirationMargin) {
.then(() => { return lastToken;
if (lastToken.expiresOn > Date.now() + tokenExpirationMargin) { }
return lastToken; // Existing token is going to expire.
} // Try to get a new token in background
// Existing token is going to expire. await store.dispatch('modal/providerRedirection', { providerName: 'WordPress' });
// Try to get a new token in background return this.startOauth2(sub);
return store.dispatch('modal/providerRedirection', {
providerName: 'WordPress',
onResolve: () => this.startOauth2(sub),
});
});
}, },
addAccount(fullAccess = false) { addAccount(fullAccess = false) {
return this.startOauth2(fullAccess); return this.startOauth2(fullAccess);
}, },
uploadPost(
/**
* https://developer.wordpress.com/docs/api/1.2/post/sites/%24site/posts/new/
* https://developer.wordpress.com/docs/api/1.2/post/sites/%24site/posts/%24post_ID/
*/
async uploadPost({
token, token,
domain, domain,
siteId, siteId,
@ -78,23 +82,22 @@ export default {
featuredImage, featuredImage,
status, status,
date, date,
) { }) {
return this.refreshToken(token) const refreshedToken = await this.refreshToken(token);
.then(refreshedToken => request(refreshedToken, { await request(refreshedToken, {
method: 'POST', method: 'POST',
url: `https://public-api.wordpress.com/rest/v1.2/sites/${siteId || domain}/posts/${postId || 'new'}`, url: `https://public-api.wordpress.com/rest/v1.2/sites/${siteId || domain}/posts/${postId || 'new'}`,
body: { body: {
content, content,
title, title,
tags, tags,
categories, categories,
excerpt, excerpt,
author, author,
featured_image: featuredImage || '', featured_image: featuredImage || '',
status, status,
date: date && date.toISOString(), date: date && date.toISOString(),
}, },
}) });
.then(res => res.body));
}, },
}; };

View File

@ -7,11 +7,16 @@ const request = (token, options) => networkSvc.request({
...options.headers || {}, ...options.headers || {},
Authorization: `Bearer ${token.accessToken}`, Authorization: `Bearer ${token.accessToken}`,
}, },
}); })
.then(res => res.body);
export default { export default {
startOauth2(subdomain, clientId, sub = null, silent = false) { /**
return networkSvc.startOauth2( * https://support.zendesk.com/hc/en-us/articles/203663836-Using-OAuth-authentication-with-your-application
*/
async startOauth2(subdomain, clientId, sub = null, silent = false) {
const { accessToken } = await networkSvc.startOauth2(
`https://${subdomain}.zendesk.com/oauth/authorizations/new`, `https://${subdomain}.zendesk.com/oauth/authorizations/new`,
{ {
client_id: clientId, client_id: clientId,
@ -19,33 +24,39 @@ export default {
scope: 'read hc:write', scope: 'read hc:write',
}, },
silent, silent,
) );
// Call the user info endpoint
.then(({ accessToken }) => request({ accessToken }, { // Call the user info endpoint
url: `https://${subdomain}.zendesk.com/api/v2/users/me.json`, const { user } = await request({ accessToken }, {
}) url: `https://${subdomain}.zendesk.com/api/v2/users/me.json`,
.then((res) => { });
const uniqueSub = `${subdomain}/${res.body.user.id}`; const uniqueSub = `${subdomain}/${user.id}`;
// Check the returned sub consistency
if (sub && uniqueSub !== sub) { // Check the returned sub consistency
throw new Error('Zendesk account ID not expected.'); if (sub && uniqueSub !== sub) {
} throw new Error('Zendesk account ID not expected.');
// Build token object including scopes and sub }
const token = {
accessToken, // Build token object including scopes and sub
name: res.body.user.name, const token = {
subdomain, accessToken,
sub: uniqueSub, name: user.name,
}; subdomain,
// Add token to zendeskTokens sub: uniqueSub,
store.dispatch('data/setZendeskToken', token); };
return token;
})); // Add token to zendeskTokens
store.dispatch('data/setZendeskToken', token);
return token;
}, },
addAccount(subdomain, clientId) { addAccount(subdomain, clientId) {
return this.startOauth2(subdomain, clientId); return this.startOauth2(subdomain, clientId);
}, },
uploadArticle(
/**
* https://developer.zendesk.com/rest_api/docs/help_center/articles
*/
async uploadArticle({
token, token,
sectionId, sectionId,
articleId, articleId,
@ -54,20 +65,25 @@ export default {
labels, labels,
locale, locale,
isDraft, isDraft,
) { }) {
const article = { const article = {
title, title,
body: content, body: content,
locale, locale,
draft: isDraft, draft: isDraft,
}; };
if (articleId) { if (articleId) {
return request(token, { // Update article
await request(token, {
method: 'PUT', method: 'PUT',
url: `https://${token.subdomain}.zendesk.com/api/v2/help_center/articles/${articleId}/translations/${locale}.json`, url: `https://${token.subdomain}.zendesk.com/api/v2/help_center/articles/${articleId}/translations/${locale}.json`,
body: { translation: article }, body: { translation: article },
}) });
.then(() => labels && request(token, {
// Add labels
if (labels) {
await request(token, {
method: 'PUT', method: 'PUT',
url: `https://${token.subdomain}.zendesk.com/api/v2/help_center/articles/${articleId}.json`, url: `https://${token.subdomain}.zendesk.com/api/v2/help_center/articles/${articleId}.json`,
body: { body: {
@ -75,17 +91,20 @@ export default {
label_names: labels, label_names: labels,
}, },
}, },
})) });
.then(() => articleId); }
return articleId;
} }
// Create new article
if (labels) { if (labels) {
article.label_names = labels; article.label_names = labels;
} }
return request(token, { const body = await request(token, {
method: 'POST', method: 'POST',
url: `https://${token.subdomain}.zendesk.com/api/v2/help_center/sections/${sectionId}/articles.json`, url: `https://${token.subdomain}.zendesk.com/api/v2/help_center/sections/${sectionId}/articles.json`,
body: { article }, body: { article },
}) });
.then(res => `${res.body.article.id}`); return `${body.article.id}`;
}, },
}; };

View File

@ -14,27 +14,18 @@ export default new Provider({
const token = this.getToken(location); const token = this.getToken(location);
return `${location.postId}${location.domain}${token.name}`; return `${location.postId}${location.domain}${token.name}`;
}, },
publish(token, html, metadata, publishLocation) { async publish(token, html, metadata, publishLocation) {
return wordpressHelper.uploadPost( const post = await wordpressHelper.uploadPost({
...publishLocation,
...metadata,
token, token,
publishLocation.domain, content: html,
publishLocation.siteId, });
publishLocation.postId, return {
metadata.title, ...publishLocation,
html, siteId: `${post.site_ID}`,
metadata.tags, postId: `${post.ID}`,
metadata.categories, };
metadata.excerpt,
metadata.author,
metadata.featuredImage,
metadata.status,
metadata.date,
)
.then(post => ({
...publishLocation,
siteId: `${post.site_ID}`,
postId: `${post.ID}`,
}));
}, },
makeLocation(token, domain, postId) { makeLocation(token, domain, postId) {
const location = { const location = {

View File

@ -15,21 +15,19 @@ export default new Provider({
const token = this.getToken(location); const token = this.getToken(location);
return `${location.articleId}${token.name}${token.subdomain}`; return `${location.articleId}${token.name}${token.subdomain}`;
}, },
publish(token, html, metadata, publishLocation) { async publish(token, html, metadata, publishLocation) {
return zendeskHelper.uploadArticle( const articleId = await zendeskHelper.uploadArticle({
...publishLocation,
token, token,
publishLocation.sectionId, title: metadata.title,
publishLocation.articleId, content: html,
metadata.title, labels: metadata.tags,
html, isDraft: metadata.status === 'draft',
metadata.tags, });
publishLocation.locale, return {
metadata.status === 'draft', ...publishLocation,
) articleId,
.then(articleId => ({ };
...publishLocation,
articleId,
}));
}, },
makeLocation(token, sectionId, locale, articleId) { makeLocation(token, sectionId, locale, articleId) {
const location = { const location = {

View File

@ -38,80 +38,66 @@ const ensureDate = (value, defaultValue) => {
return new Date(`${value}`); return new Date(`${value}`);
}; };
function publish(publishLocation) { const publish = async (publishLocation) => {
const { fileId } = publishLocation; const { fileId } = publishLocation;
const template = store.getters['data/allTemplates'][publishLocation.templateId]; const template = store.getters['data/allTemplates'][publishLocation.templateId];
return exportSvc.applyTemplate(fileId, template) const html = await exportSvc.applyTemplate(fileId, template);
.then(html => localDbSvc.loadItem(`${fileId}/content`) const content = await localDbSvc.loadItem(`${fileId}/content`);
.then((content) => { const file = store.state.file.itemMap[fileId];
const file = store.state.file.itemMap[fileId]; const properties = utils.computeProperties(content.properties);
const properties = utils.computeProperties(content.properties); const provider = providerRegistry.providers[publishLocation.providerId];
const provider = providerRegistry.providers[publishLocation.providerId]; const token = provider.getToken(publishLocation);
const token = provider.getToken(publishLocation); const metadata = {
const metadata = { title: ensureString(properties.title, file.name),
title: ensureString(properties.title, file.name), author: ensureString(properties.author),
author: ensureString(properties.author), tags: ensureArray(properties.tags),
tags: ensureArray(properties.tags), categories: ensureArray(properties.categories),
categories: ensureArray(properties.categories), excerpt: ensureString(properties.excerpt),
excerpt: ensureString(properties.excerpt), featuredImage: ensureString(properties.featuredImage),
featuredImage: ensureString(properties.featuredImage), status: ensureString(properties.status),
status: ensureString(properties.status), date: ensureDate(properties.date, new Date()),
date: ensureDate(properties.date, new Date()), };
}; return provider.publish(token, html, metadata, publishLocation);
return provider.publish(token, html, metadata, publishLocation); };
}));
}
function publishFile(fileId) { const publishFile = async (fileId) => {
let counter = 0; let counter = 0;
return loadContent(fileId) await loadContent(fileId);
.then(() => { const publishLocations = [
const publishLocations = [ ...store.getters['publishLocation/filteredGroupedByFileId'][fileId] || [],
...store.getters['publishLocation/filteredGroupedByFileId'][fileId] || [], ];
]; try {
const publishOneContentLocation = () => { await utils.awaitSequence(publishLocations, async (publishLocation) => {
const publishLocation = publishLocations.shift(); await store.dispatch('queue/doWithLocation', {
if (!publishLocation) { location: publishLocation,
return null; action: async () => {
} const publishLocationToStore = await publish(publishLocation);
return store.dispatch('queue/doWithLocation', { try {
location: publishLocation, // Replace publish location if modified
promise: publish(publishLocation) if (utils.serializeObject(publishLocation) !==
.then((publishLocationToStore) => { utils.serializeObject(publishLocationToStore)
// Replace publish location if modified ) {
if (utils.serializeObject(publishLocation) !== store.commit('publishLocation/patchItem', publishLocationToStore);
utils.serializeObject(publishLocationToStore) }
) { counter += 1;
store.commit('publishLocation/patchItem', publishLocationToStore); } catch (err) {
} if (store.state.offline) {
counter += 1; throw err;
return publishOneContentLocation(); }
}, (err) => { console.error(err); // eslint-disable-line no-console
if (store.state.offline) { store.dispatch('notification/error', err);
throw err; }
} },
console.error(err); // eslint-disable-line no-console });
store.dispatch('notification/error', err); });
return publishOneContentLocation(); const file = store.state.file.itemMap[fileId];
}), store.dispatch('notification/info', `"${file.name}" was published to ${counter} location(s).`);
}); } finally {
}; await localDbSvc.unloadContents();
return publishOneContentLocation(); }
}) };
.then(() => {
const file = store.state.file.itemMap[fileId];
store.dispatch('notification/info', `"${file.name}" was published to ${counter} location(s).`);
})
.then(
() => localDbSvc.unloadContents(),
err => localDbSvc.unloadContents()
.then(() => {
throw err;
}),
);
}
function requestPublish() { const requestPublish = () => {
// No publish in light mode // No publish in light mode
if (store.state.light) { if (store.state.light) {
return; return;
@ -135,21 +121,21 @@ function requestPublish() {
intervalId = utils.setInterval(() => attempt(), 1000); intervalId = utils.setInterval(() => attempt(), 1000);
attempt(); attempt();
})); }));
} };
function createPublishLocation(publishLocation) { const createPublishLocation = (publishLocation) => {
publishLocation.id = utils.uid(); publishLocation.id = utils.uid();
const currentFile = store.getters['file/current']; const currentFile = store.getters['file/current'];
publishLocation.fileId = currentFile.id; publishLocation.fileId = currentFile.id;
store.dispatch( store.dispatch(
'queue/enqueue', 'queue/enqueue',
() => publish(publishLocation) async () => {
.then((publishLocationToStore) => { const publishLocationToStore = await publish(publishLocation);
store.commit('publishLocation/setItem', publishLocationToStore); store.commit('publishLocation/setItem', publishLocationToStore);
store.dispatch('notification/info', `A new publication location was added to "${currentFile.name}".`); store.dispatch('notification/info', `A new publication location was added to "${currentFile.name}".`);
}), },
); );
} };
export default { export default {
requestPublish, requestPublish,

View File

@ -1,46 +1,46 @@
function SectionDimension(startOffset, endOffset) { class SectionDimension {
this.startOffset = startOffset; constructor(startOffset, endOffset) {
this.endOffset = endOffset; this.startOffset = startOffset;
this.height = endOffset - startOffset; this.endOffset = endOffset;
this.height = endOffset - startOffset;
}
} }
function dimensionNormalizer(dimensionName) { const dimensionNormalizer = dimensionName => (editorSvc) => {
return (editorSvc) => { const dimensionList = editorSvc.previewCtx.sectionDescList
const dimensionList = editorSvc.previewCtx.sectionDescList .map(sectionDesc => sectionDesc[dimensionName]);
.map(sectionDesc => sectionDesc[dimensionName]); let dimension;
let dimension; let i;
let i; let j;
let j; for (i = 0; i < dimensionList.length; i += 1) {
for (i = 0; i < dimensionList.length; i += 1) { dimension = dimensionList[i];
dimension = dimensionList[i]; if (dimension.height) {
if (dimension.height) { for (j = i + 1; j < dimensionList.length && dimensionList[j].height === 0; j += 1) {
for (j = i + 1; j < dimensionList.length && dimensionList[j].height === 0; j += 1) { // Loop
// Loop }
} const normalizeFactor = j - i;
const normalizeFactor = j - i; if (normalizeFactor !== 1) {
if (normalizeFactor !== 1) { const normalizedHeight = dimension.height / normalizeFactor;
const normalizedHeight = dimension.height / normalizeFactor; dimension.height = normalizedHeight;
dimension.endOffset = dimension.startOffset + dimension.height;
for (j = i + 1; j < i + normalizeFactor; j += 1) {
const startOffset = dimension.endOffset;
dimension = dimensionList[j];
dimension.startOffset = startOffset;
dimension.height = normalizedHeight; dimension.height = normalizedHeight;
dimension.endOffset = dimension.startOffset + dimension.height; dimension.endOffset = dimension.startOffset + dimension.height;
for (j = i + 1; j < i + normalizeFactor; j += 1) {
const startOffset = dimension.endOffset;
dimension = dimensionList[j];
dimension.startOffset = startOffset;
dimension.height = normalizedHeight;
dimension.endOffset = dimension.startOffset + dimension.height;
}
i = j - 1;
} }
i = j - 1;
} }
} }
}; }
} };
const normalizeEditorDimensions = dimensionNormalizer('editorDimension'); const normalizeEditorDimensions = dimensionNormalizer('editorDimension');
const normalizePreviewDimensions = dimensionNormalizer('previewDimension'); const normalizePreviewDimensions = dimensionNormalizer('previewDimension');
const normalizeTocDimensions = dimensionNormalizer('tocDimension'); const normalizeTocDimensions = dimensionNormalizer('tocDimension');
function measureSectionDimensions(editorSvc) { const measureSectionDimensions = (editorSvc) => {
let editorSectionOffset = 0; let editorSectionOffset = 0;
let previewSectionOffset = 0; let previewSectionOffset = 0;
let tocSectionOffset = 0; let tocSectionOffset = 0;
@ -106,7 +106,7 @@ function measureSectionDimensions(editorSvc) {
normalizeEditorDimensions(editorSvc); normalizeEditorDimensions(editorSvc);
normalizePreviewDimensions(editorSvc); normalizePreviewDimensions(editorSvc);
normalizeTocDimensions(editorSvc); normalizeTocDimensions(editorSvc);
} };
export default { export default {
measureSectionDimensions, measureSectionDimensions,

View File

@ -8,20 +8,19 @@ let lastCheck = 0;
const appId = 'ESTHdCYOi18iLhhO'; const appId = 'ESTHdCYOi18iLhhO';
let monetize; let monetize;
const getMonetize = () => Promise.resolve() const getMonetize = async () => {
.then(() => networkSvc.loadScript('https://cdn.monetizejs.com/api/js/latest/monetize.min.js')) await networkSvc.loadScript('https://cdn.monetizejs.com/api/js/latest/monetize.min.js');
.then(() => { monetize = monetize || new window.MonetizeJS({
monetize = monetize || new window.MonetizeJS({ applicationID: appId,
applicationID: appId,
});
}); });
};
const isGoogleSponsor = () => { const isGoogleSponsor = () => {
const sponsorToken = store.getters['workspace/sponsorToken']; const sponsorToken = store.getters['workspace/sponsorToken'];
return sponsorToken && sponsorToken.isSponsor; return sponsorToken && sponsorToken.isSponsor;
}; };
const checkPayment = () => { const checkPayment = async () => {
const currentDate = Date.now(); const currentDate = Date.now();
if (!isGoogleSponsor() if (!isGoogleSponsor()
&& networkSvc.isUserActive() && networkSvc.isUserActive()
@ -30,15 +29,15 @@ const checkPayment = () => {
&& lastCheck + checkPaymentEvery < currentDate && lastCheck + checkPaymentEvery < currentDate
) { ) {
lastCheck = currentDate; lastCheck = currentDate;
getMonetize() await getMonetize();
.then(() => monetize.getPaymentsImmediate((err, payments) => { monetize.getPaymentsImmediate((err, payments) => {
const isSponsor = payments && payments.app === appId && ( const isSponsor = payments && payments.app === appId && (
(payments.chargeOption && payments.chargeOption.alias === 'once') || (payments.chargeOption && payments.chargeOption.alias === 'once') ||
(payments.subscriptionOption && payments.subscriptionOption.alias === 'yearly')); (payments.subscriptionOption && payments.subscriptionOption.alias === 'yearly'));
if (isSponsor !== store.state.monetizeSponsor) { if (isSponsor !== store.state.monetizeSponsor) {
store.commit('setMonetizeSponsor', isSponsor); store.commit('setMonetizeSponsor', isSponsor);
} }
})); });
} }
}; };
@ -46,12 +45,11 @@ export default {
init: () => { init: () => {
utils.setInterval(checkPayment, 2000); utils.setInterval(checkPayment, 2000);
}, },
getToken() { async getToken() {
if (isGoogleSponsor() || store.state.offline) { if (isGoogleSponsor() || store.state.offline) {
return Promise.resolve(); return null;
} }
return getMonetize() await getMonetize();
.then(() => new Promise(resolve => return new Promise(resolve => monetize.getTokenImmediate((err, result) => resolve(result)));
monetize.getTokenImmediate((err, result) => resolve(result))));
}, },
}; };

File diff suppressed because it is too large Load Diff

View File

@ -25,75 +25,73 @@ export default {
} }
this.closed = true; this.closed = true;
}, },
init() { async init() {
if (!origin || !window.parent) { if (!origin || !window.parent) {
return Promise.resolve(); return;
} }
store.commit('setLight', true); store.commit('setLight', true);
return fileSvc.createFile({ const file = await fileSvc.createFile({
name: fileName || utils.getHostname(origin), name: fileName || utils.getHostname(origin),
text: contentText || '\n', text: contentText || '\n',
properties: contentProperties, properties: contentProperties,
parentId: 'temp', parentId: 'temp',
}, true) }, true);
.then((file) => {
const fileItemMap = store.state.file.itemMap;
// Sanitize file creations const fileItemMap = store.state.file.itemMap;
const lastCreated = {};
Object.entries(store.getters['data/lastCreated']).forEach(([id, createdOn]) => {
if (fileItemMap[id] && fileItemMap[id].parentId === 'temp') {
lastCreated[id] = createdOn;
}
});
// Track file creation from other site // Sanitize file creations
lastCreated[file.id] = { const lastCreated = {};
created: Date.now(), Object.entries(store.getters['data/lastCreated']).forEach(([id, createdOn]) => {
}; if (fileItemMap[id] && fileItemMap[id].parentId === 'temp') {
lastCreated[id] = createdOn;
}
});
// Keep only the last 10 temp files created by other sites // Track file creation from other site
Object.entries(lastCreated) lastCreated[file.id] = {
.sort(([, createdOn1], [, createdOn2]) => createdOn2 - createdOn1) created: Date.now(),
.splice(10) };
.forEach(([id]) => {
delete lastCreated[id];
fileSvc.deleteFile(id);
});
// Store file creations and open the file // Keep only the last 10 temp files created by other sites
store.dispatch('data/setLastCreated', lastCreated); Object.entries(lastCreated)
store.commit('file/setCurrentId', file.id); .sort(([, createdOn1], [, createdOn2]) => createdOn2 - createdOn1)
.splice(10)
const onChange = cledit.Utils.debounce(() => { .forEach(([id]) => {
const currentFile = store.getters['file/current']; delete lastCreated[id];
if (currentFile.id !== file.id) { fileSvc.deleteFile(id);
// Close editor if file has changed for some reason
this.close();
} else if (!this.closed && editorSvc.previewCtx.html != null) {
const content = store.getters['content/current'];
const properties = utils.computeProperties(content.properties);
window.parent.postMessage({
type: 'fileChange',
payload: {
id: file.id,
name: currentFile.name,
content: {
text: content.text.slice(0, -1), // Remove trailing LF
properties,
yamlProperties: content.properties,
html: editorSvc.previewCtx.html,
},
},
}, origin);
}
}, 25);
// Watch preview refresh and file name changes
editorSvc.$on('previewCtx', onChange);
store.watch(() => store.getters['file/current'].name, onChange);
}); });
// Store file creations and open the file
store.dispatch('data/setLastCreated', lastCreated);
store.commit('file/setCurrentId', file.id);
const onChange = cledit.Utils.debounce(() => {
const currentFile = store.getters['file/current'];
if (currentFile.id !== file.id) {
// Close editor if file has changed for some reason
this.close();
} else if (!this.closed && editorSvc.previewCtx.html != null) {
const content = store.getters['content/current'];
const properties = utils.computeProperties(content.properties);
window.parent.postMessage({
type: 'fileChange',
payload: {
id: file.id,
name: currentFile.name,
content: {
text: content.text.slice(0, -1), // Remove trailing LF
properties,
yamlProperties: content.properties,
html: editorSvc.previewCtx.html,
},
},
}, origin);
}
}, 25);
// Watch preview refresh and file name changes
editorSvc.$on('previewCtx', onChange);
store.watch(() => store.getters['file/current'].name, onChange);
}, },
}; };

View File

@ -16,7 +16,7 @@ export default {
promised[id] = true; promised[id] = true;
store.commit('userInfo/addItem', { id, name, imageUrl }); store.commit('userInfo/addItem', { id, name, imageUrl });
}, },
getInfo(userId) { async getInfo(userId) {
if (!promised[userId]) { if (!promised[userId]) {
const [type, sub] = parseUserId(userId); const [type, sub] = parseUserId(userId);
@ -33,27 +33,26 @@ export default {
if (!store.state.offline) { if (!store.state.offline) {
promised[userId] = true; promised[userId] = true;
switch (type) { switch (type) {
case 'github': { case 'github':
return githubHelper.getUser(sub) try {
.catch((err) => { await githubHelper.getUser(sub);
if (err.status !== 404) { } catch (err) {
promised[userId] = false; if (err.status !== 404) {
} promised[userId] = false;
}); }
} }
break;
case 'google': case 'google':
default: { default:
return googleHelper.getUser(sub) try {
.catch((err) => { await googleHelper.getUser(sub);
if (err.status !== 404) { } catch (err) {
promised[userId] = false; if (err.status !== 404) {
} promised[userId] = false;
}); }
} }
} }
} }
} }
return null;
}, },
}; };

View File

@ -224,6 +224,14 @@ export default {
}; };
return runWithNextValue(); return runWithNextValue();
}, },
someResult(values, func) {
let result;
values.some((value) => {
result = func(value);
return result;
});
return result;
},
parseQueryParams, parseQueryParams,
addQueryParams(url = '', params = {}, hash = false) { addQueryParams(url = '', params = {}, hash = false) {
const keys = Object.keys(params).filter(key => params[key] != null); const keys = Object.keys(params).filter(key => params[key] != null);

View File

@ -31,11 +31,11 @@ module.mutations = {
module.getters = { module.getters = {
...module.getters, ...module.getters,
current: (state, getters, rootState, rootGetters) => { current: ({ itemMap, revisionContent }, getters, rootState, rootGetters) => {
if (state.revisionContent) { if (revisionContent) {
return state.revisionContent; return revisionContent;
} }
return state.itemMap[`${rootGetters['file/current'].id}/content`] || empty(); return itemMap[`${rootGetters['file/current'].id}/content`] || empty();
}, },
currentChangeTrigger: (state, getters) => { currentChangeTrigger: (state, getters) => {
const { current } = getters; const { current } = getters;
@ -45,11 +45,9 @@ module.getters = {
current.hash, current.hash,
]); ]);
}, },
currentProperties: (state, getters) => utils.computeProperties(getters.current.properties), currentProperties: (state, { current }) => utils.computeProperties(current.properties),
isCurrentEditable: (state, getters, rootState, rootGetters) => isCurrentEditable: ({ revisionContent }, { current }, rootState, rootGetters) =>
!state.revisionContent && !revisionContent && current.id && rootGetters['layout/styles'].showEditor,
getters.current.id &&
rootGetters['layout/styles'].showEditor,
}; };
module.actions = { module.actions = {
@ -76,7 +74,7 @@ module.actions = {
}); });
} }
}, },
restoreRevision({ async restoreRevision({
state, state,
getters, getters,
commit, commit,
@ -84,31 +82,29 @@ module.actions = {
}) { }) {
const { revisionContent } = state; const { revisionContent } = state;
if (revisionContent) { if (revisionContent) {
dispatch('modal/fileRestoration', null, { root: true }) await dispatch('modal/fileRestoration', null, { root: true });
.then(() => { // Close revision
// Close revision commit('setRevisionContent');
commit('setRevisionContent'); const currentContent = utils.deepCopy(getters.current);
const currentContent = utils.deepCopy(getters.current); if (currentContent) {
if (currentContent) { // Restore text and move discussions
// Restore text and move discussions const diffs = diffMatchPatch
const diffs = diffMatchPatch .diff_main(currentContent.text, revisionContent.originalText);
.diff_main(currentContent.text, revisionContent.originalText); diffMatchPatch.diff_cleanupSemantic(diffs);
diffMatchPatch.diff_cleanupSemantic(diffs); Object.entries(currentContent.discussions).forEach(([, discussion]) => {
Object.entries(currentContent.discussions).forEach(([, discussion]) => { const adjustOffset = (offsetName) => {
const adjustOffset = (offsetName) => { const marker = new cledit.Marker(discussion[offsetName], offsetName === 'end');
const marker = new cledit.Marker(discussion[offsetName], offsetName === 'end'); marker.adjustOffset(diffs);
marker.adjustOffset(diffs); discussion[offsetName] = marker.offset;
discussion[offsetName] = marker.offset; };
}; adjustOffset('start');
adjustOffset('start'); adjustOffset('end');
adjustOffset('end');
});
dispatch('patchCurrent', {
...currentContent,
text: revisionContent.originalText,
});
}
}); });
dispatch('patchCurrent', {
...currentContent,
text: revisionContent.originalText,
});
}
} }
}, },
}; };

View File

@ -5,8 +5,8 @@ const module = moduleTemplate(empty, true);
module.getters = { module.getters = {
...module.getters, ...module.getters,
current: (state, getters, rootState, rootGetters) => current: ({ itemMap }, getters, rootState, rootGetters) =>
state.itemMap[`${rootGetters['file/current'].id}/contentState`] || empty(), itemMap[`${rootGetters['file/current'].id}/contentState`] || empty(),
}; };
module.actions = { module.actions = {

View File

@ -104,7 +104,7 @@ export default {
lsItemMap: {}, lsItemMap: {},
}, },
mutations: { mutations: {
setItem: (state, value) => { setItem: ({ itemMap, lsItemMap }, value) => {
// Create an empty item and override its data field // Create an empty item and override its data field
const emptyItem = empty(value.id); const emptyItem = empty(value.id);
const data = typeof value.data === 'object' const data = typeof value.data === 'object'
@ -118,19 +118,19 @@ export default {
}); });
// Store item in itemMap or lsItemMap if its stored in the localStorage // Store item in itemMap or lsItemMap if its stored in the localStorage
Vue.set(lsItemIdSet.has(item.id) ? state.lsItemMap : state.itemMap, item.id, item); Vue.set(lsItemIdSet.has(item.id) ? lsItemMap : itemMap, item.id, item);
}, },
deleteItem(state, id) { deleteItem({ itemMap }, id) {
// Only used by localDbSvc to clean itemMap from object moved to localStorage // Only used by localDbSvc to clean itemMap from object moved to localStorage
Vue.delete(state.itemMap, id); Vue.delete(itemMap, id);
}, },
}, },
getters: { getters: {
workspaces: getter('workspaces'), workspaces: getter('workspaces'),
sanitizedWorkspaces: (state, getters, rootState, rootGetters) => { sanitizedWorkspaces: (state, { workspaces }, rootState, rootGetters) => {
const sanitizedWorkspaces = {}; const sanitizedWorkspaces = {};
const mainWorkspaceToken = rootGetters['workspace/mainWorkspaceToken']; const mainWorkspaceToken = rootGetters['workspace/mainWorkspaceToken'];
Object.entries(getters.workspaces).forEach(([id, workspace]) => { Object.entries(workspaces).forEach(([id, workspace]) => {
const sanitizedWorkspace = { const sanitizedWorkspace = {
id, id,
providerId: mainWorkspaceToken && 'googleDriveAppData', providerId: mainWorkspaceToken && 'googleDriveAppData',
@ -146,9 +146,9 @@ export default {
return sanitizedWorkspaces; return sanitizedWorkspaces;
}, },
settings: getter('settings'), settings: getter('settings'),
computedSettings: (state, getters) => { computedSettings: (state, { settings }) => {
const customSettings = yaml.safeLoad(getters.settings); const customSettings = yaml.safeLoad(settings);
const settings = yaml.safeLoad(defaultSettings); const parsedSettings = yaml.safeLoad(defaultSettings);
const override = (obj, opt) => { const override = (obj, opt) => {
const objType = Object.prototype.toString.call(obj); const objType = Object.prototype.toString.call(obj);
const optType = Object.prototype.toString.call(opt); const optType = Object.prototype.toString.call(opt);
@ -166,44 +166,44 @@ export default {
}); });
return obj; return obj;
}; };
return override(settings, customSettings); return override(parsedSettings, customSettings);
}, },
localSettings: getter('localSettings'), localSettings: getter('localSettings'),
layoutSettings: getter('layoutSettings'), layoutSettings: getter('layoutSettings'),
templates: getter('templates'), templates: getter('templates'),
allTemplates: (state, getters) => ({ allTemplates: (state, { templates }) => ({
...getters.templates, ...templates,
...additionalTemplates, ...additionalTemplates,
}), }),
lastCreated: getter('lastCreated'), lastCreated: getter('lastCreated'),
lastOpened: getter('lastOpened'), lastOpened: getter('lastOpened'),
lastOpenedIds: (state, getters, rootState) => { lastOpenedIds: (state, { lastOpened }, rootState) => {
const lastOpened = { const result = {
...getters.lastOpened, ...lastOpened,
}; };
const currentFileId = rootState.file.currentId; const currentFileId = rootState.file.currentId;
if (currentFileId && !lastOpened[currentFileId]) { if (currentFileId && !result[currentFileId]) {
lastOpened[currentFileId] = Date.now(); result[currentFileId] = Date.now();
} }
return Object.keys(lastOpened) return Object.keys(result)
.filter(id => rootState.file.itemMap[id]) .filter(id => rootState.file.itemMap[id])
.sort((id1, id2) => lastOpened[id2] - lastOpened[id1]) .sort((id1, id2) => result[id2] - result[id1])
.slice(0, 20); .slice(0, 20);
}, },
syncData: getter('syncData'), syncData: getter('syncData'),
syncDataByItemId: (state, getters) => { syncDataByItemId: (state, { syncData }) => {
const result = {}; const result = {};
Object.entries(getters.syncData).forEach(([, value]) => { Object.entries(syncData).forEach(([, value]) => {
result[value.itemId] = value; result[value.itemId] = value;
}); });
return result; return result;
}, },
syncDataByType: (state, getters) => { syncDataByType: (state, { syncData }) => {
const result = {}; const result = {};
utils.types.forEach((type) => { utils.types.forEach((type) => {
result[type] = {}; result[type] = {};
}); });
Object.entries(getters.syncData).forEach(([, item]) => { Object.entries(syncData).forEach(([, item]) => {
if (result[item.type]) { if (result[item.type]) {
result[item.type][item.itemId] = item; result[item.type][item.itemId] = item;
} }
@ -212,12 +212,12 @@ export default {
}, },
dataSyncData: getter('dataSyncData'), dataSyncData: getter('dataSyncData'),
tokens: getter('tokens'), tokens: getter('tokens'),
googleTokens: (state, getters) => getters.tokens.google || {}, googleTokens: (state, { tokens }) => tokens.google || {},
couchdbTokens: (state, getters) => getters.tokens.couchdb || {}, couchdbTokens: (state, { tokens }) => tokens.couchdb || {},
dropboxTokens: (state, getters) => getters.tokens.dropbox || {}, dropboxTokens: (state, { tokens }) => tokens.dropbox || {},
githubTokens: (state, getters) => getters.tokens.github || {}, githubTokens: (state, { tokens }) => tokens.github || {},
wordpressTokens: (state, getters) => getters.tokens.wordpress || {}, wordpressTokens: (state, { tokens }) => tokens.wordpress || {},
zendeskTokens: (state, getters) => getters.tokens.zendesk || {}, zendeskTokens: (state, { tokens }) => tokens.zendesk || {},
}, },
actions: { actions: {
setWorkspaces: setter('workspaces'), setWorkspaces: setter('workspaces'),

View File

@ -59,8 +59,8 @@ export default {
}, },
}, },
getters: { getters: {
newDiscussion: state => newDiscussion: ({ currentDiscussionId, newDiscussionId, newDiscussion }) =>
state.currentDiscussionId === state.newDiscussionId && state.newDiscussion, currentDiscussionId === newDiscussionId && newDiscussion,
currentFileDiscussionLastComments: (state, getters, rootState, rootGetters) => { currentFileDiscussionLastComments: (state, getters, rootState, rootGetters) => {
const { discussions, comments } = rootGetters['content/current']; const { discussions, comments } = rootGetters['content/current'];
const discussionLastComments = {}; const discussionLastComments = {};
@ -74,14 +74,18 @@ export default {
}); });
return discussionLastComments; return discussionLastComments;
}, },
currentFileDiscussions: (state, getters, rootState, rootGetters) => { currentFileDiscussions: (
{ newDiscussionId },
{ newDiscussion, currentFileDiscussionLastComments },
rootState,
rootGetters,
) => {
const currentFileDiscussions = {}; const currentFileDiscussions = {};
const { newDiscussion } = getters;
if (newDiscussion) { if (newDiscussion) {
currentFileDiscussions[state.newDiscussionId] = newDiscussion; currentFileDiscussions[newDiscussionId] = newDiscussion;
} }
const { discussions } = rootGetters['content/current']; const { discussions } = rootGetters['content/current'];
Object.entries(getters.currentFileDiscussionLastComments) Object.entries(currentFileDiscussionLastComments)
.sort(([, lastComment1], [, lastComment2]) => .sort(([, lastComment1], [, lastComment2]) =>
lastComment1.created - lastComment2.created) lastComment1.created - lastComment2.created)
.forEach(([discussionId]) => { .forEach(([discussionId]) => {
@ -89,17 +93,22 @@ export default {
}); });
return currentFileDiscussions; return currentFileDiscussions;
}, },
currentDiscussion: (state, getters) => currentDiscussion: ({ currentDiscussionId }, { currentFileDiscussions }) =>
getters.currentFileDiscussions[state.currentDiscussionId], currentFileDiscussions[currentDiscussionId],
previousDiscussionId: idShifter(-1), previousDiscussionId: idShifter(-1),
nextDiscussionId: idShifter(1), nextDiscussionId: idShifter(1),
currentDiscussionComments: (state, getters, rootState, rootGetters) => { currentDiscussionComments: (
{ currentDiscussionId },
{ currentDiscussion },
rootState,
rootGetters,
) => {
const comments = {}; const comments = {};
if (getters.currentDiscussion) { if (currentDiscussion) {
const contentComments = rootGetters['content/current'].comments; const contentComments = rootGetters['content/current'].comments;
Object.entries(contentComments) Object.entries(contentComments)
.filter(([, comment]) => .filter(([, comment]) =>
comment.discussionId === state.currentDiscussionId) comment.discussionId === currentDiscussionId)
.sort(([, comment1], [, comment2]) => .sort(([, comment1], [, comment2]) =>
comment1.created - comment2.created) comment1.created - comment2.created)
.forEach(([commentId, comment]) => { .forEach(([commentId, comment]) => {
@ -108,10 +117,12 @@ export default {
} }
return comments; return comments;
}, },
currentDiscussionLastCommentId: (state, getters) => currentDiscussionLastCommentId: (state, { currentDiscussionComments }) =>
Object.keys(getters.currentDiscussionComments).pop(), Object.keys(currentDiscussionComments).pop(),
currentDiscussionLastComment: (state, getters) => currentDiscussionLastComment: (
getters.currentDiscussionComments[getters.currentDiscussionLastCommentId], state,
{ currentDiscussionComments, currentDiscussionLastCommentId },
) => currentDiscussionComments[currentDiscussionLastCommentId],
}, },
actions: { actions: {
cancelNewComment({ commit, getters }) { cancelNewComment({ commit, getters }) {
@ -120,15 +131,15 @@ export default {
commit('setCurrentDiscussionId', getters.nextDiscussionId); commit('setCurrentDiscussionId', getters.nextDiscussionId);
} }
}, },
createNewDiscussion({ commit, dispatch, rootGetters }, selection) { async createNewDiscussion({ commit, dispatch, rootGetters }, selection) {
const loginToken = rootGetters['workspace/loginToken']; const loginToken = rootGetters['workspace/loginToken'];
if (!loginToken) { if (!loginToken) {
dispatch('modal/signInForComment', { try {
onResolve: () => googleHelper.signin() await dispatch('modal/signInForComment', null, { root: true });
.then(() => syncSvc.requestSync()) await googleHelper.signin();
.then(() => dispatch('createNewDiscussion', selection)), syncSvc.requestSync();
}, { root: true }) await dispatch('createNewDiscussion', selection);
.catch(() => { /* Cancel */ }); } catch (e) { /* cancel */ }
} else if (selection) { } else if (selection) {
let text = rootGetters['content/current'].text.slice(selection.start, selection.end).trim(); let text = rootGetters['content/current'].text.slice(selection.start, selection.end).trim();
const maxLength = 80; const maxLength = 80;

View File

@ -44,11 +44,11 @@ const fakeFileNode = new Node(emptyFile());
fakeFileNode.item.id = 'fake'; fakeFileNode.item.id = 'fake';
fakeFileNode.noDrag = true; fakeFileNode.noDrag = true;
function getParent(node, getters) { function getParent({ item, isNil }, { nodeMap, rootNode }) {
if (node.isNil) { if (isNil) {
return nilFileNode; return nilFileNode;
} }
return getters.nodeMap[node.item.parentId] || getters.rootNode; return nodeMap[item.parentId] || rootNode;
} }
function getFolder(node, getters) { function getFolder(node, getters) {
@ -67,6 +67,21 @@ export default {
newChildNode: nilFileNode, newChildNode: nilFileNode,
openNodes: {}, openNodes: {},
}, },
mutations: {
setSelectedId: setter('selectedId'),
setEditingId: setter('editingId'),
setDragSourceId: setter('dragSourceId'),
setDragTargetId: setter('dragTargetId'),
setNewItem(state, item) {
state.newChildNode = item ? new Node(item, [], item.type === 'folder') : nilFileNode;
},
setNewItemName(state, name) {
state.newChildNode.item.name = name;
},
toggleOpenNode(state, id) {
Vue.set(state.openNodes, id, !state.openNodes[id]);
},
},
getters: { getters: {
nodeStructure: (state, getters, rootState, rootGetters) => { nodeStructure: (state, getters, rootState, rootGetters) => {
const rootNode = new Node(emptyFolder(), [], true, true); const rootNode = new Node(emptyFolder(), [], true, true);
@ -138,41 +153,26 @@ export default {
rootNode, rootNode,
}; };
}, },
nodeMap: (state, getters) => getters.nodeStructure.nodeMap, nodeMap: (state, { nodeStructure }) => nodeStructure.nodeMap,
rootNode: (state, getters) => getters.nodeStructure.rootNode, rootNode: (state, { nodeStructure }) => nodeStructure.rootNode,
newChildNodeParent: (state, getters) => getParent(state.newChildNode, getters), newChildNodeParent: (state, getters) => getParent(state.newChildNode, getters),
selectedNode: (state, getters) => getters.nodeMap[state.selectedId] || nilFileNode, selectedNode: ({ selectedId }, { nodeMap }) => nodeMap[selectedId] || nilFileNode,
selectedNodeFolder: (state, getters) => getFolder(getters.selectedNode, getters), selectedNodeFolder: (state, getters) => getFolder(getters.selectedNode, getters),
editingNode: (state, getters) => getters.nodeMap[state.editingId] || nilFileNode, editingNode: ({ editingId }, { nodeMap }) => nodeMap[editingId] || nilFileNode,
dragSourceNode: (state, getters) => getters.nodeMap[state.dragSourceId] || nilFileNode, dragSourceNode: ({ dragSourceId }, { nodeMap }) => nodeMap[dragSourceId] || nilFileNode,
dragTargetNode: (state, getters) => { dragTargetNode: ({ dragTargetId }, { nodeMap }) => {
if (state.dragTargetId === 'fake') { if (dragTargetId === 'fake') {
return fakeFileNode; return fakeFileNode;
} }
return getters.nodeMap[state.dragTargetId] || nilFileNode; return nodeMap[dragTargetId] || nilFileNode;
}, },
dragTargetNodeFolder: (state, getters) => { dragTargetNodeFolder: ({ dragTargetId }, getters) => {
if (state.dragTargetId === 'fake') { if (dragTargetId === 'fake') {
return getters.rootNode; return getters.rootNode;
} }
return getFolder(getters.dragTargetNode, getters); return getFolder(getters.dragTargetNode, getters);
}, },
}, },
mutations: {
setSelectedId: setter('selectedId'),
setEditingId: setter('editingId'),
setDragSourceId: setter('dragSourceId'),
setDragTargetId: setter('dragTargetId'),
setNewItem(state, item) {
state.newChildNode = item ? new Node(item, [], item.type === 'folder') : nilFileNode;
},
setNewItemName(state, name) {
state.newChildNode.item.name = name;
},
toggleOpenNode(state, id) {
Vue.set(state.openNodes, id, !state.openNodes[id]);
},
},
actions: { actions: {
openNode({ openNode({
state, state,

View File

@ -10,10 +10,10 @@ module.state = {
module.getters = { module.getters = {
...module.getters, ...module.getters,
current: state => state.itemMap[state.currentId] || empty(), current: ({ itemMap, currentId }) => itemMap[currentId] || empty(),
isCurrentTemp: (state, getters) => getters.current.parentId === 'temp', isCurrentTemp: (state, { current }) => current.parentId === 'temp',
lastOpened: (state, getters, rootState, rootGetters) => lastOpened: ({ itemMap }, { items }, rootState, rootGetters) =>
state.itemMap[rootGetters['data/lastOpenedIds'][0]] || getters.items[0] || empty(), itemMap[rootGetters['data/lastOpenedIds'][0]] || items[0] || empty(),
}; };
module.mutations = { module.mutations = {

View File

@ -54,13 +54,33 @@ const store = new Vuex.Store({
minuteCounter: 0, minuteCounter: 0,
monetizeSponsor: false, monetizeSponsor: false,
}, },
mutations: {
setLight: (state, value) => {
state.light = value;
},
setOffline: (state, value) => {
state.offline = value;
},
updateLastOfflineCheck: (state) => {
state.lastOfflineCheck = Date.now();
},
updateMinuteCounter: (state) => {
state.minuteCounter += 1;
},
setMonetizeSponsor: (state, value) => {
state.monetizeSponsor = value;
},
setGoogleSponsor: (state, value) => {
state.googleSponsor = value;
},
},
getters: { getters: {
allItemMap: (state) => { allItemMap: (state) => {
const result = {}; const result = {};
utils.types.forEach(type => Object.assign(result, state[type].itemMap)); utils.types.forEach(type => Object.assign(result, state[type].itemMap));
return result; return result;
}, },
itemPaths: (state) => { itemPaths: (state, getters) => {
const result = {}; const result = {};
const folderMap = state.folder.itemMap; const folderMap = state.folder.itemMap;
const getPath = (item) => { const getPath = (item) => {
@ -84,8 +104,10 @@ const store = new Vuex.Store({
result[item.id] = itemPath; result[item.id] = itemPath;
return itemPath; return itemPath;
}; };
[
[...state.folder.items, ...state.file.items].forEach(item => getPath(item)); ...getters['folder/items'],
...getters['file/items'],
].forEach(item => getPath(item));
return result; return result;
}, },
pathItems: (state, { allItemMap, itemPaths }) => { pathItems: (state, { allItemMap, itemPaths }) => {
@ -97,29 +119,9 @@ const store = new Vuex.Store({
}); });
return result; return result;
}, },
isSponsor: (state, getters) => { isSponsor: ({ light, monetizeSponsor }, getters) => {
const sponsorToken = getters['workspace/sponsorToken']; const sponsorToken = getters['workspace/sponsorToken'];
return state.light || state.monetizeSponsor || (sponsorToken && sponsorToken.isSponsor); return light || monetizeSponsor || (sponsorToken && sponsorToken.isSponsor);
},
},
mutations: {
setLight: (state, value) => {
state.light = value;
},
setOffline: (state, value) => {
state.offline = value;
},
updateLastOfflineCheck: (state) => {
state.lastOfflineCheck = Date.now();
},
updateMinuteCounter: (state) => {
state.minuteCounter += 1;
},
setMonetizeSponsor: (state, value) => {
state.monetizeSponsor = value;
},
setGoogleSponsor: (state, value) => {
state.googleSponsor = value;
}, },
}, },
actions: { actions: {

View File

@ -12,22 +12,22 @@ export default (empty) => {
module.getters = { module.getters = {
...module.getters, ...module.getters,
groupedByFileId: (state, getters) => { groupedByFileId: (state, { items }) => {
const groups = {}; const groups = {};
getters.items.forEach(item => addToGroup(groups, item)); items.forEach(item => addToGroup(groups, item));
return groups; return groups;
}, },
filteredGroupedByFileId: (state, getters) => { filteredGroupedByFileId: (state, { items }) => {
const groups = {}; const groups = {};
getters.items.filter((item) => { items.filter((item) => {
// Filter items that we can't use // Filter items that we can't use
const provider = providerRegistry.providers[item.providerId]; const provider = providerRegistry.providers[item.providerId];
return provider && provider.getToken(item); return provider && provider.getToken(item);
}).forEach(item => addToGroup(groups, item)); }).forEach(item => addToGroup(groups, item));
return groups; return groups;
}, },
current: (state, getters, rootState, rootGetters) => { current: (state, { filteredGroupedByFileId }, rootState, rootGetters) => {
const locations = getters.filteredGroupedByFileId[rootGetters['file/current'].id] || []; const locations = filteredGroupedByFileId[rootGetters['file/current'].id] || [];
return locations.map((location) => { return locations.map((location) => {
const provider = providerRegistry.providers[location.providerId]; const provider = providerRegistry.providers[location.providerId];
return { return {

View File

@ -13,39 +13,28 @@ export default {
}, },
}, },
getters: { getters: {
config: state => !state.hidden && state.stack[0], config: ({ hidden, stack }) => !hidden && stack[0],
}, },
actions: { actions: {
open({ commit, state }, param) { async open({ commit, state }, param) {
return new Promise((resolve, reject) => { const config = typeof param === 'object' ? { ...param } : { type: param };
const config = typeof param === 'object' ? { ...param } : { type: param }; try {
const clean = () => commit('setStack', state.stack.filter((otherConfig => otherConfig !== config))); return await new Promise((resolve, reject) => {
config.resolve = (result) => { config.resolve = resolve;
clean(); config.reject = reject;
if (config.onResolve) { commit('setStack', [config, ...state.stack]);
// Call onResolve immediately (mostly to prevent browsers from blocking popup windows) });
config.onResolve(result) } finally {
.then(res => resolve(res)); commit('setStack', state.stack.filter((otherConfig => otherConfig !== config)));
} else { }
resolve(result);
}
};
config.reject = (error) => {
clean();
reject(error);
};
commit('setStack', [config, ...state.stack]);
});
}, },
hideUntil({ commit }, promise) { async hideUntil({ commit }, promise) {
commit('setHidden', true); try {
return promise.then((res) => { commit('setHidden', true);
return await promise;
} finally {
commit('setHidden', false); commit('setHidden', false);
return res; }
}, (err) => {
commit('setHidden', false);
throw err;
});
}, },
folderDeletion: ({ dispatch }, item) => dispatch('open', { folderDeletion: ({ dispatch }, item) => dispatch('open', {
content: `<p>You are about to delete the folder <b>${item.name}</b>. Its files will be moved to Trash. Are you sure?</p>`, content: `<p>You are about to delete the folder <b>${item.name}</b>. Its files will be moved to Trash. Are you sure?</p>`,
@ -105,39 +94,34 @@ export default {
resolveText: 'Yes, clean', resolveText: 'Yes, clean',
rejectText: 'No', rejectText: 'No',
}), }),
providerRedirection: ({ dispatch }, { providerName, onResolve }) => dispatch('open', { providerRedirection: ({ dispatch }, { providerName }) => dispatch('open', {
content: `<p>You are about to navigate to the <b>${providerName}</b> authorization page.</p>`, content: `<p>You are about to navigate to the <b>${providerName}</b> authorization page.</p>`,
resolveText: 'Ok, go on', resolveText: 'Ok, go on',
rejectText: 'Cancel', rejectText: 'Cancel',
onResolve,
}), }),
workspaceGoogleRedirection: ({ dispatch }, { onResolve }) => dispatch('open', { workspaceGoogleRedirection: ({ dispatch }) => dispatch('open', {
content: '<p>StackEdit needs full Google Drive access to open this workspace.</p>', content: '<p>StackEdit needs full Google Drive access to open this workspace.</p>',
resolveText: 'Ok, grant', resolveText: 'Ok, grant',
rejectText: 'Cancel', rejectText: 'Cancel',
onResolve,
}), }),
signInForSponsorship: ({ dispatch }, { onResolve }) => dispatch('open', { signInForSponsorship: ({ dispatch }) => dispatch('open', {
type: 'signInForSponsorship', type: 'signInForSponsorship',
content: `<p>You have to sign in with Google to sponsor.</p> content: `<p>You have to sign in with Google to sponsor.</p>
<div class="modal__info"><b>Note:</b> This will sync your main workspace.</div>`, <div class="modal__info"><b>Note:</b> This will sync your main workspace.</div>`,
resolveText: 'Ok, sign in', resolveText: 'Ok, sign in',
rejectText: 'Cancel', rejectText: 'Cancel',
onResolve,
}), }),
signInForComment: ({ dispatch }, { onResolve }) => dispatch('open', { signInForComment: ({ dispatch }) => dispatch('open', {
content: `<p>You have to sign in with Google to start commenting.</p> content: `<p>You have to sign in with Google to start commenting.</p>
<div class="modal__info"><b>Note:</b> This will sync your main workspace.</div>`, <div class="modal__info"><b>Note:</b> This will sync your main workspace.</div>`,
resolveText: 'Ok, sign in', resolveText: 'Ok, sign in',
rejectText: 'Cancel', rejectText: 'Cancel',
onResolve,
}), }),
signInForHistory: ({ dispatch }, { onResolve }) => dispatch('open', { signInForHistory: ({ dispatch }) => dispatch('open', {
content: `<p>You have to sign in with Google to enable revision history.</p> content: `<p>You have to sign in with Google to enable revision history.</p>
<div class="modal__info"><b>Note:</b> This will sync your main workspace.</div>`, <div class="modal__info"><b>Note:</b> This will sync your main workspace.</div>`,
resolveText: 'Ok, sign in', resolveText: 'Ok, sign in',
rejectText: 'Cancel', rejectText: 'Cancel',
onResolve,
}), }),
sponsorOnly: ({ dispatch }) => dispatch('open', { sponsorOnly: ({ dispatch }) => dispatch('open', {
content: '<p>This feature is restricted to sponsors as it relies on server resources.</p>', content: '<p>This feature is restricted to sponsors as it relies on server resources.</p>',

View File

@ -11,7 +11,7 @@ export default (empty, simpleHash = false) => {
itemMap: {}, itemMap: {},
}, },
getters: { getters: {
items: state => Object.values(state.itemMap), items: ({ itemMap }) => Object.values(itemMap),
}, },
mutations: { mutations: {
setItem(state, value) { setItem(state, value) {

View File

@ -71,16 +71,13 @@ export default {
})); }));
} }
}, },
doWithLocation({ commit }, { location, promise }) { async doWithLocation({ commit }, { location, action }) {
commit('setCurrentLocation', location); try {
return promise commit('setCurrentLocation', location);
.then((res) => { return await action();
commit('setCurrentLocation', {}); } finally {
return res; commit('setCurrentLocation', {});
}, (err) => { }
commit('setCurrentLocation', {});
throw err;
});
}, },
}, },
}; };

View File

@ -5,8 +5,8 @@ const module = moduleTemplate(empty, true);
module.getters = { module.getters = {
...module.getters, ...module.getters,
current: (state, getters, rootState, rootGetters) => current: ({ itemMap }, getters, rootState, rootGetters) =>
state.itemMap[`${rootGetters['file/current'].id}/syncedContent`] || empty(), itemMap[`${rootGetters['file/current'].id}/syncedContent`] || empty(),
}; };
export default module; export default module;

View File

@ -6,8 +6,8 @@ export default {
itemMap: {}, itemMap: {},
}, },
mutations: { mutations: {
addItem: (state, item) => { addItem: ({ itemMap }, item) => {
Vue.set(state.itemMap, item.id, item); Vue.set(itemMap, item.id, item);
}, },
}, },
}; };

View File

@ -19,54 +19,50 @@ export default {
const workspaces = rootGetters['data/sanitizedWorkspaces']; const workspaces = rootGetters['data/sanitizedWorkspaces'];
return workspaces.main; return workspaces.main;
}, },
currentWorkspace: (state, getters, rootState, rootGetters) => { currentWorkspace: ({ currentWorkspaceId }, { mainWorkspace }, rootState, rootGetters) => {
const workspaces = rootGetters['data/sanitizedWorkspaces']; const workspaces = rootGetters['data/sanitizedWorkspaces'];
return workspaces[state.currentWorkspaceId] || getters.mainWorkspace; return workspaces[currentWorkspaceId] || mainWorkspace;
}, },
hasUniquePaths: (state, getters) => { hasUniquePaths: (state, { currentWorkspace }) =>
const workspace = getters.currentWorkspace; currentWorkspace.providerId === 'githubWorkspace',
return workspace.providerId === 'githubWorkspace'; lastSyncActivityKey: (state, { currentWorkspace }) => `${currentWorkspace.id}/lastSyncActivity`,
}, lastFocusKey: (state, { currentWorkspace }) => `${currentWorkspace.id}/lastWindowFocus`,
lastSyncActivityKey: (state, getters) => `${getters.currentWorkspace.id}/lastSyncActivity`,
lastFocusKey: (state, getters) => `${getters.currentWorkspace.id}/lastWindowFocus`,
mainWorkspaceToken: (state, getters, rootState, rootGetters) => { mainWorkspaceToken: (state, getters, rootState, rootGetters) => {
const googleTokens = rootGetters['data/googleTokens']; const googleTokens = rootGetters['data/googleTokens'];
const loginSubs = Object.keys(googleTokens) const loginSubs = Object.keys(googleTokens)
.filter(sub => googleTokens[sub].isLogin); .filter(sub => googleTokens[sub].isLogin);
return googleTokens[loginSubs[0]]; return googleTokens[loginSubs[0]];
}, },
syncToken: (state, getters, rootState, rootGetters) => { syncToken: (state, { currentWorkspace, mainWorkspaceToken }, rootState, rootGetters) => {
const workspace = getters.currentWorkspace; switch (currentWorkspace.providerId) {
switch (workspace.providerId) {
case 'googleDriveWorkspace': { case 'googleDriveWorkspace': {
const googleTokens = rootGetters['data/googleTokens']; const googleTokens = rootGetters['data/googleTokens'];
return googleTokens[workspace.sub]; return googleTokens[currentWorkspace.sub];
} }
case 'githubWorkspace': { case 'githubWorkspace': {
const githubTokens = rootGetters['data/githubTokens']; const githubTokens = rootGetters['data/githubTokens'];
return githubTokens[workspace.sub]; return githubTokens[currentWorkspace.sub];
} }
case 'couchdbWorkspace': { case 'couchdbWorkspace': {
const couchdbTokens = rootGetters['data/couchdbTokens']; const couchdbTokens = rootGetters['data/couchdbTokens'];
return couchdbTokens[workspace.id]; return couchdbTokens[currentWorkspace.id];
} }
default: default:
return getters.mainWorkspaceToken; return mainWorkspaceToken;
} }
}, },
loginToken: (state, getters, rootState, rootGetters) => { loginToken: (state, { currentWorkspace, mainWorkspaceToken }, rootState, rootGetters) => {
const workspace = getters.currentWorkspace; switch (currentWorkspace.providerId) {
switch (workspace.providerId) {
case 'googleDriveWorkspace': { case 'googleDriveWorkspace': {
const googleTokens = rootGetters['data/googleTokens']; const googleTokens = rootGetters['data/googleTokens'];
return googleTokens[workspace.sub]; return googleTokens[currentWorkspace.sub];
} }
case 'githubWorkspace': { case 'githubWorkspace': {
const githubTokens = rootGetters['data/githubTokens']; const githubTokens = rootGetters['data/githubTokens'];
return githubTokens[workspace.sub]; return githubTokens[currentWorkspace.sub];
} }
default: default:
return getters.mainWorkspaceToken; return mainWorkspaceToken;
} }
}, },
userId: (state, { loginToken }, rootState, rootGetters) => { userId: (state, { loginToken }, rootState, rootGetters) => {
@ -82,7 +78,7 @@ export default {
}); });
return prefix ? `${prefix}:${loginToken.sub}` : loginToken.sub; return prefix ? `${prefix}:${loginToken.sub}` : loginToken.sub;
}, },
sponsorToken: (state, getters) => getters.mainWorkspaceToken, sponsorToken: (state, { mainWorkspaceToken }) => mainWorkspaceToken,
}, },
actions: { actions: {
setCurrentWorkspaceId: ({ commit, getters }, value) => { setCurrentWorkspaceId: ({ commit, getters }, value) => {