entries.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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. moment = require('moment');
  8. /**
  9. * Entries Model
  10. */
  11. module.exports = {
  12. _repoPath: 'repo',
  13. _cachePath: 'data/cache',
  14. /**
  15. * Initialize Entries model
  16. *
  17. * @return {Object} Entries model instance
  18. */
  19. init() {
  20. let self = this;
  21. self._repoPath = path.resolve(ROOTPATH, appconfig.paths.repo);
  22. self._cachePath = path.resolve(ROOTPATH, appconfig.paths.data, 'cache');
  23. return self;
  24. },
  25. /**
  26. * Check if a document already exists
  27. *
  28. * @param {String} entryPath The entry path
  29. * @return {Promise<Boolean>} True if exists, false otherwise
  30. */
  31. exists(entryPath) {
  32. let self = this;
  33. return self.fetchOriginal(entryPath, {
  34. parseMarkdown: false,
  35. parseMeta: false,
  36. parseTree: false,
  37. includeMarkdown: false,
  38. includeParentInfo: false,
  39. cache: false
  40. }).then(() => {
  41. return true;
  42. }).catch((err) => {
  43. return false;
  44. });
  45. },
  46. /**
  47. * Fetch a document from cache, otherwise the original
  48. *
  49. * @param {String} entryPath The entry path
  50. * @return {Promise<Object>} Page Data
  51. */
  52. fetch(entryPath) {
  53. let self = this;
  54. let cpath = self.getCachePath(entryPath);
  55. return fs.statAsync(cpath).then((st) => {
  56. return st.isFile();
  57. }).catch((err) => {
  58. return false;
  59. }).then((isCache) => {
  60. if(isCache) {
  61. // Load from cache
  62. return fs.readFileAsync(cpath).then((contents) => {
  63. return JSON.parse(contents);
  64. }).catch((err) => {
  65. winston.error('Corrupted cache file. Deleting it...');
  66. fs.unlinkSync(cpath);
  67. return false;
  68. });
  69. } else {
  70. // Load original
  71. return self.fetchOriginal(entryPath);
  72. }
  73. });
  74. },
  75. /**
  76. * Fetches the original document entry
  77. *
  78. * @param {String} entryPath The entry path
  79. * @param {Object} options The options
  80. * @return {Promise<Object>} Page data
  81. */
  82. fetchOriginal(entryPath, options) {
  83. let self = this;
  84. let fpath = self.getFullPath(entryPath);
  85. let cpath = self.getCachePath(entryPath);
  86. options = _.defaults(options, {
  87. parseMarkdown: true,
  88. parseMeta: true,
  89. parseTree: true,
  90. includeMarkdown: false,
  91. includeParentInfo: true,
  92. cache: true
  93. });
  94. return fs.statAsync(fpath).then((st) => {
  95. if(st.isFile()) {
  96. return fs.readFileAsync(fpath, 'utf8').then((contents) => {
  97. // Parse contents
  98. let pageData = {
  99. markdown: (options.includeMarkdown) ? contents : '',
  100. html: (options.parseMarkdown) ? mark.parseContent(contents) : '',
  101. meta: (options.parseMeta) ? mark.parseMeta(contents) : {},
  102. tree: (options.parseTree) ? mark.parseTree(contents) : []
  103. };
  104. if(!pageData.meta.title) {
  105. pageData.meta.title = _.startCase(entryPath);
  106. }
  107. pageData.meta.path = entryPath;
  108. // Get parent
  109. let parentPromise = (options.includeParentInfo) ? self.getParentInfo(entryPath).then((parentData) => {
  110. return (pageData.parent = parentData);
  111. }).catch((err) => {
  112. return (pageData.parent = false);
  113. }) : Promise.resolve(true);
  114. return parentPromise.then(() => {
  115. // Cache to disk
  116. if(options.cache) {
  117. let cacheData = JSON.stringify(_.pick(pageData, ['html', 'meta', 'tree', 'parent']), false, false, false);
  118. return fs.writeFileAsync(cpath, cacheData).catch((err) => {
  119. winston.error('Unable to write to cache! Performance may be affected.');
  120. return true;
  121. });
  122. } else {
  123. return true;
  124. }
  125. }).return(pageData);
  126. });
  127. } else {
  128. return false;
  129. }
  130. }).catch((err) => {
  131. return Promise.reject(new Promise.OperationalError('Entry ' + entryPath + ' does not exist!'));
  132. });
  133. },
  134. /**
  135. * Parse raw url path and make it safe
  136. *
  137. * @param {String} urlPath The url path
  138. * @return {String} Safe entry path
  139. */
  140. parsePath(urlPath) {
  141. let wlist = new RegExp('[^a-z0-9/\-]','g');
  142. urlPath = _.toLower(urlPath).replace(wlist, '');
  143. if(urlPath === '/') {
  144. urlPath = 'home';
  145. }
  146. let urlParts = _.filter(_.split(urlPath, '/'), (p) => { return !_.isEmpty(p); });
  147. return _.join(urlParts, '/');
  148. },
  149. /**
  150. * Gets the parent information.
  151. *
  152. * @param {String} entryPath The entry path
  153. * @return {Promise<Object|False>} The parent information.
  154. */
  155. getParentInfo(entryPath) {
  156. let self = this;
  157. if(_.includes(entryPath, '/')) {
  158. let parentParts = _.initial(_.split(entryPath, '/'));
  159. let parentPath = _.join(parentParts,'/');
  160. let parentFile = _.last(parentParts);
  161. let fpath = self.getFullPath(parentPath);
  162. return fs.statAsync(fpath).then((st) => {
  163. if(st.isFile()) {
  164. return fs.readFileAsync(fpath, 'utf8').then((contents) => {
  165. let pageMeta = mark.parseMeta(contents);
  166. return {
  167. path: parentPath,
  168. title: (pageMeta.title) ? pageMeta.title : _.startCase(parentFile),
  169. subtitle: (pageMeta.subtitle) ? pageMeta.subtitle : false
  170. };
  171. });
  172. } else {
  173. return Promise.reject(new Error('Parent entry is not a valid file.'));
  174. }
  175. });
  176. } else {
  177. return Promise.reject(new Error('Parent entry is root.'));
  178. }
  179. },
  180. /**
  181. * Gets the full original path of a document.
  182. *
  183. * @param {String} entryPath The entry path
  184. * @return {String} The full path.
  185. */
  186. getFullPath(entryPath) {
  187. return path.join(this._repoPath, entryPath + '.md');
  188. },
  189. /**
  190. * Gets the full cache path of a document.
  191. *
  192. * @param {String} entryPath The entry path
  193. * @return {String} The full cache path.
  194. */
  195. getCachePath(entryPath) {
  196. return path.join(this._cachePath, farmhash.fingerprint32(entryPath) + '.json');
  197. },
  198. /**
  199. * Gets the entry path from full path.
  200. *
  201. * @param {String} fullPath The full path
  202. * @return {String} The entry path
  203. */
  204. getEntryPathFromFullPath(fullPath) {
  205. let absRepoPath = path.resolve(ROOTPATH, this._repoPath);
  206. return _.chain(fullPath).replace(absRepoPath, '').replace('.md', '').replace(new RegExp('\\\\', 'g'),'/').value();
  207. },
  208. /**
  209. * Update an existing document
  210. *
  211. * @param {String} entryPath The entry path
  212. * @param {String} contents The markdown-formatted contents
  213. * @return {Promise<Boolean>} True on success, false on failure
  214. */
  215. update(entryPath, contents) {
  216. let self = this;
  217. let fpath = self.getFullPath(entryPath);
  218. return fs.statAsync(fpath).then((st) => {
  219. if(st.isFile()) {
  220. return self.makePersistent(entryPath, contents).then(() => {
  221. return self.updateCache(entryPath);
  222. });
  223. } else {
  224. return Promise.reject(new Error('Entry does not exist!'));
  225. }
  226. }).catch((err) => {
  227. winston.error(err);
  228. return Promise.reject(new Error('Failed to save document.'));
  229. });
  230. },
  231. /**
  232. * Update local cache and search index
  233. *
  234. * @param {String} entryPath The entry path
  235. * @return {Promise} Promise of the operation
  236. */
  237. updateCache(entryPath) {
  238. let self = this;
  239. return self.fetchOriginal(entryPath, {
  240. parseMarkdown: true,
  241. parseMeta: true,
  242. parseTree: true,
  243. includeMarkdown: true,
  244. includeParentInfo: true,
  245. cache: true
  246. }).then((pageData) => {
  247. return {
  248. entryPath,
  249. meta: pageData.meta,
  250. parent: pageData.parent || {},
  251. text: mark.removeMarkdown(pageData.markdown)
  252. };
  253. }).then((content) => {
  254. return db.Entry.findOneAndUpdate({
  255. _id: content.entryPath
  256. }, {
  257. _id: content.entryPath,
  258. title: content.meta.title || content.entryPath,
  259. subtitle: content.meta.subtitle || '',
  260. parent: content.parent.title || '',
  261. content: content.text || ''
  262. }, {
  263. new: true,
  264. upsert: true
  265. });
  266. });
  267. },
  268. /**
  269. * Create a new document
  270. *
  271. * @param {String} entryPath The entry path
  272. * @param {String} contents The markdown-formatted contents
  273. * @return {Promise<Boolean>} True on success, false on failure
  274. */
  275. create(entryPath, contents) {
  276. let self = this;
  277. return self.exists(entryPath).then((docExists) => {
  278. if(!docExists) {
  279. return self.makePersistent(entryPath, contents).then(() => {
  280. return self.updateCache(entryPath);
  281. });
  282. } else {
  283. return Promise.reject(new Error('Entry already exists!'));
  284. }
  285. }).catch((err) => {
  286. winston.error(err);
  287. return Promise.reject(new Error('Something went wrong.'));
  288. });
  289. },
  290. /**
  291. * Makes a document persistent to disk and git repository
  292. *
  293. * @param {String} entryPath The entry path
  294. * @param {String} contents The markdown-formatted contents
  295. * @return {Promise<Boolean>} True on success, false on failure
  296. */
  297. makePersistent(entryPath, contents) {
  298. let self = this;
  299. let fpath = self.getFullPath(entryPath);
  300. return fs.outputFileAsync(fpath, contents).then(() => {
  301. return git.commitDocument(entryPath);
  302. });
  303. },
  304. /**
  305. * Move a document
  306. *
  307. * @param {String} entryPath The current entry path
  308. * @param {String} newEntryPath The new entry path
  309. * @return {Promise} Promise of the operation
  310. */
  311. move(entryPath, newEntryPath) {
  312. let self = this;
  313. if(_.isEmpty(entryPath) || entryPath === 'home') {
  314. return Promise.reject(new Error('Invalid path!'));
  315. }
  316. return git.moveDocument(entryPath, newEntryPath).then(() => {
  317. return git.commitDocument(newEntryPath).then(() => {
  318. // Delete old cache version
  319. let oldEntryCachePath = self.getCachePath(entryPath);
  320. fs.unlinkAsync(oldEntryCachePath).catch((err) => { return true; });
  321. // Delete old index entry
  322. ws.emit('searchDel', {
  323. auth: WSInternalKey,
  324. entryPath
  325. });
  326. // Create cache for new entry
  327. return self.updateCache(newEntryPath);
  328. });
  329. });
  330. },
  331. /**
  332. * Generate a starter page content based on the entry path
  333. *
  334. * @param {String} entryPath The entry path
  335. * @return {Promise<String>} Starter content
  336. */
  337. getStarter(entryPath) {
  338. let self = this;
  339. let formattedTitle = _.startCase(_.last(_.split(entryPath, '/')));
  340. return fs.readFileAsync(path.join(ROOTPATH, 'client/content/create.md'), 'utf8').then((contents) => {
  341. return _.replace(contents, new RegExp('{TITLE}', 'g'), formattedTitle);
  342. });
  343. },
  344. /**
  345. * Searches entries based on terms.
  346. *
  347. * @param {String} terms The terms to search for
  348. * @return {Promise<Object>} Promise of the search results
  349. */
  350. search(terms) {
  351. let self = this;
  352. terms = _.chain(terms)
  353. .deburr()
  354. .toLower()
  355. .trim()
  356. .replace(/[^a-z0-9\- ]/g, '')
  357. .split(' ')
  358. .filter((f) => { return !_.isEmpty(f); })
  359. .join(' ')
  360. .value();
  361. return db.Entry.find(
  362. { $text: { $search: terms } },
  363. { score: { $meta: "textScore" }, title: 1 }
  364. )
  365. .sort({ score: { $meta: "textScore" } })
  366. .limit(10)
  367. .exec()
  368. .then((hits) => {
  369. if(hits.length < 5) {
  370. let regMatch = new RegExp('^' + _.split(terms, ' ')[0]);
  371. return db.Entry.find({
  372. _id: { $regex: regMatch }
  373. }, '_id')
  374. .sort('_id')
  375. .limit(5)
  376. .exec()
  377. .then((matches) => {
  378. return {
  379. match: hits,
  380. suggest: (matches) ? _.map(matches, '_id') : []
  381. };
  382. });
  383. } else {
  384. return {
  385. match: _.filter(hits, (h) => { return h._doc.score >= 1; }),
  386. suggest: []
  387. };
  388. }
  389. }).catch((err) => {
  390. winston.error(err);
  391. return {
  392. match: [],
  393. suggest: []
  394. };
  395. });
  396. }
  397. };