- 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
- 197
- 198
- 199
- 200
- 201
- 202
- 203
- 204
- 205
- 206
- 207
- 208
- 209
- 210
- 211
- 212
- 213
- 214
- 215
- 216
- 217
- 218
- 219
- 220
- 221
- 222
- 223
- 224
- 225
- 226
- 227
- 228
- 229
- 230
- 231
- 232
- 233
- 234
- 235
- 236
- 237
- 238
- 239
- 240
- 241
- 242
- 243
- 244
- 245
- 246
- 247
- 248
- 249
- 250
- 251
- 252
- 253
- 254
- 255
- 256
- 257
- 258
- 259
- 260
- 261
- 262
- 263
- 264
- 265
- 266
- 267
- 268
- 269
- 270
- 271
- 272
- 273
- 274
- 275
- 276
- 277
- 278
- 279
- 280
- 281
- 282
- 283
- 284
- 285
- 286
- 287
- 288
- 289
- 290
- 291
- 292
- 293
- 294
- 295
- 296
- 297
- 298
- 299
- 300
- 301
- 302
- 303
- 304
- 305
- 306
- 307
- 308
- 309
- 310
- 311
- 312
- 313
- 314
- 315
- 316
- 317
- 318
- 319
- 320
- 321
- 322
- 323
- 324
- 325
- 326
- 327
- 328
- 329
- 330
- 331
- 332
- 333
- 334
- 335
- 336
- 337
- 338
- 339
- 340
- 341
- 342
- 343
- 344
- 345
- 346
- 347
- 348
- 349
- 350
- 351
- 352
- 353
- 354
- 355
- 356
- 357
- 358
- 359
- 360
- 361
- 362
- 363
- 364
- 365
- 366
- 367
- 368
- 369
- 370
- 371
- 372
- 373
- 374
- 375
- 376
- 377
- 378
- 379
- 380
- 381
- 382
- 383
- 384
- 385
- 386
- 387
- 388
- 389
- 390
- 391
- 392
- 393
- 394
- 395
- 396
- 397
- 398
- 399
- 400
- 401
- 402
- 403
- 404
- 405
- 406
- 407
- 408
- 409
- 410
- 411
- 412
- 413
- 414
- 415
- 416
- 417
- 418
- 419
- 420
- 421
- 422
- 423
- 424
import fs from 'fs-extra'
import moment from 'moment'
import prettyjson from 'json-format'
import base64 from 'base64-img'
import _ from 'lodash'
import cfg from './config'
import Validate from './validate'
const stringify = JSON.stringify
const parse = JSON.parse
/*
* Home handler. Simply list
* our scheduled flips.
*/
export function home(ctx, next) {
ctx.body = 'Hello Koa';
}
/*
* Grabs all pages.
*
* @returns {obj} pages object
*/
export function getPages(ctx, next) {
ctx.body = fs.readFileSync(cfg.localUris.pages, 'utf8')
}
/*
* Grabs all promosets.
* @returns {obj} promosets object
*/
export function getPromosets(ctx, next) {
ctx.body = parse(fs.readFileSync(cfg.localUris.promos, 'utf8'))
}
/*
* Grabs list of all crescendos.
* Strips out the '.json'
*
* * @returns {obj} pages object
*/
export function getCrescendos(ctx, next) {
ctx.body = fs.readdirSync(cfg['localUris']['crescendos']).map(c => c.slice(0, -5))
}
/*
* Grabs of all flips - stored in schedule.json
*
* @returns {list} object containing flips
*/
export function getFlipsSchedule(ctx, next) {
return ctx.body = fs.readFileSync(cfg.localUris.flipSchedule, 'utf8')
}
/*
* Grabs list of all masthead images from sbsr.
* Converting the imgs to base64 so we can serve them.
* How else are we gonna server imgs from ../../deploy/etc
* when the root folder is pi/ ?
* This will probably be slow when directory gets lofs of imgs.
* It will be ok to cry then.
*/
export function getMastheads(ctx, next) {
ctx.body = fs.readdirSync(cfg['localUris']['mastheads']).map(f => f)
}
/*
* Grabs list of all masthead types.
*/
export function getMastheadTypes(ctx, next) {
ctx.body = fs.readdirSync(cfg['localUris']['mastheadTypes'])
}
/*
* Create flip.
* Will create a folder with the flip date as its name,
* containing a file (flip.json) inside with the flip info.
* The actual cron script doing the flip will read flip.json.
* flip.json basically contains user-inputted values from the
* /create-flip ui form.
* We also write filesdata/schedule.json, which contains a
* an array of {name: foo, date: bar} objects. This file is read by
* the cron job script periodically. If the script sees the
* current datetime in "date", it will perform a flip.
* This function will abort if a flip is scheduled and there's already
* a directory with that date schedule. But if you pass ?overwrite=true,
* it will delete the directory that exists, and create new.
* Structure:
* pi/
* |-- schedule.json ({name:xmas, date: dec 25})
* |
* |-- data/
* | |-- flips/
* | | |-- dec 25 2016, 11:00 PM/
* | | | |-- flip.json (constants, rtos, promoset, etc)
* | | | |-- sitewide-promo/ (assets for this flip)
* | | | |
* | | | |
* |-- server/
* |-- client/
*
*/
export function createFlip(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) {
// TODO - return error to UI
}
const date = moment(new Date(data.rawdate)).format('MMM DD YYYY, hh:mm a')
var schedule = parse(fs.readFileSync(cfg['localUris']['flipSchedule'], 'utf8'))
// First make sure we don't have a flip already scheduled on this date.
// We can check schedule.json or read the firs in data/flips.
const dirs = fs.readdirSync(cfg.localUris.flips)
if (dirs.includes(date)) {
if ( !overwrite ) {
return ctx.body = {
result: 0,
code: 'exists',
payload: "Flip already exists on this datetime."
}
} else {
// We decided to overwrite. Delete what's there then.
fs.removeSync(`../data/flips/${date}`)
schedule = schedule.filter(f => f.rawdate != data.rawdate)
}
}
// Create directory to store flip files and info
fs.ensureDirSync(`../data/flips/${date}/sitewide-promo`)
// 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
}
// "rto": {
// "desktop": data['desktop-rto'] || null,
// "desktopUrl": data['desktop-rto-url'] || null,
// "mobile": data['mobile-rto'] || null,
// "mobileUrl": data['mobile-rto-url'] || null
// },
/* If we have assets to upload, do so here. */
if (typeof assets != 'undefined') {
// koa-body doesnt put file into an array if it's a single file
// fucking broken.
assets = Array.isArray(assets) ? assets : [assets]
var ret = {}
var failedUploads = []
// Move uploaded assets. TODO criteo
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, code: 'upload', payload: failedUploads}
}
}
fs.writeFileSync(`${cfg['localUris']['flips']}/${date}/flip.json`, prettyjson(flip))
// Append {name: .., date: ..} to schedule.json
schedule.push({name: data.name, dirname: date, rawdate: data.rawdate})
fs.writeFileSync(cfg['localUris']['flipSchedule'], prettyjson(schedule))
return ctx.body = {result: 1, code: 'success', payload: 'Flip created & Scheduled.'}
}
function upsertPage(pages, data) {
pages.push({
"name": data.name,
"promoset": data.promoset,
"mastheadtype": data.mastheadtype,
"mastheadimage": data.mastheadimage,
"strikethrough": [],
"tophtml": data.tophtml,
"bottomhtml": data.bottomhtml,
"phone": data.phone,
"expiration": data.expiration,
"crescendo": data.crescendo,
"js": data.js,
"css": data.css,
"metadata": {
"constant": data.constant === 'true',
"inprod": data.inprod === 'true',
"market": data.market
}
})
//const env = data.inprod == '' ? 'www.stg.'
//const link = `http://${env}rosettastone.com/lp/sbsr/${data.name}`
try {
fs.writeFileSync(cfg['localUris']['pages'], prettyjson(pages))
return true
} catch(e) {
return false
}
//const action = 5==5 ? 'updated' : 'created'
//return ctx.body = { result: 1, payload: `Page ${action}. See it <a href='${link}'>here</a>.` }
}
/*
* UPDATE a page.
* Do some validation then send data to upsertPage
*/
export function updatePage(ctx, next) {
//validatePageData()
const data = ctx.request.body.fields
var pages = fs.readJsonSync(cfg['localUris']['pages'], 'utf8')
pages = pages.filter(p => p.name != data.name)
}
/*
* CREATE a page.
* Do some validation then send data to upsertPage
*/
export function createPage(ctx, next) {
const data = ctx.request.body.fields
var pages = fs.readJsonSync(cfg['localUris']['pages'], 'utf8')
if (_.some(pages, ['name', data.name]) ) {
return ctx.body = { result: 0, payload: "Page exists. Try a different name." }
}
const validate = new Validate()
var result
if (validate.page(data) === true) {
if (upsertPage(pages, data)) {
result = {reuslt: 1, payload: 'Page created.'}
} else {
result = {reuslt: 0, payload: 'Could not write to pages.json.'}
}
} else {
result = {reuslt: 0, payload: 'Some invalid data was passed'}
}
return ctx.body = result
// if (data === undefined) return ctx.body = 'No data.'
// if (
// ! data.name
// || !data.promoset
// || !data.phone
// || !data.expiration
// || !data.mastheadimage
// || !data.mastheadtype
// ) {
// return ctx.body = {
// result: 0,
// payload: "Error. Missing data reached the server."
// }
// }
//const update = ctx.method === 'PUT' ? true : false
// Check if page with this name exists
//var pages = fs.readJsonSync(cfg['localUris']['pages'], 'utf8')
// If we're upating, delete the one that exists
//return ctx.body = { result: 0, payload: 'Could not write to pages.json' }
}
/*
* Creates a promoset by adding it to promos.json
*/
export function createPromoset( ctx, next) {
const data = parse(ctx.request.body)
const name = Object.keys(data)[0]
const file = fs.readJsonSync(cfg['localUris']['promos'])
// Make sure it doesn't already exist
if (Object.keys(file).includes(name)) {
return ctx.body = {
result: false,
code: 'exists',
payload: 'A promoset with this name exists.'
}
}
file[name] = data
fs.writeJson( cfg['localUris']['promos'], file)
try {
fs.writeJsonSync( cfg['localUris']['promos'], file)
return ctx.body = {
result: true,
code: 'success',
payload: 'Promoset has been added.'
}
} catch (e) {
return ctx.body = {
result: false,
code: 'file',
payload: 'Could not write to promos file.'
}
}
}
/*
* Upload mastheads.
* Two arrays are send here from the client:
* formdata("files[]"), formdata("overwrites[]").
* These are parallel arrays, to see if we should
* overwrite a file if it exists
*/
export function uploadMastheads(ctx, next) {
var files = ctx.request.body.files['files[]']
const overwrites = parse(ctx.request.body.fields['overwrites[]'])
if (typeof files === 'undefined') {
return ctx.body = {result: 0, code: 'empty', payload: 'No files received'}
}
// koa-body doesnt put file into an array if it's a single file
// fucking broken.
files = Array.isArray(files) ? files : [files]
files.forEach( (file, i) => {
let dst = `${cfg.localUris.mastheadsSymlink}/${file.name}`
var opt = {clobber: overwrites[i]}
console.log(file.name, ' overwrite: ', overwrites[i])
fs.move(file.path, dst, opt, err => {
if (err) {
return ctx.body = {result: 0, code: 'upload', payload: 'Could not upload files'}
} else {
return ctx.body = {result: 1, code: 'upload', payload: 'Files uploaded'}
}
})
})
}