pages.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  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. const he = require('he')
  11. /* global WIKI */
  12. const frontmatterRegex = {
  13. html: /^(<!-{2}(?:\n|\r)([\w\W]+?)(?:\n|\r)-{2}>)?(?:\n|\r)*([\w\W]*)*/,
  14. legacy: /^(<!-- TITLE: ?([\w\W]+?) -{2}>)?(?:\n|\r)?(<!-- SUBTITLE: ?([\w\W]+?) -{2}>)?(?:\n|\r)*([\w\W]*)*/i,
  15. markdown: /^(-{3}(?:\n|\r)([\w\W]+?)(?:\n|\r)-{3})?(?:\n|\r)*([\w\W]*)*/
  16. }
  17. const punctuationRegex = /[!,:;/\\_+\-=()&#@<>$~%^*[\]{}"'|]+|(\.\s)|(\s\.)/ig
  18. // const htmlEntitiesRegex = /(&#[0-9]{3};)|(&#x[a-zA-Z0-9]{2};)/ig
  19. /**
  20. * Pages model
  21. */
  22. module.exports = class Page extends Model {
  23. static get tableName() { return 'pages' }
  24. static get jsonSchema () {
  25. return {
  26. type: 'object',
  27. required: ['path', 'title'],
  28. properties: {
  29. id: {type: 'integer'},
  30. path: {type: 'string'},
  31. hash: {type: 'string'},
  32. title: {type: 'string'},
  33. description: {type: 'string'},
  34. isPublished: {type: 'boolean'},
  35. privateNS: {type: 'string'},
  36. publishStartDate: {type: 'string'},
  37. publishEndDate: {type: 'string'},
  38. content: {type: 'string'},
  39. contentType: {type: 'string'},
  40. createdAt: {type: 'string'},
  41. updatedAt: {type: 'string'}
  42. }
  43. }
  44. }
  45. static get relationMappings() {
  46. return {
  47. tags: {
  48. relation: Model.ManyToManyRelation,
  49. modelClass: require('./tags'),
  50. join: {
  51. from: 'pages.id',
  52. through: {
  53. from: 'pageTags.pageId',
  54. to: 'pageTags.tagId'
  55. },
  56. to: 'tags.id'
  57. }
  58. },
  59. links: {
  60. relation: Model.HasManyRelation,
  61. modelClass: require('./pageLinks'),
  62. join: {
  63. from: 'pages.id',
  64. to: 'pageLinks.pageId'
  65. }
  66. },
  67. author: {
  68. relation: Model.BelongsToOneRelation,
  69. modelClass: require('./users'),
  70. join: {
  71. from: 'pages.authorId',
  72. to: 'users.id'
  73. }
  74. },
  75. creator: {
  76. relation: Model.BelongsToOneRelation,
  77. modelClass: require('./users'),
  78. join: {
  79. from: 'pages.creatorId',
  80. to: 'users.id'
  81. }
  82. },
  83. editor: {
  84. relation: Model.BelongsToOneRelation,
  85. modelClass: require('./editors'),
  86. join: {
  87. from: 'pages.editorKey',
  88. to: 'editors.key'
  89. }
  90. },
  91. locale: {
  92. relation: Model.BelongsToOneRelation,
  93. modelClass: require('./locales'),
  94. join: {
  95. from: 'pages.localeCode',
  96. to: 'locales.code'
  97. }
  98. }
  99. }
  100. }
  101. $beforeUpdate() {
  102. this.updatedAt = new Date().toISOString()
  103. }
  104. $beforeInsert() {
  105. this.createdAt = new Date().toISOString()
  106. this.updatedAt = new Date().toISOString()
  107. }
  108. /**
  109. * Cache Schema
  110. */
  111. static get cacheSchema() {
  112. return new JSBinType({
  113. id: 'uint',
  114. authorId: 'uint',
  115. authorName: 'string',
  116. createdAt: 'string',
  117. creatorId: 'uint',
  118. creatorName: 'string',
  119. description: 'string',
  120. isPrivate: 'boolean',
  121. isPublished: 'boolean',
  122. publishEndDate: 'string',
  123. publishStartDate: 'string',
  124. render: 'string',
  125. tags: [
  126. {
  127. tag: 'string',
  128. title: 'string'
  129. }
  130. ],
  131. title: 'string',
  132. toc: 'string',
  133. updatedAt: 'string'
  134. })
  135. }
  136. /**
  137. * Inject page metadata into contents
  138. *
  139. * @returns {string} Page Contents with Injected Metadata
  140. */
  141. injectMetadata () {
  142. return pageHelper.injectPageMetadata(this)
  143. }
  144. /**
  145. * Get the page's file extension based on content type
  146. *
  147. * @returns {string} File Extension
  148. */
  149. getFileExtension() {
  150. return pageHelper.getFileExtension(this.contentType)
  151. }
  152. /**
  153. * Parse injected page metadata from raw content
  154. *
  155. * @param {String} raw Raw file contents
  156. * @param {String} contentType Content Type
  157. * @returns {Object} Parsed Page Metadata with Raw Content
  158. */
  159. static parseMetadata (raw, contentType) {
  160. let result
  161. switch (contentType) {
  162. case 'markdown':
  163. result = frontmatterRegex.markdown.exec(raw)
  164. if (result[2]) {
  165. return {
  166. ...yaml.safeLoad(result[2]),
  167. content: result[3]
  168. }
  169. } else {
  170. // Attempt legacy v1 format
  171. result = frontmatterRegex.legacy.exec(raw)
  172. if (result[2]) {
  173. return {
  174. title: result[2],
  175. description: result[4],
  176. content: result[5]
  177. }
  178. }
  179. }
  180. break
  181. case 'html':
  182. result = frontmatterRegex.html.exec(raw)
  183. if (result[2]) {
  184. return {
  185. ...yaml.safeLoad(result[2]),
  186. content: result[3]
  187. }
  188. }
  189. break
  190. }
  191. return {
  192. content: raw
  193. }
  194. }
  195. /**
  196. * Create a New Page
  197. *
  198. * @param {Object} opts Page Properties
  199. * @returns {Promise} Promise of the Page Model Instance
  200. */
  201. static async createPage(opts) {
  202. const dupCheck = await WIKI.models.pages.query().select('id').where('localeCode', opts.locale).where('path', opts.path).first()
  203. if (dupCheck) {
  204. throw new WIKI.Error.PageDuplicateCreate()
  205. }
  206. if (!opts.content || _.trim(opts.content).length < 1) {
  207. throw new WIKI.Error.PageEmptyContent()
  208. }
  209. await WIKI.models.pages.query().insert({
  210. authorId: opts.authorId,
  211. content: opts.content,
  212. creatorId: opts.authorId,
  213. contentType: _.get(_.find(WIKI.data.editors, ['key', opts.editor]), `contentType`, 'text'),
  214. description: opts.description,
  215. editorKey: opts.editor,
  216. hash: pageHelper.generateHash({ path: opts.path, locale: opts.locale, privateNS: opts.isPrivate ? 'TODO' : '' }),
  217. isPrivate: opts.isPrivate,
  218. isPublished: opts.isPublished,
  219. localeCode: opts.locale,
  220. path: opts.path,
  221. publishEndDate: opts.publishEndDate || '',
  222. publishStartDate: opts.publishStartDate || '',
  223. title: opts.title,
  224. toc: '[]'
  225. })
  226. const page = await WIKI.models.pages.getPageFromDb({
  227. path: opts.path,
  228. locale: opts.locale,
  229. userId: opts.authorId,
  230. isPrivate: opts.isPrivate
  231. })
  232. // -> Save Tags
  233. if (opts.tags.length > 0) {
  234. await WIKI.models.tags.associateTags({ tags: opts.tags, page })
  235. }
  236. // -> Render page to HTML
  237. await WIKI.models.pages.renderPage(page)
  238. // -> Add to Search Index
  239. const pageContents = await WIKI.models.pages.query().findById(page.id).select('render')
  240. page.safeContent = WIKI.models.pages.cleanHTML(pageContents.render)
  241. await WIKI.data.searchEngine.created(page)
  242. // -> Add to Storage
  243. if (!opts.skipStorage) {
  244. await WIKI.models.storage.pageEvent({
  245. event: 'created',
  246. page
  247. })
  248. }
  249. // -> Reconnect Links
  250. await WIKI.models.pages.reconnectLinks({
  251. locale: page.localeCode,
  252. path: page.path,
  253. mode: 'create'
  254. })
  255. return page
  256. }
  257. /**
  258. * Update an Existing Page
  259. *
  260. * @param {Object} opts Page Properties
  261. * @returns {Promise} Promise of the Page Model Instance
  262. */
  263. static async updatePage(opts) {
  264. const ogPage = await WIKI.models.pages.query().findById(opts.id)
  265. if (!ogPage) {
  266. throw new Error('Invalid Page Id')
  267. }
  268. if (!opts.content || _.trim(opts.content).length < 1) {
  269. throw new WIKI.Error.PageEmptyContent()
  270. }
  271. await WIKI.models.pageHistory.addVersion({
  272. ...ogPage,
  273. isPublished: ogPage.isPublished === true || ogPage.isPublished === 1,
  274. action: 'updated'
  275. })
  276. await WIKI.models.pages.query().patch({
  277. authorId: opts.authorId,
  278. content: opts.content,
  279. description: opts.description,
  280. isPublished: opts.isPublished === true || opts.isPublished === 1,
  281. publishEndDate: opts.publishEndDate || '',
  282. publishStartDate: opts.publishStartDate || '',
  283. title: opts.title
  284. }).where('id', ogPage.id)
  285. const page = await WIKI.models.pages.getPageFromDb({
  286. path: ogPage.path,
  287. locale: ogPage.localeCode,
  288. userId: ogPage.authorId,
  289. isPrivate: ogPage.isPrivate
  290. })
  291. // -> Save Tags
  292. await WIKI.models.tags.associateTags({ tags: opts.tags, page })
  293. // -> Render page to HTML
  294. await WIKI.models.pages.renderPage(page)
  295. // -> Update Search Index
  296. const pageContents = await WIKI.models.pages.query().findById(page.id).select('render')
  297. page.safeContent = WIKI.models.pages.cleanHTML(pageContents.render)
  298. await WIKI.data.searchEngine.updated(page)
  299. // -> Update on Storage
  300. if (!opts.skipStorage) {
  301. await WIKI.models.storage.pageEvent({
  302. event: 'updated',
  303. page
  304. })
  305. }
  306. return page
  307. }
  308. /**
  309. * Delete an Existing Page
  310. *
  311. * @param {Object} opts Page Properties
  312. * @returns {Promise} Promise with no value
  313. */
  314. static async deletePage(opts) {
  315. let page
  316. if (_.has(opts, 'id')) {
  317. page = await WIKI.models.pages.query().findById(opts.id)
  318. } else {
  319. page = await await WIKI.models.pages.query().findOne({
  320. path: opts.path,
  321. localeCode: opts.locale
  322. })
  323. }
  324. if (!page) {
  325. throw new Error('Invalid Page Id')
  326. }
  327. await WIKI.models.pageHistory.addVersion({
  328. ...page,
  329. action: 'deleted'
  330. })
  331. await WIKI.models.pages.query().delete().where('id', page.id)
  332. await WIKI.models.pages.deletePageFromCache(page)
  333. // -> Delete from Search Index
  334. await WIKI.data.searchEngine.deleted(page)
  335. // -> Delete from Storage
  336. if (!opts.skipStorage) {
  337. await WIKI.models.storage.pageEvent({
  338. event: 'deleted',
  339. page
  340. })
  341. }
  342. // -> Reconnect Links
  343. await WIKI.models.pages.reconnectLinks({
  344. locale: page.localeCode,
  345. path: page.path,
  346. mode: 'delete'
  347. })
  348. }
  349. /**
  350. * Reconnect links to new/updated/deleted page
  351. *
  352. * @param {Object} opts - Page parameters
  353. * @param {string} opts.path - Page Path
  354. * @param {string} opts.locale - Page Locale Code
  355. * @param {string} [opts.sourcePath] - Previous Page Path (move only)
  356. * @param {string} [opts.sourceLocale] - Previous Page Locale Code (move only)
  357. * @param {string} opts.mode - Page Update mode (new, move, delete)
  358. * @returns {Promise} Promise with no value
  359. */
  360. static async reconnectLinks (opts) {
  361. const pageHref = `/${opts.locale}/${opts.path}`
  362. let replaceArgs = {
  363. from: '',
  364. to: ''
  365. }
  366. switch (opts.mode) {
  367. case 'create':
  368. replaceArgs.from = `<a href="${pageHref}" class="is-internal-link is-invalid-page">`
  369. replaceArgs.to = `<a href="${pageHref}" class="is-internal-link is-valid-page">`
  370. break
  371. case 'move':
  372. const prevPageHref = `/${opts.sourceLocale}/${opts.sourcePath}`
  373. replaceArgs.from = `<a href="${prevPageHref}" class="is-internal-link is-invalid-page">`
  374. replaceArgs.to = `<a href="${pageHref}" class="is-internal-link is-valid-page">`
  375. break
  376. case 'delete':
  377. replaceArgs.from = `<a href="${pageHref}" class="is-internal-link is-valid-page">`
  378. replaceArgs.to = `<a href="${pageHref}" class="is-internal-link is-invalid-page">`
  379. break
  380. default:
  381. return false
  382. }
  383. let affectedHashes = []
  384. // -> Perform replace and return affected page hashes (POSTGRES, MSSQL only)
  385. if (WIKI.config.db.type === 'postgres' || WIKI.config.db.type === 'mssql') {
  386. affectedHashes = await WIKI.models.pages.query()
  387. .returning('hash')
  388. .patch({
  389. render: WIKI.models.knex.raw('REPLACE(??, ?, ?)', ['render', replaceArgs.from, replaceArgs.to])
  390. })
  391. .whereIn('pages.id', function () {
  392. this.select('pageLinks.pageId').from('pageLinks').where({
  393. 'pageLinks.path': opts.path,
  394. 'pageLinks.localeCode': opts.locale
  395. })
  396. })
  397. .pluck('hash')
  398. } else {
  399. // -> Perform replace, then query affected page hashes (MYSQL, MARIADB, SQLITE only)
  400. await WIKI.models.pages.query()
  401. .patch({
  402. render: WIKI.models.knex.raw('REPLACE(??, ?, ?)', ['render', replaceArgs.from, replaceArgs.to])
  403. })
  404. .whereIn('pages.id', function () {
  405. this.select('pageLinks.pageId').from('pageLinks').where({
  406. 'pageLinks.path': opts.path,
  407. 'pageLinks.localeCode': opts.locale
  408. })
  409. })
  410. affectedHashes = await WIKI.models.pages.query()
  411. .column('hash')
  412. .whereIn('pages.id', function () {
  413. this.select('pageLinks.pageId').from('pageLinks').where({
  414. 'pageLinks.path': opts.path,
  415. 'pageLinks.localeCode': opts.locale
  416. })
  417. })
  418. .pluck('hash')
  419. }
  420. for (const hash of affectedHashes) {
  421. await WIKI.models.pages.deletePageFromCache({ hash })
  422. }
  423. }
  424. /**
  425. * Trigger the rendering of a page
  426. *
  427. * @param {Object} page Page Model Instance
  428. * @returns {Promise} Promise with no value
  429. */
  430. static async renderPage(page) {
  431. const renderJob = await WIKI.scheduler.registerJob({
  432. name: 'render-page',
  433. immediate: true,
  434. worker: true
  435. }, page.id)
  436. return renderJob.finished
  437. }
  438. /**
  439. * Fetch an Existing Page from Cache if possible, from DB otherwise and save render to Cache
  440. *
  441. * @param {Object} opts Page Properties
  442. * @returns {Promise} Promise of the Page Model Instance
  443. */
  444. static async getPage(opts) {
  445. // -> Get from cache first
  446. let page = await WIKI.models.pages.getPageFromCache(opts)
  447. if (!page) {
  448. // -> Get from DB
  449. page = await WIKI.models.pages.getPageFromDb(opts)
  450. if (page) {
  451. if (page.render) {
  452. // -> Save render to cache
  453. await WIKI.models.pages.savePageToCache(page)
  454. } else {
  455. // -> No render? Possible duplicate issue
  456. /* TODO: Detect duplicate and delete */
  457. throw new Error('Error while fetching page. Duplicate entry detected. Reload the page to try again.')
  458. }
  459. }
  460. }
  461. return page
  462. }
  463. /**
  464. * Fetch an Existing Page from the Database
  465. *
  466. * @param {Object} opts Page Properties
  467. * @returns {Promise} Promise of the Page Model Instance
  468. */
  469. static async getPageFromDb(opts) {
  470. const queryModeID = _.isNumber(opts)
  471. try {
  472. return WIKI.models.pages.query()
  473. .column([
  474. 'pages.*',
  475. {
  476. authorName: 'author.name',
  477. authorEmail: 'author.email',
  478. creatorName: 'creator.name',
  479. creatorEmail: 'creator.email'
  480. }
  481. ])
  482. .joinRelation('author')
  483. .joinRelation('creator')
  484. .eagerAlgorithm(Model.JoinEagerAlgorithm)
  485. .eager('tags(selectTags)', {
  486. selectTags: builder => {
  487. builder.select('tag', 'title')
  488. }
  489. })
  490. .where(queryModeID ? {
  491. 'pages.id': opts
  492. } : {
  493. 'pages.path': opts.path,
  494. 'pages.localeCode': opts.locale
  495. })
  496. // .andWhere(builder => {
  497. // if (queryModeID) return
  498. // builder.where({
  499. // 'pages.isPublished': true
  500. // }).orWhere({
  501. // 'pages.isPublished': false,
  502. // 'pages.authorId': opts.userId
  503. // })
  504. // })
  505. // .andWhere(builder => {
  506. // if (queryModeID) return
  507. // if (opts.isPrivate) {
  508. // builder.where({ 'pages.isPrivate': true, 'pages.privateNS': opts.privateNS })
  509. // } else {
  510. // builder.where({ 'pages.isPrivate': false })
  511. // }
  512. // })
  513. .first()
  514. } catch (err) {
  515. WIKI.logger.warn(err)
  516. throw err
  517. }
  518. }
  519. /**
  520. * Save a Page Model Instance to Cache
  521. *
  522. * @param {Object} page Page Model Instance
  523. * @returns {Promise} Promise with no value
  524. */
  525. static async savePageToCache(page) {
  526. const cachePath = path.join(process.cwd(), `data/cache/${page.hash}.bin`)
  527. await fs.outputFile(cachePath, WIKI.models.pages.cacheSchema.encode({
  528. id: page.id,
  529. authorId: page.authorId,
  530. authorName: page.authorName,
  531. createdAt: page.createdAt,
  532. creatorId: page.creatorId,
  533. creatorName: page.creatorName,
  534. description: page.description,
  535. isPrivate: page.isPrivate === 1 || page.isPrivate === true,
  536. isPublished: page.isPublished === 1 || page.isPublished === true,
  537. publishEndDate: page.publishEndDate,
  538. publishStartDate: page.publishStartDate,
  539. render: page.render,
  540. tags: page.tags.map(t => _.pick(t, ['tag', 'title'])),
  541. title: page.title,
  542. toc: _.isString(page.toc) ? page.toc : JSON.stringify(page.toc),
  543. updatedAt: page.updatedAt
  544. }))
  545. }
  546. /**
  547. * Fetch an Existing Page from Cache
  548. *
  549. * @param {Object} opts Page Properties
  550. * @returns {Promise} Promise of the Page Model Instance
  551. */
  552. static async getPageFromCache(opts) {
  553. const pageHash = pageHelper.generateHash({ path: opts.path, locale: opts.locale, privateNS: opts.isPrivate ? 'TODO' : '' })
  554. const cachePath = path.join(process.cwd(), `data/cache/${pageHash}.bin`)
  555. try {
  556. const pageBuffer = await fs.readFile(cachePath)
  557. let page = WIKI.models.pages.cacheSchema.decode(pageBuffer)
  558. return {
  559. ...page,
  560. path: opts.path,
  561. localeCode: opts.locale,
  562. isPrivate: opts.isPrivate
  563. }
  564. } catch (err) {
  565. if (err.code === 'ENOENT') {
  566. return false
  567. }
  568. WIKI.logger.error(err)
  569. throw err
  570. }
  571. }
  572. /**
  573. * Delete an Existing Page from Cache
  574. *
  575. * @param {Object} page Page Model Instance
  576. * @param {string} page.hash Hash of the Page
  577. * @returns {Promise} Promise with no value
  578. */
  579. static async deletePageFromCache(page) {
  580. return fs.remove(path.join(process.cwd(), `data/cache/${page.hash}.bin`))
  581. }
  582. /**
  583. * Flush the contents of the Cache
  584. */
  585. static async flushCache() {
  586. return fs.emptyDir(path.join(process.cwd(), `data/cache`))
  587. }
  588. /**
  589. * Migrate all pages from a source locale to the target locale
  590. *
  591. * @param {Object} opts Migration properties
  592. * @param {string} opts.sourceLocale Source Locale Code
  593. * @param {string} opts.targetLocale Target Locale Code
  594. * @returns {Promise} Promise with no value
  595. */
  596. static async migrateToLocale({ sourceLocale, targetLocale }) {
  597. return WIKI.models.pages.query()
  598. .patch({
  599. localeCode: targetLocale
  600. })
  601. .where({
  602. localeCode: sourceLocale
  603. })
  604. .whereNotExists(function() {
  605. this.select('id').from('pages AS pagesm').where('pagesm.localeCode', targetLocale).andWhereRaw('pagesm.path = pages.path')
  606. })
  607. }
  608. /**
  609. * Clean raw HTML from content for use in search engines
  610. *
  611. * @param {string} rawHTML Raw HTML
  612. * @returns {string} Cleaned Content Text
  613. */
  614. static cleanHTML(rawHTML = '') {
  615. let data = striptags(rawHTML || '')
  616. .replace(emojiRegex(), '')
  617. // .replace(htmlEntitiesRegex, '')
  618. return he.decode(data)
  619. .replace(punctuationRegex, ' ')
  620. .replace(/(\r\n|\n|\r)/gm, ' ')
  621. .replace(/\s\s+/g, ' ')
  622. .split(' ').filter(w => w.length > 1).join(' ').toLowerCase()
  623. }
  624. }