pages.js 13 KB

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