forked from rbren/mediumexporter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
get-post.js
106 lines (87 loc) · 2.8 KB
/
get-post.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
var utils = require('./utils')
, fs = require('fs')
, Promise = require('bluebird')
, moment = require('moment')
;
module.exports = function(mediumURL, program, callback) {
utils.loadMediumPost(mediumURL, function(err, json) {
var s = json.payload.value;
var story = {};
story.title = s.title;
story.date = moment(s.createdAt).format();
story.url = s.canonicalUrl;
story.language = s.detectedLanguage;
story.license = s.license;
if(program.info) {
console.log(story);
process.exit(0);
}
var outputText = '';
if(program.headers) {
outputText += 'url:' + story.url + '\n';
outputText += 'date:' + story.date + '\n';
outputText += 'title:' + story.title + '\n';
outputText += program.separator + '\n';
}
console.log( "Processing story: " + story.title);
story.sections = s.content.bodyModel.sections;
story.paragraphs = s.content.bodyModel.paragraphs;
var sections = [];
for(var i=0;i<story.sections.length;i++) {
var s = story.sections[i];
var section = utils.processSection(s);
sections[s.startIndex] = section;
}
story.subtitle = story.paragraphs[1].text;
story.markdown = [];
story.markdown.push("+++");
story.markdown.push("title="+"'"+story.title.replace(/\n/g,'\n# ')+"'");
if (undefined != story.subtitle) {
story.markdown.push("subtitle="+"'"+story.subtitle.replace(/\n/g,'\n# ')+"'");
}
story.markdown.push("date="+"'"+story.date+"'");
story.markdown.push("+++");
let lastParagraph = null;
story.paragraphs = story.paragraphs.filter((p, idx) => {
if (p.type === 8 && lastParagraph && lastParagraph.type === 8) {
lastParagraph.text += '\n\n' + p.text;
return false;
}
lastParagraph = p;
return true;
})
var promises = [];
for(var i=1;i<story.paragraphs.length;i++) {
if(sections[i]) story.markdown.push(sections[i]);
var promise = new Promise(function (resolve, reject) {
var p = story.paragraphs[i];
utils.processParagraph(p, function(err, text) {
// Avoid double title/subtitle
if(text != story.markdown[i])
return resolve(text);
else
return resolve();
});
});
promises.push(promise);
}
Promise.all(promises).then((results) => {
results.map(text => {
story.markdown.push(text);
})
if (program.debug) {
console.log("debug", story.paragraphs);
}
outputText += story.markdown.join('\n');
if (callback) {
callback(null, outputText);
} else if (program.output) {
fs.writeFile(program.output, outputText, err => {
if (err) throw err;
})
} else {
console.log(outputText);
}
});
});
}