entries.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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. })
  237. }).then(result => {
  238. return self.updateTreeInfo().then(() => {
  239. return result
  240. })
  241. }).catch(err => {
  242. winston.error(err)
  243. return err
  244. })
  245. },
  246. /**
  247. * Update tree info for all directory and parent entries
  248. *
  249. * @returns {Promise<Boolean>} Promise of the operation
  250. */
  251. updateTreeInfo () {
  252. return db.Entry.distinct('parentPath', { parentPath: { $ne: '' } }).then(allPaths => {
  253. if (allPaths.length > 0) {
  254. return Promise.map(allPaths, pathItem => {
  255. let parentPath = _.chain(pathItem).split('/').initial().join('/').value()
  256. let guessedTitle = _.chain(pathItem).split('/').last().startCase().value()
  257. return db.Entry.update({ _id: pathItem }, {
  258. $set: { isDirectory: true },
  259. $setOnInsert: { isEntry: false, title: guessedTitle, parentPath }
  260. }, { upsert: true })
  261. })
  262. } else {
  263. return true
  264. }
  265. })
  266. },
  267. /**
  268. * Create a new document
  269. *
  270. * @param {String} entryPath The entry path
  271. * @param {String} contents The markdown-formatted contents
  272. * @param {Object} author The author user object
  273. * @return {Promise<Boolean>} True on success, false on failure
  274. */
  275. create (entryPath, contents, author) {
  276. let self = this
  277. return self.exists(entryPath).then((docExists) => {
  278. if (!docExists) {
  279. return self.makePersistent(entryPath, contents, author).then(() => {
  280. return self.updateCache(entryPath).then(entry => {
  281. return search.add(entry)
  282. })
  283. })
  284. } else {
  285. return Promise.reject(new Error(lang.t('errors:alreadyexists')))
  286. }
  287. }).catch((err) => {
  288. winston.error(err)
  289. return Promise.reject(new Error(lang.t('errors:generic')))
  290. })
  291. },
  292. /**
  293. * Makes a document persistent to disk and git repository
  294. *
  295. * @param {String} entryPath The entry path
  296. * @param {String} contents The markdown-formatted contents
  297. * @param {Object} author The author user object
  298. * @return {Promise<Boolean>} True on success, false on failure
  299. */
  300. makePersistent (entryPath, contents, author) {
  301. let fpath = entryHelper.getFullPath(entryPath)
  302. return fs.outputFileAsync(fpath, contents).then(() => {
  303. return git.commitDocument(entryPath, author)
  304. })
  305. },
  306. /**
  307. * Move a document
  308. *
  309. * @param {String} entryPath The current entry path
  310. * @param {String} newEntryPath The new entry path
  311. * @param {Object} author The author user object
  312. * @return {Promise} Promise of the operation
  313. */
  314. move (entryPath, newEntryPath, author) {
  315. let self = this
  316. if (_.isEmpty(entryPath) || entryPath === 'home') {
  317. return Promise.reject(new Error(lang.t('errors:invalidpath')))
  318. }
  319. return git.moveDocument(entryPath, newEntryPath).then(() => {
  320. return git.commitDocument(newEntryPath, author).then(() => {
  321. // Delete old cache version
  322. let oldEntryCachePath = entryHelper.getCachePath(entryPath)
  323. fs.unlinkAsync(oldEntryCachePath).catch((err) => { return true }) // eslint-disable-line handle-callback-err
  324. // Delete old index entry
  325. search.delete(entryPath)
  326. // Create cache for new entry
  327. return self.updateCache(newEntryPath).then(entry => {
  328. return search.add(entry)
  329. })
  330. })
  331. })
  332. },
  333. /**
  334. * Generate a starter page content based on the entry path
  335. *
  336. * @param {String} entryPath The entry path
  337. * @return {Promise<String>} Starter content
  338. */
  339. getStarter (entryPath) {
  340. let formattedTitle = _.startCase(_.last(_.split(entryPath, '/')))
  341. return fs.readFileAsync(path.join(SERVERPATH, 'app/content/create.md'), 'utf8').then((contents) => {
  342. return _.replace(contents, new RegExp('{TITLE}', 'g'), formattedTitle)
  343. })
  344. },
  345. /**
  346. * Get all entries from base path
  347. *
  348. * @param {String} basePath Path to list from
  349. * @param {Object} usr Current user
  350. * @return {Promise<Array>} List of entries
  351. */
  352. getFromTree (basePath, usr) {
  353. return db.Entry.find({ parentPath: basePath }, 'title parentPath isDirectory isEntry').sort({ title: 'asc' }).then(results => {
  354. return _.filter(results, r => {
  355. return rights.checkRole('/' + r._id, usr.rights, 'read')
  356. })
  357. })
  358. },
  359. getHistory (entryPath) {
  360. return db.Entry.findOne({ _id: entryPath, isEntry: true }).then(entry => {
  361. if (!entry) { return false }
  362. return git.getHistory(entryPath).then(history => {
  363. return {
  364. meta: entry,
  365. history
  366. }
  367. })
  368. })
  369. }
  370. }