pages.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  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. // -> Validate path
  203. if (opts.path.indexOf('.') >= 0 || opts.path.indexOf(' ') >= 0) {
  204. throw new WIKI.Error.PageIllegalPath()
  205. }
  206. // -> Check for page access
  207. if (!WIKI.auth.checkAccess(opts.user, ['write:pages'], {
  208. locale: opts.locale,
  209. path: opts.path
  210. })) {
  211. throw new WIKI.Error.PageDeleteForbidden()
  212. }
  213. // -> Check for duplicate
  214. const dupCheck = await WIKI.models.pages.query().select('id').where('localeCode', opts.locale).where('path', opts.path).first()
  215. if (dupCheck) {
  216. throw new WIKI.Error.PageDuplicateCreate()
  217. }
  218. // -> Check for empty content
  219. if (!opts.content || _.trim(opts.content).length < 1) {
  220. throw new WIKI.Error.PageEmptyContent()
  221. }
  222. // -> Create page
  223. await WIKI.models.pages.query().insert({
  224. authorId: opts.user.id,
  225. content: opts.content,
  226. creatorId: opts.user.id,
  227. contentType: _.get(_.find(WIKI.data.editors, ['key', opts.editor]), `contentType`, 'text'),
  228. description: opts.description,
  229. editorKey: opts.editor,
  230. hash: pageHelper.generateHash({ path: opts.path, locale: opts.locale, privateNS: opts.isPrivate ? 'TODO' : '' }),
  231. isPrivate: opts.isPrivate,
  232. isPublished: opts.isPublished,
  233. localeCode: opts.locale,
  234. path: opts.path,
  235. publishEndDate: opts.publishEndDate || '',
  236. publishStartDate: opts.publishStartDate || '',
  237. title: opts.title,
  238. toc: '[]'
  239. })
  240. const page = await WIKI.models.pages.getPageFromDb({
  241. path: opts.path,
  242. locale: opts.locale,
  243. userId: opts.user.id,
  244. isPrivate: opts.isPrivate
  245. })
  246. // -> Save Tags
  247. if (opts.tags && opts.tags.length > 0) {
  248. await WIKI.models.tags.associateTags({ tags: opts.tags, page })
  249. }
  250. // -> Render page to HTML
  251. await WIKI.models.pages.renderPage(page)
  252. // -> Rebuild page tree
  253. await WIKI.models.pages.rebuildTree()
  254. // -> Add to Search Index
  255. const pageContents = await WIKI.models.pages.query().findById(page.id).select('render')
  256. page.safeContent = WIKI.models.pages.cleanHTML(pageContents.render)
  257. await WIKI.data.searchEngine.created(page)
  258. // -> Add to Storage
  259. if (!opts.skipStorage) {
  260. await WIKI.models.storage.pageEvent({
  261. event: 'created',
  262. page
  263. })
  264. }
  265. // -> Reconnect Links
  266. await WIKI.models.pages.reconnectLinks({
  267. locale: page.localeCode,
  268. path: page.path,
  269. mode: 'create'
  270. })
  271. return page
  272. }
  273. /**
  274. * Update an Existing Page
  275. *
  276. * @param {Object} opts Page Properties
  277. * @returns {Promise} Promise of the Page Model Instance
  278. */
  279. static async updatePage(opts) {
  280. // -> Fetch original page
  281. const ogPage = await WIKI.models.pages.query().findById(opts.id)
  282. if (!ogPage) {
  283. throw new Error('Invalid Page Id')
  284. }
  285. // -> Check for page access
  286. if (!WIKI.auth.checkAccess(opts.user, ['write:pages'], {
  287. locale: opts.locale,
  288. path: opts.path
  289. })) {
  290. throw new WIKI.Error.PageUpdateForbidden()
  291. }
  292. // -> Check for empty content
  293. if (!opts.content || _.trim(opts.content).length < 1) {
  294. throw new WIKI.Error.PageEmptyContent()
  295. }
  296. // -> Create version snapshot
  297. await WIKI.models.pageHistory.addVersion({
  298. ...ogPage,
  299. isPublished: ogPage.isPublished === true || ogPage.isPublished === 1,
  300. action: 'updated'
  301. })
  302. // -> Update page
  303. await WIKI.models.pages.query().patch({
  304. authorId: opts.user.id,
  305. content: opts.content,
  306. description: opts.description,
  307. isPublished: opts.isPublished === true || opts.isPublished === 1,
  308. publishEndDate: opts.publishEndDate || '',
  309. publishStartDate: opts.publishStartDate || '',
  310. title: opts.title
  311. }).where('id', ogPage.id)
  312. let page = await WIKI.models.pages.getPageFromDb({
  313. path: ogPage.path,
  314. locale: ogPage.localeCode,
  315. userId: ogPage.authorId,
  316. isPrivate: ogPage.isPrivate
  317. })
  318. // -> Save Tags
  319. await WIKI.models.tags.associateTags({ tags: opts.tags, page })
  320. // -> Render page to HTML
  321. await WIKI.models.pages.renderPage(page)
  322. // -> Update Search Index
  323. const pageContents = await WIKI.models.pages.query().findById(page.id).select('render')
  324. page.safeContent = WIKI.models.pages.cleanHTML(pageContents.render)
  325. await WIKI.data.searchEngine.updated(page)
  326. // -> Update on Storage
  327. if (!opts.skipStorage) {
  328. await WIKI.models.storage.pageEvent({
  329. event: 'updated',
  330. page
  331. })
  332. }
  333. // -> Perform move?
  334. if ((opts.locale && opts.locale !== page.localeCode) || (opts.path && opts.path !== page.path)) {
  335. await WIKI.models.pages.movePage({
  336. id: page.id,
  337. destinationLocale: opts.locale,
  338. destinationPath: opts.path,
  339. user: opts.user
  340. })
  341. } else {
  342. // -> Update title of page tree entry
  343. await WIKI.models.knex.table('pageTree').where({
  344. pageId: page.id
  345. }).update('title', page.title)
  346. }
  347. return page
  348. }
  349. /**
  350. * Move a Page
  351. *
  352. * @param {Object} opts Page Properties
  353. * @returns {Promise} Promise with no value
  354. */
  355. static async movePage(opts) {
  356. const page = await WIKI.models.pages.query().findById(opts.id)
  357. if (!page) {
  358. throw new WIKI.Error.PageNotFound()
  359. }
  360. // -> Check for source page access
  361. if (!WIKI.auth.checkAccess(opts.user, ['manage:pages'], {
  362. locale: page.sourceLocale,
  363. path: page.sourcePath
  364. })) {
  365. throw new WIKI.Error.PageMoveForbidden()
  366. }
  367. // -> Check for destination page access
  368. if (!WIKI.auth.checkAccess(opts.user, ['write:pages'], {
  369. locale: opts.destinationLocale,
  370. path: opts.destinationPath
  371. })) {
  372. throw new WIKI.Error.PageMoveForbidden()
  373. }
  374. // -> Check for existing page at destination path
  375. const destPage = await await WIKI.models.pages.query().findOne({
  376. path: opts.destinationPath,
  377. localeCode: opts.destinationLocale
  378. })
  379. if (destPage) {
  380. throw new WIKI.Error.PagePathCollision()
  381. }
  382. // -> Create version snapshot
  383. await WIKI.models.pageHistory.addVersion({
  384. ...page,
  385. action: 'moved'
  386. })
  387. const destinationHash = pageHelper.generateHash({ path: opts.destinationPath, locale: opts.destinationLocale, privateNS: opts.isPrivate ? 'TODO' : '' })
  388. // -> Move page
  389. await WIKI.models.pages.query().patch({
  390. path: opts.destinationPath,
  391. localeCode: opts.destinationLocale,
  392. hash: destinationHash
  393. }).findById(page.id)
  394. await WIKI.models.pages.deletePageFromCache(page)
  395. // -> Rebuild page tree
  396. await WIKI.models.pages.rebuildTree()
  397. // -> Rename in Search Index
  398. await WIKI.data.searchEngine.renamed({
  399. ...page,
  400. destinationPath: opts.destinationPath,
  401. destinationLocaleCode: opts.destinationLocale,
  402. destinationHash
  403. })
  404. // -> Rename in Storage
  405. if (!opts.skipStorage) {
  406. await WIKI.models.storage.pageEvent({
  407. event: 'renamed',
  408. page: {
  409. ...page,
  410. destinationPath: opts.destinationPath,
  411. destinationLocaleCode: opts.destinationLocale,
  412. destinationHash,
  413. moveAuthorId: opts.user.id,
  414. moveAuthorName: opts.user.name,
  415. moveAuthorEmail: opts.user.email
  416. }
  417. })
  418. }
  419. // -> Reconnect Links
  420. await WIKI.models.pages.reconnectLinks({
  421. sourceLocale: page.localeCode,
  422. sourcePath: page.path,
  423. locale: opts.destinationLocale,
  424. path: opts.destinationPath,
  425. mode: 'move'
  426. })
  427. }
  428. /**
  429. * Delete an Existing Page
  430. *
  431. * @param {Object} opts Page Properties
  432. * @returns {Promise} Promise with no value
  433. */
  434. static async deletePage(opts) {
  435. let page
  436. if (_.has(opts, 'id')) {
  437. page = await WIKI.models.pages.query().findById(opts.id)
  438. } else {
  439. page = await await WIKI.models.pages.query().findOne({
  440. path: opts.path,
  441. localeCode: opts.locale
  442. })
  443. }
  444. if (!page) {
  445. throw new Error('Invalid Page Id')
  446. }
  447. // -> Check for page access
  448. if (!WIKI.auth.checkAccess(opts.user, ['delete:pages'], {
  449. locale: page.locale,
  450. path: page.path
  451. })) {
  452. throw new WIKI.Error.PageDeleteForbidden()
  453. }
  454. // -> Create version snapshot
  455. await WIKI.models.pageHistory.addVersion({
  456. ...page,
  457. action: 'deleted'
  458. })
  459. // -> Delete page
  460. await WIKI.models.pages.query().delete().where('id', page.id)
  461. await WIKI.models.pages.deletePageFromCache(page)
  462. // -> Rebuild page tree
  463. await WIKI.models.pages.rebuildTree()
  464. // -> Delete from Search Index
  465. await WIKI.data.searchEngine.deleted(page)
  466. // -> Delete from Storage
  467. if (!opts.skipStorage) {
  468. await WIKI.models.storage.pageEvent({
  469. event: 'deleted',
  470. page
  471. })
  472. }
  473. // -> Reconnect Links
  474. await WIKI.models.pages.reconnectLinks({
  475. locale: page.localeCode,
  476. path: page.path,
  477. mode: 'delete'
  478. })
  479. }
  480. /**
  481. * Reconnect links to new/move/deleted page
  482. *
  483. * @param {Object} opts - Page parameters
  484. * @param {string} opts.path - Page Path
  485. * @param {string} opts.locale - Page Locale Code
  486. * @param {string} [opts.sourcePath] - Previous Page Path (move only)
  487. * @param {string} [opts.sourceLocale] - Previous Page Locale Code (move only)
  488. * @param {string} opts.mode - Page Update mode (create, move, delete)
  489. * @returns {Promise} Promise with no value
  490. */
  491. static async reconnectLinks (opts) {
  492. const pageHref = `/${opts.locale}/${opts.path}`
  493. let replaceArgs = {
  494. from: '',
  495. to: ''
  496. }
  497. switch (opts.mode) {
  498. case 'create':
  499. replaceArgs.from = `<a href="${pageHref}" class="is-internal-link is-invalid-page">`
  500. replaceArgs.to = `<a href="${pageHref}" class="is-internal-link is-valid-page">`
  501. break
  502. case 'move':
  503. const prevPageHref = `/${opts.sourceLocale}/${opts.sourcePath}`
  504. replaceArgs.from = `<a href="${prevPageHref}" class="is-internal-link is-invalid-page">`
  505. replaceArgs.to = `<a href="${pageHref}" class="is-internal-link is-valid-page">`
  506. break
  507. case 'delete':
  508. replaceArgs.from = `<a href="${pageHref}" class="is-internal-link is-valid-page">`
  509. replaceArgs.to = `<a href="${pageHref}" class="is-internal-link is-invalid-page">`
  510. break
  511. default:
  512. return false
  513. }
  514. let affectedHashes = []
  515. // -> Perform replace and return affected page hashes (POSTGRES only)
  516. if (WIKI.config.db.type === 'postgres') {
  517. affectedHashes = await WIKI.models.pages.query()
  518. .returning('hash')
  519. .patch({
  520. render: WIKI.models.knex.raw('REPLACE(??, ?, ?)', ['render', replaceArgs.from, replaceArgs.to])
  521. })
  522. .whereIn('pages.id', function () {
  523. this.select('pageLinks.pageId').from('pageLinks').where({
  524. 'pageLinks.path': opts.path,
  525. 'pageLinks.localeCode': opts.locale
  526. })
  527. })
  528. .pluck('hash')
  529. } else {
  530. // -> Perform replace, then query affected page hashes (MYSQL, MARIADB, MSSQL, SQLITE only)
  531. await WIKI.models.pages.query()
  532. .patch({
  533. render: WIKI.models.knex.raw('REPLACE(??, ?, ?)', ['render', replaceArgs.from, replaceArgs.to])
  534. })
  535. .whereIn('pages.id', function () {
  536. this.select('pageLinks.pageId').from('pageLinks').where({
  537. 'pageLinks.path': opts.path,
  538. 'pageLinks.localeCode': opts.locale
  539. })
  540. })
  541. affectedHashes = await WIKI.models.pages.query()
  542. .column('hash')
  543. .whereIn('pages.id', function () {
  544. this.select('pageLinks.pageId').from('pageLinks').where({
  545. 'pageLinks.path': opts.path,
  546. 'pageLinks.localeCode': opts.locale
  547. })
  548. })
  549. .pluck('hash')
  550. }
  551. for (const hash of affectedHashes) {
  552. await WIKI.models.pages.deletePageFromCache({ hash })
  553. }
  554. }
  555. /**
  556. * Rebuild page tree for new/updated/deleted page
  557. *
  558. * @returns {Promise} Promise with no value
  559. */
  560. static async rebuildTree() {
  561. const rebuildJob = await WIKI.scheduler.registerJob({
  562. name: 'rebuild-tree',
  563. immediate: true,
  564. worker: true
  565. })
  566. return rebuildJob.finished
  567. }
  568. /**
  569. * Trigger the rendering of a page
  570. *
  571. * @param {Object} page Page Model Instance
  572. * @returns {Promise} Promise with no value
  573. */
  574. static async renderPage(page) {
  575. const renderJob = await WIKI.scheduler.registerJob({
  576. name: 'render-page',
  577. immediate: true,
  578. worker: true
  579. }, page.id)
  580. return renderJob.finished
  581. }
  582. /**
  583. * Fetch an Existing Page from Cache if possible, from DB otherwise and save render to Cache
  584. *
  585. * @param {Object} opts Page Properties
  586. * @returns {Promise} Promise of the Page Model Instance
  587. */
  588. static async getPage(opts) {
  589. // -> Get from cache first
  590. let page = await WIKI.models.pages.getPageFromCache(opts)
  591. if (!page) {
  592. // -> Get from DB
  593. page = await WIKI.models.pages.getPageFromDb(opts)
  594. if (page) {
  595. if (page.render) {
  596. // -> Save render to cache
  597. await WIKI.models.pages.savePageToCache(page)
  598. } else {
  599. // -> No render? Possible duplicate issue
  600. /* TODO: Detect duplicate and delete */
  601. throw new Error('Error while fetching page. Duplicate entry detected. Reload the page to try again.')
  602. }
  603. }
  604. }
  605. return page
  606. }
  607. /**
  608. * Fetch an Existing Page from the Database
  609. *
  610. * @param {Object} opts Page Properties
  611. * @returns {Promise} Promise of the Page Model Instance
  612. */
  613. static async getPageFromDb(opts) {
  614. const queryModeID = _.isNumber(opts)
  615. try {
  616. return WIKI.models.pages.query()
  617. .column([
  618. 'pages.id',
  619. 'pages.path',
  620. 'pages.hash',
  621. 'pages.title',
  622. 'pages.description',
  623. 'pages.isPrivate',
  624. 'pages.isPublished',
  625. 'pages.privateNS',
  626. 'pages.publishStartDate',
  627. 'pages.publishEndDate',
  628. 'pages.content',
  629. 'pages.render',
  630. 'pages.toc',
  631. 'pages.contentType',
  632. 'pages.createdAt',
  633. 'pages.updatedAt',
  634. 'pages.editorKey',
  635. 'pages.localeCode',
  636. 'pages.authorId',
  637. 'pages.creatorId',
  638. {
  639. authorName: 'author.name',
  640. authorEmail: 'author.email',
  641. creatorName: 'creator.name',
  642. creatorEmail: 'creator.email'
  643. }
  644. ])
  645. .joinRelation('author')
  646. .joinRelation('creator')
  647. .eagerAlgorithm(Model.JoinEagerAlgorithm)
  648. .eager('tags(selectTags)', {
  649. selectTags: builder => {
  650. builder.select('tag', 'title')
  651. }
  652. })
  653. .where(queryModeID ? {
  654. 'pages.id': opts
  655. } : {
  656. 'pages.path': opts.path,
  657. 'pages.localeCode': opts.locale
  658. })
  659. // .andWhere(builder => {
  660. // if (queryModeID) return
  661. // builder.where({
  662. // 'pages.isPublished': true
  663. // }).orWhere({
  664. // 'pages.isPublished': false,
  665. // 'pages.authorId': opts.userId
  666. // })
  667. // })
  668. // .andWhere(builder => {
  669. // if (queryModeID) return
  670. // if (opts.isPrivate) {
  671. // builder.where({ 'pages.isPrivate': true, 'pages.privateNS': opts.privateNS })
  672. // } else {
  673. // builder.where({ 'pages.isPrivate': false })
  674. // }
  675. // })
  676. .first()
  677. } catch (err) {
  678. WIKI.logger.warn(err)
  679. throw err
  680. }
  681. }
  682. /**
  683. * Save a Page Model Instance to Cache
  684. *
  685. * @param {Object} page Page Model Instance
  686. * @returns {Promise} Promise with no value
  687. */
  688. static async savePageToCache(page) {
  689. const cachePath = path.resolve(WIKI.ROOTPATH, WIKI.config.dataPath, `cache/${page.hash}.bin`)
  690. await fs.outputFile(cachePath, WIKI.models.pages.cacheSchema.encode({
  691. id: page.id,
  692. authorId: page.authorId,
  693. authorName: page.authorName,
  694. createdAt: page.createdAt,
  695. creatorId: page.creatorId,
  696. creatorName: page.creatorName,
  697. description: page.description,
  698. isPrivate: page.isPrivate === 1 || page.isPrivate === true,
  699. isPublished: page.isPublished === 1 || page.isPublished === true,
  700. publishEndDate: page.publishEndDate,
  701. publishStartDate: page.publishStartDate,
  702. render: page.render,
  703. tags: page.tags.map(t => _.pick(t, ['tag', 'title'])),
  704. title: page.title,
  705. toc: _.isString(page.toc) ? page.toc : JSON.stringify(page.toc),
  706. updatedAt: page.updatedAt
  707. }))
  708. }
  709. /**
  710. * Fetch an Existing Page from Cache
  711. *
  712. * @param {Object} opts Page Properties
  713. * @returns {Promise} Promise of the Page Model Instance
  714. */
  715. static async getPageFromCache(opts) {
  716. const pageHash = pageHelper.generateHash({ path: opts.path, locale: opts.locale, privateNS: opts.isPrivate ? 'TODO' : '' })
  717. const cachePath = path.resolve(WIKI.ROOTPATH, WIKI.config.dataPath, `cache/${pageHash}.bin`)
  718. try {
  719. const pageBuffer = await fs.readFile(cachePath)
  720. let page = WIKI.models.pages.cacheSchema.decode(pageBuffer)
  721. return {
  722. ...page,
  723. path: opts.path,
  724. localeCode: opts.locale,
  725. isPrivate: opts.isPrivate
  726. }
  727. } catch (err) {
  728. if (err.code === 'ENOENT') {
  729. return false
  730. }
  731. WIKI.logger.error(err)
  732. throw err
  733. }
  734. }
  735. /**
  736. * Delete an Existing Page from Cache
  737. *
  738. * @param {Object} page Page Model Instance
  739. * @param {string} page.hash Hash of the Page
  740. * @returns {Promise} Promise with no value
  741. */
  742. static async deletePageFromCache(page) {
  743. return fs.remove(path.resolve(WIKI.ROOTPATH, WIKI.config.dataPath, `cache/${page.hash}.bin`))
  744. }
  745. /**
  746. * Flush the contents of the Cache
  747. */
  748. static async flushCache() {
  749. return fs.emptyDir(path.resolve(WIKI.ROOTPATH, WIKI.config.dataPath, `cache`))
  750. }
  751. /**
  752. * Migrate all pages from a source locale to the target locale
  753. *
  754. * @param {Object} opts Migration properties
  755. * @param {string} opts.sourceLocale Source Locale Code
  756. * @param {string} opts.targetLocale Target Locale Code
  757. * @returns {Promise} Promise with no value
  758. */
  759. static async migrateToLocale({ sourceLocale, targetLocale }) {
  760. return WIKI.models.pages.query()
  761. .patch({
  762. localeCode: targetLocale
  763. })
  764. .where({
  765. localeCode: sourceLocale
  766. })
  767. .whereNotExists(function() {
  768. this.select('id').from('pages AS pagesm').where('pagesm.localeCode', targetLocale).andWhereRaw('pagesm.path = pages.path')
  769. })
  770. }
  771. /**
  772. * Clean raw HTML from content for use in search engines
  773. *
  774. * @param {string} rawHTML Raw HTML
  775. * @returns {string} Cleaned Content Text
  776. */
  777. static cleanHTML(rawHTML = '') {
  778. let data = striptags(rawHTML || '', [], ' ')
  779. .replace(emojiRegex(), '')
  780. // .replace(htmlEntitiesRegex, '')
  781. return he.decode(data)
  782. .replace(punctuationRegex, ' ')
  783. .replace(/(\r\n|\n|\r)/gm, ' ')
  784. .replace(/\s\s+/g, ' ')
  785. .split(' ').filter(w => w.length > 1).join(' ').toLowerCase()
  786. }
  787. }