page.js 3.95 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

const contentToExt = {
  markdown: 'md',
13
  asciidoc: 'adoc',
14 15 16
  html: 'html'
}
const extToContent = _.invert(contentToExt)
17

18 19
/* global WIKI */

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

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

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

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

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

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