UNPKG

3.25 kBJavaScriptView Raw
1var xml2js = require('xml2js'),
2 async = require('async'),
3 tomd = require('to-markdown').toMarkdown,
4 request = require('request'),
5 util = hexo.util,
6 file = util.file2;
7
8var captialize = function(str){
9 return str[0].toUpperCase() + str.substring(1);
10};
11
12hexo.extend.migrator.register('wordpress', function(args, callback){
13 var source = args._.shift();
14
15 if (!source){
16 var help = [
17 'Usage: hexo migrate wordpress <source>',
18 '',
19 'For more help, you can check the docs: http://hexo.io/docs/migration.html'
20 ];
21
22 console.log(help.join('\n'));
23 return callback();
24 }
25
26 var log = hexo.log,
27 post = hexo.post;
28
29 log.i('Analyzing %s...', source);
30
31 async.waterfall([
32 function(next){
33 // URL regular expression from: http://blog.mattheworiordan.com/post/13174566389/url-regular-expression-for-links-with-or-without-the
34 if (source.match(/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[.\!\/\\w]*))?)/)){
35 request(source, function(err, res, body){
36 if (err) throw err;
37 if (res.statusCode == 200) next(null, body);
38 });
39 } else {
40 file.readFile(source, next);
41 }
42 },
43 function(content, next){
44 xml2js.parseString(content, next);
45 },
46 function(xml, next){
47 var count = 0;
48
49 async.each(xml.rss.channel[0].item, function(item, next){
50 if (!item['wp:post_type']){
51 return next();
52 }
53
54 var title = item.title[0],
55 id = item['wp:post_id'][0],
56 date = item['wp:post_date'][0],
57 slug = item['wp:post_name'][0],
58 content = item['content:encoded'][0],
59 comment = item['wp:comment_status'][0],
60 status = item['wp:status'][0],
61 type = item['wp:post_type'][0],
62 categories = [],
63 tags = [];
64
65 if (!title && !slug) return next();
66 if (type !== 'post' && type !== 'page') return next();
67 if (typeof content !== 'string') content = '';
68
69 content = tomd(content).replace(/\r\n/g, '\n');
70 count++;
71
72 if (item.category){
73 item.category.forEach(function(category, next){
74 var name = category._;
75
76 switch (category.$.domain){
77 case 'category':
78 categories.push(name);
79 break;
80
81 case 'post_tag':
82 tags.push(name);
83 break;
84 }
85 });
86 }
87
88 var data = {
89 title: title || slug,
90 id: +id,
91 date: date,
92 content: content,
93 layout: status === 'draft' ? 'draft' : 'post',
94 };
95
96 if (type === 'page') data.layout = 'page';
97 if (slug) data.slug = slug;
98 if (comment === 'closed') data.comment = false;
99 if (categories.length && type === 'post') data.categories = categories;
100 if (tags.length && type === 'post') data.tags = tags;
101
102 log.i('%s found: %s', captialize(type), title);
103 post.create(data, next);
104 }, function(err){
105 if (err) return next(err);
106
107 log.i('%d posts migrated.', count);
108 });
109 }
110 ], callback);
111});
\No newline at end of file