pages.js 25 KB

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