pages.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. const Model = require('objection').Model
  2. const _ = require('lodash')
  3. const JSBinType = require('js-binary').Type
  4. const pageHelper = require('../helpers/page')
  5. const path = require('path')
  6. const fs = require('fs-extra')
  7. const yaml = require('js-yaml')
  8. /* global WIKI */
  9. const frontmatterRegex = {
  10. html: /^(<!-{2}(?:\n|\r)([\w\W]+?)(?:\n|\r)-{2}>)?(?:\n|\r)*([\w\W]*)*/,
  11. legacy: /^(<!-- TITLE: ?([\w\W]+?) -{2}>)?(?:\n|\r)?(<!-- SUBTITLE: ?([\w\W]+?) -{2}>)?(?:\n|\r)*([\w\W]*)*/i,
  12. markdown: /^(-{3}(?:\n|\r)([\w\W]+?)(?:\n|\r)-{3})?(?:\n|\r)*([\w\W]*)*/
  13. }
  14. /**
  15. * Pages model
  16. */
  17. module.exports = class Page extends Model {
  18. static get tableName() { return 'pages' }
  19. static get jsonSchema () {
  20. return {
  21. type: 'object',
  22. required: ['path', 'title'],
  23. properties: {
  24. id: {type: 'integer'},
  25. path: {type: 'string'},
  26. hash: {type: 'string'},
  27. title: {type: 'string'},
  28. description: {type: 'string'},
  29. isPublished: {type: 'boolean'},
  30. privateNS: {type: 'string'},
  31. publishStartDate: {type: 'string'},
  32. publishEndDate: {type: 'string'},
  33. content: {type: 'string'},
  34. contentType: {type: 'string'},
  35. createdAt: {type: 'string'},
  36. updatedAt: {type: 'string'}
  37. }
  38. }
  39. }
  40. static get relationMappings() {
  41. return {
  42. tags: {
  43. relation: Model.ManyToManyRelation,
  44. modelClass: require('./tags'),
  45. join: {
  46. from: 'pages.id',
  47. through: {
  48. from: 'pageTags.pageId',
  49. to: 'pageTags.tagId'
  50. },
  51. to: 'tags.id'
  52. }
  53. },
  54. author: {
  55. relation: Model.BelongsToOneRelation,
  56. modelClass: require('./users'),
  57. join: {
  58. from: 'pages.authorId',
  59. to: 'users.id'
  60. }
  61. },
  62. creator: {
  63. relation: Model.BelongsToOneRelation,
  64. modelClass: require('./users'),
  65. join: {
  66. from: 'pages.creatorId',
  67. to: 'users.id'
  68. }
  69. },
  70. editor: {
  71. relation: Model.BelongsToOneRelation,
  72. modelClass: require('./editors'),
  73. join: {
  74. from: 'pages.editorKey',
  75. to: 'editors.key'
  76. }
  77. },
  78. locale: {
  79. relation: Model.BelongsToOneRelation,
  80. modelClass: require('./locales'),
  81. join: {
  82. from: 'pages.localeCode',
  83. to: 'locales.code'
  84. }
  85. }
  86. }
  87. }
  88. $beforeUpdate() {
  89. this.updatedAt = new Date().toISOString()
  90. }
  91. $beforeInsert() {
  92. this.createdAt = new Date().toISOString()
  93. this.updatedAt = new Date().toISOString()
  94. }
  95. static get cacheSchema() {
  96. return new JSBinType({
  97. id: 'uint',
  98. authorId: 'uint',
  99. authorName: 'string',
  100. createdAt: 'string',
  101. creatorId: 'uint',
  102. creatorName: 'string',
  103. description: 'string',
  104. isPrivate: 'boolean',
  105. isPublished: 'boolean',
  106. publishEndDate: 'string',
  107. publishStartDate: 'string',
  108. render: 'string',
  109. title: 'string',
  110. toc: 'string',
  111. updatedAt: 'string'
  112. })
  113. }
  114. /**
  115. * Inject page metadata into contents
  116. */
  117. injectMetadata () {
  118. let meta = [
  119. ['title', this.title],
  120. ['description', this.description],
  121. ['published', this.isPublished.toString()],
  122. ['date', this.updatedAt],
  123. ['tags', '']
  124. ]
  125. switch (this.contentType) {
  126. case 'markdown':
  127. return '---\n' + meta.map(mt => `${mt[0]}: ${mt[1]}`).join('\n') + '\n---\n\n' + this.content
  128. case 'html':
  129. return '<!--\n' + meta.map(mt => `${mt[0]}: ${mt[1]}`).join('\n') + '\n-->\n\n' + this.content
  130. default:
  131. return this.content
  132. }
  133. }
  134. /**
  135. * Parse injected page metadata from raw content
  136. *
  137. * @param {String} raw Raw file contents
  138. * @param {String} contentType Content Type
  139. */
  140. static parseMetadata (raw, contentType) {
  141. let result
  142. switch (contentType) {
  143. case 'markdown':
  144. result = frontmatterRegex.markdown.exec(raw)
  145. if (result[2]) {
  146. return {
  147. ...yaml.safeLoad(result[2]),
  148. content: result[3]
  149. }
  150. } else {
  151. // Attempt legacy v1 format
  152. result = frontmatterRegex.legacy.exec(raw)
  153. if (result[2]) {
  154. return {
  155. title: result[2],
  156. description: result[4],
  157. content: result[5]
  158. }
  159. }
  160. }
  161. break
  162. case 'html':
  163. result = frontmatterRegex.html.exec(raw)
  164. if (result[2]) {
  165. return {
  166. ...yaml.safeLoad(result[2]),
  167. content: result[3]
  168. }
  169. }
  170. break
  171. }
  172. return {
  173. content: raw
  174. }
  175. }
  176. static async createPage(opts) {
  177. await WIKI.models.pages.query().insert({
  178. authorId: opts.authorId,
  179. content: opts.content,
  180. creatorId: opts.authorId,
  181. contentType: _.get(_.find(WIKI.data.editors, ['key', opts.editor]), `contentType`, 'text'),
  182. description: opts.description,
  183. editorKey: opts.editor,
  184. hash: pageHelper.generateHash({ path: opts.path, locale: opts.locale, privateNS: opts.isPrivate ? 'TODO' : '' }),
  185. isPrivate: opts.isPrivate,
  186. isPublished: opts.isPublished,
  187. localeCode: opts.locale,
  188. path: opts.path,
  189. publishEndDate: opts.publishEndDate || '',
  190. publishStartDate: opts.publishStartDate || '',
  191. title: opts.title,
  192. toc: '[]'
  193. })
  194. const page = await WIKI.models.pages.getPageFromDb({
  195. path: opts.path,
  196. locale: opts.locale,
  197. userId: opts.authorId,
  198. isPrivate: opts.isPrivate
  199. })
  200. await WIKI.models.pages.renderPage(page)
  201. if (!opts.skipStorage) {
  202. await WIKI.models.storage.pageEvent({
  203. event: 'created',
  204. page
  205. })
  206. }
  207. return page
  208. }
  209. static async updatePage(opts) {
  210. const ogPage = await WIKI.models.pages.query().findById(opts.id)
  211. if (!ogPage) {
  212. throw new Error('Invalid Page Id')
  213. }
  214. await WIKI.models.pageHistory.addVersion({
  215. ...ogPage,
  216. isPublished: ogPage.isPublished === true || ogPage.isPublished === 1,
  217. action: 'updated'
  218. })
  219. await WIKI.models.pages.query().patch({
  220. authorId: opts.authorId,
  221. content: opts.content,
  222. description: opts.description,
  223. isPublished: opts.isPublished === true || opts.isPublished === 1,
  224. publishEndDate: opts.publishEndDate || '',
  225. publishStartDate: opts.publishStartDate || '',
  226. title: opts.title
  227. }).where('id', ogPage.id)
  228. const page = await WIKI.models.pages.getPageFromDb({
  229. path: ogPage.path,
  230. locale: ogPage.localeCode,
  231. userId: ogPage.authorId,
  232. isPrivate: ogPage.isPrivate
  233. })
  234. await WIKI.models.pages.renderPage(page)
  235. if (!opts.skipStorage) {
  236. await WIKI.models.storage.pageEvent({
  237. event: 'updated',
  238. page
  239. })
  240. }
  241. return page
  242. }
  243. static async deletePage(opts) {
  244. let page
  245. if (_.has(opts, 'id')) {
  246. page = await WIKI.models.pages.query().findById(opts.id)
  247. } else {
  248. page = await await WIKI.models.pages.query().findOne({
  249. path: opts.path,
  250. localeCode: opts.locale
  251. })
  252. }
  253. if (!page) {
  254. throw new Error('Invalid Page Id')
  255. }
  256. await WIKI.models.pageHistory.addVersion({
  257. ...page,
  258. action: 'deleted'
  259. })
  260. await WIKI.models.pages.query().delete().where('id', page.id)
  261. await WIKI.models.pages.deletePageFromCache(page)
  262. if (!opts.skipStorage) {
  263. await WIKI.models.storage.pageEvent({
  264. event: 'deleted',
  265. page
  266. })
  267. }
  268. }
  269. static async renderPage(page) {
  270. const renderJob = await WIKI.scheduler.registerJob({
  271. name: 'render-page',
  272. immediate: true,
  273. worker: true
  274. }, page.id)
  275. return renderJob.finished
  276. }
  277. static async getPage(opts) {
  278. let page = await WIKI.models.pages.getPageFromCache(opts)
  279. if (!page) {
  280. page = await WIKI.models.pages.getPageFromDb(opts)
  281. if (page) {
  282. await WIKI.models.pages.savePageToCache(page)
  283. }
  284. }
  285. return page
  286. }
  287. static async getPageFromDb(opts) {
  288. const queryModeID = _.isNumber(opts)
  289. return WIKI.models.pages.query()
  290. .column([
  291. 'pages.*',
  292. {
  293. authorName: 'author.name',
  294. authorEmail: 'author.email',
  295. creatorName: 'creator.name',
  296. creatorEmail: 'creator.email'
  297. }
  298. ])
  299. .joinRelation('author')
  300. .joinRelation('creator')
  301. .where(queryModeID ? {
  302. 'pages.id': opts
  303. } : {
  304. 'pages.path': opts.path,
  305. 'pages.localeCode': opts.locale
  306. })
  307. .andWhere(builder => {
  308. if (queryModeID) return
  309. builder.where({
  310. 'pages.isPublished': true
  311. }).orWhere({
  312. 'pages.isPublished': false,
  313. 'pages.authorId': opts.userId
  314. })
  315. })
  316. .andWhere(builder => {
  317. if (queryModeID) return
  318. if (opts.isPrivate) {
  319. builder.where({ 'pages.isPrivate': true, 'pages.privateNS': opts.privateNS })
  320. } else {
  321. builder.where({ 'pages.isPrivate': false })
  322. }
  323. })
  324. .first()
  325. }
  326. static async savePageToCache(page) {
  327. const cachePath = path.join(process.cwd(), `data/cache/${page.hash}.bin`)
  328. await fs.outputFile(cachePath, WIKI.models.pages.cacheSchema.encode({
  329. id: page.id,
  330. authorId: page.authorId,
  331. authorName: page.authorName,
  332. createdAt: page.createdAt,
  333. creatorId: page.creatorId,
  334. creatorName: page.creatorName,
  335. description: page.description,
  336. isPrivate: page.isPrivate === 1 || page.isPrivate === true,
  337. isPublished: page.isPublished === 1 || page.isPublished === true,
  338. publishEndDate: page.publishEndDate,
  339. publishStartDate: page.publishStartDate,
  340. render: page.render,
  341. title: page.title,
  342. toc: _.isString(page.toc) ? page.toc : JSON.stringify(page.toc),
  343. updatedAt: page.updatedAt
  344. }))
  345. }
  346. static async getPageFromCache(opts) {
  347. const pageHash = pageHelper.generateHash({ path: opts.path, locale: opts.locale, privateNS: opts.isPrivate ? 'TODO' : '' })
  348. const cachePath = path.join(process.cwd(), `data/cache/${pageHash}.bin`)
  349. try {
  350. const pageBuffer = await fs.readFile(cachePath)
  351. let page = WIKI.models.pages.cacheSchema.decode(pageBuffer)
  352. return {
  353. ...page,
  354. path: opts.path,
  355. localeCode: opts.locale,
  356. isPrivate: opts.isPrivate
  357. }
  358. } catch (err) {
  359. if (err.code === 'ENOENT') {
  360. return false
  361. }
  362. WIKI.logger.error(err)
  363. throw err
  364. }
  365. }
  366. static async deletePageFromCache(page) {
  367. return fs.remove(path.join(process.cwd(), `data/cache/${page.hash}.bin`))
  368. }
  369. }