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.

424 lines
12 KiB

  1. 'use strict'
  2. /* global db, git, lang, mark, rights, search, winston */
  3. const Promise = require('bluebird')
  4. const path = require('path')
  5. const fs = Promise.promisifyAll(require('fs-extra'))
  6. const _ = require('lodash')
  7. const entryHelper = require('../helpers/entry')
  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. appdata.repoPath = self._repoPath
  24. appdata.cachePath = self._cachePath
  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) => { // eslint-disable-line handle-callback-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 = entryHelper.getCachePath(entryPath)
  57. return fs.statAsync(cpath).then((st) => {
  58. return st.isFile()
  59. }).catch((err) => { // eslint-disable-line handle-callback-err
  60. return false
  61. }).then((isCache) => {
  62. if (isCache) {
  63. // Load from cache
  64. return fs.readFileAsync(cpath).then((contents) => {
  65. return JSON.parse(contents)
  66. }).catch((err) => { // eslint-disable-line handle-callback-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 = entryHelper.getFullPath(entryPath)
  87. let cpath = entryHelper.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) => { // eslint-disable-line handle-callback-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 = JSON.stringify(_.pick(pageData, ['html', 'meta', 'tree', 'parent']), false, false, false)
  120. return fs.writeFileAsync(cpath, cacheData).catch((err) => {
  121. winston.error('Unable to write to cache! Performance may be affected.')
  122. winston.error(err)
  123. return true
  124. })
  125. } else {
  126. return true
  127. }
  128. }).return(pageData)
  129. })
  130. } else {
  131. return false
  132. }
  133. }).catch((err) => { // eslint-disable-line handle-callback-err
  134. throw new Promise.OperationalError(lang.t('errors:notexist', { path: entryPath }))
  135. })
  136. },
  137. /**
  138. * Gets the parent information.
  139. *
  140. * @param {String} entryPath The entry path
  141. * @return {Promise<Object|False>} The parent information.
  142. */
  143. getParentInfo (entryPath) {
  144. if (_.includes(entryPath, '/')) {
  145. let parentParts = _.initial(_.split(entryPath, '/'))
  146. let parentPath = _.join(parentParts, '/')
  147. let parentFile = _.last(parentParts)
  148. let fpath = entryHelper.getFullPath(parentPath)
  149. return fs.statAsync(fpath).then((st) => {
  150. if (st.isFile()) {
  151. return fs.readFileAsync(fpath, 'utf8').then((contents) => {
  152. let pageMeta = mark.parseMeta(contents)
  153. return {
  154. path: parentPath,
  155. title: (pageMeta.title) ? pageMeta.title : _.startCase(parentFile),
  156. subtitle: (pageMeta.subtitle) ? pageMeta.subtitle : false
  157. }
  158. })
  159. } else {
  160. return Promise.reject(new Error(lang.t('errors:parentinvalid')))
  161. }
  162. })
  163. } else {
  164. return Promise.reject(new Error(lang.t('errors:parentisroot')))
  165. }
  166. },
  167. /**
  168. * Update an existing document
  169. *
  170. * @param {String} entryPath The entry path
  171. * @param {String} contents The markdown-formatted contents
  172. * @param {Object} author The author user object
  173. * @return {Promise<Boolean>} True on success, false on failure
  174. */
  175. update (entryPath, contents, author) {
  176. let self = this
  177. let fpath = entryHelper.getFullPath(entryPath)
  178. return fs.statAsync(fpath).then((st) => {
  179. if (st.isFile()) {
  180. return self.makePersistent(entryPath, contents, author).then(() => {
  181. return self.updateCache(entryPath).then(entry => {
  182. return search.add(entry)
  183. })
  184. })
  185. } else {
  186. return Promise.reject(new Error(lang.t('errors:notexist', { path: entryPath })))
  187. }
  188. }).catch((err) => {
  189. winston.error(err)
  190. return Promise.reject(new Error(lang.t('errors:savefailed')))
  191. })
  192. },
  193. /**
  194. * Update local cache
  195. *
  196. * @param {String} entryPath The entry path
  197. * @return {Promise} Promise of the operation
  198. */
  199. updateCache (entryPath) {
  200. let self = this
  201. return self.fetchOriginal(entryPath, {
  202. parseMarkdown: true,
  203. parseMeta: true,
  204. parseTree: true,
  205. includeMarkdown: true,
  206. includeParentInfo: true,
  207. cache: true
  208. }).catch(err => {
  209. winston.error(err)
  210. return err
  211. }).then((pageData) => {
  212. return {
  213. entryPath,
  214. meta: pageData.meta,
  215. parent: pageData.parent || {},
  216. text: mark.removeMarkdown(pageData.markdown)
  217. }
  218. }).catch(err => {
  219. winston.error(err)
  220. return err
  221. }).then((content) => {
  222. let parentPath = _.chain(content.entryPath).split('/').initial().join('/').value()
  223. return db.Entry.findOneAndUpdate({
  224. _id: content.entryPath
  225. }, {
  226. _id: content.entryPath,
  227. title: content.meta.title || content.entryPath,
  228. subtitle: content.meta.subtitle || '',
  229. parentTitle: content.parent.title || '',
  230. parentPath: parentPath,
  231. isDirectory: false,
  232. isEntry: true
  233. }, {
  234. new: true,
  235. upsert: true
  236. }).then(result => {
  237. let plainResult = result.toObject()
  238. plainResult.text = content.text
  239. return plainResult
  240. })
  241. }).then(result => {
  242. return self.updateTreeInfo().then(() => {
  243. return result
  244. })
  245. }).catch(err => {
  246. winston.error(err)
  247. return err
  248. })
  249. },
  250. /**
  251. * Update tree info for all directory and parent entries
  252. *
  253. * @returns {Promise<Boolean>} Promise of the operation
  254. */
  255. updateTreeInfo () {
  256. return db.Entry.distinct('parentPath', { parentPath: { $ne: '' } }).then(allPaths => {
  257. if (allPaths.length > 0) {
  258. return Promise.map(allPaths, pathItem => {
  259. let parentPath = _.chain(pathItem).split('/').initial().join('/').value()
  260. let guessedTitle = _.chain(pathItem).split('/').last().startCase().value()
  261. return db.Entry.update({ _id: pathItem }, {
  262. $set: { isDirectory: true },
  263. $setOnInsert: { isEntry: false, title: guessedTitle, parentPath }
  264. }, { upsert: true })
  265. })
  266. } else {
  267. return true
  268. }
  269. })
  270. },
  271. /**
  272. * Create a new document
  273. *
  274. * @param {String} entryPath The entry path
  275. * @param {String} contents The markdown-formatted contents
  276. * @param {Object} author The author user object
  277. * @return {Promise<Boolean>} True on success, false on failure
  278. */
  279. create (entryPath, contents, author) {
  280. let self = this
  281. return self.exists(entryPath).then((docExists) => {
  282. if (!docExists) {
  283. return self.makePersistent(entryPath, contents, author).then(() => {
  284. return self.updateCache(entryPath).then(entry => {
  285. return search.add(entry)
  286. })
  287. })
  288. } else {
  289. return Promise.reject(new Error(lang.t('errors:alreadyexists')))
  290. }
  291. }).catch((err) => {
  292. winston.error(err)
  293. return Promise.reject(new Error(lang.t('errors:generic')))
  294. })
  295. },
  296. /**
  297. * Makes a document persistent to disk and git repository
  298. *
  299. * @param {String} entryPath The entry path
  300. * @param {String} contents The markdown-formatted contents
  301. * @param {Object} author The author user object
  302. * @return {Promise<Boolean>} True on success, false on failure
  303. */
  304. makePersistent (entryPath, contents, author) {
  305. let fpath = entryHelper.getFullPath(entryPath)
  306. return fs.outputFileAsync(fpath, contents).then(() => {
  307. return git.commitDocument(entryPath, author)
  308. })
  309. },
  310. /**
  311. * Move a document
  312. *
  313. * @param {String} entryPath The current entry path
  314. * @param {String} newEntryPath The new entry path
  315. * @param {Object} author The author user object
  316. * @return {Promise} Promise of the operation
  317. */
  318. move (entryPath, newEntryPath, author) {
  319. let self = this
  320. if (_.isEmpty(entryPath) || entryPath === 'home') {
  321. return Promise.reject(new Error(lang.t('errors:invalidpath')))
  322. }
  323. return git.moveDocument(entryPath, newEntryPath).then(() => {
  324. return git.commitDocument(newEntryPath, author).then(() => {
  325. // Delete old cache version
  326. let oldEntryCachePath = entryHelper.getCachePath(entryPath)
  327. fs.unlinkAsync(oldEntryCachePath).catch((err) => { return true }) // eslint-disable-line handle-callback-err
  328. // Delete old index entry
  329. search.delete(entryPath)
  330. // Create cache for new entry
  331. return self.updateCache(newEntryPath).then(entry => {
  332. return search.add(entry)
  333. })
  334. })
  335. })
  336. },
  337. /**
  338. * Generate a starter page content based on the entry path
  339. *
  340. * @param {String} entryPath The entry path
  341. * @return {Promise<String>} Starter content
  342. */
  343. getStarter (entryPath) {
  344. let formattedTitle = _.startCase(_.last(_.split(entryPath, '/')))
  345. return fs.readFileAsync(path.join(SERVERPATH, 'app/content/create.md'), 'utf8').then((contents) => {
  346. return _.replace(contents, new RegExp('{TITLE}', 'g'), formattedTitle)
  347. })
  348. },
  349. /**
  350. * Get all entries from base path
  351. *
  352. * @param {String} basePath Path to list from
  353. * @param {Object} usr Current user
  354. * @return {Promise<Array>} List of entries
  355. */
  356. getFromTree (basePath, usr) {
  357. return db.Entry.find({ parentPath: basePath }, 'title parentPath isDirectory isEntry').sort({ title: 'asc' }).then(results => {
  358. return _.filter(results, r => {
  359. return rights.checkRole('/' + r._id, usr.rights, 'read')
  360. })
  361. })
  362. },
  363. getHistory (entryPath) {
  364. return db.Entry.findOne({ _id: entryPath, isEntry: true }).then(entry => {
  365. if (!entry) { return false }
  366. return git.getHistory(entryPath).then(history => {
  367. return {
  368. meta: entry,
  369. history
  370. }
  371. })
  372. })
  373. }
  374. }