pages.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  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. if (opts.path.indexOf('.') >= 0 || opts.path.indexOf(' ') >= 0) {
  203. throw new WIKI.Error.PageIllegalPath()
  204. }
  205. const dupCheck = await WIKI.models.pages.query().select('id').where('localeCode', opts.locale).where('path', opts.path).first()
  206. if (dupCheck) {
  207. throw new WIKI.Error.PageDuplicateCreate()
  208. }
  209. if (!opts.content || _.trim(opts.content).length < 1) {
  210. throw new WIKI.Error.PageEmptyContent()
  211. }
  212. await WIKI.models.pages.query().insert({
  213. authorId: opts.authorId,
  214. content: opts.content,
  215. creatorId: opts.authorId,
  216. contentType: _.get(_.find(WIKI.data.editors, ['key', opts.editor]), `contentType`, 'text'),
  217. description: opts.description,
  218. editorKey: opts.editor,
  219. hash: pageHelper.generateHash({ path: opts.path, locale: opts.locale, privateNS: opts.isPrivate ? 'TODO' : '' }),
  220. isPrivate: opts.isPrivate,
  221. isPublished: opts.isPublished,
  222. localeCode: opts.locale,
  223. path: opts.path,
  224. publishEndDate: opts.publishEndDate || '',
  225. publishStartDate: opts.publishStartDate || '',
  226. title: opts.title,
  227. toc: '[]'
  228. })
  229. const page = await WIKI.models.pages.getPageFromDb({
  230. path: opts.path,
  231. locale: opts.locale,
  232. userId: opts.authorId,
  233. isPrivate: opts.isPrivate
  234. })
  235. // -> Save Tags
  236. if (opts.tags.length > 0) {
  237. await WIKI.models.tags.associateTags({ tags: opts.tags, page })
  238. }
  239. // -> Render page to HTML
  240. await WIKI.models.pages.renderPage(page)
  241. // -> Add to Search Index
  242. const pageContents = await WIKI.models.pages.query().findById(page.id).select('render')
  243. page.safeContent = WIKI.models.pages.cleanHTML(pageContents.render)
  244. await WIKI.data.searchEngine.created(page)
  245. // -> Add to Storage
  246. if (!opts.skipStorage) {
  247. await WIKI.models.storage.pageEvent({
  248. event: 'created',
  249. page
  250. })
  251. }
  252. // -> Reconnect Links
  253. await WIKI.models.pages.reconnectLinks({
  254. locale: page.localeCode,
  255. path: page.path,
  256. mode: 'create'
  257. })
  258. return page
  259. }
  260. /**
  261. * Update an Existing Page
  262. *
  263. * @param {Object} opts Page Properties
  264. * @returns {Promise} Promise of the Page Model Instance
  265. */
  266. static async updatePage(opts) {
  267. const ogPage = await WIKI.models.pages.query().findById(opts.id)
  268. if (!ogPage) {
  269. throw new Error('Invalid Page Id')
  270. }
  271. if (!opts.content || _.trim(opts.content).length < 1) {
  272. throw new WIKI.Error.PageEmptyContent()
  273. }
  274. await WIKI.models.pageHistory.addVersion({
  275. ...ogPage,
  276. isPublished: ogPage.isPublished === true || ogPage.isPublished === 1,
  277. action: 'updated'
  278. })
  279. await WIKI.models.pages.query().patch({
  280. authorId: opts.authorId,
  281. content: opts.content,
  282. description: opts.description,
  283. isPublished: opts.isPublished === true || opts.isPublished === 1,
  284. publishEndDate: opts.publishEndDate || '',
  285. publishStartDate: opts.publishStartDate || '',
  286. title: opts.title
  287. }).where('id', ogPage.id)
  288. const page = await WIKI.models.pages.getPageFromDb({
  289. path: ogPage.path,
  290. locale: ogPage.localeCode,
  291. userId: ogPage.authorId,
  292. isPrivate: ogPage.isPrivate
  293. })
  294. // -> Save Tags
  295. await WIKI.models.tags.associateTags({ tags: opts.tags, page })
  296. // -> Render page to HTML
  297. await WIKI.models.pages.renderPage(page)
  298. // -> Update Search Index
  299. const pageContents = await WIKI.models.pages.query().findById(page.id).select('render')
  300. page.safeContent = WIKI.models.pages.cleanHTML(pageContents.render)
  301. await WIKI.data.searchEngine.updated(page)
  302. // -> Update on Storage
  303. if (!opts.skipStorage) {
  304. await WIKI.models.storage.pageEvent({
  305. event: 'updated',
  306. page
  307. })
  308. }
  309. return page
  310. }
  311. /**
  312. * Delete an Existing Page
  313. *
  314. * @param {Object} opts Page Properties
  315. * @returns {Promise} Promise with no value
  316. */
  317. static async deletePage(opts) {
  318. let page
  319. if (_.has(opts, 'id')) {
  320. page = await WIKI.models.pages.query().findById(opts.id)
  321. } else {
  322. page = await await WIKI.models.pages.query().findOne({
  323. path: opts.path,
  324. localeCode: opts.locale
  325. })
  326. }
  327. if (!page) {
  328. throw new Error('Invalid Page Id')
  329. }
  330. await WIKI.models.pageHistory.addVersion({
  331. ...page,
  332. action: 'deleted'
  333. })
  334. await WIKI.models.pages.query().delete().where('id', page.id)
  335. await WIKI.models.pages.deletePageFromCache(page)
  336. // -> Delete from Search Index
  337. await WIKI.data.searchEngine.deleted(page)
  338. // -> Delete from Storage
  339. if (!opts.skipStorage) {
  340. await WIKI.models.storage.pageEvent({
  341. event: 'deleted',
  342. page
  343. })
  344. }
  345. // -> Reconnect Links
  346. await WIKI.models.pages.reconnectLinks({
  347. locale: page.localeCode,
  348. path: page.path,
  349. mode: 'delete'
  350. })
  351. }
  352. /**
  353. * Reconnect links to new/updated/deleted page
  354. *
  355. * @param {Object} opts - Page parameters
  356. * @param {string} opts.path - Page Path
  357. * @param {string} opts.locale - Page Locale Code
  358. * @param {string} [opts.sourcePath] - Previous Page Path (move only)
  359. * @param {string} [opts.sourceLocale] - Previous Page Locale Code (move only)
  360. * @param {string} opts.mode - Page Update mode (new, move, delete)
  361. * @returns {Promise} Promise with no value
  362. */
  363. static async reconnectLinks (opts) {
  364. const pageHref = `/${opts.locale}/${opts.path}`
  365. let replaceArgs = {
  366. from: '',
  367. to: ''
  368. }
  369. switch (opts.mode) {
  370. case 'create':
  371. replaceArgs.from = `<a href="${pageHref}" class="is-internal-link is-invalid-page">`
  372. replaceArgs.to = `<a href="${pageHref}" class="is-internal-link is-valid-page">`
  373. break
  374. case 'move':
  375. const prevPageHref = `/${opts.sourceLocale}/${opts.sourcePath}`
  376. replaceArgs.from = `<a href="${prevPageHref}" class="is-internal-link is-invalid-page">`
  377. replaceArgs.to = `<a href="${pageHref}" class="is-internal-link is-valid-page">`
  378. break
  379. case 'delete':
  380. replaceArgs.from = `<a href="${pageHref}" class="is-internal-link is-valid-page">`
  381. replaceArgs.to = `<a href="${pageHref}" class="is-internal-link is-invalid-page">`
  382. break
  383. default:
  384. return false
  385. }
  386. let affectedHashes = []
  387. // -> Perform replace and return affected page hashes (POSTGRES, MSSQL only)
  388. if (WIKI.config.db.type === 'postgres' || WIKI.config.db.type === 'mssql') {
  389. affectedHashes = await WIKI.models.pages.query()
  390. .returning('hash')
  391. .patch({
  392. render: WIKI.models.knex.raw('REPLACE(??, ?, ?)', ['render', replaceArgs.from, replaceArgs.to])
  393. })
  394. .whereIn('pages.id', function () {
  395. this.select('pageLinks.pageId').from('pageLinks').where({
  396. 'pageLinks.path': opts.path,
  397. 'pageLinks.localeCode': opts.locale
  398. })
  399. })
  400. .pluck('hash')
  401. } else {
  402. // -> Perform replace, then query affected page hashes (MYSQL, MARIADB, SQLITE only)
  403. await WIKI.models.pages.query()
  404. .patch({
  405. render: WIKI.models.knex.raw('REPLACE(??, ?, ?)', ['render', replaceArgs.from, replaceArgs.to])
  406. })
  407. .whereIn('pages.id', function () {
  408. this.select('pageLinks.pageId').from('pageLinks').where({
  409. 'pageLinks.path': opts.path,
  410. 'pageLinks.localeCode': opts.locale
  411. })
  412. })
  413. affectedHashes = await WIKI.models.pages.query()
  414. .column('hash')
  415. .whereIn('pages.id', function () {
  416. this.select('pageLinks.pageId').from('pageLinks').where({
  417. 'pageLinks.path': opts.path,
  418. 'pageLinks.localeCode': opts.locale
  419. })
  420. })
  421. .pluck('hash')
  422. }
  423. for (const hash of affectedHashes) {
  424. await WIKI.models.pages.deletePageFromCache({ hash })
  425. }
  426. }
  427. /**
  428. * Trigger the rendering of a page
  429. *
  430. * @param {Object} page Page Model Instance
  431. * @returns {Promise} Promise with no value
  432. */
  433. static async renderPage(page) {
  434. const renderJob = await WIKI.scheduler.registerJob({
  435. name: 'render-page',
  436. immediate: true,
  437. worker: true
  438. }, page.id)
  439. return renderJob.finished
  440. }
  441. /**
  442. * Fetch an Existing Page from Cache if possible, from DB otherwise and save render to Cache
  443. *
  444. * @param {Object} opts Page Properties
  445. * @returns {Promise} Promise of the Page Model Instance
  446. */
  447. static async getPage(opts) {
  448. // -> Get from cache first
  449. let page = await WIKI.models.pages.getPageFromCache(opts)
  450. if (!page) {
  451. // -> Get from DB
  452. page = await WIKI.models.pages.getPageFromDb(opts)
  453. if (page) {
  454. if (page.render) {
  455. // -> Save render to cache
  456. await WIKI.models.pages.savePageToCache(page)
  457. } else {
  458. // -> No render? Possible duplicate issue
  459. /* TODO: Detect duplicate and delete */
  460. throw new Error('Error while fetching page. Duplicate entry detected. Reload the page to try again.')
  461. }
  462. }
  463. }
  464. return page
  465. }
  466. /**
  467. * Fetch an Existing Page from the Database
  468. *
  469. * @param {Object} opts Page Properties
  470. * @returns {Promise} Promise of the Page Model Instance
  471. */
  472. static async getPageFromDb(opts) {
  473. const queryModeID = _.isNumber(opts)
  474. try {
  475. return WIKI.models.pages.query()
  476. .column([
  477. 'pages.*',
  478. {
  479. authorName: 'author.name',
  480. authorEmail: 'author.email',
  481. creatorName: 'creator.name',
  482. creatorEmail: 'creator.email'
  483. }
  484. ])
  485. .joinRelation('author')
  486. .joinRelation('creator')
  487. .eagerAlgorithm(Model.JoinEagerAlgorithm)
  488. .eager('tags(selectTags)', {
  489. selectTags: builder => {
  490. builder.select('tag', 'title')
  491. }
  492. })
  493. .where(queryModeID ? {
  494. 'pages.id': opts
  495. } : {
  496. 'pages.path': opts.path,
  497. 'pages.localeCode': opts.locale
  498. })
  499. // .andWhere(builder => {
  500. // if (queryModeID) return
  501. // builder.where({
  502. // 'pages.isPublished': true
  503. // }).orWhere({
  504. // 'pages.isPublished': false,
  505. // 'pages.authorId': opts.userId
  506. // })
  507. // })
  508. // .andWhere(builder => {
  509. // if (queryModeID) return
  510. // if (opts.isPrivate) {
  511. // builder.where({ 'pages.isPrivate': true, 'pages.privateNS': opts.privateNS })
  512. // } else {
  513. // builder.where({ 'pages.isPrivate': false })
  514. // }
  515. // })
  516. .first()
  517. } catch (err) {
  518. WIKI.logger.warn(err)
  519. throw err
  520. }
  521. }
  522. /**
  523. * Save a Page Model Instance to Cache
  524. *
  525. * @param {Object} page Page Model Instance
  526. * @returns {Promise} Promise with no value
  527. */
  528. static async savePageToCache(page) {
  529. const cachePath = path.join(process.cwd(), `data/cache/${page.hash}.bin`)
  530. await fs.outputFile(cachePath, WIKI.models.pages.cacheSchema.encode({
  531. id: page.id,
  532. authorId: page.authorId,
  533. authorName: page.authorName,
  534. createdAt: page.createdAt,
  535. creatorId: page.creatorId,
  536. creatorName: page.creatorName,
  537. description: page.description,
  538. isPrivate: page.isPrivate === 1 || page.isPrivate === true,
  539. isPublished: page.isPublished === 1 || page.isPublished === true,
  540. publishEndDate: page.publishEndDate,
  541. publishStartDate: page.publishStartDate,
  542. render: page.render,
  543. tags: page.tags.map(t => _.pick(t, ['tag', 'title'])),
  544. title: page.title,
  545. toc: _.isString(page.toc) ? page.toc : JSON.stringify(page.toc),
  546. updatedAt: page.updatedAt
  547. }))
  548. }
  549. /**
  550. * Fetch an Existing Page from Cache
  551. *
  552. * @param {Object} opts Page Properties
  553. * @returns {Promise} Promise of the Page Model Instance
  554. */
  555. static async getPageFromCache(opts) {
  556. const pageHash = pageHelper.generateHash({ path: opts.path, locale: opts.locale, privateNS: opts.isPrivate ? 'TODO' : '' })
  557. const cachePath = path.join(process.cwd(), `data/cache/${pageHash}.bin`)
  558. try {
  559. const pageBuffer = await fs.readFile(cachePath)
  560. let page = WIKI.models.pages.cacheSchema.decode(pageBuffer)
  561. return {
  562. ...page,
  563. path: opts.path,
  564. localeCode: opts.locale,
  565. isPrivate: opts.isPrivate
  566. }
  567. } catch (err) {
  568. if (err.code === 'ENOENT') {
  569. return false
  570. }
  571. WIKI.logger.error(err)
  572. throw err
  573. }
  574. }
  575. /**
  576. * Delete an Existing Page from Cache
  577. *
  578. * @param {Object} page Page Model Instance
  579. * @param {string} page.hash Hash of the Page
  580. * @returns {Promise} Promise with no value
  581. */
  582. static async deletePageFromCache(page) {
  583. return fs.remove(path.join(process.cwd(), `data/cache/${page.hash}.bin`))
  584. }
  585. /**
  586. * Flush the contents of the Cache
  587. */
  588. static async flushCache() {
  589. return fs.emptyDir(path.join(process.cwd(), `data/cache`))
  590. }
  591. /**
  592. * Migrate all pages from a source locale to the target locale
  593. *
  594. * @param {Object} opts Migration properties
  595. * @param {string} opts.sourceLocale Source Locale Code
  596. * @param {string} opts.targetLocale Target Locale Code
  597. * @returns {Promise} Promise with no value
  598. */
  599. static async migrateToLocale({ sourceLocale, targetLocale }) {
  600. return WIKI.models.pages.query()
  601. .patch({
  602. localeCode: targetLocale
  603. })
  604. .where({
  605. localeCode: sourceLocale
  606. })
  607. .whereNotExists(function() {
  608. this.select('id').from('pages AS pagesm').where('pagesm.localeCode', targetLocale).andWhereRaw('pagesm.path = pages.path')
  609. })
  610. }
  611. /**
  612. * Clean raw HTML from content for use in search engines
  613. *
  614. * @param {string} rawHTML Raw HTML
  615. * @returns {string} Cleaned Content Text
  616. */
  617. static cleanHTML(rawHTML = '') {
  618. let data = striptags(rawHTML || '')
  619. .replace(emojiRegex(), '')
  620. // .replace(htmlEntitiesRegex, '')
  621. return he.decode(data)
  622. .replace(punctuationRegex, ' ')
  623. .replace(/(\r\n|\n|\r)/gm, ' ')
  624. .replace(/\s\s+/g, ' ')
  625. .split(' ').filter(w => w.length > 1).join(' ').toLowerCase()
  626. }
  627. }