pages.js 13 KB

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