page.js 3.93 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
// eslint-disable-next-line no-control-regex
const unsafeCharsRegex = /[\x00-\x1f\x80-\x9f\\"|<>:*?]/
10 11 12 13 14 15

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

17 18
/* global WIKI */

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

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

38
    rawPath = rawPath.replace(/\\/g, '').replace(/\/\//g, '').replace(/\.\.+/ig, '')
39

40
    // Extract Info
41 42 43 44
    let pathParts = _.filter(_.split(rawPath, '/'), p => {
      p = _.trim(p)
      return !_.isEmpty(p) && p !== '..' && p !== '.'
    })
45 46 47
    if (pathParts[0].length === 1) {
      pathParts.shift()
    }
48
    if (localeSegmentRegex.test(pathParts[0])) {
49
      pathObj.locale = pathParts[0]
50
      pathObj.explicitLocale = true
51 52
      pathParts.shift()
    }
53 54

    // Strip extension
55
    if (opts.stripExt && pathParts.length > 0) {
56 57 58 59 60 61 62 63
      const lastPart = _.last(pathParts)
      if (lastPart.indexOf('.') > 0) {
        pathParts.pop()
        const lastPartMeta = path.parse(lastPart)
        pathParts.push(lastPartMeta.name)
      }
    }

64 65
    pathObj.path = _.join(pathParts, '/')
    return pathObj
66 67 68 69 70 71
  },
  /**
   * Generate unique hash from page
   */
  generateHash(opts) {
    return crypto.createHash('sha1').update(`${opts.locale}|${opts.path}|${opts.privateNS}`).digest('hex')
72 73 74 75 76 77 78 79 80 81
  },
  /**
   * Inject Page Metadata
   */
  injectPageMetadata(page) {
    let meta = [
      ['title', page.title],
      ['description', page.description],
      ['published', page.isPublished.toString()],
      ['date', page.updatedAt],
82
      ['tags', page.tags ? page.tags.map(t => t.tag).join(', ') : ''],
83
      ['editor', page.editorKey],
84
      ['dateCreated', page.createdAt]
85
    ]
86 87 88 89 90
    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
91 92 93 94 95
      case 'json':
        return {
          ...page.content,
          _meta: _.fromPairs(meta)
        }
96 97
      default:
        return page.content
98
    }
99 100 101 102
  },
  /**
   * Check if path is a reserved path
   */
103 104
  isReservedPath(rawPath) {
    const firstSection = _.head(rawPath.split('/'))
105
    if (firstSection.length <= 1) {
106 107 108 109 110 111 112 113 114 115 116
      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
117 118 119 120 121
  },
  /**
   * Get file extension from content type
   */
  getFileExtension(contentType) {
122
    return _.get(contentToExt, contentType, 'txt')
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
  },
  /**
   * 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 = {
146
        locale: result[1].replace('/', ''),
147 148
        path: result[2]
      }
Nick's avatar
Nick committed
149
    }
150
    return meta
151 152
  }
}