pages.js 19 KB

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