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.

94 lines
2.4 KiB

  1. const qs = require('querystring')
  2. const _ = require('lodash')
  3. const crypto = require('crypto')
  4. const path = require('path')
  5. const localeSegmentRegex = /^[A-Z]{2}(-[A-Z]{2})?$/i
  6. /* global WIKI */
  7. module.exports = {
  8. /**
  9. * Parse raw url path and make it safe
  10. */
  11. parsePath (rawPath, opts = {}) {
  12. let pathObj = {
  13. locale: WIKI.config.lang.code,
  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. // Strip extension
  32. if (opts.stripExt && pathParts.length > 0) {
  33. const lastPart = _.last(pathParts)
  34. if (lastPart.indexOf('.') > 0) {
  35. pathParts.pop()
  36. const lastPartMeta = path.parse(lastPart)
  37. pathParts.push(lastPartMeta.name)
  38. }
  39. }
  40. pathObj.path = _.join(pathParts, '/')
  41. return pathObj
  42. },
  43. /**
  44. * Generate unique hash from page
  45. */
  46. generateHash(opts) {
  47. return crypto.createHash('sha1').update(`${opts.locale}|${opts.path}|${opts.privateNS}`).digest('hex')
  48. },
  49. /**
  50. * Inject Page Metadata
  51. */
  52. injectPageMetadata(page) {
  53. let meta = [
  54. ['title', page.title],
  55. ['description', page.description],
  56. ['published', page.isPublished.toString()],
  57. ['date', page.updatedAt],
  58. ['tags', '']
  59. ]
  60. switch (page.contentType) {
  61. case 'markdown':
  62. return '---\n' + meta.map(mt => `${mt[0]}: ${mt[1]}`).join('\n') + '\n---\n\n' + page.content
  63. case 'html':
  64. return '<!--\n' + meta.map(mt => `${mt[0]}: ${mt[1]}`).join('\n') + '\n-->\n\n' + page.content
  65. default:
  66. return page.content
  67. }
  68. },
  69. /**
  70. * Check if path is a reserved path
  71. */
  72. isReservedPath(rawPath) {
  73. const firstSection = _.head(rawPath.split('/'))
  74. if (firstSection.length <= 1) {
  75. return true
  76. } else if (localeSegmentRegex.test(firstSection)) {
  77. return true
  78. } else if (
  79. _.some(WIKI.data.reservedPaths, p => {
  80. return p === firstSection
  81. })) {
  82. return true
  83. } else {
  84. return false
  85. }
  86. }
  87. }