Sat Jan 07 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
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 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
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
/*
 * Handles all routes regarding flips.
 * I changed up my brackets/braces style here
 * to be very Java-like, for shits and giggles.
 * Let us know what you think by emailing  Vinoth
 * at vjohn@rosettastone.com
 * :D
 */

import fs from 'fs-extra'
import prettyjson from 'json-format'
import cfg from '../config'
import logger from '../logger'

export default class Flips
{

  static getFlips(ctx, next)
  {
    ctx.body = fs.readFileSync(cfg.localUris.flipSchedule, 'utf8')
  }



  /*
   * Create flip.
   * Mainly does 3 things:
   * 1. Write to schedule.json
   * 2. Create folder flips/<flipdate>/sitewide-promo
   * 3. Create file flips/<flipdate>/flip.json.
   * The cron job script will periodically scan
   * schedule.json trying to match a datetime. If it
   * matches, it's time to flip. It then looks for a
   * folder with the datetime as its name. Inside this
   * folder is flips.json, which basically contains user
   * input from client's create-flip form. It also contains
   * the folder sitewide-promo which holds assets
   * to upload. When creating a flip and there's a flip
   * already schedule for the same datetime, we delete the
   * flip/<datime>/ folder so we can overwrite.
   * Structure:
   * pi/
   * |
   * |-- data/
   * |-- |-- schedule.json
   * |   |-- flips/
   * |   |   |-- dec 25 2016, 11:00 PM/
   * |   |   |   |-- flip.json (constants, rtos, promoset, etc)
   * |   |   |   |-- sitewide-promo/ (assets for this flip)
   * |   |   |   |
   * |   |   |   |
   * |-- server/
   * |-- client/
   *
   */

  static upsertFlip(ctx, next)
  {
    const data = ctx.request.body.fields
    const overwrite = ctx.query.overwrite
    var assets = ctx.request.body.files['assets[]']

    if (!data.name || !data.date || !data.promoset)
    {
      logger.error(`
        Error. missing required data.
        Name: ${data.name},
        Date: ${data.date},
        Promoset: ${data.promoset}`,
        { user: 'username' }
      )
      return ctx.body =  { result: 0, payload: `Error. Missing required data.` }
    }

    const date = moment(new Date(data.rawdate)).format('MMM DD YYYY, hh:mm a')
    try
    {
      var schedule = fs.readJsonSync(cfg.localUris.flipSchedule, 'utf8')
    }
    catch(e)
    {
      logger.error(`Couldn't open schedule.json: ${e}`, { user: 'username' })
      return ctx.body = { result: 0, payload: `Error. Couldn't open schedule.json.` }
    }

   /*
    * We always overwrite. So see if we have a folder with this date
    * as the name, and if so, delete it, since we'll be creating
    * a new one.
    */

    const dirs = fs.readdirSync(cfg.localUris.flips)
    if (dirs.includes(date))
    {
      try
      {
        fs.removeSync(`${cfg.localUris.flips}/${date}`)
      }
      catch(e)
      {
        logger.error(`Could not remove flips/${date}: ${e}.`, { user: 'username' })
        return ctx.body = { result: 0, payload: 'Could not remove old flip direcory.' }
      }
    }

    /* Create our new dir and subdirs. The name is the date. */

    try
    {
      fs.ensureDirSync(`../data/flips/${date}/sitewide-promo`)
    }
    catch(e)
    {
      logger.error(`Could not create flips/${date}/ and its subdirs: ${e}`, { user: 'username' })
      return ctx.body = { result: 0, payload: 'Error. Could not create folder(s).' }
    }

    /*
     * This object will become flip.json
     * We default to null, since undefined won't make it to output file.
     */

    const flip = {
      "name"       : data.name                   || null,
      "promoset"   : data.promoset               || null,
      "constants"  : JSON.parse(data.constants)  || null,
      "router"     : "santatradafi"              || null
    }

    /* If we have assets to upload, do so here. */

    if (undefined !== assets)
    {
      // koa-body doesnt put obj into an array if it's a single file.
      // Fucking broken. Put single obj inside an array here.
      assets = Array.isArray(assets) ? assets : [assets]

      var ret = {}
      var failedUploads = []

      for (let file in assets)
      {
        let dst = `${cfg.localUris.flips}/${date}/sitewide-promo/${assets[file].name}`
        fs.move(assets[file].path, dst, err =>
        {
          if (err)
          {
            failedUploads.push(`${assets[file].name}`)
          }
        })
      }

      if (failedUploads.length)
      {
        fs.removeSync(`${cfg.localUris.flips}/${date}`)
        return ctx.body =  {result: 0, payload: `Failed up upload: ${failedUploads}`}
      }
    }

    // Write this flip to our flip.json.
    try
    {
      fs.writeFileSync(`${cfg['localUris']['flips']}/${date}/flip.json`, prettyjson(flip))
    }
    catch(e)
    {
      logger.error(`Could write to ${date}/flips.json: ${e}`, { user: 'username' })
      return ctx.body = {result: 0, payload: `Could not write to flips.json`}
    }


    //schedule = schedule.filter(f => f.r)
    // Append {name: .., date: ..} to schedule.json.
    schedule.push({name: data.name, dirname: date, rawdate: data.rawdate})

    try
    {
      fs.writeFileSync(cfg.localUris.flipSchedule, prettyjson(schedule))
    }
    catch(e)
    {
      logger.error(`Could write to schedule.json: ${e}`, { user: 'username' })

    }

    return ctx.body =  {result: 1, payload: `Success. Flip created.`}


  }



}