page.js 2.41 KB
Newer Older
1 2
const qs = require('querystring')
const _ = require('lodash')
3
const crypto = require('crypto')
4
const path = require('path')
5

6
const localeSegmentRegex = /^[A-Z]{2}(-[A-Z]{2})?$/i
7

8 9
/* global WIKI */

10 11 12 13
module.exports = {
  /**
   * Parse raw url path and make it safe
   */
14
  parsePath (rawPath, opts = {}) {
15
    let pathObj = {
16
      locale: WIKI.config.lang.code,
17 18
      path: 'home',
      private: false,
19 20
      privateNS: '',
      explicitLocale: false
21 22 23 24 25 26 27 28 29
    }

    // Clean Path
    rawPath = _.trim(qs.unescape(rawPath))
    if (_.startsWith(rawPath, '/')) { rawPath = rawPath.substring(1) }
    if (rawPath === '') { rawPath = 'home' }

    // Extract Info
    let pathParts = _.filter(_.split(rawPath, '/'), p => !_.isEmpty(p))
30 31 32
    if (pathParts[0].length === 1) {
      pathParts.shift()
    }
33
    if (localeSegmentRegex.test(pathParts[0])) {
34
      pathObj.locale = pathParts[0]
35
      pathObj.explicitLocale = true
36 37
      pathParts.shift()
    }
38 39

    // Strip extension
40
    if (opts.stripExt && pathParts.length > 0) {
41 42 43 44 45 46 47 48
      const lastPart = _.last(pathParts)
      if (lastPart.indexOf('.') > 0) {
        pathParts.pop()
        const lastPartMeta = path.parse(lastPart)
        pathParts.push(lastPartMeta.name)
      }
    }

49 50
    pathObj.path = _.join(pathParts, '/')
    return pathObj
51 52 53 54 55 56
  },
  /**
   * Generate unique hash from page
   */
  generateHash(opts) {
    return crypto.createHash('sha1').update(`${opts.locale}|${opts.path}|${opts.privateNS}`).digest('hex')
57 58 59 60 61 62 63 64 65 66 67 68
  },
  /**
   * Inject Page Metadata
   */
  injectPageMetadata(page) {
    let meta = [
      ['title', page.title],
      ['description', page.description],
      ['published', page.isPublished.toString()],
      ['date', page.updatedAt],
      ['tags', '']
    ]
69 70 71
    const inject = {
      'markdown': '---\n' + meta.map(mt => `${mt[0]}: ${mt[1]}`).join('\n') + '\n---\n\n' + page.content,
      'html': '<!--\n' + meta.map(mt => `${mt[0]}: ${mt[1]}`).join('\n') + '\n-->\n\n' + page.content
72
    }
73
    return _.get(inject, page.contentType, page.content)
74 75 76 77
  },
  /**
   * Check if path is a reserved path
   */
78 79
  isReservedPath(rawPath) {
    const firstSection = _.head(rawPath.split('/'))
80
    if (firstSection.length <= 1) {
81 82 83 84 85 86 87 88 89 90 91
      return true
    } else if (localeSegmentRegex.test(firstSection)) {
      return true
    } else if (
      _.some(WIKI.data.reservedPaths, p => {
        return p === firstSection
      })) {
      return true
    } else {
      return false
    }
92 93
  }
}