ghost 4.13.0 → 4.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/content/themes/casper/assets/built/screen.css +1 -1
  2. package/content/themes/casper/assets/built/screen.css.map +1 -1
  3. package/content/themes/casper/assets/css/screen.css +1 -1
  4. package/content/themes/casper/default.hbs +2 -2
  5. package/content/themes/casper/package.json +1 -1
  6. package/content/themes/casper/page.hbs +28 -26
  7. package/content/themes/casper/partials/post-card.hbs +2 -2
  8. package/content/themes/casper/post.hbs +67 -65
  9. package/content/themes/casper/tag.hbs +2 -2
  10. package/core/built/assets/{chunk.3.f80c7fbb7573ce508a05.js → chunk.3.4b1d9e20e57164ac9c29.js} +31 -29
  11. package/core/built/assets/ghost-dark-bb2831fc27fcb02893ed0a761207dc63.css +1 -0
  12. package/core/built/assets/{ghost.min-ba7f03a78d7d98444af386b8ae9347a7.js → ghost.min-d1d99f3ed6e0f427874b2a11e7078475.js} +1777 -1685
  13. package/core/built/assets/ghost.min-e7612edfa72b0fe2c201b387923e6fc7.css +1 -0
  14. package/core/built/assets/icons/check-2.svg +1 -0
  15. package/core/built/assets/icons/discount-bubble.svg +1 -0
  16. package/core/built/assets/icons/no-data-line-chart.svg +1 -0
  17. package/core/built/assets/icons/no-data-list.svg +9 -8
  18. package/core/built/assets/icons/no-data-subscription.svg +1 -0
  19. package/core/built/assets/{vendor.min-29784d514390cb5abc74ae660cb2fbc7.js → vendor.min-3660ec7864887f1496fe7a27fd23ab76.js} +1570 -1289
  20. package/core/frontend/helpers/ghost_head.js +7 -1
  21. package/core/frontend/helpers/match.js +19 -4
  22. package/core/frontend/helpers/products.js +68 -0
  23. package/core/frontend/helpers/tpl/content-cta.hbs +1 -1
  24. package/core/frontend/services/routing/controllers/email-post.js +3 -2
  25. package/core/frontend/services/settings/loader.js +2 -2
  26. package/core/frontend/services/sitemap/base-generator.js +12 -8
  27. package/core/frontend/services/sitemap/manager.js +1 -1
  28. package/core/frontend/services/theme-engine/handlebars/helpers.js +1 -0
  29. package/core/frontend/services/theme-engine/middleware.js +4 -1
  30. package/core/server/api/canary/email-preview.js +15 -33
  31. package/core/server/api/canary/integrations.js +7 -30
  32. package/core/server/api/canary/labels.js +8 -9
  33. package/core/server/api/canary/members.js +13 -9
  34. package/core/server/api/canary/schedules.js +9 -57
  35. package/core/server/api/canary/settings.js +20 -158
  36. package/core/server/api/canary/themes.js +5 -59
  37. package/core/server/api/canary/utils/serializers/output/members.js +2 -14
  38. package/core/server/api/canary/utils/validators/input/settings.js +23 -1
  39. package/core/server/api/canary/webhooks.js +6 -24
  40. package/core/server/api/v2/schedules.js +9 -57
  41. package/core/server/api/v3/email-preview.js +15 -28
  42. package/core/server/api/v3/integrations.js +7 -30
  43. package/core/server/api/v3/labels.js +8 -9
  44. package/core/server/api/v3/members.js +4 -1
  45. package/core/server/api/v3/schedules.js +9 -57
  46. package/core/server/api/v3/settings.js +13 -132
  47. package/core/server/api/v3/utils/validators/input/settings.js +23 -1
  48. package/core/server/api/v3/webhooks.js +6 -28
  49. package/core/server/data/exporter/table-lists.js +1 -0
  50. package/core/server/data/importer/import-manager.js +398 -0
  51. package/core/server/data/importer/importers/data/data-importer.js +162 -0
  52. package/core/server/data/importer/importers/data/index.js +1 -162
  53. package/core/server/data/importer/index.js +1 -379
  54. package/core/server/data/migrations/versions/4.14/01-fix-comped-member-statuses.js +70 -0
  55. package/core/server/data/migrations/versions/4.14/02-fix-free-members-status-events.js +60 -0
  56. package/core/server/data/migrations/versions/4.15/01-add-temp-members-analytic-events-table.js +12 -0
  57. package/core/server/data/migrations/versions/4.16/01-add-custom-theme-settings-table.js +9 -0
  58. package/core/server/data/schema/fixtures/utils.js +6 -1
  59. package/core/server/data/schema/schema.js +26 -0
  60. package/core/server/lib/request-external.js +3 -2
  61. package/core/server/models/action.js +1 -1
  62. package/core/server/models/api-key.js +1 -1
  63. package/core/server/models/base/bookshelf.js +0 -3
  64. package/core/server/models/base/index.js +2 -0
  65. package/core/server/models/base/plugins/events.js +2 -2
  66. package/core/server/models/base/plugins/raw-knex.js +10 -10
  67. package/core/server/models/custom-theme-setting.js +9 -0
  68. package/core/server/models/email.js +2 -2
  69. package/core/server/models/index.js +2 -0
  70. package/core/server/models/integration.js +1 -1
  71. package/core/server/models/label.js +2 -2
  72. package/core/server/models/member-analytic-event.js +9 -0
  73. package/core/server/models/member.js +2 -2
  74. package/core/server/models/post.js +2 -2
  75. package/core/server/models/settings.js +2 -2
  76. package/core/server/models/tag.js +2 -2
  77. package/core/server/models/user.js +2 -2
  78. package/core/server/models/webhook.js +2 -2
  79. package/core/server/services/bulk-email/bulk-email-processor.js +1 -4
  80. package/core/server/services/custom-theme-settings.js +8 -0
  81. package/core/server/services/integrations/integrations-service.js +61 -0
  82. package/core/server/services/mail/GhostMailer.js +29 -37
  83. package/core/server/services/mega/email-preview.js +41 -0
  84. package/core/server/services/mega/index.js +4 -0
  85. package/core/server/services/mega/mega.js +27 -23
  86. package/core/server/services/mega/post-email-serializer.js +28 -21
  87. package/core/server/services/mega/template.js +11 -0
  88. package/core/server/services/members/api.js +1 -0
  89. package/core/server/services/members/emails/signup.js +1 -1
  90. package/core/server/services/oembed.js +7 -2
  91. package/core/server/services/posts/post-scheduling-service.js +100 -0
  92. package/core/server/services/settings/index.js +13 -16
  93. package/core/server/services/settings/settings-bread-service.js +188 -0
  94. package/core/server/services/settings/settings-utils.js +32 -0
  95. package/core/server/services/themes/ThemeStorage.js +5 -4
  96. package/core/server/services/themes/activation-bridge.js +14 -0
  97. package/core/server/services/themes/index.js +2 -0
  98. package/core/server/services/themes/installer.js +72 -0
  99. package/core/server/services/themes/validate.js +5 -2
  100. package/core/server/services/webhooks/webhooks-service.js +55 -0
  101. package/core/server/web/admin/views/default-prod.html +4 -4
  102. package/core/server/web/admin/views/default.html +4 -4
  103. package/core/server/web/members/app.js +3 -0
  104. package/core/shared/config/defaults.json +2 -2
  105. package/core/shared/custom-theme-settings-cache.js +3 -0
  106. package/core/shared/i18n/translations/en.json +1 -6
  107. package/core/shared/labs.js +5 -7
  108. package/package.json +64 -62
  109. package/yarn.lock +1490 -1055
  110. package/core/built/assets/ghost-dark-98d56e4973a502750748090f9dbc8280.css +0 -1
  111. package/core/built/assets/ghost.min-6932a664a1cb92a8e4a15f540cae3ad8.css +0 -1
  112. package/core/server/services/mega/template-labs.js +0 -1024
@@ -1,162 +1 @@
1
- const _ = require('lodash');
2
- const Promise = require('bluebird');
3
- const semver = require('semver');
4
- const {IncorrectUsageError} = require('@tryghost/errors');
5
- const debug = require('@tryghost/debug')('importer:data');
6
- const {sequence} = require('@tryghost/promise');
7
- const models = require('../../../../models');
8
- const PostsImporter = require('./posts');
9
- const TagsImporter = require('./tags');
10
- const SettingsImporter = require('./settings');
11
- const UsersImporter = require('./users');
12
- const RolesImporter = require('./roles');
13
- let importers = {};
14
- let DataImporter;
15
-
16
- DataImporter = {
17
- type: 'data',
18
-
19
- preProcess: function preProcess(importData) {
20
- importData.preProcessedByData = true;
21
- return importData;
22
- },
23
-
24
- init: function init(importData) {
25
- importers.users = new UsersImporter(importData.data);
26
- importers.roles = new RolesImporter(importData.data);
27
- importers.tags = new TagsImporter(importData.data);
28
- importers.posts = new PostsImporter(importData.data);
29
- importers.settings = new SettingsImporter(importData.data);
30
-
31
- return importData;
32
- },
33
-
34
- // Allow importing with an options object that is passed through the importer
35
- doImport: function doImport(importData, importOptions) {
36
- importOptions = importOptions || {};
37
-
38
- const ops = [];
39
- let errors = [];
40
- let results = [];
41
-
42
- const modelOptions = {
43
- importing: true,
44
- context: {
45
- internal: true
46
- }
47
- };
48
-
49
- if (!Object.prototype.hasOwnProperty.call(importOptions, 'returnImportedData')) {
50
- importOptions.returnImportedData = false;
51
- }
52
-
53
- if (importOptions.importPersistUser) {
54
- modelOptions.importPersistUser = importOptions.importPersistUser;
55
- }
56
-
57
- if (!importData.meta) {
58
- return Promise.reject(new IncorrectUsageError({
59
- message: 'Wrong importer structure. `meta` is missing.',
60
- help: 'https://ghost.org/docs/migration/custom/'
61
- }));
62
- }
63
-
64
- if (!importData.meta.version) {
65
- return Promise.reject(new IncorrectUsageError({
66
- message: 'Wrong importer structure. `meta.version` is missing.',
67
- help: 'https://ghost.org/docs/migration/custom/'
68
- }));
69
- }
70
-
71
- // CASE: We deny LTS imports, because these are major version jumps. Only imports from v1 until the latest are supported.
72
- // We can detect a wrong structure by checking the meta version field. Ghost v0 doesn't use semver compliant versions.
73
- if (!semver.valid(importData.meta.version)) {
74
- return Promise.reject(new IncorrectUsageError({
75
- message: 'Detected unsupported file structure.',
76
- help: 'Please install Ghost 1.0, import the file and then update your blog to the latest Ghost version.\nVisit https://ghost.org/docs/update/ or ask for help in our https://forum.ghost.org.'
77
- }));
78
- }
79
-
80
- this.init(importData);
81
-
82
- return models.Base.transaction(function (transacting) {
83
- modelOptions.transacting = transacting;
84
-
85
- _.each(importers, function (importer) {
86
- ops.push(function doModelImport() {
87
- return importer.fetchExisting(modelOptions, importOptions)
88
- .then(function () {
89
- return importer.beforeImport(modelOptions, importOptions);
90
- })
91
- .then(function () {
92
- if (importer.options.requiredImportedData.length) {
93
- _.each(importer.options.requiredImportedData, (key) => {
94
- importer.requiredImportedData[key] = importers[key].importedData;
95
- });
96
- }
97
-
98
- if (importer.options.requiredExistingData.length) {
99
- _.each(importer.options.requiredExistingData, (key) => {
100
- importer.requiredExistingData[key] = importers[key].existingData;
101
- });
102
- }
103
-
104
- return importer.replaceIdentifiers(modelOptions, importOptions);
105
- })
106
- .then(function () {
107
- return importer.doImport(modelOptions, importOptions)
108
- .then(function (_results) {
109
- results = results.concat(_results);
110
- });
111
- });
112
- });
113
- });
114
-
115
- sequence(ops)
116
- .then(function () {
117
- results.forEach(function (promise) {
118
- if (!promise.isFulfilled()) {
119
- errors = errors.concat(promise.reason());
120
- }
121
- });
122
-
123
- if (errors.length === 0) {
124
- transacting.commit();
125
- } else {
126
- transacting.rollback(errors);
127
- }
128
- });
129
- }).then(function () {
130
- /**
131
- * data: imported data
132
- * originalData: data from the json file
133
- * problems: warnings
134
- */
135
- const toReturn = {
136
- data: {},
137
- originalData: importData.data,
138
- problems: []
139
- };
140
-
141
- _.each(importers, function (importer) {
142
- toReturn.problems = toReturn.problems.concat(importer.problems);
143
-
144
- if (importOptions.returnImportedData) {
145
- toReturn.data[importer.dataKeyToImport] = importer.importedDataToReturn;
146
- }
147
- });
148
-
149
- return toReturn;
150
- }).catch(function (err) {
151
- debug(err);
152
- return Promise.reject(err);
153
- }).finally(() => {
154
- // release memory
155
- importers = {};
156
- results = null;
157
- importData = null;
158
- });
159
- }
160
- };
161
-
162
- module.exports = DataImporter;
1
+ module.exports = require('./data-importer');
@@ -1,379 +1 @@
1
- const _ = require('lodash');
2
- const Promise = require('bluebird');
3
- const fs = require('fs-extra');
4
- const path = require('path');
5
- const os = require('os');
6
- const glob = require('glob');
7
- const uuid = require('uuid');
8
- const {extract} = require('@tryghost/zip');
9
- const {pipeline, sequence} = require('@tryghost/promise');
10
- const i18n = require('../../../shared/i18n');
11
- const logging = require('@tryghost/logging');
12
- const errors = require('@tryghost/errors');
13
- const ImageHandler = require('./handlers/image');
14
- const JSONHandler = require('./handlers/json');
15
- const MarkdownHandler = require('./handlers/markdown');
16
- const ImageImporter = require('./importers/image');
17
- const DataImporter = require('./importers/data');
18
-
19
- // Glob levels
20
- const ROOT_ONLY = 0;
21
-
22
- const ROOT_OR_SINGLE_DIR = 1;
23
- const ALL_DIRS = 2;
24
- let defaults;
25
-
26
- defaults = {
27
- extensions: ['.zip'],
28
- contentTypes: ['application/zip', 'application/x-zip-compressed'],
29
- directories: []
30
- };
31
-
32
- function ImportManager() {
33
- this.importers = [ImageImporter, DataImporter];
34
- this.handlers = [ImageHandler, JSONHandler, MarkdownHandler];
35
- // Keep track of file to cleanup at the end
36
- this.fileToDelete = null;
37
- }
38
-
39
- /**
40
- * A number, or a string containing a number.
41
- * @typedef {Object} ImportData
42
- * @property [Object] data
43
- * @property [Array] images
44
- */
45
-
46
- _.extend(ImportManager.prototype, {
47
- /**
48
- * Get an array of all the file extensions for which we have handlers
49
- * @returns {string[]}
50
- */
51
- getExtensions: function () {
52
- return _.flatten(_.union(_.map(this.handlers, 'extensions'), defaults.extensions));
53
- },
54
- /**
55
- * Get an array of all the mime types for which we have handlers
56
- * @returns {string[]}
57
- */
58
- getContentTypes: function () {
59
- return _.flatten(_.union(_.map(this.handlers, 'contentTypes'), defaults.contentTypes));
60
- },
61
- /**
62
- * Get an array of directories for which we have handlers
63
- * @returns {string[]}
64
- */
65
- getDirectories: function () {
66
- return _.flatten(_.union(_.map(this.handlers, 'directories'), defaults.directories));
67
- },
68
- /**
69
- * Convert items into a glob string
70
- * @param {String[]} items
71
- * @returns {String}
72
- */
73
- getGlobPattern: function (items) {
74
- return '+(' + _.reduce(items, function (memo, ext) {
75
- return memo !== '' ? memo + '|' + ext : ext;
76
- }, '') + ')';
77
- },
78
- /**
79
- * @param {String[]} extensions
80
- * @param {Number} level
81
- * @returns {String}
82
- */
83
- getExtensionGlob: function (extensions, level) {
84
- const prefix = level === ALL_DIRS ? '**/*' :
85
- (level === ROOT_OR_SINGLE_DIR ? '{*/*,*}' : '*');
86
-
87
- return prefix + this.getGlobPattern(extensions);
88
- },
89
- /**
90
- *
91
- * @param {String[]} directories
92
- * @param {Number} level
93
- * @returns {String}
94
- */
95
- getDirectoryGlob: function (directories, level) {
96
- const prefix = level === ALL_DIRS ? '**/' :
97
- (level === ROOT_OR_SINGLE_DIR ? '{*/,}' : '');
98
-
99
- return prefix + this.getGlobPattern(directories);
100
- },
101
- /**
102
- * Remove files after we're done (abstracted into a function for easier testing)
103
- * @returns {Function}
104
- */
105
- cleanUp: function () {
106
- const self = this;
107
-
108
- if (self.fileToDelete === null) {
109
- return;
110
- }
111
-
112
- fs.remove(self.fileToDelete, function (err) {
113
- if (err) {
114
- logging.error(new errors.GhostError({
115
- err: err,
116
- context: i18n.t('errors.data.importer.index.couldNotCleanUpFile.error'),
117
- help: i18n.t('errors.data.importer.index.couldNotCleanUpFile.context')
118
- }));
119
- }
120
-
121
- self.fileToDelete = null;
122
- });
123
- },
124
- /**
125
- * Return true if the given file is a Zip
126
- * @returns Boolean
127
- */
128
- isZip: function (ext) {
129
- return _.includes(defaults.extensions, ext);
130
- },
131
- /**
132
- * Checks the content of a zip folder to see if it is valid.
133
- * Importable content includes any files or directories which the handlers can process
134
- * Importable content must be found either in the root, or inside one base directory
135
- *
136
- * @param {String} directory
137
- * @returns {Promise}
138
- */
139
- isValidZip: function (directory) {
140
- // Globs match content in the root or inside a single directory
141
- const extMatchesBase = glob.sync(this.getExtensionGlob(this.getExtensions(), ROOT_OR_SINGLE_DIR), {cwd: directory});
142
-
143
- const extMatchesAll = glob.sync(
144
- this.getExtensionGlob(this.getExtensions(), ALL_DIRS), {cwd: directory}
145
- );
146
-
147
- const dirMatches = glob.sync(
148
- this.getDirectoryGlob(this.getDirectories(), ROOT_OR_SINGLE_DIR), {cwd: directory}
149
- );
150
-
151
- const oldRoonMatches = glob.sync(this.getDirectoryGlob(['drafts', 'published', 'deleted'], ROOT_OR_SINGLE_DIR),
152
- {cwd: directory});
153
-
154
- // This is a temporary extra message for the old format roon export which doesn't work with Ghost
155
- if (oldRoonMatches.length > 0) {
156
- throw new errors.UnsupportedMediaTypeError({message: i18n.t('errors.data.importer.index.unsupportedRoonExport')});
157
- }
158
-
159
- // If this folder contains importable files or a content or images directory
160
- if (extMatchesBase.length > 0 || (dirMatches.length > 0 && extMatchesAll.length > 0)) {
161
- return true;
162
- }
163
-
164
- if (extMatchesAll.length < 1) {
165
- throw new errors.UnsupportedMediaTypeError({message: i18n.t('errors.data.importer.index.noContentToImport')});
166
- }
167
-
168
- throw new errors.UnsupportedMediaTypeError({message: i18n.t('errors.data.importer.index.invalidZipStructure')});
169
- },
170
- /**
171
- * Use the extract module to extract the given zip file to a temp directory & return the temp directory path
172
- * @param {String} filePath
173
- * @returns {Promise[]} Files
174
- */
175
- extractZip: function (filePath) {
176
- const tmpDir = path.join(os.tmpdir(), uuid.v4());
177
- this.fileToDelete = tmpDir;
178
-
179
- return extract(filePath, tmpDir).then(function () {
180
- return tmpDir;
181
- });
182
- },
183
- /**
184
- * Use the handler extensions to get a globbing pattern, then use that to fetch all the files from the zip which
185
- * are relevant to the given handler, and return them as a name and path combo
186
- * @param {Object} handler
187
- * @param {String} directory
188
- * @returns [] Files
189
- */
190
- getFilesFromZip: function (handler, directory) {
191
- const globPattern = this.getExtensionGlob(handler.extensions, ALL_DIRS);
192
- return _.map(glob.sync(globPattern, {cwd: directory}), function (file) {
193
- return {name: file, path: path.join(directory, file)};
194
- });
195
- },
196
- /**
197
- * Get the name of the single base directory if there is one, else return an empty string
198
- * @param {String} directory
199
- * @returns {Promise (String)}
200
- */
201
- getBaseDirectory: function (directory) {
202
- // Globs match root level only
203
- const extMatches = glob.sync(this.getExtensionGlob(this.getExtensions(), ROOT_ONLY), {cwd: directory});
204
-
205
- const dirMatches = glob.sync(this.getDirectoryGlob(this.getDirectories(), ROOT_ONLY), {cwd: directory});
206
- let extMatchesAll;
207
-
208
- // There is no base directory
209
- if (extMatches.length > 0 || dirMatches.length > 0) {
210
- return;
211
- }
212
- // There is a base directory, grab it from any ext match
213
- extMatchesAll = glob.sync(
214
- this.getExtensionGlob(this.getExtensions(), ALL_DIRS), {cwd: directory}
215
- );
216
- if (extMatchesAll.length < 1 || extMatchesAll[0].split('/') < 1) {
217
- throw new errors.ValidationError({message: i18n.t('errors.data.importer.index.invalidZipFileBaseDirectory')});
218
- }
219
-
220
- return extMatchesAll[0].split('/')[0];
221
- },
222
- /**
223
- * Process Zip
224
- * Takes a reference to a zip file, extracts it, sends any relevant files from inside to the right handler, and
225
- * returns an object in the importData format: {data: {}, images: []}
226
- * The data key contains JSON representing any data that should be imported
227
- * The image key contains references to images that will be stored (and where they will be stored)
228
- * @param {File} file
229
- * @returns {Promise(ImportData)}
230
- */
231
- processZip: function (file) {
232
- const self = this;
233
-
234
- return this.extractZip(file.path).then(function (zipDirectory) {
235
- const ops = [];
236
- const importData = {};
237
- let baseDir;
238
-
239
- self.isValidZip(zipDirectory);
240
- baseDir = self.getBaseDirectory(zipDirectory);
241
-
242
- _.each(self.handlers, function (handler) {
243
- if (Object.prototype.hasOwnProperty.call(importData, handler.type)) {
244
- // This limitation is here to reduce the complexity of the importer for now
245
- return Promise.reject(new errors.UnsupportedMediaTypeError({
246
- message: i18n.t('errors.data.importer.index.zipContainsMultipleDataFormats')
247
- }));
248
- }
249
-
250
- const files = self.getFilesFromZip(handler, zipDirectory);
251
-
252
- if (files.length > 0) {
253
- ops.push(function () {
254
- return handler.loadFile(files, baseDir).then(function (data) {
255
- importData[handler.type] = data;
256
- });
257
- });
258
- }
259
- });
260
-
261
- if (ops.length === 0) {
262
- return Promise.reject(new errors.UnsupportedMediaTypeError({
263
- message: i18n.t('errors.data.importer.index.noContentToImport')
264
- }));
265
- }
266
-
267
- return sequence(ops).then(function () {
268
- return importData;
269
- });
270
- });
271
- },
272
- /**
273
- * Process File
274
- * Takes a reference to a single file, sends it to the relevant handler to be loaded and returns an object in the
275
- * importData format: {data: {}, images: []}
276
- * The data key contains JSON representing any data that should be imported
277
- * The image key contains references to images that will be stored (and where they will be stored)
278
- * @param {File} file
279
- * @returns {Promise(ImportData)}
280
- */
281
- processFile: function (file, ext) {
282
- const fileHandler = _.find(this.handlers, function (handler) {
283
- return _.includes(handler.extensions, ext);
284
- });
285
-
286
- return fileHandler.loadFile([_.pick(file, 'name', 'path')]).then(function (loadedData) {
287
- // normalize the returned data
288
- const importData = {};
289
- importData[fileHandler.type] = loadedData;
290
- return importData;
291
- });
292
- },
293
- /**
294
- * Import Step 1:
295
- * Load the given file into usable importData in the format: {data: {}, images: []}, regardless of
296
- * whether the file is a single importable file like a JSON file, or a zip file containing loads of files.
297
- * @param {File} file
298
- * @returns {Promise}
299
- */
300
- loadFile: function (file) {
301
- const self = this;
302
- const ext = path.extname(file.name).toLowerCase();
303
- return this.isZip(ext) ? self.processZip(file) : self.processFile(file, ext);
304
- },
305
- /**
306
- * Import Step 2:
307
- * Pass the prepared importData through the preProcess function of the various importers, so that the importers can
308
- * make any adjustments to the data based on relationships between it
309
- * @param {ImportData} importData
310
- * @returns {Promise(ImportData)}
311
- */
312
- preProcess: function (importData) {
313
- const ops = [];
314
- _.each(this.importers, function (importer) {
315
- ops.push(function () {
316
- return importer.preProcess(importData);
317
- });
318
- });
319
-
320
- return pipeline(ops);
321
- },
322
- /**
323
- * Import Step 3:
324
- * Each importer gets passed the data from importData which has the key matching its type - i.e. it only gets the
325
- * data that it should import. Each importer then handles actually importing that data into Ghost
326
- * @param {ImportData} importData
327
- * @param {importOptions} importOptions to allow override of certain import features such as locking a user
328
- * @returns {Promise(ImportData)}
329
- */
330
- doImport: function (importData, importOptions) {
331
- importOptions = importOptions || {};
332
- const ops = [];
333
- _.each(this.importers, function (importer) {
334
- if (Object.prototype.hasOwnProperty.call(importData, importer.type)) {
335
- ops.push(function () {
336
- return importer.doImport(importData[importer.type], importOptions);
337
- });
338
- }
339
- });
340
-
341
- return sequence(ops).then(function (importResult) {
342
- return importResult;
343
- });
344
- },
345
- /**
346
- * Import Step 4:
347
- * Report on what was imported, currently a no-op
348
- * @param {ImportData} importData
349
- * @returns {Promise(ImportData)}
350
- */
351
- generateReport: function (importData) {
352
- return Promise.resolve(importData);
353
- },
354
- /**
355
- * Import From File
356
- * The main method of the ImportManager, call this to kick everything off!
357
- * @param {File} file
358
- * @param {importOptions} importOptions to allow override of certain import features such as locking a user
359
- * @returns {Promise}
360
- */
361
- importFromFile: function (file, importOptions = {}) {
362
- const self = this;
363
-
364
- // Step 1: Handle converting the file to usable data
365
- return this.loadFile(file).then(function (importData) {
366
- // Step 2: Let the importers pre-process the data
367
- return self.preProcess(importData);
368
- }).then(function (importData) {
369
- // Step 3: Actually do the import
370
- // @TODO: It would be cool to have some sort of dry run flag here
371
- return self.doImport(importData, importOptions);
372
- }).then(function (importData) {
373
- // Step 4: Report on the import
374
- return self.generateReport(importData);
375
- }).finally(() => self.cleanUp()); // Step 5: Cleanup any files
376
- }
377
- });
378
-
379
- module.exports = new ImportManager();
1
+ module.exports = require('./import-manager');
@@ -0,0 +1,70 @@
1
+ const {chunk} = require('lodash');
2
+ const {createTransactionalMigration} = require('../../utils');
3
+ const logging = require('@tryghost/logging');
4
+
5
+ module.exports = createTransactionalMigration(async function up(knex) {
6
+ const compedMemberIds = (await knex('members')
7
+ .select('members.id')
8
+ .innerJoin(
9
+ 'members_stripe_customers',
10
+ 'members.id',
11
+ 'members_stripe_customers.member_id'
12
+ ).innerJoin(
13
+ 'members_stripe_customers_subscriptions',
14
+ function () {
15
+ this.on(
16
+ 'members_stripe_customers.customer_id',
17
+ 'members_stripe_customers_subscriptions.customer_id'
18
+ ).onIn(
19
+ 'members_stripe_customers_subscriptions.status',
20
+ ['active', 'trialing', 'past_due', 'unpaid']
21
+ );
22
+ }
23
+ ).where(
24
+ 'members_stripe_customers_subscriptions.plan_nickname',
25
+ '=',
26
+ 'Complimentary'
27
+ ).andWhere(
28
+ 'members.status',
29
+ '!=',
30
+ 'comped'
31
+ )).map(({id}) => id);
32
+
33
+ if (!compedMemberIds.length) {
34
+ logging.warn('No Complimentary members found with incorrect status');
35
+ return;
36
+ } else {
37
+ logging.info(`Found ${compedMemberIds.length} Complimentary members with the incorrect status`);
38
+ }
39
+
40
+ // Umm? Well... The current version of SQLite3 bundled with Ghost supports
41
+ // a maximum of 999 variables, we use one variable for the SET value
42
+ // and so we're left with 998 for our WHERE IN clause values
43
+ const chunkSize = 998;
44
+
45
+ const compedMemberIdChunks = chunk(compedMemberIds, chunkSize);
46
+
47
+ for (const compedMemberIdsChunk of compedMemberIdChunks) {
48
+ await knex('members')
49
+ .update('status', 'comped')
50
+ .whereIn('id', compedMemberIdsChunk);
51
+ }
52
+
53
+ for (const memberId of compedMemberIds) {
54
+ const mostRecentStatusEvent = await knex('members_status_events')
55
+ .select('*')
56
+ .where('member_id', memberId)
57
+ .orderBy('created_at', 'desc')
58
+ .limit(1)
59
+ .first();
60
+
61
+ if (!mostRecentStatusEvent) {
62
+ logging.warn(`Could not find a status event for member ${memberId} - skipping this member`);
63
+ } else if (mostRecentStatusEvent.to_status !== 'comped') {
64
+ logging.info(`Updating members_status_event ${mostRecentStatusEvent.id}`);
65
+ await knex('members_status_events')
66
+ .update('to_status', 'comped')
67
+ .where('id', mostRecentStatusEvent.id);
68
+ }
69
+ }
70
+ }, async function down() {});
@@ -0,0 +1,60 @@
1
+ const _ = require('lodash');
2
+ const logging = require('@tryghost/logging');
3
+ const {createTransactionalMigration} = require('../../utils.js');
4
+
5
+ module.exports = createTransactionalMigration(
6
+ async function up(knex) {
7
+ logging.info('Updating members_status_events for free members');
8
+ const freeMemberEvents = await knex('members')
9
+ .select(
10
+ 'members.id as member_id',
11
+ 'members_status_events.id',
12
+ 'members_status_events.to_status',
13
+ 'members_status_events.created_at'
14
+ )
15
+ .innerJoin(
16
+ 'members_status_events',
17
+ 'members.id',
18
+ 'members_status_events.member_id'
19
+ )
20
+ .where('members.status', 'free');
21
+
22
+ if (freeMemberEvents.length === 0) {
23
+ logging.info('No free members found - skipping migration');
24
+ return;
25
+ }
26
+
27
+ const eventsByMember = _.groupBy(freeMemberEvents, 'member_id');
28
+
29
+ const eventsToUpdate = Object.keys(eventsByMember).reduce((incorrectEvents, memberId) => {
30
+ const events = eventsByMember[memberId];
31
+
32
+ events.sort((a, b) => {
33
+ return new Date(b.created_at) - new Date(a.created_at);
34
+ });
35
+
36
+ const mostRecentStatusEvent = events[0];
37
+
38
+ if (mostRecentStatusEvent && mostRecentStatusEvent.to_status !== 'free') {
39
+ return incorrectEvents.concat(mostRecentStatusEvent.id);
40
+ }
41
+
42
+ return incorrectEvents;
43
+ }, []);
44
+
45
+ logging.info(`Found ${eventsToUpdate.length} member status events that need updating`);
46
+
47
+ // Umm? Well... The current version of SQLite3 bundled with Ghost supports
48
+ // a maximum of 999 variables, we use one variable for the SET value
49
+ // and so we're left with 998 for our WHERE IN clause values
50
+ const chunkedEventsToUpdate = _.chunk(eventsToUpdate, 998);
51
+
52
+ for (const chunk of chunkedEventsToUpdate) {
53
+ logging.info(`Updating a chunk of ${chunk.length} member status events`);
54
+ await knex('members_status_events')
55
+ .update('to_status', 'free')
56
+ .whereIn('id', chunk);
57
+ }
58
+ },
59
+ async function down() {}
60
+ );
@@ -0,0 +1,12 @@
1
+ const utils = require('../../utils');
2
+
3
+ module.exports = utils.addTable('temp_member_analytic_events', {
4
+ id: {type: 'string', maxlength: 24, nullable: false, primary: true},
5
+ event_name: {type: 'string', maxlength: 50, nullable: false},
6
+ created_at: {type: 'dateTime', nullable: false},
7
+ member_id: {type: 'string', maxlength: 24, nullable: false},
8
+ member_status: {type: 'string', maxlength: 50, nullable: false},
9
+ entry_id: {type: 'string', maxlength: 24, nullable: true},
10
+ source_url: {type: 'string', maxlength: 2000, nullable: true},
11
+ metadata: {type: 'string', maxlength: 191, nullable: true}
12
+ });