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.

74 lines
1.9 KiB

  1. const qs = require('querystring')
  2. const _ = require('lodash')
  3. const crypto = require('crypto')
  4. const localeSegmentRegex = /^[A-Z]{2}(-[A-Z]{2})?$/i
  5. const systemSegmentRegex = /^[A-Z]\//i
  6. /* global WIKI */
  7. module.exports = {
  8. /**
  9. * Parse raw url path and make it safe
  10. */
  11. parsePath (rawPath) {
  12. let pathObj = {
  13. locale: 'en',
  14. path: 'home',
  15. private: false,
  16. privateNS: ''
  17. }
  18. // Clean Path
  19. rawPath = _.trim(qs.unescape(rawPath))
  20. if (_.startsWith(rawPath, '/')) { rawPath = rawPath.substring(1) }
  21. if (rawPath === '') { rawPath = 'home' }
  22. // Extract Info
  23. let pathParts = _.filter(_.split(rawPath, '/'), p => !_.isEmpty(p))
  24. if (pathParts[0].length === 1) {
  25. pathParts.shift()
  26. }
  27. if (localeSegmentRegex.test(pathParts[0])) {
  28. pathObj.locale = pathParts[0]
  29. pathParts.shift()
  30. }
  31. pathObj.path = _.join(pathParts, '/')
  32. return pathObj
  33. },
  34. /**
  35. * Generate unique hash from page
  36. */
  37. generateHash(opts) {
  38. return crypto.createHash('sha1').update(`${opts.locale}|${opts.path}|${opts.privateNS}`).digest('hex')
  39. },
  40. /**
  41. * Inject Page Metadata
  42. */
  43. injectPageMetadata(page) {
  44. let meta = [
  45. ['title', page.title],
  46. ['description', page.description],
  47. ['published', page.isPublished.toString()],
  48. ['date', page.updatedAt],
  49. ['tags', '']
  50. ]
  51. switch (page.contentType) {
  52. case 'markdown':
  53. return '---\n' + meta.map(mt => `${mt[0]}: ${mt[1]}`).join('\n') + '\n---\n\n' + page.content
  54. case 'html':
  55. return '<!--\n' + meta.map(mt => `${mt[0]}: ${mt[1]}`).join('\n') + '\n-->\n\n' + page.content
  56. default:
  57. return page.content
  58. }
  59. },
  60. /**
  61. * Check if path is a reserved path
  62. */
  63. isReservedPath(rawPath) {
  64. const firstSection = _.head(rawPath.split('/'))
  65. return _.some(WIKI.data.reservedPaths, p => {
  66. return p === firstSection || systemSegmentRegex.test(rawPath)
  67. })
  68. }
  69. }