Ghost/core/server/api/themes.js
Katharina Irrgang 817b8d09ca 😱 🎨 Refactor storage adapter (#8229)
refs #7687

There are four main changes in this PR:

we have outsourced the base storage adapter to npm, because for storage developers it's annoying to inherit from a script within Ghost
we hacked theme storage handling into the default local storage adapter - this was reverted, instead we have added a static theme storage here
use classes instead of prototyping
optimise the storage adapter in general - everything is explained in each commit

----

* rename local-file-store to LocalFileStorage

I would like to keep the name pattern i have used for scheduling.
If a file is a class, the file name reflects the class name.
We can discuss this, if concerns are raised.

* Transform LocalFileStorage to class and inherit from new base

- inherit from npm ghost-storage-base
- rewrite to class
- no further refactoring, happens later

* Rename core/test/unit/storage/local-file-store_spec.js -> core/test/unit/storage/LocalFileStorage_spec.js

* Fix wrong require in core/test/unit/storage/LocalFileStorage_spec.js

* remove base storage and test

- see https://github.com/kirrg001/Ghost-Storage-Base
- the test has moved to this repo as well

* Use npm ghost-storage-base in storage/index.js

* remove the concept of getStorage('themes')

This concept was added when we added themes as a feature.
Back then, we have changed the local storage adapter to support images and themes.
This has added some hacks into the local storage adapters.
We want to revert this change and add a simple static theme storage.

Will adapt the api/themes layer in the next commits.

* Revert LocalFileStorage

- revert serve
- revert delete

* add storagePath as property to LocalFileStorage

- define one property which holds the storage path
- could be considered to pass from outside, but found that not helpful, as other storage adapters do not need this property
- IMPORTANT: save has no longer a targetDir option, because this was used to pass the alternative theme storage path
- IMPORTANT: exists has now an alternative targetDir, this makes sense, because
  - you can either ask the storage exists('my-file') and it will look in the base storage path
  - or you pass a specific path where to look exists('my-file', /path/to/dir)

* LocalFileStorage: get rid of store pattern

- getUniqueFileName(THIS)
- this doesn't make sense, instances always have access to this by default

* Add static theme storage

- inherits from the local file storage, because they both operate on the file system
- IMPORTANT: added a TODO to consider a merge of themes/loader and themes/storage
- but will be definitely not part of this PR

* Use new static theme storage in api/themes

- storage functions are simplified!

* Add https://github.com/kirrg001/Ghost-Storage-Base as dependency

- tarball for now, as i am still testing
- will release if PR review get's accepted

* Adapt tests and jscs/jshint

* 🐛  fix storage.read in favicon utility

- wrong implementation of error handling

* 🎨  optimise error messages for custom storage adapter errors

* little renaming in the storage utlity

- purpose is to have access to the custom storage instance and to the custom storage class
- see next commit why

* optimise instanceof base storage

- instanceof is always tricky in javascript
- if multiple modules exist, it can happen that instanceof is false

* fix getTargetDir

- the importer uses the `targetDir` option to ensure that images land in the correct folder

* ghost-storage-base@0.0.1 package.json dependency
2017-04-05 15:10:34 +01:00

219 lines
7.8 KiB
JavaScript

// # Themes API
// RESTful API for Themes
var debug = require('debug')('ghost:api:themes'),
Promise = require('bluebird'),
fs = require('fs-extra'),
errors = require('../errors'),
events = require('../events'),
logging = require('../logging'),
apiUtils = require('./utils'),
i18n = require('../i18n'),
settingsModel = require('../models/settings').Settings,
settingsCache = require('../settings/cache'),
themeUtils = require('../themes'),
themeList = themeUtils.list,
themes;
/**
* ## Themes API Methods
*
* **See:** [API Methods](index.js.html#api%20methods)
*/
themes = {
browse: function browse(options) {
return apiUtils
// Permissions
.handlePermissions('themes', 'browse')(options)
// Main action
.then(function makeApiResult() {
// Return JSON result
return themeUtils.toJSON();
});
},
activate: function activate(options) {
var themeName = options.name,
newSettings = [{
key: 'activeTheme',
value: themeName
}],
loadedTheme,
checkedTheme;
return apiUtils
// Permissions
.handlePermissions('themes', 'activate')(options)
// Validation
.then(function validateTheme() {
loadedTheme = themeList.get(themeName);
if (!loadedTheme) {
return Promise.reject(new errors.ValidationError({
message: i18n.t('notices.data.validation.index.themeCannotBeActivated', {themeName: themeName}),
context: 'activeTheme'
}));
}
return themeUtils.validate.check(loadedTheme);
})
// Update setting
.then(function changeActiveThemeSetting(_checkedTheme) {
checkedTheme = _checkedTheme;
// We use the model, not the API here, as we don't want to trigger permissions
return settingsModel.edit(newSettings, options);
})
// Call activate
.then(function hasEditedSetting() {
// Activate! (sort of)
debug('Activating theme (method B on API "activate")', themeName);
themeUtils.activate(loadedTheme, checkedTheme);
// Return JSON result
return themeUtils.toJSON(themeName, checkedTheme);
});
},
upload: function upload(options) {
options = options || {};
// consistent filename uploads
options.originalname = options.originalname.toLowerCase();
var zip = {
path: options.path,
name: options.originalname,
shortName: themeUtils.storage.getSanitizedFileName(options.originalname.split('.zip')[0])
},
checkedTheme;
// check if zip name is casper.zip
if (zip.name === 'casper.zip') {
throw new errors.ValidationError({message: i18n.t('errors.api.themes.overrideCasper')});
}
return apiUtils
// Permissions
.handlePermissions('themes', 'add')(options)
// Validation
.then(function validateTheme() {
return themeUtils.validate.check(zip, true);
})
// More validation (existence check)
.then(function checkExists(_checkedTheme) {
checkedTheme = _checkedTheme;
return themeUtils.storage.exists(zip.shortName);
})
// If the theme existed we need to delete it
.then(function removeOldTheme(themeExists) {
// delete existing theme
if (themeExists) {
return themeUtils.storage.delete(zip.shortName);
}
})
.then(function storeNewTheme() {
events.emit('theme.uploaded', zip.shortName);
// store extracted theme
return themeUtils.storage.save({
name: zip.shortName,
path: checkedTheme.path
});
})
.then(function loadNewTheme() {
// Loads the theme from the filesystem
// Sets the theme on the themeList
return themeUtils.loadOne(zip.shortName);
})
.then(function activateAndReturn(loadedTheme) {
// If this is the active theme, we are overriding
// This is a special case of activation
if (zip.shortName === settingsCache.get('activeTheme')) {
// Activate! (sort of)
debug('Activating theme (method C, on API "override")', zip.shortName);
themeUtils.activate(loadedTheme, checkedTheme);
}
// @TODO: unify the name across gscan and Ghost!
return themeUtils.toJSON(zip.shortName, checkedTheme);
})
.finally(function () {
// @TODO we should probably do this as part of saving the theme
// remove zip upload from multer
// happens in background
Promise.promisify(fs.removeSync)(zip.path)
.catch(function (err) {
logging.error(new errors.GhostError({err: err}));
});
// @TODO we should probably do this as part of saving the theme
// remove extracted dir from gscan
// happens in background
if (checkedTheme) {
Promise.promisify(fs.removeSync)(checkedTheme.path)
.catch(function (err) {
logging.error(new errors.GhostError({err: err}));
});
}
});
},
download: function download(options) {
var themeName = options.name,
theme = themeList.get(themeName);
if (!theme) {
return Promise.reject(new errors.BadRequestError({message: i18n.t('errors.api.themes.invalidRequest')}));
}
return apiUtils
// Permissions
.handlePermissions('themes', 'read')(options)
.then(function sendTheme() {
events.emit('theme.downloaded', themeName);
return themeUtils.storage.serve({
name: themeName
});
});
},
/**
* remove theme zip
* remove theme folder
*/
destroy: function destroy(options) {
var themeName = options.name,
theme;
return apiUtils
// Permissions
.handlePermissions('themes', 'destroy')(options)
// Validation
.then(function validateTheme() {
if (themeName === 'casper') {
throw new errors.ValidationError({message: i18n.t('errors.api.themes.destroyCasper')});
}
if (themeName === settingsCache.get('activeTheme')) {
throw new errors.ValidationError({message: i18n.t('errors.api.themes.destroyActive')});
}
theme = themeList.get(themeName);
if (!theme) {
throw new errors.NotFoundError({message: i18n.t('errors.api.themes.themeDoesNotExist')});
}
// Actually do the deletion here
return themeUtils.storage.delete(themeName);
})
// And some extra stuff to maintain state here
.then(function deleteTheme() {
themeList.del(themeName);
events.emit('theme.deleted', themeName);
// Delete returns an empty 204 response
});
}
};
module.exports = themes;