Ghost/core/server/update-check.js

254 lines
9.5 KiB
JavaScript
Raw Normal View History

// # Update Checking Service
//
// Makes a request to Ghost.org to check if there is a new version of Ghost available.
// The service is provided in return for users opting in to anonymous usage data collection.
//
// Blog owners can opt-out of update checks by setting `privacy: { useUpdateCheck: false }` in their config.js
//
// The data collected is as follows:
//
// - blog id - a hash of the blog hostname, pathname and dbHash. No identifiable info is stored.
// - ghost version
// - node version
// - npm version
// - env - production or development
// - database type - SQLite, MySQL
// - email transport - mail.options.service, or otherwise mail.transport
// - created date - database creation date
// - post count - total number of posts
// - user count - total number of users
// - theme - name of the currently active theme
2014-01-21 12:45:27 +04:00
// - apps - names of any active apps
var crypto = require('crypto'),
exec = require('child_process').exec,
https = require('https'),
moment = require('moment'),
semver = require('semver'),
Promise = require('bluebird'),
2014-02-05 12:40:30 +04:00
_ = require('lodash'),
url = require('url'),
api = require('./api'),
config = require('./config'),
utils = require('./utils'),
logging = require('./logging'),
errors = require('./errors'),
i18n = require('./i18n'),
currentVersion = require('./utils/ghost-version').full,
internal = {context: {internal: true}},
checkEndpoint = 'updates.ghost.org';
function updateCheckError(err) {
err = errors.utils.deserialize(err);
api.settings.edit(
{settings: [{key: 'nextUpdateCheck', value: Math.round(Date.now() / 1000 + 24 * 3600)}]},
internal
);
err.context = i18n.t('errors.update-check.checkingForUpdatesFailed.error');
err.help = i18n.t('errors.update-check.checkingForUpdatesFailed.help', {url: 'http://support.ghost.org'});
logging.error(err);
}
/**
* If the custom message is intended for current version, create and store a custom notification.
* @param {Object} message {id: uuid, version: '0.9.x', content: '' }
* @return {*|Promise}
*/
function createCustomNotification(message) {
if (!semver.satisfies(currentVersion, message.version)) {
return Promise.resolve();
}
var notification = {
status: 'alert',
type: 'info',
custom: true,
uuid: message.id,
dismissible: true,
message: message.content
},
getAllNotifications = api.notifications.browse({context: {internal: true}}),
getSeenNotifications = api.settings.read(_.extend({key: 'seenNotifications'}, internal));
return Promise.join(getAllNotifications, getSeenNotifications, function joined(all, seen) {
✨ replace auto increment id's by object id (#7495) * 🛠 bookshelf tarball, bson-objectid * 🎨 schema changes - change increment type to string - add a default fallback for string length 191 (to avoid adding this logic to every single column which uses an ID) - remove uuid, because ID now represents a global resource identifier - keep uuid for post, because we are using this as preview id - keep uuid for clients for now - we are using this param for Ghost-Auth * ✨ base model: generate ObjectId on creating event - each new resource get's a auto generate ObjectId - this logic won't work for attached models, this commit comes later * 🎨 centralised attach method When attaching models there are two things important two know 1. To be able to attach an ObjectId, we need to register the `onCreating` event the fetched model!This is caused by the Bookshelf design in general. On this target model we are attaching the new model. 2. We need to manually fetch the target model, because Bookshelf has a weird behaviour (which is known as a bug, see see https://github.com/tgriesser/bookshelf/issues/629). The most important property when attaching a model is `parentFk`, which is the foreign key. This can be null when fetching the model with the option `withRelated`. To ensure quality and consistency, the custom attach wrapper always fetches the target model manual. By fetching the target model (again) is a little performance decrease, but it also has advantages: we can register the event, and directly unregister the event again. So very clean code. Important: please only use the custom attach wrapper in the future. * 🎨 token model had overriden the onCreating function because of the created_at field - we need to ensure that the base onCreating hook get's triggered for ALL models - if not, they don't get an ObjectId assigned - in this case: be smart and check if the target model has a created_at field * 🎨 we don't have a uuid field anymore, remove the usages - no default uuid creation in models - i am pretty sure we have some more definitions in our tests (for example in the export json files), but that is too much work to delete them all * 🎨 do not parse ID to Number - we had various occurances of parsing all ID's to numbers - we don't need this behaviour anymore - ID is string - i will adapt the ID validation in the next commit * 🎨 change ID regex for validation - we only allow: ID as ObjectId, ID as 1 and ID as me - we need to keep ID 1, because our whole software relies on ID 1 (permissions etc) * 🎨 owner fixture - roles: [4] does not work anymore - 4 means -> static id 4 - this worked in an auto increment system (not even in a system with distributed writes) - with ObjectId we generate each ID automatically (for static and dynamic resources) - it is possible to define all id's for static resources still, but that means we need to know which ID is already used and for consistency we have to define ObjectId's for these static resources - so no static id's anymore, except of: id 1 for owner and id 0 for external usage (because this is required from our permission system) - NOTE: please read through the comment in the user model * 🎨 tests: DataGenerator and test utils First of all: we need to ensure using ObjectId's in the tests. When don't, we can't ensure that ObjectId's work properly. This commit brings lot's of dynamic into all the static defined id's. In one of the next commits, i will adapt all the tests. * 🚨 remove counter in Notification API - no need to add a counter - we simply generate ObjectId's (they are auto incremental as well) - our id validator does only allow ObjectId as id,1 and me * 🎨 extend contextUser in Base Model - remove isNumber check, because id's are no longer numbers, except of id 0/1 - use existing isExternalUser - support id 0/1 as string or number * ✨ Ghost Owner has id 1 - ensure we define this id in the fixtures.json - doesn't matter if number or string * 🎨 functional tests adaptions - use dynamic id's * 🎨 fix unit tests * 🎨 integration tests adaptions * 🎨 change importer utils - all our export examples (test/fixtures/exports) contain id's as numbers - fact: but we ignore them anyway when inserting into the database, see https://github.com/TryGhost/Ghost/blob/master/core/server/data/import/utils.js#L249 - in https://github.com/TryGhost/Ghost/pull/7495/commits/0e6ed957cd54dc02a25cf6fb1ab7d7e723295e2c#diff-70f514a06347c048648be464819503c4L67 i removed parsing id's to integers - i realised that this ^ check just existed, because the userIdToMap was an object key and object keys are always strings! - i think this logic is a little bit complicated, but i don't want to refactor this now - this commit ensures when trying to find the user, the id comparison works again - i've added more documentation to understand this logic ;) - plus i renamed an attribute to improve readability * 🎨 Data-Generator: add more defaults to createUser - if i use the function DataGenerator.forKnex.createUser i would like to get a full set of defaults * 🎨 test utils: change/extend function set for functional tests - functional tests work a bit different - they boot Ghost and seed the database - some functional tests have mis-used the test setup - the test setup needs two sections: integration/unit and functional tests - any functional test is allowed to either add more data or change data in the existing Ghost db - but what it should not do is: add test fixtures like roles or users from our DataGenerator and cross fingers it will work - this commit adds a clean method for functional tests to add extra users * 🎨 functional tests adaptions - use last commit to insert users for functional tests clean - tidy up usage of testUtils.setup or testUtils.doAuth * 🐛 test utils: reset database before init - ensure we don't have any left data from other tests in the database when starting ghost * 🐛 fix test (unrelated to this PR) - fixes a random failure - return statement was missing * 🎨 make changes for invites
2016-11-17 12:09:11 +03:00
var isSeen = _.includes(JSON.parse(seen.settings[0].value || []), notification.id),
isDuplicate = _.some(all.notifications, {message: notification.message});
if (!isSeen && !isDuplicate) {
return api.notifications.add({notifications: [notification]}, {context: {internal: true}});
}
});
}
function updateCheckData() {
var data = {},
mailConfig = config.get('mail');
data.ghost_version = currentVersion;
data.node_version = process.versions.node;
data.env = config.get('env');
data.database_type = config.get('database').client;
data.email_transport = mailConfig &&
(mailConfig.options && mailConfig.options.service ?
mailConfig.options.service :
mailConfig.transport);
return Promise.props({
hash: api.settings.read(_.extend({key: 'dbHash'}, internal)).reflect(),
theme: api.settings.read(_.extend({key: 'activeTheme'}, internal)).reflect(),
apps: api.settings.read(_.extend({key: 'activeApps'}, internal))
.then(function (response) {
var apps = response.settings[0];
apps = JSON.parse(apps.value);
return _.reduce(apps, function (memo, item) { return memo === '' ? memo + item : memo + ', ' + item; }, '');
}).reflect(),
posts: api.posts.browse().reflect(),
users: api.users.browse(internal).reflect(),
npm: Promise.promisify(exec)('npm -v').reflect()
}).then(function (descriptors) {
var hash = descriptors.hash.value().settings[0],
theme = descriptors.theme.value().settings[0],
apps = descriptors.apps.value(),
posts = descriptors.posts.value(),
users = descriptors.users.value(),
npm = descriptors.npm.value(),
blogUrl = url.parse(utils.url.urlFor('home', true)),
blogId = blogUrl.hostname + blogUrl.pathname.replace(/\//, '') + hash.value;
data.blog_id = crypto.createHash('md5').update(blogId).digest('hex');
data.theme = theme ? theme.value : '';
data.apps = apps || '';
data.post_count = posts && posts.meta && posts.meta.pagination ? posts.meta.pagination.total : 0;
data.user_count = users && users.users && users.users.length ? users.users.length : 0;
data.blog_created_at = users && users.users && users.users[0] && users.users[0].created_at ? moment(users.users[0].created_at).unix() : '';
data.npm_version = npm.trim();
data.lts = false;
return data;
}).catch(updateCheckError);
}
function updateCheckRequest() {
return updateCheckData().then(function then(reqData) {
var resData = '',
headers,
req;
reqData = JSON.stringify(reqData);
headers = {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(reqData)
};
return new Promise(function p(resolve, reject) {
req = https.request({
hostname: checkEndpoint,
method: 'POST',
headers: headers
}, function handler(res) {
res.on('error', function onError(error) { reject(error); });
res.on('data', function onData(chunk) { resData += chunk; });
res.on('end', function onEnd() {
try {
resData = JSON.parse(resData);
if (this.statusCode >= 400) {
return reject(resData);
}
resolve(resData);
} catch (e) {
reject(i18n.t('errors.update-check.unableToDecodeUpdateResponse.error'));
}
});
});
req.on('socket', function onSocket(socket) {
// Wait a maximum of 10seconds
socket.setTimeout(10000);
socket.on('timeout', function onTimeout() {
req.abort();
});
});
req.on('error', function onError(error) {
reject(error);
});
req.write(reqData);
req.end();
});
});
}
/**
* Handles the response from the update check
* Does three things with the information received:
* 1. Updates the time we can next make a check
* 2. Checks if the version in the response is new, and updates the notification setting
* 3. Create custom notifications is response from UpdateCheck as "messages" array which has the following structure:
*
* "messages": [{
* "id": ed9dc38c-73e5-4d72-a741-22b11f6e151a,
* "version": "0.5.x",
* "content": "<p>Hey there! 0.6 is available, visit <a href=\"https://ghost.org/download\">Ghost.org</a> to grab your copy now<!/p>"
* ]}
*
* @param {Object} response
* @return {Promise}
*/
function updateCheckResponse(response) {
return Promise.all([
api.settings.edit({settings: [{key: 'nextUpdateCheck', value: response.next_check}]}, internal),
api.settings.edit({settings: [{key: 'displayUpdateNotification', value: response.version}]}, internal)
]).then(function () {
var messages = response.messages || [];
/**
* by default the update check service returns messages: []
* but the latest release version get's stored anyway, because we adding the `displayUpdateNotification` ^
*/
return Promise.map(messages, createCustomNotification);
});
}
function updateCheck() {
if (config.isPrivacyDisabled('useUpdateCheck')) {
return Promise.resolve();
} else {
return api.settings.read(_.extend({key: 'nextUpdateCheck'}, internal)).then(function then(result) {
var nextUpdateCheck = result.settings[0];
if (nextUpdateCheck && nextUpdateCheck.value && nextUpdateCheck.value > moment().unix()) {
// It's not time to check yet
return;
} else {
// We need to do a check
return updateCheckRequest()
.then(updateCheckResponse)
.catch(updateCheckError);
}
}).catch(updateCheckError);
}
}
function showUpdateNotification() {
return api.settings.read(_.extend({key: 'displayUpdateNotification'}, internal)).then(function then(response) {
var display = response.settings[0];
if (display && display.value && currentVersion && semver.gt(display.value, currentVersion)) {
return display.value;
}
return false;
});
}
module.exports = updateCheck;
module.exports.showUpdateNotification = showUpdateNotification;