entries.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. 'use strict'
  2. const Promise = require('bluebird')
  3. const path = require('path')
  4. const fs = Promise.promisifyAll(require('fs-extra'))
  5. const _ = require('lodash')
  6. const farmhash = require('farmhash')
  7. /**
  8. * Entries Model
  9. */
  10. module.exports = {
  11. _repoPath: 'repo',
  12. _cachePath: 'data/cache',
  13. /**
  14. * Initialize Entries model
  15. *
  16. * @return {Object} Entries model instance
  17. */
  18. init () {
  19. let self = this
  20. self._repoPath = path.resolve(ROOTPATH, appconfig.paths.repo)
  21. self._cachePath = path.resolve(ROOTPATH, appconfig.paths.data, 'cache')
  22. return self
  23. },
  24. /**
  25. * Check if a document already exists
  26. *
  27. * @param {String} entryPath The entry path
  28. * @return {Promise<Boolean>} True if exists, false otherwise
  29. */
  30. exists (entryPath) {
  31. let self = this
  32. return self.fetchOriginal(entryPath, {
  33. parseMarkdown: false,
  34. parseMeta: false,
  35. parseTree: false,
  36. includeMarkdown: false,
  37. includeParentInfo: false,
  38. cache: false
  39. }).then(() => {
  40. return true
  41. }).catch((err) => { // eslint-disable-line handle-callback-err
  42. return false
  43. })
  44. },
  45. /**
  46. * Fetch a document from cache, otherwise the original
  47. *
  48. * @param {String} entryPath The entry path
  49. * @return {Promise<Object>} Page Data
  50. */
  51. fetch (entryPath) {
  52. let self = this
  53. let cpath = self.getCachePath(entryPath)
  54. return fs.statAsync(cpath).then((st) => {
  55. return st.isFile()
  56. }).catch((err) => { // eslint-disable-line handle-callback-err
  57. return false
  58. }).then((isCache) => {
  59. if (isCache) {
  60. // Load from cache
  61. return fs.readFileAsync(cpath).then((contents) => {
  62. return JSON.parse(contents)
  63. }).catch((err) => { // eslint-disable-line handle-callback-err
  64. winston.error('Corrupted cache file. Deleting it...')
  65. fs.unlinkSync(cpath)
  66. return false
  67. })
  68. } else {
  69. // Load original
  70. return self.fetchOriginal(entryPath)
  71. }
  72. })
  73. },
  74. /**
  75. * Fetches the original document entry
  76. *
  77. * @param {String} entryPath The entry path
  78. * @param {Object} options The options
  79. * @return {Promise<Object>} Page data
  80. */
  81. fetchOriginal (entryPath, options) {
  82. let self = this
  83. let fpath = self.getFullPath(entryPath)
  84. let cpath = self.getCachePath(entryPath)
  85. options = _.defaults(options, {
  86. parseMarkdown: true,
  87. parseMeta: true,
  88. parseTree: true,
  89. includeMarkdown: false,
  90. includeParentInfo: true,
  91. cache: true
  92. })
  93. return fs.statAsync(fpath).then((st) => {
  94. if (st.isFile()) {
  95. return fs.readFileAsync(fpath, 'utf8').then((contents) => {
  96. // Parse contents
  97. let pageData = {
  98. markdown: (options.includeMarkdown) ? contents : '',
  99. html: (options.parseMarkdown) ? mark.parseContent(contents) : '',
  100. meta: (options.parseMeta) ? mark.parseMeta(contents) : {},
  101. tree: (options.parseTree) ? mark.parseTree(contents) : []
  102. }
  103. if (!pageData.meta.title) {
  104. pageData.meta.title = _.startCase(entryPath)
  105. }
  106. pageData.meta.path = entryPath
  107. // Get parent
  108. let parentPromise = (options.includeParentInfo) ? self.getParentInfo(entryPath).then((parentData) => {
  109. return (pageData.parent = parentData)
  110. }).catch((err) => { // eslint-disable-line handle-callback-err
  111. return (pageData.parent = false)
  112. }) : Promise.resolve(true)
  113. return parentPromise.then(() => {
  114. // Cache to disk
  115. if (options.cache) {
  116. let cacheData = JSON.stringify(_.pick(pageData, ['html', 'meta', 'tree', 'parent']), false, false, false)
  117. return fs.writeFileAsync(cpath, cacheData).catch((err) => {
  118. winston.error('Unable to write to cache! Performance may be affected.')
  119. winston.error(err)
  120. return true
  121. })
  122. } else {
  123. return true
  124. }
  125. }).return(pageData)
  126. })
  127. } else {
  128. return false
  129. }
  130. }).catch((err) => { // eslint-disable-line handle-callback-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 }) // eslint-disable-line handle-callback-err
  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 formattedTitle = _.startCase(_.last(_.split(entryPath, '/')))
  339. return fs.readFileAsync(path.join(ROOTPATH, 'client/content/create.md'), 'utf8').then((contents) => {
  340. return _.replace(contents, new RegExp('{TITLE}', 'g'), formattedTitle)
  341. })
  342. },
  343. /**
  344. * Searches entries based on terms.
  345. *
  346. * @param {String} terms The terms to search for
  347. * @return {Promise<Object>} Promise of the search results
  348. */
  349. search (terms) {
  350. terms = _.chain(terms)
  351. .deburr()
  352. .toLower()
  353. .trim()
  354. .replace(/[^a-z0-9\- ]/g, '')
  355. .split(' ')
  356. .filter((f) => { return !_.isEmpty(f) })
  357. .join(' ')
  358. .value()
  359. return db.Entry.find(
  360. { $text: { $search: terms } },
  361. { score: { $meta: 'textScore' }, title: 1 }
  362. )
  363. .sort({ score: { $meta: 'textScore' } })
  364. .limit(10)
  365. .exec()
  366. .then((hits) => {
  367. if (hits.length < 5) {
  368. let regMatch = new RegExp('^' + _.split(terms, ' ')[0])
  369. return db.Entry.find({
  370. _id: { $regex: regMatch }
  371. }, '_id')
  372. .sort('_id')
  373. .limit(5)
  374. .exec()
  375. .then((matches) => {
  376. return {
  377. match: hits,
  378. suggest: (matches) ? _.map(matches, '_id') : []
  379. }
  380. })
  381. } else {
  382. return {
  383. match: _.filter(hits, (h) => { return h._doc.score >= 1 }),
  384. suggest: []
  385. }
  386. }
  387. }).catch((err) => {
  388. winston.error(err)
  389. return {
  390. match: [],
  391. suggest: []
  392. }
  393. })
  394. }
  395. }