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.

406 lines
12 KiB

  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 entryHelper = require('../helpers/entry')
  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. appdata.repoPath = self._repoPath
  23. appdata.cachePath = self._cachePath
  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) => { // eslint-disable-line handle-callback-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 = entryHelper.getCachePath(entryPath)
  56. return fs.statAsync(cpath).then((st) => {
  57. return st.isFile()
  58. }).catch((err) => { // eslint-disable-line handle-callback-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) => { // eslint-disable-line handle-callback-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 = entryHelper.getFullPath(entryPath)
  86. let cpath = entryHelper.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) => { // eslint-disable-line handle-callback-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. winston.error(err)
  122. return true
  123. })
  124. } else {
  125. return true
  126. }
  127. }).return(pageData)
  128. })
  129. } else {
  130. return false
  131. }
  132. }).catch((err) => { // eslint-disable-line handle-callback-err
  133. throw new Promise.OperationalError('Entry ' + entryPath + ' does not exist!')
  134. })
  135. },
  136. /**
  137. * Gets the parent information.
  138. *
  139. * @param {String} entryPath The entry path
  140. * @return {Promise<Object|False>} The parent information.
  141. */
  142. getParentInfo (entryPath) {
  143. if (_.includes(entryPath, '/')) {
  144. let parentParts = _.initial(_.split(entryPath, '/'))
  145. let parentPath = _.join(parentParts, '/')
  146. let parentFile = _.last(parentParts)
  147. let fpath = entryHelper.getFullPath(parentPath)
  148. return fs.statAsync(fpath).then((st) => {
  149. if (st.isFile()) {
  150. return fs.readFileAsync(fpath, 'utf8').then((contents) => {
  151. let pageMeta = mark.parseMeta(contents)
  152. return {
  153. path: parentPath,
  154. title: (pageMeta.title) ? pageMeta.title : _.startCase(parentFile),
  155. subtitle: (pageMeta.subtitle) ? pageMeta.subtitle : false
  156. }
  157. })
  158. } else {
  159. return Promise.reject(new Error('Parent entry is not a valid file.'))
  160. }
  161. })
  162. } else {
  163. return Promise.reject(new Error('Parent entry is root.'))
  164. }
  165. },
  166. /**
  167. * Update an existing document
  168. *
  169. * @param {String} entryPath The entry path
  170. * @param {String} contents The markdown-formatted contents
  171. * @param {Object} author The author user object
  172. * @return {Promise<Boolean>} True on success, false on failure
  173. */
  174. update (entryPath, contents, author) {
  175. let self = this
  176. let fpath = entryHelper.getFullPath(entryPath)
  177. return fs.statAsync(fpath).then((st) => {
  178. if (st.isFile()) {
  179. return self.makePersistent(entryPath, contents, author).then(() => {
  180. return self.updateCache(entryPath).then(entry => {
  181. return search.add(entry)
  182. })
  183. })
  184. } else {
  185. return Promise.reject(new Error('Entry does not exist!'))
  186. }
  187. }).catch((err) => {
  188. winston.error(err)
  189. return Promise.reject(new Error('Failed to save document.'))
  190. })
  191. },
  192. /**
  193. * Update local cache
  194. *
  195. * @param {String} entryPath The entry path
  196. * @return {Promise} Promise of the operation
  197. */
  198. updateCache (entryPath) {
  199. let self = this
  200. return self.fetchOriginal(entryPath, {
  201. parseMarkdown: true,
  202. parseMeta: true,
  203. parseTree: true,
  204. includeMarkdown: true,
  205. includeParentInfo: true,
  206. cache: true
  207. }).catch(err => {
  208. winston.error(err)
  209. return err
  210. }).then((pageData) => {
  211. return {
  212. entryPath,
  213. meta: pageData.meta,
  214. parent: pageData.parent || {},
  215. text: mark.removeMarkdown(pageData.markdown)
  216. }
  217. }).catch(err => {
  218. winston.error(err)
  219. return err
  220. }).then((content) => {
  221. let parentPath = _.chain(content.entryPath).split('/').initial().join('/').value()
  222. return db.Entry.findOneAndUpdate({
  223. _id: content.entryPath
  224. }, {
  225. _id: content.entryPath,
  226. title: content.meta.title || content.entryPath,
  227. subtitle: content.meta.subtitle || '',
  228. parentTitle: content.parent.title || '',
  229. parentPath: parentPath,
  230. isDirectory: false,
  231. isEntry: true
  232. }, {
  233. new: true,
  234. upsert: true
  235. })
  236. }).then(result => {
  237. return self.updateTreeInfo().then(() => {
  238. return result
  239. })
  240. }).catch(err => {
  241. winston.error(err)
  242. return err
  243. })
  244. },
  245. /**
  246. * Update tree info for all directory and parent entries
  247. *
  248. * @returns {Promise<Boolean>} Promise of the operation
  249. */
  250. updateTreeInfo () {
  251. return db.Entry.distinct('parentPath', { parentPath: { $ne: '' } }).then(allPaths => {
  252. if (allPaths.length > 0) {
  253. return Promise.map(allPaths, pathItem => {
  254. let parentPath = _.chain(pathItem).split('/').initial().join('/').value()
  255. let guessedTitle = _.chain(pathItem).split('/').last().startCase().value()
  256. return db.Entry.update({ _id: pathItem }, {
  257. $set: { isDirectory: true },
  258. $setOnInsert: { isEntry: false, title: guessedTitle, parentPath }
  259. }, { upsert: true })
  260. })
  261. } else {
  262. return true
  263. }
  264. })
  265. },
  266. /**
  267. * Create a new document
  268. *
  269. * @param {String} entryPath The entry path
  270. * @param {String} contents The markdown-formatted contents
  271. * @param {Object} author The author user object
  272. * @return {Promise<Boolean>} True on success, false on failure
  273. */
  274. create (entryPath, contents, author) {
  275. let self = this
  276. return self.exists(entryPath).then((docExists) => {
  277. if (!docExists) {
  278. return self.makePersistent(entryPath, contents, author).then(() => {
  279. return self.updateCache(entryPath).then(entry => {
  280. return search.add(entry)
  281. })
  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. * @param {Object} author The author user object
  297. * @return {Promise<Boolean>} True on success, false on failure
  298. */
  299. makePersistent (entryPath, contents, author) {
  300. let fpath = entryHelper.getFullPath(entryPath)
  301. return fs.outputFileAsync(fpath, contents).then(() => {
  302. return git.commitDocument(entryPath, author)
  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. * @param {Object} author The author user object
  311. * @return {Promise} Promise of the operation
  312. */
  313. move (entryPath, newEntryPath, author) {
  314. let self = this
  315. if (_.isEmpty(entryPath) || entryPath === 'home') {
  316. return Promise.reject(new Error('Invalid path!'))
  317. }
  318. return git.moveDocument(entryPath, newEntryPath).then(() => {
  319. return git.commitDocument(newEntryPath, author).then(() => {
  320. // Delete old cache version
  321. let oldEntryCachePath = entryHelper.getCachePath(entryPath)
  322. fs.unlinkAsync(oldEntryCachePath).catch((err) => { return true }) // eslint-disable-line handle-callback-err
  323. // Delete old index entry
  324. search.delete(entryPath)
  325. // Create cache for new entry
  326. return self.updateCache(newEntryPath).then(entry => {
  327. return search.add(entry)
  328. })
  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 formattedTitle = _.startCase(_.last(_.split(entryPath, '/')))
  340. return fs.readFileAsync(path.join(SERVERPATH, 'app/content/create.md'), 'utf8').then((contents) => {
  341. return _.replace(contents, new RegExp('{TITLE}', 'g'), formattedTitle)
  342. })
  343. },
  344. /**
  345. * Get all entries from base path
  346. *
  347. * @param {String} basePath Path to list from
  348. * @param {Object} usr Current user
  349. * @return {Promise<Array>} List of entries
  350. */
  351. getFromTree (basePath, usr) {
  352. return db.Entry.find({ parentPath: basePath }, 'title parentPath isDirectory isEntry').sort({ title: 'asc' }).then(results => {
  353. return _.filter(results, r => {
  354. return rights.checkRole('/' + r._id, usr.rights, 'read')
  355. })
  356. })
  357. }
  358. }