-
Notifications
You must be signed in to change notification settings - Fork 3
/
importer.js
190 lines (158 loc) · 5.59 KB
/
importer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
const _ = require('lodash');
const fs = require('fs');
const path = require('path');
const pAll = require('p-all');
const unzipper = require('unzipper');
const matter = require('gray-matter');
const chalk = require('chalk');
const Errors = require('./errors');
const Post = require('./model/post');
const Profile = require('./model/profile');
const downloadImages = require('./image-downloader');
const convertHtml = require('./converter');
function unzipInput(inputFilePath, outputDir) {
return fs.createReadStream(inputFilePath)
.pipe(unzipper.Extract({ path: outputDir }))
.promise()
.catch((err) => {
console.error(err);
throw Errors.InvalidZip;
});
}
function processPost(postFilePath, outputDir, assetsDir, shouldDownloadImages, shouldImportDrafts) {
console.log(chalk.bold('processing post ' + postFilePath));
const post = new Post(fs.readFileSync(postFilePath));
const fileName = path.parse(postFilePath).name;
if (!shouldImportDrafts && fileName.startsWith('draft_')) {
console.log('skipping draft: ' + fileName);
return Promise.resolve();
}
const slug = fileName
.substring(0, fileName.lastIndexOf('-'))
.substring(fileName.indexOf('_') + 1)
.replace(/-+$/, '')
.substring(0, 200);
const imagesDir = path.join(assetsDir, slug);
if (!fs.existsSync(imagesDir)) {
fs.mkdirSync(imagesDir);
}
const imageUrls = post.imageUrls;
const downloadPromise = shouldDownloadImages
? downloadImages(imageUrls, imagesDir)
: Promise.resolve([]);
return downloadPromise.then((results) => {
const images = results.filter(Boolean);
const imageMap = new Map(images.map(item => [item.url, item.filename]));
const thumbPath = _.isEmpty(images)
? (_.isEmpty(imageUrls) ? null : imageUrls[0])
: `images/${slug}/${images[0].filename}`;
const bodyMarkdown = convertHtml(post.bodyHtml, slug, imageMap);
const data = {
template: 'post',
title: post.title,
date: post.publishDate || new Date()
};
if (post.subtitle) {
data.subtitle = post.subtitle;
}
if (post.excerpt) {
data.excerpt = post.excerpt;
}
if (thumbPath) {
data.thumb_img_path = thumbPath;
}
if (post.splashImageUrl) {
data.content_img_path = imageMap.has(post.splashImageUrl)
? `images/${slug}/${imageMap.get(post.splashImageUrl)}`
: post.splashImageUrl;
}
const outputFilename = path.join(outputDir, `${slug}.md`);
const yamlContent = matter.stringify(bodyMarkdown, data);
fs.writeFileSync(outputFilename, yamlContent);
console.log('done with ' + outputFilename);
});
}
function processPosts(inputDir, outputDir, assetsDir, concurrency, shouldDownloadImages, shouldImportDrafts) {
if (!fs.existsSync(inputDir)) {
throw Errors.EmptyInput;
}
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir);
}
if (!fs.existsSync(assetsDir)) {
fs.mkdirSync(assetsDir);
}
const postFiles = fs.readdirSync(inputDir);
if (_.isEmpty(postFiles)) {
throw Errors.EmptyInput;
}
return pAll(postFiles.map((filename) => {
return () => processPost(path.join(inputDir, filename), outputDir, assetsDir, shouldDownloadImages, shouldImportDrafts);
}), { concurrency: concurrency });
}
function processProfile(inputFile, dataFile, assetsDir) {
console.log(chalk.bold('processing profile ' + inputFile));
if (!fs.existsSync(inputFile)) {
console.log('no profile file');
return Promise.resolve();
}
const profile = new Profile(fs.readFileSync(inputFile));
let data = {
author: {},
social: {}
};
if (profile.name) {
data.author.name = profile.name;
}
if (profile.email) {
data.author.email = profile.email;
}
if (profile.twitterUsername) {
data.social.twitter = {
username: profile.twitterUsername,
url: `https://twitter.com/${profile.twitterUsername}`
};
}
const avatarUrl = profile.avatarUrl;
if (avatarUrl) {
return downloadImages([avatarUrl], assetsDir).then((results) => {
const filename = _.get(results, '[0].filename');
if (filename) {
fs.renameSync(
path.join(assetsDir, filename),
path.join(assetsDir, 'avatar.png')
);
data.author.avatar = 'images/avatar.png';
fs.writeFileSync(dataFile, JSON.stringify(data));
}
});
}
fs.writeFileSync(dataFile, JSON.stringify(data));
return Promise.resolve();
}
function doImport(inputFilePath, postsDir, imagesDir, dataFile, originalDir, shouldDownloadImages=true, shouldImportDrafts=false, concurrency=1) {
if (!fs.existsSync(inputFilePath)) {
return Promise.reject(Errors.InputFileNotFound);
}
return unzipInput(inputFilePath, originalDir).then(() => {
return processPosts(
path.join(originalDir, 'posts'),
postsDir,
imagesDir,
concurrency,
shouldDownloadImages,
shouldImportDrafts
);
}).then(() => {
if (dataFile) {
return processProfile(
path.join(originalDir, 'profile/profile.html'),
dataFile,
imagesDir
);
}
});
}
module.exports = {
doImport
};