import fs from 'fs-extra'
import moment from 'moment'
import prettyjson from 'json-format'
import base64 from 'base64-img'
import cfg from './config'
import _ from 'lodash'
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'))
return
}
/*
* 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.'}
}
export function updatePage(ctx, next) {
//validatePageData()
}
/*
* Creates a landing page by adding info to the
* pages.json file
*/
export function createPage(ctx, next) {
const data = ctx.request.body.fields
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 (!update && _.some(pages, ['name', data.name]) ) {
return ctx.body = { result: 0, payload: "Page exists. Try a different name." }
}
// If we're upating, delete the one that exists
if (update) {
pages = pages.filter(p => p.name != data.name)
console.log(pages)
}
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
}
})
try {
const link = 'http://' + (data.inprod == 'true' ? '' : 'www.stg.' ) + `rosettastone.com/lp/sbsr/${data.name}`
fs.writeFileSync(cfg['localUris']['pages'], prettyjson(pages))
const action = update ? 'updated' : 'created'
return ctx.body = { result: 1, payload: `Page ${action}. See it <a href='${link}'>here</a>.` }
} catch (e) {
console.log(e)
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'}
}
})
})
}