common.js 5.92 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
const fs = require('fs-extra')
const path = require('path')
const stream = require('stream')
const Promise = require('bluebird')
const pipeline = Promise.promisify(stream.pipeline)
const klaw = require('klaw')
const mime = require('mime-types').lookup
const _ = require('lodash')

const pageHelper = require('../../../helpers/page.js')

/* global WIKI */

module.exports = {
  assetFolders: null,
  async importFromDisk ({ fullPath, moduleName }) {
    const rootUser = await WIKI.models.users.getRootUser()

    await pipeline(
      klaw(fullPath, {
        filter: (f) => {
          return !_.includes(f, '.git')
        }
      }),
      new stream.Transform({
        objectMode: true,
        transform: async (file, enc, cb) => {
          const relPath = file.path.substr(fullPath.length + 1)
          if (file.stats.size < 1) {
            // Skip directories and zero-byte files
            return cb()
          } else if (relPath && relPath.length > 3) {
            WIKI.logger.info(`(STORAGE/${moduleName}) Processing ${relPath}...`)
            const contentType = pageHelper.getContentType(relPath)
            if (contentType) {
              // -> Page

              try {
                await this.processPage({
                  user: rootUser,
                  relPath: relPath,
                  fullPath: fullPath,
                  contentType: contentType,
                  moduleName: moduleName
                })
              } catch (err) {
                WIKI.logger.warn(`(STORAGE/${moduleName}) Failed to process page ${relPath}`)
                WIKI.logger.warn(err)
              }
            } else {
              // -> Asset

              try {
                await this.processAsset({
                  user: rootUser,
                  relPath: relPath,
                  file: file,
                  contentType: contentType,
                  moduleName: moduleName
                })
              } catch (err) {
                WIKI.logger.warn(`(STORAGE/${moduleName}) Failed to process asset ${relPath}`)
                WIKI.logger.warn(err)
              }
            }
          }
          cb()
        }
      })
    )
    this.clearFolderCache()
  },

  async processPage ({ user, fullPath, relPath, contentType, moduleName }) {
75 76
    const normalizedRelPath = relPath.replace(/\\/g, '/')
    const contentPath = pageHelper.getPagePath(normalizedRelPath)
77 78
    const itemContents = await fs.readFile(path.join(fullPath, relPath), 'utf8')
    const pageData = WIKI.models.pages.parseMetadata(itemContents, contentType)
79
    const currentPage = await WIKI.models.pages.getPageFromDb({
80
      path: contentPath.path,
81
      locale: contentPath.locale
82
    })
83
    const newTags = !_.isNil(pageData.tags) ? _.get(pageData, 'tags', '').split(', ') : false
84 85
    if (currentPage) {
      // Already in the DB, can mark as modified
86
      WIKI.logger.info(`(STORAGE/${moduleName}) Page marked as modified: ${normalizedRelPath}`)
87 88 89 90
      await WIKI.models.pages.updatePage({
        id: currentPage.id,
        title: _.get(pageData, 'title', currentPage.title),
        description: _.get(pageData, 'description', currentPage.description) || '',
91
        tags: newTags || currentPage.tags.map(t => t.tag),
92 93 94 95 96 97 98 99
        isPublished: _.get(pageData, 'isPublished', currentPage.isPublished),
        isPrivate: false,
        content: pageData.content,
        user: user,
        skipStorage: true
      })
    } else {
      // Not in the DB, can mark as new
100
      WIKI.logger.info(`(STORAGE/${moduleName}) Page marked as new: ${normalizedRelPath}`)
101 102 103 104 105 106
      const pageEditor = await WIKI.models.editors.getDefaultEditor(contentType)
      await WIKI.models.pages.createPage({
        path: contentPath.path,
        locale: contentPath.locale,
        title: _.get(pageData, 'title', _.last(contentPath.path.split('/'))),
        description: _.get(pageData, 'description', '') || '',
107
        tags: newTags || [],
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
        isPublished: _.get(pageData, 'isPublished', true),
        isPrivate: false,
        content: pageData.content,
        user: user,
        editor: pageEditor,
        skipStorage: true
      })
    }
  },

  async processAsset ({ user, relPath, file, moduleName }) {
    WIKI.logger.info(`(STORAGE/${moduleName}) Asset marked for import: ${relPath}`)

    // -> Get all folder paths
    if (!this.assetFolders) {
      this.assetFolders = await WIKI.models.assetFolders.getAllPaths()
    }

    // -> Find existing folder
    const filePathInfo = path.parse(file.path)
    const folderPath = path.dirname(relPath).replace(/\\/g, '/')
    let folderId = _.toInteger(_.findKey(this.assetFolders, fld => { return fld === folderPath })) || null

    // -> Create missing folder structure
    if (!folderId && folderPath !== '.') {
      const folderParts = folderPath.split('/')
      let currentFolderPath = []
      let currentFolderParentId = null
      for (const folderPart of folderParts) {
        currentFolderPath.push(folderPart)
        const existingFolderId = _.findKey(this.assetFolders, fld => { return fld === currentFolderPath.join('/') })
        if (!existingFolderId) {
          const newFolderObj = await WIKI.models.assetFolders.query().insert({
            slug: folderPart,
            name: folderPart,
            parentId: currentFolderParentId
          })
          _.set(this.assetFolders, newFolderObj.id, currentFolderPath.join('/'))
          currentFolderParentId = newFolderObj.id
        } else {
          currentFolderParentId = _.toInteger(existingFolderId)
        }
      }
      folderId = currentFolderParentId
    }

    // -> Import asset
    await WIKI.models.assets.upload({
      mode: 'import',
      originalname: filePathInfo.base,
      ext: filePathInfo.ext,
      mimetype: mime(filePathInfo.base) || 'application/octet-stream',
      size: file.stats.size,
      folderId: folderId,
      path: file.path,
      assetPath: relPath,
      user: user,
      skipStorage: true
    })
  },

  clearFolderCache () {
    this.assetFolders = null
  }
}