pages.js 13 KB

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