pages.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  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. static get cacheSchema() {
  108. return new JSBinType({
  109. id: 'uint',
  110. authorId: 'uint',
  111. authorName: 'string',
  112. createdAt: 'string',
  113. creatorId: 'uint',
  114. creatorName: 'string',
  115. description: 'string',
  116. isPrivate: 'boolean',
  117. isPublished: 'boolean',
  118. publishEndDate: 'string',
  119. publishStartDate: 'string',
  120. render: 'string',
  121. tags: [
  122. {
  123. tag: 'string',
  124. title: 'string'
  125. }
  126. ],
  127. title: 'string',
  128. toc: 'string',
  129. updatedAt: 'string'
  130. })
  131. }
  132. /**
  133. * Inject page metadata into contents
  134. */
  135. injectMetadata () {
  136. return pageHelper.injectPageMetadata(this)
  137. }
  138. /**
  139. * Get the page's file extension based on content type
  140. */
  141. getFileExtension() {
  142. switch (this.contentType) {
  143. case 'markdown':
  144. return 'md'
  145. case 'html':
  146. return 'html'
  147. default:
  148. return 'txt'
  149. }
  150. }
  151. /**
  152. * Parse injected page metadata from raw content
  153. *
  154. * @param {String} raw Raw file contents
  155. * @param {String} contentType Content Type
  156. */
  157. static parseMetadata (raw, contentType) {
  158. let result
  159. switch (contentType) {
  160. case 'markdown':
  161. result = frontmatterRegex.markdown.exec(raw)
  162. if (result[2]) {
  163. return {
  164. ...yaml.safeLoad(result[2]),
  165. content: result[3]
  166. }
  167. } else {
  168. // Attempt legacy v1 format
  169. result = frontmatterRegex.legacy.exec(raw)
  170. if (result[2]) {
  171. return {
  172. title: result[2],
  173. description: result[4],
  174. content: result[5]
  175. }
  176. }
  177. }
  178. break
  179. case 'html':
  180. result = frontmatterRegex.html.exec(raw)
  181. if (result[2]) {
  182. return {
  183. ...yaml.safeLoad(result[2]),
  184. content: result[3]
  185. }
  186. }
  187. break
  188. }
  189. return {
  190. content: raw
  191. }
  192. }
  193. static async createPage(opts) {
  194. const dupCheck = await WIKI.models.pages.query().select('id').where('localeCode', opts.locale).where('path', opts.path).first()
  195. if (dupCheck) {
  196. throw new WIKI.Error.PageDuplicateCreate()
  197. }
  198. if (!opts.content || _.trim(opts.content).length < 1) {
  199. throw new WIKI.Error.PageEmptyContent()
  200. }
  201. await WIKI.models.pages.query().insert({
  202. authorId: opts.authorId,
  203. content: opts.content,
  204. creatorId: opts.authorId,
  205. contentType: _.get(_.find(WIKI.data.editors, ['key', opts.editor]), `contentType`, 'text'),
  206. description: opts.description,
  207. editorKey: opts.editor,
  208. hash: pageHelper.generateHash({ path: opts.path, locale: opts.locale, privateNS: opts.isPrivate ? 'TODO' : '' }),
  209. isPrivate: opts.isPrivate,
  210. isPublished: opts.isPublished,
  211. localeCode: opts.locale,
  212. path: opts.path,
  213. publishEndDate: opts.publishEndDate || '',
  214. publishStartDate: opts.publishStartDate || '',
  215. title: opts.title,
  216. toc: '[]'
  217. })
  218. const page = await WIKI.models.pages.getPageFromDb({
  219. path: opts.path,
  220. locale: opts.locale,
  221. userId: opts.authorId,
  222. isPrivate: opts.isPrivate
  223. })
  224. // -> Save Tags
  225. if (opts.tags.length > 0) {
  226. await WIKI.models.tags.associateTags({ tags: opts.tags, page })
  227. }
  228. // -> Render page to HTML
  229. await WIKI.models.pages.renderPage(page)
  230. // -> Add to Search Index
  231. const pageContents = await WIKI.models.pages.query().findById(page.id).select('render')
  232. page.safeContent = WIKI.models.pages.cleanHTML(pageContents.render)
  233. await WIKI.data.searchEngine.created(page)
  234. // -> Add to Storage
  235. if (!opts.skipStorage) {
  236. await WIKI.models.storage.pageEvent({
  237. event: 'created',
  238. page
  239. })
  240. }
  241. return page
  242. }
  243. static async updatePage(opts) {
  244. const ogPage = await WIKI.models.pages.query().findById(opts.id)
  245. if (!ogPage) {
  246. throw new Error('Invalid Page Id')
  247. }
  248. if (!opts.content || _.trim(opts.content).length < 1) {
  249. throw new WIKI.Error.PageEmptyContent()
  250. }
  251. await WIKI.models.pageHistory.addVersion({
  252. ...ogPage,
  253. isPublished: ogPage.isPublished === true || ogPage.isPublished === 1,
  254. action: 'updated'
  255. })
  256. await WIKI.models.pages.query().patch({
  257. authorId: opts.authorId,
  258. content: opts.content,
  259. description: opts.description,
  260. isPublished: opts.isPublished === true || opts.isPublished === 1,
  261. publishEndDate: opts.publishEndDate || '',
  262. publishStartDate: opts.publishStartDate || '',
  263. title: opts.title
  264. }).where('id', ogPage.id)
  265. const page = await WIKI.models.pages.getPageFromDb({
  266. path: ogPage.path,
  267. locale: ogPage.localeCode,
  268. userId: ogPage.authorId,
  269. isPrivate: ogPage.isPrivate
  270. })
  271. // -> Save Tags
  272. await WIKI.models.tags.associateTags({ tags: opts.tags, page })
  273. // -> Render page to HTML
  274. await WIKI.models.pages.renderPage(page)
  275. // -> Update Search Index
  276. const pageContents = await WIKI.models.pages.query().findById(page.id).select('render')
  277. page.safeContent = WIKI.models.pages.cleanHTML(pageContents.render)
  278. await WIKI.data.searchEngine.updated(page)
  279. // -> Update on Storage
  280. if (!opts.skipStorage) {
  281. await WIKI.models.storage.pageEvent({
  282. event: 'updated',
  283. page
  284. })
  285. }
  286. return page
  287. }
  288. static async deletePage(opts) {
  289. let page
  290. if (_.has(opts, 'id')) {
  291. page = await WIKI.models.pages.query().findById(opts.id)
  292. } else {
  293. page = await await WIKI.models.pages.query().findOne({
  294. path: opts.path,
  295. localeCode: opts.locale
  296. })
  297. }
  298. if (!page) {
  299. throw new Error('Invalid Page Id')
  300. }
  301. await WIKI.models.pageHistory.addVersion({
  302. ...page,
  303. action: 'deleted'
  304. })
  305. await WIKI.models.pages.query().delete().where('id', page.id)
  306. await WIKI.models.pages.deletePageFromCache(page)
  307. // -> Delete from Search Index
  308. await WIKI.data.searchEngine.deleted(page)
  309. // -> Delete from Storage
  310. if (!opts.skipStorage) {
  311. await WIKI.models.storage.pageEvent({
  312. event: 'deleted',
  313. page
  314. })
  315. }
  316. }
  317. static async renderPage(page) {
  318. const renderJob = await WIKI.scheduler.registerJob({
  319. name: 'render-page',
  320. immediate: true,
  321. worker: true
  322. }, page.id)
  323. return renderJob.finished
  324. }
  325. static async getPage(opts) {
  326. // -> Get from cache first
  327. let page = await WIKI.models.pages.getPageFromCache(opts)
  328. if (!page) {
  329. // -> Get from DB
  330. page = await WIKI.models.pages.getPageFromDb(opts)
  331. if (page) {
  332. if (page.render) {
  333. // -> Save render to cache
  334. await WIKI.models.pages.savePageToCache(page)
  335. } else {
  336. // -> No render? Possible duplicate issue
  337. /* TODO: Detect duplicate and delete */
  338. throw new Error('Error while fetching page. Duplicate entry detected. Reload the page to try again.')
  339. }
  340. }
  341. }
  342. return page
  343. }
  344. static async getPageFromDb(opts) {
  345. const queryModeID = _.isNumber(opts)
  346. try {
  347. return WIKI.models.pages.query()
  348. .column([
  349. 'pages.*',
  350. {
  351. authorName: 'author.name',
  352. authorEmail: 'author.email',
  353. creatorName: 'creator.name',
  354. creatorEmail: 'creator.email'
  355. }
  356. ])
  357. .joinRelation('author')
  358. .joinRelation('creator')
  359. .eagerAlgorithm(Model.JoinEagerAlgorithm)
  360. .eager('tags(selectTags)', {
  361. selectTags: builder => {
  362. builder.select('tag', 'title')
  363. }
  364. })
  365. .where(queryModeID ? {
  366. 'pages.id': opts
  367. } : {
  368. 'pages.path': opts.path,
  369. 'pages.localeCode': opts.locale
  370. })
  371. // .andWhere(builder => {
  372. // if (queryModeID) return
  373. // builder.where({
  374. // 'pages.isPublished': true
  375. // }).orWhere({
  376. // 'pages.isPublished': false,
  377. // 'pages.authorId': opts.userId
  378. // })
  379. // })
  380. // .andWhere(builder => {
  381. // if (queryModeID) return
  382. // if (opts.isPrivate) {
  383. // builder.where({ 'pages.isPrivate': true, 'pages.privateNS': opts.privateNS })
  384. // } else {
  385. // builder.where({ 'pages.isPrivate': false })
  386. // }
  387. // })
  388. .first()
  389. } catch (err) {
  390. WIKI.logger.warn(err)
  391. throw err
  392. }
  393. }
  394. static async savePageToCache(page) {
  395. const cachePath = path.join(process.cwd(), `data/cache/${page.hash}.bin`)
  396. await fs.outputFile(cachePath, WIKI.models.pages.cacheSchema.encode({
  397. id: page.id,
  398. authorId: page.authorId,
  399. authorName: page.authorName,
  400. createdAt: page.createdAt,
  401. creatorId: page.creatorId,
  402. creatorName: page.creatorName,
  403. description: page.description,
  404. isPrivate: page.isPrivate === 1 || page.isPrivate === true,
  405. isPublished: page.isPublished === 1 || page.isPublished === true,
  406. publishEndDate: page.publishEndDate,
  407. publishStartDate: page.publishStartDate,
  408. render: page.render,
  409. tags: page.tags.map(t => _.pick(t, ['tag', 'title'])),
  410. title: page.title,
  411. toc: _.isString(page.toc) ? page.toc : JSON.stringify(page.toc),
  412. updatedAt: page.updatedAt
  413. }))
  414. }
  415. static async getPageFromCache(opts) {
  416. const pageHash = pageHelper.generateHash({ path: opts.path, locale: opts.locale, privateNS: opts.isPrivate ? 'TODO' : '' })
  417. const cachePath = path.join(process.cwd(), `data/cache/${pageHash}.bin`)
  418. try {
  419. const pageBuffer = await fs.readFile(cachePath)
  420. let page = WIKI.models.pages.cacheSchema.decode(pageBuffer)
  421. return {
  422. ...page,
  423. path: opts.path,
  424. localeCode: opts.locale,
  425. isPrivate: opts.isPrivate
  426. }
  427. } catch (err) {
  428. if (err.code === 'ENOENT') {
  429. return false
  430. }
  431. WIKI.logger.error(err)
  432. throw err
  433. }
  434. }
  435. static async deletePageFromCache(page) {
  436. return fs.remove(path.join(process.cwd(), `data/cache/${page.hash}.bin`))
  437. }
  438. static async flushCache() {
  439. return fs.emptyDir(path.join(process.cwd(), `data/cache`))
  440. }
  441. static async migrateToLocale({ sourceLocale, targetLocale }) {
  442. return WIKI.models.pages.query()
  443. .patch({
  444. localeCode: targetLocale
  445. })
  446. .where({
  447. localeCode: sourceLocale
  448. })
  449. .whereNotExists(function() {
  450. this.select('id').from('pages AS pagesm').where('pagesm.localeCode', targetLocale).andWhereRaw('pagesm.path = pages.path')
  451. })
  452. }
  453. static cleanHTML(rawHTML = '') {
  454. return striptags(rawHTML || '')
  455. .replace(emojiRegex(), '')
  456. .replace(htmlEntitiesRegex, '')
  457. .replace(punctuationRegex, ' ')
  458. .replace(/(\r\n|\n|\r)/gm, ' ')
  459. .replace(/\s\s+/g, ' ')
  460. .split(' ').filter(w => w.length > 1).join(' ').toLowerCase()
  461. }
  462. }