You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

500 lines
11 KiB

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