entries.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. "use strict";
  2. var Promise = require('bluebird'),
  3. path = require('path'),
  4. fs = Promise.promisifyAll(require("fs-extra")),
  5. _ = require('lodash'),
  6. farmhash = require('farmhash'),
  7. BSONModule = require('bson'),
  8. BSON = new BSONModule.BSONPure.BSON();
  9. /**
  10. * Entries Model
  11. */
  12. module.exports = {
  13. _repoPath: 'repo',
  14. _cachePath: 'data/cache',
  15. /**
  16. * Initialize Entries model
  17. *
  18. * @param {Object} appconfig The application config
  19. * @return {Object} Entries model instance
  20. */
  21. init(appconfig) {
  22. let self = this;
  23. self._repoPath = appconfig.datadir.repo;
  24. self._cachePath = path.join(appconfig.datadir.db, 'cache');
  25. return self;
  26. },
  27. /**
  28. * Check if a document already exists
  29. *
  30. * @param {String} entryPath The entry path
  31. * @return {Promise<Boolean>} True if exists, false otherwise
  32. */
  33. exists(entryPath) {
  34. let self = this;
  35. return self.fetchOriginal(entryPath, {
  36. parseMarkdown: false,
  37. parseMeta: false,
  38. parseTree: false,
  39. includeMarkdown: false,
  40. includeParentInfo: false,
  41. cache: false
  42. }).then(() => {
  43. return true;
  44. }).catch((err) => {
  45. return false;
  46. });
  47. },
  48. /**
  49. * Fetch a document from cache, otherwise the original
  50. *
  51. * @param {String} entryPath The entry path
  52. * @return {Promise<Object>} Page Data
  53. */
  54. fetch(entryPath) {
  55. let self = this;
  56. let cpath = self.getCachePath(entryPath);
  57. return fs.statAsync(cpath).then((st) => {
  58. return st.isFile();
  59. }).catch((err) => {
  60. return false;
  61. }).then((isCache) => {
  62. if(isCache) {
  63. // Load from cache
  64. return fs.readFileAsync(cpath).then((contents) => {
  65. return BSON.deserialize(contents);
  66. }).catch((err) => {
  67. winston.error('Corrupted cache file. Deleting it...');
  68. fs.unlinkSync(cpath);
  69. return false;
  70. });
  71. } else {
  72. // Load original
  73. return self.fetchOriginal(entryPath);
  74. }
  75. });
  76. },
  77. /**
  78. * Fetches the original document entry
  79. *
  80. * @param {String} entryPath The entry path
  81. * @param {Object} options The options
  82. * @return {Promise<Object>} Page data
  83. */
  84. fetchOriginal(entryPath, options) {
  85. let self = this;
  86. let fpath = self.getFullPath(entryPath);
  87. let cpath = self.getCachePath(entryPath);
  88. options = _.defaults(options, {
  89. parseMarkdown: true,
  90. parseMeta: true,
  91. parseTree: true,
  92. includeMarkdown: false,
  93. includeParentInfo: true,
  94. cache: true
  95. });
  96. return fs.statAsync(fpath).then((st) => {
  97. if(st.isFile()) {
  98. return fs.readFileAsync(fpath, 'utf8').then((contents) => {
  99. // Parse contents
  100. let pageData = {
  101. markdown: (options.includeMarkdown) ? contents : '',
  102. html: (options.parseMarkdown) ? mark.parseContent(contents) : '',
  103. meta: (options.parseMeta) ? mark.parseMeta(contents) : {},
  104. tree: (options.parseTree) ? mark.parseTree(contents) : []
  105. };
  106. if(!pageData.meta.title) {
  107. pageData.meta.title = _.startCase(entryPath);
  108. }
  109. pageData.meta.path = entryPath;
  110. // Get parent
  111. let parentPromise = (options.includeParentInfo) ? self.getParentInfo(entryPath).then((parentData) => {
  112. return (pageData.parent = parentData);
  113. }).catch((err) => {
  114. return (pageData.parent = false);
  115. }) : Promise.resolve(true);
  116. return parentPromise.then(() => {
  117. // Cache to disk
  118. if(options.cache) {
  119. let cacheData = BSON.serialize(pageData, false, false, false);
  120. return fs.writeFileAsync(cpath, cacheData).catch((err) => {
  121. winston.error('Unable to write to cache! Performance may be affected.');
  122. return true;
  123. });
  124. } else {
  125. return true;
  126. }
  127. }).return(pageData);
  128. });
  129. } else {
  130. return false;
  131. }
  132. }).catch((err) => {
  133. return Promise.reject(new Error('Entry ' + entryPath + ' does not exist!'));
  134. });
  135. },
  136. /**
  137. * Parse raw url path and make it safe
  138. *
  139. * @param {String} urlPath The url path
  140. * @return {String} Safe entry path
  141. */
  142. parsePath(urlPath) {
  143. let wlist = new RegExp('[^a-z0-9/\-]','g');
  144. urlPath = _.toLower(urlPath).replace(wlist, '');
  145. if(urlPath === '/') {
  146. urlPath = 'home';
  147. }
  148. let urlParts = _.filter(_.split(urlPath, '/'), (p) => { return !_.isEmpty(p); });
  149. return _.join(urlParts, '/');
  150. },
  151. /**
  152. * Gets the parent information.
  153. *
  154. * @param {String} entryPath The entry path
  155. * @return {Promise<Object|False>} The parent information.
  156. */
  157. getParentInfo(entryPath) {
  158. let self = this;
  159. if(_.includes(entryPath, '/')) {
  160. let parentParts = _.initial(_.split(entryPath, '/'));
  161. let parentPath = _.join(parentParts,'/');
  162. let parentFile = _.last(parentParts);
  163. let fpath = self.getFullPath(parentPath);
  164. return fs.statAsync(fpath).then((st) => {
  165. if(st.isFile()) {
  166. return fs.readFileAsync(fpath, 'utf8').then((contents) => {
  167. let pageMeta = mark.parseMeta(contents);
  168. return {
  169. path: parentPath,
  170. title: (pageMeta.title) ? pageMeta.title : _.startCase(parentFile),
  171. subtitle: (pageMeta.subtitle) ? pageMeta.subtitle : false
  172. };
  173. });
  174. } else {
  175. return Promise.reject(new Error('Parent entry is not a valid file.'));
  176. }
  177. });
  178. } else {
  179. return Promise.reject(new Error('Parent entry is root.'));
  180. }
  181. },
  182. /**
  183. * Gets the full original path of a document.
  184. *
  185. * @param {String} entryPath The entry path
  186. * @return {String} The full path.
  187. */
  188. getFullPath(entryPath) {
  189. return path.join(this._repoPath, entryPath + '.md');
  190. },
  191. /**
  192. * Gets the full cache path of a document.
  193. *
  194. * @param {String} entryPath The entry path
  195. * @return {String} The full cache path.
  196. */
  197. getCachePath(entryPath) {
  198. return path.join(this._cachePath, farmhash.fingerprint32(entryPath) + '.bson');
  199. },
  200. /**
  201. * Update an existing document
  202. *
  203. * @param {String} entryPath The entry path
  204. * @param {String} contents The markdown-formatted contents
  205. * @return {Promise<Boolean>} True on success, false on failure
  206. */
  207. update(entryPath, contents) {
  208. let self = this;
  209. let fpath = self.getFullPath(entryPath);
  210. return fs.statAsync(fpath).then((st) => {
  211. if(st.isFile()) {
  212. return self.makePersistent(entryPath, contents).then(() => {
  213. return self.fetchOriginal(entryPath, {});
  214. });
  215. } else {
  216. return Promise.reject(new Error('Entry does not exist!'));
  217. }
  218. }).catch((err) => {
  219. return Promise.reject(new Error('Entry does not exist!'));
  220. });
  221. },
  222. /**
  223. * Create a new document
  224. *
  225. * @param {String} entryPath The entry path
  226. * @param {String} contents The markdown-formatted contents
  227. * @return {Promise<Boolean>} True on success, false on failure
  228. */
  229. create(entryPath, contents) {
  230. let self = this;
  231. return self.exists(entryPath).then((docExists) => {
  232. if(!docExists) {
  233. return self.makePersistent(entryPath, contents).then(() => {
  234. return self.fetchOriginal(entryPath, {});
  235. });
  236. } else {
  237. return Promise.reject(new Error('Entry already exists!'));
  238. }
  239. }).catch((err) => {
  240. winston.error(err);
  241. return Promise.reject(new Error('Something went wrong.'));
  242. });
  243. },
  244. /**
  245. * Makes a document persistent to disk and git repository
  246. *
  247. * @param {String} entryPath The entry path
  248. * @param {String} contents The markdown-formatted contents
  249. * @return {Promise<Boolean>} True on success, false on failure
  250. */
  251. makePersistent(entryPath, contents) {
  252. let self = this;
  253. let fpath = self.getFullPath(entryPath);
  254. return fs.outputFileAsync(fpath, contents).then(() => {
  255. return git.commitDocument(entryPath);
  256. });
  257. },
  258. /**
  259. * Generate a starter page content based on the entry path
  260. *
  261. * @param {String} entryPath The entry path
  262. * @return {Promise<String>} Starter content
  263. */
  264. getStarter(entryPath) {
  265. let self = this;
  266. let formattedTitle = _.startCase(_.last(_.split(entryPath, '/')));
  267. return fs.readFileAsync(path.join(ROOTPATH, 'client/content/create.md'), 'utf8').then((contents) => {
  268. return _.replace(contents, new RegExp('{TITLE}', 'g'), formattedTitle);
  269. });
  270. }
  271. };