page.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. explicitLocale: false
  18. }
  19. // Clean Path
  20. rawPath = _.trim(qs.unescape(rawPath))
  21. if (_.startsWith(rawPath, '/')) { rawPath = rawPath.substring(1) }
  22. if (rawPath === '') { rawPath = 'home' }
  23. // Extract Info
  24. let pathParts = _.filter(_.split(rawPath, '/'), p => !_.isEmpty(p))
  25. if (pathParts[0].length === 1) {
  26. pathParts.shift()
  27. }
  28. if (localeSegmentRegex.test(pathParts[0])) {
  29. pathObj.locale = pathParts[0]
  30. pathObj.explicitLocale = true
  31. pathParts.shift()
  32. }
  33. // Strip extension
  34. if (opts.stripExt && pathParts.length > 0) {
  35. const lastPart = _.last(pathParts)
  36. if (lastPart.indexOf('.') > 0) {
  37. pathParts.pop()
  38. const lastPartMeta = path.parse(lastPart)
  39. pathParts.push(lastPartMeta.name)
  40. }
  41. }
  42. pathObj.path = _.join(pathParts, '/')
  43. return pathObj
  44. },
  45. /**
  46. * Generate unique hash from page
  47. */
  48. generateHash(opts) {
  49. return crypto.createHash('sha1').update(`${opts.locale}|${opts.path}|${opts.privateNS}`).digest('hex')
  50. },
  51. /**
  52. * Inject Page Metadata
  53. */
  54. injectPageMetadata(page) {
  55. let meta = [
  56. ['title', page.title],
  57. ['description', page.description],
  58. ['published', page.isPublished.toString()],
  59. ['date', page.updatedAt],
  60. ['tags', '']
  61. ]
  62. switch (page.contentType) {
  63. case 'markdown':
  64. return '---\n' + meta.map(mt => `${mt[0]}: ${mt[1]}`).join('\n') + '\n---\n\n' + page.content
  65. case 'html':
  66. return '<!--\n' + meta.map(mt => `${mt[0]}: ${mt[1]}`).join('\n') + '\n-->\n\n' + page.content
  67. default:
  68. return page.content
  69. }
  70. },
  71. /**
  72. * Check if path is a reserved path
  73. */
  74. isReservedPath(rawPath) {
  75. const firstSection = _.head(rawPath.split('/'))
  76. if (firstSection.length <= 1) {
  77. return true
  78. } else if (localeSegmentRegex.test(firstSection)) {
  79. return true
  80. } else if (
  81. _.some(WIKI.data.reservedPaths, p => {
  82. return p === firstSection
  83. })) {
  84. return true
  85. } else {
  86. return false
  87. }
  88. }
  89. }