@tryghost/mg-blogger 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2013-2022 Ghost Foundation
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,100 @@
1
+ # Migrate Blogger API
2
+
3
+ Migrate from Blogger using the Google API
4
+
5
+ This tool requires an API key, which you can get [here](https://developers.google.com/blogger/docs/3.0/using)
6
+
7
+ You also need a blog ID, which is a long number like `12345678123456781234`. You can find this by viewing the source of the Blogger site and looking for `blogId`.
8
+
9
+ ## Install
10
+
11
+ To install the CLI, which is required for the Usage commands below:
12
+
13
+ ```sh
14
+ npm install --global @tryghost/migrate
15
+ ```
16
+
17
+ To use this package in your own project:
18
+
19
+ `npm install @tryghost/mg-blogger --save`
20
+
21
+ or
22
+
23
+ `yarn add @tryghost/mg-blogger`
24
+
25
+
26
+ ## Usage
27
+
28
+ To run a Blogger migration, the required command is:
29
+
30
+ ```sh
31
+ migrate blogger --apiKey abcd --siteID 1234
32
+ ```
33
+
34
+ It's possible to pass more options, in order to achieve a better migration file for Ghost:
35
+
36
+ - **`--apiKey`** (required)
37
+ - string - default: `null`
38
+ - API Key
39
+ - **`--siteID`** (required)
40
+ - array - default: `null`
41
+ - Comma separated list of site IDs
42
+ - **`-V` `--verbose`**
43
+ - Show verbose output
44
+ - bool - default: `false`
45
+ - **`--zip`**
46
+ - Create a zip file
47
+ - bool - default: `true`
48
+ - **`-s` `--scrape`**
49
+ - Configure scraping tasks
50
+ - string - default: `all`
51
+ - Choices: `all`, `img`, `web`, `media`, `files`, `none`
52
+ - **`--sizeLimit`**
53
+ - number - default: `false`
54
+ - Media files larger than this size (defined in MB [i.e. `5`]) will be flagged as oversize
55
+ - **`--addTag`**
56
+ - string - default: `null`
57
+ - Provide a tag slug which should be added to every post in this migration
58
+ - **`--fallBackHTMLCard`**
59
+ - Fall back to convert to HTMLCard, if standard Mobiledoc convert fails
60
+ - bool - default: `true`
61
+ - **`--cache`**
62
+ - Persist local cache after migration is complete (Only if `--zip` is `true`)
63
+ - bool - default: `true`
64
+
65
+ A more complex migration command could look like this:
66
+
67
+ ```sh
68
+ migrate blogger --apiKey abcd --siteID 1234, 5678 --addTag 'Blog Posts' --pages false
69
+ ```
70
+
71
+ This will fetch posts only from 2 sites, and add a 'Blog Posts' tag to each post.
72
+
73
+
74
+ ## Develop
75
+
76
+ This is a mono repository, managed with [lerna](https://lerna.js.org).
77
+
78
+ Follow the instructions for the top-level repo.
79
+ 1. `git clone` this repo & `cd` into it as usual
80
+ 2. Run `yarn` to install top-level dependencies.
81
+
82
+
83
+ ## Run
84
+
85
+ To run a local development copy, `cd` into this directory, and use `yarn dev` instead of `migrate` like so:
86
+
87
+ ```sh
88
+ yarn dev blogger --apiKey abcd --siteID 1234
89
+ ```
90
+
91
+
92
+ ## Test
93
+
94
+ - `yarn lint` run just eslint
95
+ - `yarn test` run lint and tests
96
+
97
+
98
+ # Copyright & License
99
+
100
+ Copyright (c) 2013-2022 Ghost Foundation - Released under the [MIT license](LICENSE).
package/index.js ADDED
@@ -0,0 +1,7 @@
1
+ import fetch from './lib/fetch.js';
2
+ import process from './lib/process.js';
3
+
4
+ export default {
5
+ fetch,
6
+ process
7
+ };
package/lib/fetch.js ADDED
@@ -0,0 +1,76 @@
1
+ import errors from '@tryghost/errors';
2
+ import fetch from 'node-fetch';
3
+
4
+ const getSiteContent = async (apiKey, blogID, type = 'posts') => {
5
+ let response = null;
6
+ let results = [];
7
+ let pageToken = false;
8
+
9
+ do {
10
+ try {
11
+ const searchParams = new URLSearchParams({
12
+ key: apiKey
13
+ });
14
+
15
+ if (pageToken) {
16
+ searchParams.set('pageToken', pageToken);
17
+ }
18
+
19
+ let request = await fetch(`https://www.googleapis.com/blogger/v3/blogs/${blogID}/${type}?` + searchParams);
20
+
21
+ response = await request.json();
22
+ results = results.concat(response.items);
23
+ pageToken = response.nextPageToken;
24
+ } catch (error) {
25
+ throw new errors.InternalServerError({message: 'Failed to fetch Blogger content', error});
26
+ }
27
+ } while (response.nextPageToken);
28
+
29
+ return results;
30
+ };
31
+
32
+ const cachedFetch = async (fileCache, apiKey, blogID, type) => {
33
+ let filename = `blogger_api_${blogID}_${type}.json`;
34
+
35
+ if (fileCache.hasFile(filename, 'tmp')) {
36
+ return await fileCache.readTmpJSONFile(filename);
37
+ }
38
+
39
+ let response = await getSiteContent(apiKey, blogID, type);
40
+
41
+ await fileCache.writeTmpFile(response, filename);
42
+
43
+ return response;
44
+ };
45
+
46
+ const tasks = async ({apiKey, blogID}, ctx) => {
47
+ const tasks = []; // eslint-disable-line no-shadow
48
+
49
+ ctx.result = {
50
+ posts: []
51
+ };
52
+
53
+ blogID.forEach((singleblogID) => {
54
+ tasks.push({
55
+ title: `Fetching posts for ${singleblogID}`,
56
+ task: async (ctx) => { // eslint-disable-line no-shadow
57
+ try {
58
+ let response = await cachedFetch(ctx.fileCache, apiKey, singleblogID, 'posts');
59
+
60
+ ctx.result.posts = ctx.result.posts.concat(response);
61
+ } catch (error) {
62
+ ctx.errors.push(error);
63
+ throw error;
64
+ }
65
+ }
66
+ });
67
+ });
68
+
69
+ // console.log({blogID});
70
+
71
+ return tasks;
72
+ };
73
+
74
+ export default {
75
+ tasks
76
+ };
package/lib/process.js ADDED
@@ -0,0 +1,291 @@
1
+ import $ from 'cheerio';
2
+ import autop from 'autop';
3
+ import sanitizeHtml from 'sanitize-html';
4
+ import {slugify} from '@tryghost/string';
5
+ import errors from '@tryghost/errors';
6
+ import SimpleDom from 'simple-dom';
7
+ import imageCard from '@tryghost/kg-default-cards/lib/cards/image.js';
8
+
9
+ const serializer = new SimpleDom.HTMLSerializer(SimpleDom.voidMap);
10
+
11
+ const cleanExcerpt = (htmlContent) => {
12
+ // Convert to text only
13
+ const cleanedContent = sanitizeHtml(htmlContent, {
14
+ allowedTags: ['b', 'i', 'em', 'strong', 'a'],
15
+ allowedAttributes: {
16
+ a: ['href', 'title', 'rel', 'target']
17
+ }
18
+ });
19
+
20
+ return cleanedContent.trim();
21
+ };
22
+
23
+ const slugFromURL = (url) => {
24
+ return url.split('/').pop().replace('.html', '');
25
+ };
26
+
27
+ const increaseImageSize = (src) => {
28
+ // Increases the image size and removes special flags
29
+ // https://developers.google.com/photos/library/guides/access-media-items
30
+ let updatedSrc = src.replace(/s[0-9]{2,5}(-[a-z0-9#,*]{1,4})?/g, 's2000');
31
+ return updatedSrc;
32
+ };
33
+
34
+ const getAllAttributes = function (el) {
35
+ return el.attributes || Object.keys(el.attribs).map(
36
+ name => ({name, value: el.attribs[name]})
37
+ );
38
+ };
39
+
40
+ const processHTMLContent = async (args) => {
41
+ let {html} = args;
42
+
43
+ html = autop(html);
44
+
45
+ const $html = $.load(html);
46
+
47
+ $html('div.separator').each((i, el) => {
48
+ $(el).replaceWith(`<hr><div>${$(el).html().trim()}</div>`);
49
+ });
50
+
51
+ $html('img').each((i, el) => {
52
+ const imgSrc = $(el).attr('src');
53
+ const largerSrc = increaseImageSize(imgSrc);
54
+
55
+ $(el).attr('src', largerSrc);
56
+ });
57
+
58
+ $html('.tr-caption-container').each((i, el) => {
59
+ const hasLink = $(el).find('img').parent('a').length;
60
+ const href = (hasLink) ? $(el).find('img').parent('a').attr('href') : null;
61
+ const imgSrc = $(el).find('img').attr('src');
62
+ const caption = $(el).find('.tr-caption').html();
63
+ const cleanedExcerpt = cleanExcerpt(caption);
64
+
65
+ if (!imgSrc || imgSrc.length === 0) {
66
+ return;
67
+ }
68
+
69
+ // Update image size so we get the biggest image
70
+ const updatedImgSrc = increaseImageSize(imgSrc);
71
+
72
+ let cardOpts = {
73
+ env: {dom: new SimpleDom.Document()},
74
+ payload: {
75
+ src: updatedImgSrc,
76
+ caption: cleanedExcerpt
77
+ }
78
+ };
79
+
80
+ if (hasLink) {
81
+ const updatedHref = increaseImageSize(href);
82
+
83
+ if (updatedImgSrc !== updatedHref) {
84
+ cardOpts.payload.href = href;
85
+ }
86
+ }
87
+
88
+ const newCard = serializer.serialize(imageCard.render(cardOpts));
89
+
90
+ $(el).replaceWith(newCard);
91
+ });
92
+
93
+ $html('a > img').each((i, el) => {
94
+ const aHref = $(el).parent().attr('href');
95
+ const imgSrc = $(el).attr('src');
96
+
97
+ const updatedaHref = increaseImageSize(aHref);
98
+ const updatedImgSrc = increaseImageSize(imgSrc);
99
+
100
+ // Don't touch Koenig cards
101
+ if ($(el).parent().attr('class')?.includes('kg-') || $(el).attr('class')?.includes('kg-')) {
102
+ return;
103
+ }
104
+
105
+ if (updatedaHref === updatedImgSrc) {
106
+ $(el).parent().replaceWith(`<img src="${imgSrc}">`);
107
+ }
108
+ });
109
+
110
+ // Convert weird lists to real lists
111
+ $html('span[style*="white-space: pre"]').each((i, el) => {
112
+ const parent = $(el).parent('div');
113
+ if (parent.html()?.includes('•') || parent.html()?.includes('&#x2022;')) {
114
+ parent[0].tagName = 'li';
115
+ parent.find('span[style*="white-space: pre"]').each((ii, ell) => {
116
+ $(ell).remove();
117
+ });
118
+ parent.html(parent.html().replace('&#x2022;', '').trim());
119
+ }
120
+ });
121
+
122
+ // Wrap <li>s in <ul>
123
+ $html('li').each((i, el) => {
124
+ if ($(el).prev('ul').length) {
125
+ $(el).prev('ul').append($(el));
126
+ } else {
127
+ $(el).wrap('<ul></ul>');
128
+ }
129
+ });
130
+
131
+ $html('div[style*="color"][style*="font-family"][style*="font-size"][style*="white-space: pre-line"]').each((i, el) => {
132
+ $(el).replaceWith(`<p>${$(el).html().trim()}</p>`);
133
+ });
134
+
135
+ $html('span[style*="background-color"][style*="color"][style*="font-family"][style*="font-size"][style*="white-space: pre-line"]').each((i, el) => {
136
+ $(el).replaceWith(`<p>${$(el).html().trim()}</p>`);
137
+ });
138
+
139
+ $html('div[style="style="text-align: center;"]').each((i, el) => {
140
+ $(el).replaceWith(`<p>${$(el).html().trim()}</p>`);
141
+ });
142
+
143
+ $html('div, p').each((i, el) => {
144
+ const attrs = getAllAttributes(el);
145
+ const children = $(el).children();
146
+
147
+ if ($(el).html().trim() === '' && attrs.length === 0) {
148
+ $(el).remove();
149
+ } else if (attrs.length === 0 && children.length === 1 && children[0].name === 'img') {
150
+ $(el).replaceWith($(el).html().trim());
151
+ }
152
+ });
153
+
154
+ $html('div').each((i, el) => {
155
+ const attrs = getAllAttributes(el);
156
+ const children = $(el).children();
157
+
158
+ if (attrs.length === 0 && children.length === 0) {
159
+ $(el).replaceWith(`<p>${$(el).html().trim()}</p>`);
160
+ }
161
+ });
162
+
163
+ // Convert back to plain HTML
164
+ html = $html.html();
165
+
166
+ // Trim whitespace
167
+ html = html.trim();
168
+
169
+ // Remove first element(s) if <hr>
170
+ html = html.replace(/^(<hr\/?> ?)+/gm, '').trim();
171
+
172
+ return html;
173
+ };
174
+
175
+ const processPost = async (postData, options) => {
176
+ const {addTag} = options;
177
+
178
+ const post = {
179
+ url: postData.url,
180
+ data: {
181
+ slug: slugFromURL(postData.url),
182
+ title: postData.title,
183
+ status: 'published',
184
+ published_at: new Date(postData.published),
185
+ created_at: new Date(postData.published),
186
+ updated_at: new Date(postData.updated),
187
+ type: 'post',
188
+ tags: []
189
+ }
190
+ };
191
+
192
+ post.data.html = await processHTMLContent({
193
+ html: postData.content
194
+ });
195
+
196
+ if (postData.author) {
197
+ const authorName = postData.author.displayName.replace('&amp;', '&');
198
+ const authorSlug = slugify(authorName);
199
+
200
+ post.data.author = {
201
+ url: `migrator-added-author-${authorSlug}`,
202
+ data: {
203
+ slug: authorSlug,
204
+ email: `${authorSlug}@example.com`,
205
+ name: authorName
206
+ }
207
+ };
208
+ }
209
+
210
+ if (postData.labels) {
211
+ postData.labels.forEach((label) => {
212
+ const cleanedLabel = label.replace('&amp;', '&');
213
+ const labelSlug = slugify(cleanedLabel);
214
+
215
+ post.data.tags.push({
216
+ url: `migrator-added-tag-${labelSlug}`,
217
+ data: {
218
+ slug: labelSlug,
219
+ name: cleanedLabel
220
+ }
221
+ });
222
+ });
223
+ }
224
+
225
+ if (addTag) {
226
+ const addTagSlug = slugify(addTag);
227
+
228
+ post.data.tags.push({
229
+ url: `migrator-added-tag-${addTagSlug}`,
230
+ data: {
231
+ slug: addTagSlug,
232
+ name: addTag
233
+ }
234
+ });
235
+ }
236
+
237
+ if (postData?.blog?.id) {
238
+ post.data.tags.push({
239
+ url: `migrator-added-tag-site-id${postData.blog.id}`,
240
+ data: {
241
+ slug: `hash-blogger-site-${postData.blog.id}`,
242
+ name: `#blogger-site-${postData.blog.id}`
243
+ }
244
+ });
245
+ }
246
+
247
+ post.data.tags.push({
248
+ url: 'migrator-added-tag',
249
+ data: {
250
+ slug: 'hash-blogger',
251
+ name: '#blogger'
252
+ }
253
+ });
254
+
255
+ // console.log(post);
256
+
257
+ return post;
258
+ };
259
+
260
+ const processPosts = async (posts, options) => {
261
+ return Promise.all(posts.map(post => processPost(post, options)));
262
+ };
263
+
264
+ const all = async (input, {options}) => {
265
+ const output = {
266
+ posts: [],
267
+ users: []
268
+ };
269
+
270
+ if (input.length < 1) {
271
+ return new errors.NoContentError({message: 'Input file is empty'});
272
+ }
273
+
274
+ output.posts = await processPosts(input.posts, options);
275
+
276
+ return output;
277
+ };
278
+
279
+ export default {
280
+ processHTMLContent,
281
+ processPost,
282
+ processPosts,
283
+ all
284
+ };
285
+
286
+ export {
287
+ cleanExcerpt,
288
+ slugFromURL,
289
+ increaseImageSize,
290
+ getAllAttributes
291
+ };
package/package.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "@tryghost/mg-blogger",
3
+ "version": "0.1.0",
4
+ "repository": "https://github.com/TryGhost/migrate/tree/main/packages/mg-blogger",
5
+ "author": "Ghost Foundation",
6
+ "license": "MIT",
7
+ "main": "index.js",
8
+ "type": "module",
9
+ "scripts": {
10
+ "dev": "echo \"Implement me!\"",
11
+ "test": "node --experimental-vm-modules $(yarn bin jest)",
12
+ "lint": "eslint . --ext .js --cache",
13
+ "posttest": "yarn lint"
14
+ },
15
+ "files": [
16
+ "index.js",
17
+ "lib"
18
+ ],
19
+ "publishConfig": {
20
+ "access": "public"
21
+ },
22
+ "devDependencies": {
23
+ "jest": "29.5.0",
24
+ "jest-extended": "3.2.4"
25
+ },
26
+ "dependencies": {
27
+ "@tryghost/errors": "1.2.22",
28
+ "@tryghost/kg-default-cards": "9.0.1",
29
+ "autop": "1.0.1",
30
+ "cheerio": "0.22.0",
31
+ "node-fetch": "^3.3.1",
32
+ "sanitize-html": "2.10.0",
33
+ "simple-dom": "1.4.0"
34
+ },
35
+ "gitHead": "36b15a65cacdbb4002c195b06a434cb9742349b6"
36
+ }