page.js 3.45 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
const localeFolderRegex = /^([a-z]{2}(?:-[a-z]{2})?\/)?(.*)/i
8 9 10 11 12 13

const contentToExt = {
  markdown: 'md',
  html: 'html'
}
const extToContent = _.invert(contentToExt)
14

15 16
/* global WIKI */

17 18 19 20
module.exports = {
  /**
   * Parse raw url path and make it safe
   */
21
  parsePath (rawPath, opts = {}) {
22
    let pathObj = {
23
      locale: WIKI.config.lang.code,
24 25
      path: 'home',
      private: false,
26 27
      privateNS: '',
      explicitLocale: false
28 29 30 31 32 33 34 35 36
    }

    // 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))
37 38 39
    if (pathParts[0].length === 1) {
      pathParts.shift()
    }
40
    if (localeSegmentRegex.test(pathParts[0])) {
41
      pathObj.locale = pathParts[0]
42
      pathObj.explicitLocale = true
43 44
      pathParts.shift()
    }
45 46

    // Strip extension
47
    if (opts.stripExt && pathParts.length > 0) {
48 49 50 51 52 53 54 55
      const lastPart = _.last(pathParts)
      if (lastPart.indexOf('.') > 0) {
        pathParts.pop()
        const lastPartMeta = path.parse(lastPart)
        pathParts.push(lastPartMeta.name)
      }
    }

56 57
    pathObj.path = _.join(pathParts, '/')
    return pathObj
58 59 60 61 62 63
  },
  /**
   * Generate unique hash from page
   */
  generateHash(opts) {
    return crypto.createHash('sha1').update(`${opts.locale}|${opts.path}|${opts.privateNS}`).digest('hex')
64 65 66 67 68 69 70 71 72 73
  },
  /**
   * Inject Page Metadata
   */
  injectPageMetadata(page) {
    let meta = [
      ['title', page.title],
      ['description', page.description],
      ['published', page.isPublished.toString()],
      ['date', page.updatedAt],
74
      ['tags', page.tags ? page.tags.map(t => t.tag).join(', ') : '']
75
    ]
76 77 78 79 80 81 82
    switch (page.contentType) {
      case 'markdown':
        return '---\n' + meta.map(mt => `${mt[0]}: ${mt[1]}`).join('\n') + '\n---\n\n' + page.content
      case 'html':
        return '<!--\n' + meta.map(mt => `${mt[0]}: ${mt[1]}`).join('\n') + '\n-->\n\n' + page.content
      default:
        return page.content
83
    }
84 85 86 87
  },
  /**
   * Check if path is a reserved path
   */
88 89
  isReservedPath(rawPath) {
    const firstSection = _.head(rawPath.split('/'))
90
    if (firstSection.length <= 1) {
91 92 93 94 95 96 97 98 99 100 101
      return true
    } else if (localeSegmentRegex.test(firstSection)) {
      return true
    } else if (
      _.some(WIKI.data.reservedPaths, p => {
        return p === firstSection
      })) {
      return true
    } else {
      return false
    }
Nick's avatar
Nick committed
102 103 104 105 106
  },
  /**
   * Get file extension from content type
   */
  getFileExtension(contentType) {
107
    return _.get(contentToExt, contentType, 'txt')
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
  },
  /**
   * Get content type from file extension
   */
  getContentType (filePath) {
    const ext = _.last(filePath.split('.'))
    return _.get(extToContent, ext, false)
  },
  /**
   * Get Page Meta object from disk path
   */
  getPagePath (filePath) {
    let fpath = filePath
    if (process.platform === 'win32') {
      fpath = filePath.replace(/\\/g, '/')
    }
    let meta = {
      locale: WIKI.config.lang.code,
      path: _.initial(fpath.split('.')).join('')
    }
    const result = localeFolderRegex.exec(meta.path)
    if (result[1]) {
      meta = {
131
        locale: result[1].replace('/', ''),
132 133
        path: result[2]
      }
Nick's avatar
Nick committed
134
    }
135
    return meta
136 137
  }
}