pages.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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. await WIKI.models.pages.query().insert({
  172. authorId: opts.authorId,
  173. content: opts.content,
  174. creatorId: opts.authorId,
  175. contentType: _.get(_.find(WIKI.data.editors, ['key', opts.editor]), `contentType`, 'text'),
  176. description: opts.description,
  177. editorKey: opts.editor,
  178. hash: pageHelper.generateHash({ path: opts.path, locale: opts.locale, privateNS: opts.isPrivate ? 'TODO' : '' }),
  179. isPrivate: opts.isPrivate,
  180. isPublished: opts.isPublished,
  181. localeCode: opts.locale,
  182. path: opts.path,
  183. publishEndDate: opts.publishEndDate || '',
  184. publishStartDate: opts.publishStartDate || '',
  185. title: opts.title,
  186. toc: '[]'
  187. })
  188. const page = await WIKI.models.pages.getPageFromDb({
  189. path: opts.path,
  190. locale: opts.locale,
  191. userId: opts.authorId,
  192. isPrivate: opts.isPrivate
  193. })
  194. // -> Render page to HTML
  195. await WIKI.models.pages.renderPage(page)
  196. // -> Add to Search Index
  197. const pageContents = await WIKI.models.pages.query().findById(page.id).select('render')
  198. page.safeContent = WIKI.models.pages.cleanHTML(pageContents.render)
  199. await WIKI.data.searchEngine.created(page)
  200. // -> Add to Storage
  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. // -> Render page to HTML
  235. await WIKI.models.pages.renderPage(page)
  236. // -> Update Search Index
  237. const pageContents = await WIKI.models.pages.query().findById(page.id).select('render')
  238. page.safeContent = WIKI.models.pages.cleanHTML(pageContents.render)
  239. await WIKI.data.searchEngine.updated(page)
  240. // -> Update on Storage
  241. if (!opts.skipStorage) {
  242. await WIKI.models.storage.pageEvent({
  243. event: 'updated',
  244. page
  245. })
  246. }
  247. return page
  248. }
  249. static async deletePage(opts) {
  250. let page
  251. if (_.has(opts, 'id')) {
  252. page = await WIKI.models.pages.query().findById(opts.id)
  253. } else {
  254. page = await await WIKI.models.pages.query().findOne({
  255. path: opts.path,
  256. localeCode: opts.locale
  257. })
  258. }
  259. if (!page) {
  260. throw new Error('Invalid Page Id')
  261. }
  262. await WIKI.models.pageHistory.addVersion({
  263. ...page,
  264. action: 'deleted'
  265. })
  266. await WIKI.models.pages.query().delete().where('id', page.id)
  267. await WIKI.models.pages.deletePageFromCache(page)
  268. // -> Delete from Search Index
  269. await WIKI.data.searchEngine.deleted(page)
  270. // -> Delete from Storage
  271. if (!opts.skipStorage) {
  272. await WIKI.models.storage.pageEvent({
  273. event: 'deleted',
  274. page
  275. })
  276. }
  277. }
  278. static async renderPage(page) {
  279. const renderJob = await WIKI.scheduler.registerJob({
  280. name: 'render-page',
  281. immediate: true,
  282. worker: true
  283. }, page.id)
  284. return renderJob.finished
  285. }
  286. static async getPage(opts) {
  287. // -> Get from cache first
  288. let page = await WIKI.models.pages.getPageFromCache(opts)
  289. if (!page) {
  290. // -> Get from DB
  291. page = await WIKI.models.pages.getPageFromDb(opts)
  292. if (page) {
  293. if (page.render) {
  294. // -> Save render to cache
  295. await WIKI.models.pages.savePageToCache(page)
  296. } else {
  297. // -> No render? Possible duplicate issue
  298. /* TODO: Detect duplicate and delete */
  299. throw new Error('Error while fetching page. Duplicate entry detected. Reload the page to try again.')
  300. }
  301. }
  302. }
  303. return page
  304. }
  305. static async getPageFromDb(opts) {
  306. const queryModeID = _.isNumber(opts)
  307. return WIKI.models.pages.query()
  308. .column([
  309. 'pages.*',
  310. {
  311. authorName: 'author.name',
  312. authorEmail: 'author.email',
  313. creatorName: 'creator.name',
  314. creatorEmail: 'creator.email'
  315. }
  316. ])
  317. .joinRelation('author')
  318. .joinRelation('creator')
  319. .where(queryModeID ? {
  320. 'pages.id': opts
  321. } : {
  322. 'pages.path': opts.path,
  323. 'pages.localeCode': opts.locale
  324. })
  325. // .andWhere(builder => {
  326. // if (queryModeID) return
  327. // builder.where({
  328. // 'pages.isPublished': true
  329. // }).orWhere({
  330. // 'pages.isPublished': false,
  331. // 'pages.authorId': opts.userId
  332. // })
  333. // })
  334. // .andWhere(builder => {
  335. // if (queryModeID) return
  336. // if (opts.isPrivate) {
  337. // builder.where({ 'pages.isPrivate': true, 'pages.privateNS': opts.privateNS })
  338. // } else {
  339. // builder.where({ 'pages.isPrivate': false })
  340. // }
  341. // })
  342. .first()
  343. }
  344. static async savePageToCache(page) {
  345. const cachePath = path.join(process.cwd(), `data/cache/${page.hash}.bin`)
  346. await fs.outputFile(cachePath, WIKI.models.pages.cacheSchema.encode({
  347. id: page.id,
  348. authorId: page.authorId,
  349. authorName: page.authorName,
  350. createdAt: page.createdAt,
  351. creatorId: page.creatorId,
  352. creatorName: page.creatorName,
  353. description: page.description,
  354. isPrivate: page.isPrivate === 1 || page.isPrivate === true,
  355. isPublished: page.isPublished === 1 || page.isPublished === true,
  356. publishEndDate: page.publishEndDate,
  357. publishStartDate: page.publishStartDate,
  358. render: page.render,
  359. title: page.title,
  360. toc: _.isString(page.toc) ? page.toc : JSON.stringify(page.toc),
  361. updatedAt: page.updatedAt
  362. }))
  363. }
  364. static async getPageFromCache(opts) {
  365. const pageHash = pageHelper.generateHash({ path: opts.path, locale: opts.locale, privateNS: opts.isPrivate ? 'TODO' : '' })
  366. const cachePath = path.join(process.cwd(), `data/cache/${pageHash}.bin`)
  367. try {
  368. const pageBuffer = await fs.readFile(cachePath)
  369. let page = WIKI.models.pages.cacheSchema.decode(pageBuffer)
  370. return {
  371. ...page,
  372. path: opts.path,
  373. localeCode: opts.locale,
  374. isPrivate: opts.isPrivate
  375. }
  376. } catch (err) {
  377. if (err.code === 'ENOENT') {
  378. return false
  379. }
  380. WIKI.logger.error(err)
  381. throw err
  382. }
  383. }
  384. static async deletePageFromCache(page) {
  385. return fs.remove(path.join(process.cwd(), `data/cache/${page.hash}.bin`))
  386. }
  387. static async flushCache() {
  388. return fs.emptyDir(path.join(process.cwd(), `data/cache`))
  389. }
  390. static async migrateToLocale({ sourceLocale, targetLocale }) {
  391. return WIKI.models.pages.query()
  392. .patch({
  393. localeCode: targetLocale
  394. })
  395. .where({
  396. localeCode: sourceLocale
  397. })
  398. .whereNotExists(function() {
  399. this.select('id').from('pages AS pagesm').where('pagesm.localeCode', targetLocale).andWhereRaw('pagesm.path = pages.path')
  400. })
  401. }
  402. static cleanHTML(rawHTML = '') {
  403. return striptags(rawHTML || '')
  404. .replace(emojiRegex(), '')
  405. .replace(htmlEntitiesRegex, '')
  406. .replace(punctuationRegex, ' ')
  407. .replace(/(\r\n|\n|\r)/gm, ' ')
  408. .replace(/\s\s+/g, ' ')
  409. .split(' ').filter(w => w.length > 1).join(' ').toLowerCase()
  410. }
  411. }