You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

429 lines
12 KiB

6 years ago
6 years ago
  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. author: {
  59. relation: Model.BelongsToOneRelation,
  60. modelClass: require('./users'),
  61. join: {
  62. from: 'pages.authorId',
  63. to: 'users.id'
  64. }
  65. },
  66. creator: {
  67. relation: Model.BelongsToOneRelation,
  68. modelClass: require('./users'),
  69. join: {
  70. from: 'pages.creatorId',
  71. to: 'users.id'
  72. }
  73. },
  74. editor: {
  75. relation: Model.BelongsToOneRelation,
  76. modelClass: require('./editors'),
  77. join: {
  78. from: 'pages.editorKey',
  79. to: 'editors.key'
  80. }
  81. },
  82. locale: {
  83. relation: Model.BelongsToOneRelation,
  84. modelClass: require('./locales'),
  85. join: {
  86. from: 'pages.localeCode',
  87. to: 'locales.code'
  88. }
  89. }
  90. }
  91. }
  92. $beforeUpdate() {
  93. this.updatedAt = new Date().toISOString()
  94. }
  95. $beforeInsert() {
  96. this.createdAt = new Date().toISOString()
  97. this.updatedAt = new Date().toISOString()
  98. }
  99. static get cacheSchema() {
  100. return new JSBinType({
  101. id: 'uint',
  102. authorId: 'uint',
  103. authorName: 'string',
  104. createdAt: 'string',
  105. creatorId: 'uint',
  106. creatorName: 'string',
  107. description: 'string',
  108. isPrivate: 'boolean',
  109. isPublished: 'boolean',
  110. publishEndDate: 'string',
  111. publishStartDate: 'string',
  112. render: 'string',
  113. title: 'string',
  114. toc: 'string',
  115. updatedAt: 'string'
  116. })
  117. }
  118. /**
  119. * Inject page metadata into contents
  120. */
  121. injectMetadata () {
  122. let meta = [
  123. ['title', this.title],
  124. ['description', this.description],
  125. ['published', this.isPublished.toString()],
  126. ['date', this.updatedAt],
  127. ['tags', '']
  128. ]
  129. switch (this.contentType) {
  130. case 'markdown':
  131. return '---\n' + meta.map(mt => `${mt[0]}: ${mt[1]}`).join('\n') + '\n---\n\n' + this.content
  132. case 'html':
  133. return '<!--\n' + meta.map(mt => `${mt[0]}: ${mt[1]}`).join('\n') + '\n-->\n\n' + this.content
  134. default:
  135. return this.content
  136. }
  137. }
  138. /**
  139. * Parse injected page metadata from raw content
  140. *
  141. * @param {String} raw Raw file contents
  142. * @param {String} contentType Content Type
  143. */
  144. static parseMetadata (raw, contentType) {
  145. let result
  146. switch (contentType) {
  147. case 'markdown':
  148. result = frontmatterRegex.markdown.exec(raw)
  149. if (result[2]) {
  150. return {
  151. ...yaml.safeLoad(result[2]),
  152. content: result[3]
  153. }
  154. } else {
  155. // Attempt legacy v1 format
  156. result = frontmatterRegex.legacy.exec(raw)
  157. if (result[2]) {
  158. return {
  159. title: result[2],
  160. description: result[4],
  161. content: result[5]
  162. }
  163. }
  164. }
  165. break
  166. case 'html':
  167. result = frontmatterRegex.html.exec(raw)
  168. if (result[2]) {
  169. return {
  170. ...yaml.safeLoad(result[2]),
  171. content: result[3]
  172. }
  173. }
  174. break
  175. }
  176. return {
  177. content: raw
  178. }
  179. }
  180. static async createPage(opts) {
  181. await WIKI.models.pages.query().insert({
  182. authorId: opts.authorId,
  183. content: opts.content,
  184. creatorId: opts.authorId,
  185. contentType: _.get(_.find(WIKI.data.editors, ['key', opts.editor]), `contentType`, 'text'),
  186. description: opts.description,
  187. editorKey: opts.editor,
  188. hash: pageHelper.generateHash({ path: opts.path, locale: opts.locale, privateNS: opts.isPrivate ? 'TODO' : '' }),
  189. isPrivate: opts.isPrivate,
  190. isPublished: opts.isPublished,
  191. localeCode: opts.locale,
  192. path: opts.path,
  193. publishEndDate: opts.publishEndDate || '',
  194. publishStartDate: opts.publishStartDate || '',
  195. title: opts.title,
  196. toc: '[]'
  197. })
  198. const page = await WIKI.models.pages.getPageFromDb({
  199. path: opts.path,
  200. locale: opts.locale,
  201. userId: opts.authorId,
  202. isPrivate: opts.isPrivate
  203. })
  204. // -> Render page to HTML
  205. await WIKI.models.pages.renderPage(page)
  206. // -> Add to Search Index
  207. const pageContents = await WIKI.models.pages.query().findById(page.id).select('render')
  208. page.safeContent = WIKI.models.pages.cleanHTML(pageContents.render)
  209. await WIKI.data.searchEngine.created(page)
  210. // -> Add to Storage
  211. if (!opts.skipStorage) {
  212. await WIKI.models.storage.pageEvent({
  213. event: 'created',
  214. page
  215. })
  216. }
  217. return page
  218. }
  219. static async updatePage(opts) {
  220. const ogPage = await WIKI.models.pages.query().findById(opts.id)
  221. if (!ogPage) {
  222. throw new Error('Invalid Page Id')
  223. }
  224. await WIKI.models.pageHistory.addVersion({
  225. ...ogPage,
  226. isPublished: ogPage.isPublished === true || ogPage.isPublished === 1,
  227. action: 'updated'
  228. })
  229. await WIKI.models.pages.query().patch({
  230. authorId: opts.authorId,
  231. content: opts.content,
  232. description: opts.description,
  233. isPublished: opts.isPublished === true || opts.isPublished === 1,
  234. publishEndDate: opts.publishEndDate || '',
  235. publishStartDate: opts.publishStartDate || '',
  236. title: opts.title
  237. }).where('id', ogPage.id)
  238. const page = await WIKI.models.pages.getPageFromDb({
  239. path: ogPage.path,
  240. locale: ogPage.localeCode,
  241. userId: ogPage.authorId,
  242. isPrivate: ogPage.isPrivate
  243. })
  244. // -> Render page to HTML
  245. await WIKI.models.pages.renderPage(page)
  246. // -> Update Search Index
  247. const pageContents = await WIKI.models.pages.query().findById(page.id).select('render')
  248. page.safeContent = WIKI.models.pages.cleanHTML(pageContents.render)
  249. await WIKI.data.searchEngine.updated(page)
  250. // -> Update on Storage
  251. if (!opts.skipStorage) {
  252. await WIKI.models.storage.pageEvent({
  253. event: 'updated',
  254. page
  255. })
  256. }
  257. return page
  258. }
  259. static async deletePage(opts) {
  260. let page
  261. if (_.has(opts, 'id')) {
  262. page = await WIKI.models.pages.query().findById(opts.id)
  263. } else {
  264. page = await await WIKI.models.pages.query().findOne({
  265. path: opts.path,
  266. localeCode: opts.locale
  267. })
  268. }
  269. if (!page) {
  270. throw new Error('Invalid Page Id')
  271. }
  272. await WIKI.models.pageHistory.addVersion({
  273. ...page,
  274. action: 'deleted'
  275. })
  276. await WIKI.models.pages.query().delete().where('id', page.id)
  277. await WIKI.models.pages.deletePageFromCache(page)
  278. // -> Delete from Search Index
  279. await WIKI.data.searchEngine.deleted(page)
  280. // -> Delete from Storage
  281. if (!opts.skipStorage) {
  282. await WIKI.models.storage.pageEvent({
  283. event: 'deleted',
  284. page
  285. })
  286. }
  287. }
  288. static async renderPage(page) {
  289. const renderJob = await WIKI.scheduler.registerJob({
  290. name: 'render-page',
  291. immediate: true,
  292. worker: true
  293. }, page.id)
  294. return renderJob.finished
  295. }
  296. static async getPage(opts) {
  297. let page = await WIKI.models.pages.getPageFromCache(opts)
  298. if (!page) {
  299. page = await WIKI.models.pages.getPageFromDb(opts)
  300. if (page) {
  301. await WIKI.models.pages.savePageToCache(page)
  302. }
  303. }
  304. return page
  305. }
  306. static async getPageFromDb(opts) {
  307. const queryModeID = _.isNumber(opts)
  308. return WIKI.models.pages.query()
  309. .column([
  310. 'pages.*',
  311. {
  312. authorName: 'author.name',
  313. authorEmail: 'author.email',
  314. creatorName: 'creator.name',
  315. creatorEmail: 'creator.email'
  316. }
  317. ])
  318. .joinRelation('author')
  319. .joinRelation('creator')
  320. .where(queryModeID ? {
  321. 'pages.id': opts
  322. } : {
  323. 'pages.path': opts.path,
  324. 'pages.localeCode': opts.locale
  325. })
  326. .andWhere(builder => {
  327. if (queryModeID) return
  328. builder.where({
  329. 'pages.isPublished': true
  330. }).orWhere({
  331. 'pages.isPublished': false,
  332. 'pages.authorId': opts.userId
  333. })
  334. })
  335. .andWhere(builder => {
  336. if (queryModeID) return
  337. if (opts.isPrivate) {
  338. builder.where({ 'pages.isPrivate': true, 'pages.privateNS': opts.privateNS })
  339. } else {
  340. builder.where({ 'pages.isPrivate': false })
  341. }
  342. })
  343. .first()
  344. }
  345. static async savePageToCache(page) {
  346. const cachePath = path.join(process.cwd(), `data/cache/${page.hash}.bin`)
  347. await fs.outputFile(cachePath, WIKI.models.pages.cacheSchema.encode({
  348. id: page.id,
  349. authorId: page.authorId,
  350. authorName: page.authorName,
  351. createdAt: page.createdAt,
  352. creatorId: page.creatorId,
  353. creatorName: page.creatorName,
  354. description: page.description,
  355. isPrivate: page.isPrivate === 1 || page.isPrivate === true,
  356. isPublished: page.isPublished === 1 || page.isPublished === true,
  357. publishEndDate: page.publishEndDate,
  358. publishStartDate: page.publishStartDate,
  359. render: page.render,
  360. title: page.title,
  361. toc: _.isString(page.toc) ? page.toc : JSON.stringify(page.toc),
  362. updatedAt: page.updatedAt
  363. }))
  364. }
  365. static async getPageFromCache(opts) {
  366. const pageHash = pageHelper.generateHash({ path: opts.path, locale: opts.locale, privateNS: opts.isPrivate ? 'TODO' : '' })
  367. const cachePath = path.join(process.cwd(), `data/cache/${pageHash}.bin`)
  368. try {
  369. const pageBuffer = await fs.readFile(cachePath)
  370. let page = WIKI.models.pages.cacheSchema.decode(pageBuffer)
  371. return {
  372. ...page,
  373. path: opts.path,
  374. localeCode: opts.locale,
  375. isPrivate: opts.isPrivate
  376. }
  377. } catch (err) {
  378. if (err.code === 'ENOENT') {
  379. return false
  380. }
  381. WIKI.logger.error(err)
  382. throw err
  383. }
  384. }
  385. static async deletePageFromCache(page) {
  386. return fs.remove(path.join(process.cwd(), `data/cache/${page.hash}.bin`))
  387. }
  388. static cleanHTML(rawHTML = '') {
  389. return striptags(rawHTML || '')
  390. .replace(emojiRegex(), '')
  391. .replace(htmlEntitiesRegex, '')
  392. .replace(punctuationRegex, ' ')
  393. .replace(/(\r\n|\n|\r)/gm, ' ')
  394. .replace(/\s\s+/g, ' ')
  395. .split(' ').filter(w => w.length > 1).join(' ').toLowerCase()
  396. }
  397. }