post.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. 'use strict';
  2. const common = require('./common');
  3. const Promise = require('bluebird');
  4. const yfm = require('hexo-front-matter');
  5. const pathFn = require('path');
  6. const fs = require('hexo-fs');
  7. const util = require('hexo-util');
  8. const slugize = util.slugize;
  9. const Pattern = util.Pattern;
  10. const Permalink = util.Permalink;
  11. const postDir = '_posts/';
  12. const draftDir = '_drafts/';
  13. let permalink;
  14. const preservedKeys = {
  15. title: true,
  16. year: true,
  17. month: true,
  18. day: true,
  19. i_month: true,
  20. i_day: true
  21. };
  22. module.exports = ctx => {
  23. function processPost(file) {
  24. const Post = ctx.model('Post');
  25. const path = file.params.path;
  26. const doc = Post.findOne({source: file.path});
  27. const config = ctx.config;
  28. const timezone = config.timezone;
  29. let categories, tags;
  30. if (file.type === 'skip' && doc) {
  31. return;
  32. }
  33. if (file.type === 'delete') {
  34. if (doc) {
  35. return doc.remove();
  36. }
  37. return;
  38. }
  39. return Promise.all([
  40. file.stat(),
  41. file.read()
  42. ]).spread((stats, content) => {
  43. const data = yfm(content);
  44. const info = parseFilename(config.new_post_name, path);
  45. const keys = Object.keys(info);
  46. let key;
  47. data.source = file.path;
  48. data.raw = content;
  49. data.slug = info.title;
  50. if (file.params.published) {
  51. if (!data.hasOwnProperty('published')) data.published = true;
  52. } else {
  53. data.published = false;
  54. }
  55. for (let i = 0, len = keys.length; i < len; i++) {
  56. key = keys[i];
  57. if (!preservedKeys[key]) data[key] = info[key];
  58. }
  59. if (data.date) {
  60. data.date = common.toDate(data.date);
  61. } else if (info && info.year && (info.month || info.i_month) && (info.day || info.i_day)) {
  62. data.date = new Date(
  63. info.year,
  64. parseInt(info.month || info.i_month, 10) - 1,
  65. parseInt(info.day || info.i_day, 10)
  66. );
  67. }
  68. if (data.date) {
  69. if (timezone) data.date = common.timezone(data.date, timezone);
  70. } else {
  71. data.date = stats.birthtime;
  72. }
  73. data.updated = common.toDate(data.updated);
  74. if (data.updated) {
  75. if (timezone) data.updated = common.timezone(data.updated, timezone);
  76. } else {
  77. data.updated = stats.mtime;
  78. }
  79. if (data.category && !data.categories) {
  80. data.categories = data.category;
  81. delete data.category;
  82. }
  83. if (data.tag && !data.tags) {
  84. data.tags = data.tag;
  85. delete data.tag;
  86. }
  87. categories = data.categories || [];
  88. tags = data.tags || [];
  89. if (!Array.isArray(categories)) categories = [categories];
  90. if (!Array.isArray(tags)) tags = [tags];
  91. if (data.photo && !data.photos) {
  92. data.photos = data.photo;
  93. delete data.photo;
  94. }
  95. if (data.photos && !Array.isArray(data.photos)) {
  96. data.photos = [data.photos];
  97. }
  98. if (data.link && !data.title) {
  99. data.title = data.link.replace(/^https?:\/\/|\/$/g, '');
  100. }
  101. if (data.permalink) {
  102. data.slug = data.permalink;
  103. delete data.permalink;
  104. }
  105. // FIXME: Data may be inserted when reading files. Load it again to prevent
  106. // race condition. We have to solve this in warehouse.
  107. const doc = Post.findOne({source: file.path});
  108. if (doc) {
  109. return doc.replace(data);
  110. }
  111. return Post.insert(data);
  112. }).then(doc => Promise.all([
  113. doc.setCategories(categories),
  114. doc.setTags(tags),
  115. scanAssetDir(doc)
  116. ]));
  117. }
  118. function scanAssetDir(post) {
  119. if (!ctx.config.post_asset_folder) return;
  120. const assetDir = post.asset_dir;
  121. const baseDir = ctx.base_dir;
  122. const baseDirLength = baseDir.length;
  123. const PostAsset = ctx.model('PostAsset');
  124. return fs.stat(assetDir).then(stats => {
  125. if (!stats.isDirectory()) return [];
  126. return fs.listDir(assetDir);
  127. }).catch(err => {
  128. if (err.cause && err.cause.code === 'ENOENT') return [];
  129. throw err;
  130. }).filter(item => !common.isTmpFile(item) && !common.isHiddenFile(item)).map(item => {
  131. const id = pathFn.join(assetDir, item).substring(baseDirLength).replace(/\\/g, '/');
  132. const asset = PostAsset.findById(id);
  133. if (asset) return undefined;
  134. return PostAsset.save({
  135. _id: id,
  136. post: post._id,
  137. slug: item,
  138. modified: true
  139. });
  140. });
  141. }
  142. function processAsset(file) {
  143. const PostAsset = ctx.model('PostAsset');
  144. const Post = ctx.model('Post');
  145. const id = file.source.substring(ctx.base_dir.length).replace(/\\/g, '/');
  146. const doc = PostAsset.findById(id);
  147. if (file.type === 'delete') {
  148. if (doc) {
  149. return doc.remove();
  150. }
  151. return;
  152. }
  153. // TODO: Better post searching
  154. const posts = Post.toArray();
  155. let post;
  156. for (let i = 0, len = posts.length; i < len; i++) {
  157. post = posts[i];
  158. if (file.source.startsWith(post.asset_dir)) {
  159. return PostAsset.save({
  160. _id: id,
  161. slug: file.source.substring(post.asset_dir.length),
  162. post: post._id,
  163. modified: file.type !== 'skip',
  164. renderable: file.params.renderable
  165. });
  166. }
  167. }
  168. if (doc) {
  169. return doc.remove();
  170. }
  171. }
  172. return {
  173. pattern: new Pattern(path => {
  174. if (common.isTmpFile(path)) return;
  175. let result;
  176. if (path.startsWith(postDir)) {
  177. result = {
  178. published: true,
  179. path: path.substring(postDir.length)
  180. };
  181. } else if (path.startsWith(draftDir)) {
  182. result = {
  183. published: false,
  184. path: path.substring(draftDir.length)
  185. };
  186. }
  187. if (!result || common.isHiddenFile(result.path)) return;
  188. result.renderable = ctx.render.isRenderable(path) && !common.isMatch(path, ctx.config.skip_render);
  189. return result;
  190. }),
  191. process: function postProcessor(file) {
  192. if (file.params.renderable) {
  193. return processPost(file);
  194. } else if (ctx.config.post_asset_folder) {
  195. return processAsset(file);
  196. }
  197. }
  198. };
  199. };
  200. function parseFilename(config, path) {
  201. config = config.substring(0, config.length - pathFn.extname(config).length);
  202. path = path.substring(0, path.length - pathFn.extname(path).length);
  203. if (!permalink || permalink.rule !== config) {
  204. permalink = new Permalink(config, {
  205. segments: {
  206. year: /(\d{4})/,
  207. month: /(\d{2})/,
  208. day: /(\d{2})/,
  209. i_month: /(\d{1,2})/,
  210. i_day: /(\d{1,2})/
  211. }
  212. });
  213. }
  214. const data = permalink.parse(path);
  215. if (data) {
  216. return data;
  217. }
  218. return {
  219. title: slugize(path)
  220. };
  221. }