Tue Jan 31 2017
Copied to clipboard! Copy reply
  • 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
import os from 'os'
import fs from 'fs'
import path from 'path'
import client from 'scp2'
import cfg from '../config'
import logger from '../logger'

export default class Upload {


  /*
   * Push assets (sitewide-promo) files to the server
   * Very basic. Just take from tmp dir and transfer
   */

  static async asset(ctx, next)
  {
    const file = ctx.request.body.files['file']
    
    if (!file)
    {
      return ctx.body = {result: 0, payload: 'no file'}
    }

    var res
    const localUri = file.path
    const remotelUri = `${cfg.stg_base}/sitewide-promo/${file.name}`
    const result = Upload.transfer(localUri, remotelUri)
    await result.then(() => {
        // Here, i'd like to loop through ws clients and .send() a message
        res = {result: 1, payload: 'success'}
      })
      .catch(e => {
        res = {result: 1, payload: 'could not upload'}
      })
      ctx.body = res
    }



 
  static transfer(localUri, remoteUri)
  {
    const promise = new Promise((resolve, reject) => {
      client.scp(localUri, remoteUri , err => {
        if (err)
        {
          reject(err)
        }
        else
        {
          resolve()
        }
      })
    })
    return promise
  }

}