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.

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