<commit_before>let Promise       = require('bluebird')
let child_process = require('child_process')

let redisRepository       = require('../Repositories/RedisRepository')
let projectRepoisitory    = require('../Repositories/ProjectRepository')
let projectTypeRepository = require('../Repositories/ProjectTypeRepository')
let dataRepository        = require('../Repositories/DataRepository')

let simulationService = require('./SimulationService')
let fileService       = require('./FileService')
let errorMsgService   = require('./ErrorMsgService')

let compare = function (a, b) {
  return a.localeCompare(b)
}

let simulation = function (id, path, data, method) {
  simulationService.makeFile(path).then(() => {
    return simulationService.simulation(path, data)
  }).then(() => {
    handleSimulationData(id, path, method)
  }).catch(error => {
    //console.log(error)
  })
}

let handleSimulationData = function (id, path, method) {
  let configPath = '../.' + path + 'config'
  let config = require(configPath).config.simulationOutPutFileName

  let filesName  = ['baseSpin', 'bonusSpin', 'overallSpin', 'survivalRate']
  let tablesName = ['basegame', 'freegame', 'overall', 'survivalrate']

  for (let index in filesName) {
    if (config[filesName[index]]) {
      if (filesName[index] !== 'survivalRate') {
        dataRepository.uploadData(id, tablesName[index], path + 'result/' + config[filesName[index]] + csv, 'netWin' + ((filesName[index] === 'overallSpin') ? ',triger' : ''))
      } else {
        dataRepository.uploadData(id, tablesName[index], path + 'result/' + config[filesName[index]] + csv, 'id,hand,isSurvival')
      }
    }
  }
  for (let othersInfo of config.othersInfo) {
    let data = {
      name: othersInfo.infoName,
      data: path + 'result/' + othersInfo.fileName
    }
    if (method === 'insert') {
      dataRepository.insertData(id, 'others', data)
    } else if (method === 'update') {
      dataRepository.updateData(id, 'others', data)
    }
  }
}

// get all project
let getAllProject = function (token) {
  return new Promise((resolve, reject) => {
    // check if the token is valid
    redisRepository.getAccountId(token).then(accountId => {
      return projectRepoisitory.getAllProject(accountId)
    }).then(allProject => {
      resolve(allProject)
    }).catch(error => {
      if (error === 'token expired') {
        reject(errorMsgService.tokenExpired)
      } else {
        reject(errorMsgService.serverError)
      }
    })
  })
}

//get spectify project
let getProjectById = function (token, id) {
  return new Promise((resolve, reject) => {
    let data = {}
    // check if the token is valid
    redisRepository.getAccountId(token).then(accountId => {
      return projectRepoisitory.getProjectById(id)
    }).then(projectInfo => {
      resolve(projectInfo)
    }).catch(error => {
      if (error === 'token expired') {
        reject(errorMsgService.tokenExpired)
      } else if (error === 'file error') {
        reject(errorMsgService.fsError)
      } else {
        reject(errorMsgService.serverError)
      }
    })
  })
}

//get all type of project
let getAllProjectType = function (token) {
  return new Promise((resolve, reject) => {
    // check if the token is valid
    redisRepository.getAccountId(token).then(accountId => {
      return projectTypeRepository.getAllType()
    }).then(type => {
      resolve(type)
    }).catch(error => {
      if (error === 'token expired') {
        reject(errorMsgService.tokenExpired)
      } else {
        reject(errorMsgService.serverError)
      }
    })
  })
}

// get spectify type of project
let getProjectTypeById = function (token, id) {
  return new Promise((resolve, reject) => {
    // check if the token is valid
    redisRepository.getAccountId(token).then(accountId => {
      return projectTypeRepository.getTypeById(id)
    }).then(type => {
      resolve(type)
    }).catch(error => {
      if (error === 'token expired') {
        reject(errorMsgService.tokenExpired)
      } else if (error === 'Project type error') {
        reject(errorMsgService.noProjectType)
      } else {
        reject(errorMsgService.serverError)
      }
    })
  })
}

let dataSet  = ['name', 'block', 'thread', 'runTime', 'reels', 'rows', 'betCost']
let fileName = ['symbol', 'stops', 'payTable', 'attr', 'pattern']

let csv    = '.csv'
let folder = './userProject/'

// create a new project
let create = function (token, body) {
  let userId
  let data
  let id
  let path
  let fields
  let files
  return new Promise((resolve, reject) => {
    // check if the token is valid
    redisRepository.getAccountId(token).then(accountId => {
      userId = accountId
      data = {
        userId: userId
      }

      return fileService.processFormData(body)
    }).then(result => {
      fields = result.fields
      files  = result.files

      for (let i of dataSet) {
        if (fields[i] === undefined) {
          reject(errorMsgService.emptyInput)
          return
        } else {
          data[i] = fields[i]
        }
      }

      for (let i of fileName) {
        data[i] = './'
      }

      data.config    = './'
      data.gameLogic = './'

      return projectRepoisitory.createProject(data)
    }).then(() => {
      return projectRepoisitory.getNewestProject(userId)
    }).then(projectInfo => {
      id = projectInfo.id
      path = folder + userId + '/' + id + '/'
      return fileService.createFolder(path)
    }).then(() => {
      return fileService.createFolder(path + 'result')
    }).then(() => {
      let promise = []
      for (let i of fileName) {
        if (files[i] !== undefined) {
          if (!Array.isArray(files[i])) {
            data[i] = path + i + csv
            promise.push(fileService.moveFile(files[i].path, data[i]))
            if (i === 'payTable' && Array.isArray(files['stops'])) {
              data[i] = (data[i] + ',').repeat(files['stops'].length)
              data[i] = data[i].slice(0, -1)
            }
          } else {
            data[i] = ''
            files[i].sort(compare)
            for (let j in files[i]) {
              let filePath = path + i + j + csv
              data[i] += filePath + ','
              promise.push(fileService.moveFile(files[i][j].path, filePath))
            }
            data[i] = data[i].slice(0, -1)
          }
        }
      }

      if (files.config !== undefined) {
        data.config = path + 'config.js'
        promise.push(fileService.moveFile(files.config.path, data.config))
      }
      if (files.gameLogic !== undefined) {
        data.gameLogic = path + 'gameLogic.cu'
        promise.push(fileService.moveFile(files.gameLogic.path, data.gameLogic))
      }

      let inputFile = ',' + (files['symbol'] !== undefined ? data['symbol'] : '') + '\n'
      for (let i of ['reels', 'rows', 'betCost']) {
        inputFile += ',' + data[i] + '\n'
      }
      for (let i of ['stops', 'payTable', 'attr', 'pattern']) {
        if (files[i] !== undefined) {
          inputFile += ',' + data[i] + '\n'
        }
      }

      promise.push(fileService.createFile(path + 'input.csv', inputFile))
      promise.push(projectRepoisitory.updateProject(id, data))

      return Promise.all(promise)
    }).then(() => {
      simulation(id, path, data, 'insert')
      resolve()
    }).catch(error => {
      console.log(error)
      if (error === 'token expired') {
        reject(errorMsgService.tokenExpired)
      } else if (error === 'Project type error') {
        reject(errorMsgService.noProjectType)
      } else if (error === 'file error') {
        reject(errorMsgService.fsError)
      } else {
        reject(errorMsgService.serverError)
      }
    })
  })
}

// update project
let update = function (token, id, body) {
  let data
  let userId
  let path
  let fields
  let files
  let oldData
  return new Promise((resolve, reject) => {
    // check if the token is valid
    redisRepository.getAccountId(token).then(accountId => {
      userId = accountId
      path   = folder + userId + '/' + id + '/'

      data = {
        userId: userId
      }
      return projectRepoisitory.getProjectById(id)
    }).then(data => {
      oldData = data
      return fileService.processFormData(body)
    }).then(result => {
      fields = result.fields
      files = result.files

      for (let i of dataSet) {
        if (fields[i] !== undefined) {
          data[i] = fields[i]
        }
      }

      let promise = []

      for (let i of fileName) {
        if (files[i] !== undefined) {
          if (!Array.isArray(files[i])) {
            data[i] = path + i + csv
            promise.push(fileService.moveFile(files[i].path, data[i]))
            if (i === 'payTable' && Array.isArray(files['stops'])) {
              data[i] = (data[i] + ',').repeat(files['stops'].length)
              data[i] = data[i].slice(0, -1)
            }
          } else {
            data[i] = ''
            files[i].sort(compare)
            for (let j in files[i]) {
              let filePath = path + i + j + csv
              data[i] += filePath + ','
              promise.push(fileService.moveFile(files[i][j].path, filePath))
            }
            data[i] = data[i].slice(0, -1)
          }

        }
      }

      if (files.config !== undefined) {
        data.config = path + 'config.js'
        promise.push(fileService.moveFile(files.config.path, data.config))
      }
      if (files.gameLogic !== undefined) {
        data.gameLogic = path + 'gameLogic.cu'
        promise.push(fileService.moveFile(files.gameLogic.path, data.gameLogic))
      }

      let inputFile = ''
      for (let i of ['symbol', 'reels', 'rows', 'betCost', 'stops', 'payTable', 'attr', 'pattern']) {
        inputFile += ',' + (data[i] !== undefined ? data[i] : oldData[i]) + '\n'
      }

      promise.push(fileService.createFile(path + 'input.csv', inputFile))
      promise.push(projectRepoisitory.updateProject(id, data))

      return Promise.all(promise)
    }).then(() => {
      simulation(id, path, data, 'update')
      resolve()
    }).catch(error => {
      console.log(error)
      if (error === 'token expired') {
        reject(errorMsgService.tokenExpired)
      } else if (error === 'file error') {
        reject(errorMsgService.fsError)
      } else {
        reject(errorMsgService.serverError)
      }
    })
  })
}

//delete project
let deleteProject = function (token, id) {
  let userId
  return new Promise((resolve, reject) => {
    // check if the token is valid
    redisRepository.getAccountId(token).then(accountId => {
      userId = accountId
      return projectRepoisitory.deleteProject(id)
    }).then(() => {
      return fileService.deleteFolder(folder + userId + '/' + id)
    }).then(() => {
      resolve()
    }).catch(error => {
      if (error === 'token expired') {
        reject(errorMsgService.tokenExpired)
      } else if (error === 'file error') {
        reject(errorMsgService.fsError)
      } else {
        reject(errorMsgService.serverError)
      }
    })
  })
}

let getConfig = function (token, id) {
  let userId
  return new Promise((resolve, reject) => {
    redisRepository.getAccountId(token).then(accountId => {
      let path = '../../userProject/' + accountId + '/' + id + '/config'
      let config = require(path)
      resolve(config.config)
    }).catch(error => {
      if (error === 'token expired') {
        reject(errorMsgService.tokenExpired)
      } else {
        reject(errorMsgService.serverError)
      }
    })
  })
}

module.exports = {
  getAllProject:      getAllProject,
  getProjectById:     getProjectById,
  getAllProjectType:  getAllProjectType,
  getProjectTypeById: getProjectTypeById,
  create:             create,
  update:             update,
  deleteProject:      deleteProject,
  getConfig:          getConfig
}<commit_msg>fix some bugs<commit_after>let Promise       = require('bluebird')
let child_process = require('child_process')

let redisRepository       = require('../Repositories/RedisRepository')
let projectRepoisitory    = require('../Repositories/ProjectRepository')
let projectTypeRepository = require('../Repositories/ProjectTypeRepository')
let dataRepository        = require('../Repositories/DataRepository')

let simulationService = require('./SimulationService')
let fileService       = require('./FileService')
let errorMsgService   = require('./ErrorMsgService')

let compare = function (a, b) {
  return a.name.localeCompare(b.name)
}

let simulation = function (id, path, data, method) {
  simulationService.makeFile(path).then(() => {
    return simulationService.simulation(path, data)
  }).then(() => {
    handleSimulationData(id, path, method)
  }).catch(error => {
    //console.log(error)
  })
}

let handleSimulationData = function (id, path, method) {
  let configPath = '../.' + path + 'config'
  let config = require(configPath).config.simulationOutPutFileName

  let filesName  = ['baseSpin', 'bonusSpin', 'overallSpin', 'survivalRate']
  let tablesName = ['basegame', 'freegame', 'overall', 'survivalrate']

  for (let index in filesName) {
    if (config[filesName[index]]) {
      if (filesName[index] !== 'survivalRate') {
        dataRepository.uploadData(id, tablesName[index], path + 'result/' + config[filesName[index]] + csv, 'netWin' + ((filesName[index] === 'overallSpin') ? ',triger' : ''))
      } else {
        dataRepository.uploadData(id, tablesName[index], path + 'result/' + config[filesName[index]] + csv, 'id,hand,isSurvival')
      }
    }
  }
  for (let othersInfo of config.othersInfo) {
    let data = {
      name: othersInfo.infoName,
      data: path + 'result/' + othersInfo.fileName
    }
    if (method === 'insert') {
      dataRepository.insertData(id, 'others', data)
    } else if (method === 'update') {
      dataRepository.updateData(id, 'others', data)
    }
  }
}

// get all project
let getAllProject = function (token) {
  return new Promise((resolve, reject) => {
    // check if the token is valid
    redisRepository.getAccountId(token).then(accountId => {
      return projectRepoisitory.getAllProject(accountId)
    }).then(allProject => {
      resolve(allProject)
    }).catch(error => {
      if (error === 'token expired') {
        reject(errorMsgService.tokenExpired)
      } else {
        reject(errorMsgService.serverError)
      }
    })
  })
}

//get spectify project
let getProjectById = function (token, id) {
  return new Promise((resolve, reject) => {
    let data = {}
    // check if the token is valid
    redisRepository.getAccountId(token).then(accountId => {
      return projectRepoisitory.getProjectById(id)
    }).then(projectInfo => {
      resolve(projectInfo)
    }).catch(error => {
      if (error === 'token expired') {
        reject(errorMsgService.tokenExpired)
      } else if (error === 'file error') {
        reject(errorMsgService.fsError)
      } else {
        reject(errorMsgService.serverError)
      }
    })
  })
}

//get all type of project
let getAllProjectType = function (token) {
  return new Promise((resolve, reject) => {
    // check if the token is valid
    redisRepository.getAccountId(token).then(accountId => {
      return projectTypeRepository.getAllType()
    }).then(type => {
      resolve(type)
    }).catch(error => {
      if (error === 'token expired') {
        reject(errorMsgService.tokenExpired)
      } else {
        reject(errorMsgService.serverError)
      }
    })
  })
}

// get spectify type of project
let getProjectTypeById = function (token, id) {
  return new Promise((resolve, reject) => {
    // check if the token is valid
    redisRepository.getAccountId(token).then(accountId => {
      return projectTypeRepository.getTypeById(id)
    }).then(type => {
      resolve(type)
    }).catch(error => {
      if (error === 'token expired') {
        reject(errorMsgService.tokenExpired)
      } else if (error === 'Project type error') {
        reject(errorMsgService.noProjectType)
      } else {
        reject(errorMsgService.serverError)
      }
    })
  })
}

let dataSet  = ['name', 'block', 'thread', 'runTime', 'reels', 'rows', 'betCost']
let fileName = ['symbol', 'stops', 'payTable', 'attr', 'pattern']

let csv    = '.csv'
let folder = './userProject/'

// create a new project
let create = function (token, body) {
  let userId
  let data
  let id
  let path
  let fields
  let files
  return new Promise((resolve, reject) => {
    // check if the token is valid
    redisRepository.getAccountId(token).then(accountId => {
      userId = accountId
      data = {
        userId: userId
      }

      return fileService.processFormData(body)
    }).then(result => {
      fields = result.fields
      files  = result.files

      for (let i of dataSet) {
        if (fields[i] === undefined) {
          reject(errorMsgService.emptyInput)
          return
        } else {
          data[i] = fields[i]
        }
      }

      for (let i of fileName) {
        data[i] = './'
      }

      data.config    = './'
      data.gameLogic = './'

      return projectRepoisitory.createProject(data)
    }).then(() => {
      return projectRepoisitory.getNewestProject(userId)
    }).then(projectInfo => {
      id = projectInfo.id
      path = folder + userId + '/' + id + '/'
      return fileService.createFolder(path)
    }).then(() => {
      return fileService.createFolder(path + 'result')
    }).then(() => {
      let promise = []
      for (let i of fileName) {
        if (files[i] !== undefined) {
          if (!Array.isArray(files[i])) {
            data[i] = path + i + csv
            promise.push(fileService.moveFile(files[i].path, data[i]))
            if (i === 'payTable' && Array.isArray(files['stops'])) {
              data[i] = (data[i] + ',').repeat(files['stops'].length)
              data[i] = data[i].slice(0, -1)
            }
          } else {
            data[i] = ''
            files[i].sort(compare)
            for (let j in files[i]) {
              let filePath = path + i + j + csv
              data[i] += filePath + ','
              promise.push(fileService.moveFile(files[i][j].path, filePath))
            }
            data[i] = data[i].slice(0, -1)
          }
        }
      }

      if (files.config !== undefined) {
        data.config = path + 'config.js'
        promise.push(fileService.moveFile(files.config.path, data.config))
      }
      if (files.gameLogic !== undefined) {
        data.gameLogic = path + 'gameLogic.cu'
        promise.push(fileService.moveFile(files.gameLogic.path, data.gameLogic))
      }

      let inputFile = ',' + (files['symbol'] !== undefined ? data['symbol'] : '') + '\n'
      for (let i of ['reels', 'rows', 'betCost']) {
        inputFile += ',' + data[i] + '\n'
      }
      for (let i of ['stops', 'payTable', 'attr', 'pattern']) {
        if (files[i] !== undefined) {
          inputFile += ',' + data[i] + '\n'
        }
      }

      promise.push(fileService.createFile(path + 'input.csv', inputFile))
      promise.push(projectRepoisitory.updateProject(id, data))

      return Promise.all(promise)
    }).then(() => {
      simulation(id, path, data, 'insert')
      resolve()
    }).catch(error => {
      console.log(error)
      if (error === 'token expired') {
        reject(errorMsgService.tokenExpired)
      } else if (error === 'Project type error') {
        reject(errorMsgService.noProjectType)
      } else if (error === 'file error') {
        reject(errorMsgService.fsError)
      } else {
        reject(errorMsgService.serverError)
      }
    })
  })
}

// update project
let update = function (token, id, body) {
  let data
  let userId
  let path
  let fields
  let files
  let oldData
  return new Promise((resolve, reject) => {
    // check if the token is valid
    redisRepository.getAccountId(token).then(accountId => {
      userId = accountId
      path   = folder + userId + '/' + id + '/'

      data = {
        userId: userId
      }
      return projectRepoisitory.getProjectById(id)
    }).then(data => {
      oldData = data
      return fileService.processFormData(body)
    }).then(result => {
      fields = result.fields
      files = result.files

      for (let i of dataSet) {
        if (fields[i] !== undefined) {
          data[i] = fields[i]
        }
      }

      let promise = []

      for (let i of fileName) {
        if (files[i] !== undefined) {
          if (!Array.isArray(files[i])) {
            data[i] = path + i + csv
            promise.push(fileService.moveFile(files[i].path, data[i]))
            if (i === 'payTable' && Array.isArray(files['stops'])) {
              data[i] = (data[i] + ',').repeat(files['stops'].length)
              data[i] = data[i].slice(0, -1)
            }
          } else {
            data[i] = ''
            files[i].sort(compare)
            for (let j in files[i]) {
              let filePath = path + i + j + csv
              data[i] += filePath + ','
              promise.push(fileService.moveFile(files[i][j].path, filePath))
            }
            data[i] = data[i].slice(0, -1)
          }

        }
      }

      if (files.config !== undefined) {
        data.config = path + 'config.js'
        promise.push(fileService.moveFile(files.config.path, data.config))
      }
      if (files.gameLogic !== undefined) {
        data.gameLogic = path + 'gameLogic.cu'
        promise.push(fileService.moveFile(files.gameLogic.path, data.gameLogic))
      }

      let inputFile = ''
      for (let i of ['symbol', 'reels', 'rows', 'betCost', 'stops', 'payTable', 'attr', 'pattern']) {
        inputFile += ',' + (data[i] !== undefined ? data[i] : oldData[i]) + '\n'
      }

      promise.push(fileService.createFile(path + 'input.csv', inputFile))
      promise.push(projectRepoisitory.updateProject(id, data))

      return Promise.all(promise)
    }).then(() => {
      simulation(id, path, data, 'update')
      resolve()
    }).catch(error => {
      console.log(error)
      if (error === 'token expired') {
        reject(errorMsgService.tokenExpired)
      } else if (error === 'file error') {
        reject(errorMsgService.fsError)
      } else {
        reject(errorMsgService.serverError)
      }
    })
  })
}

//delete project
let deleteProject = function (token, id) {
  let userId
  return new Promise((resolve, reject) => {
    // check if the token is valid
    redisRepository.getAccountId(token).then(accountId => {
      userId = accountId
      return projectRepoisitory.deleteProject(id)
    }).then(() => {
      return fileService.deleteFolder(folder + userId + '/' + id)
    }).then(() => {
      resolve()
    }).catch(error => {
      if (error === 'token expired') {
        reject(errorMsgService.tokenExpired)
      } else if (error === 'file error') {
        reject(errorMsgService.fsError)
      } else {
        reject(errorMsgService.serverError)
      }
    })
  })
}

let getConfig = function (token, id) {
  let userId
  return new Promise((resolve, reject) => {
    redisRepository.getAccountId(token).then(accountId => {
      let path = '../../userProject/' + accountId + '/' + id + '/config'
      let config = require(path)
      resolve(config.config)
    }).catch(error => {
      if (error === 'token expired') {
        reject(errorMsgService.tokenExpired)
      } else {
        reject(errorMsgService.serverError)
      }
    })
  })
}

module.exports = {
  getAllProject:      getAllProject,
  getProjectById:     getProjectById,
  getAllProjectType:  getAllProjectType,
  getProjectTypeById: getProjectTypeById,
  create:             create,
  update:             update,
  deleteProject:      deleteProject,
  getConfig:          getConfig
}<|endoftext|>


<commit_before>'use strict';
var config = require('./config');
var RippleAPI = require('../api');
var logger = require('./logger').logger;

var options = {
  servers: config.get('rippled_servers'),
  max_fee: parseFloat(config.get('max_transaction_fee')),
  database_path: config.get('NODE_ENV') === 'test'
    ? ':memory:' : config.get('db_path'),
  logger: logger,
  mock: config.get('NODE_ENV') === 'test',
  trace: config.get('debug')
};

module.exports = new RippleAPI(options);
<commit_msg>[FIX] Tests can run without a config.json<commit_after>'use strict';
var config = require('./config');
var RippleAPI = require('../api');
var logger = require('./logger').logger;

var options = {
  servers: config.get('rippled_servers'),
  max_fee: parseFloat(config.get('max_transaction_fee')),
  database_path: config.get('NODE_ENV') === 'test'
    ? ':memory:' : config.get('db_path'),
  logger: logger,
  mock: config.get('NODE_ENV') === 'test',
  trace: config.get('debug') || false
};

module.exports = new RippleAPI(options);
<|endoftext|>


<commit_before>(function () {
    'use strict';

    angular
        .module('atlas')
        .factory('reducer', reducerFactory);

    reducerFactory.$inject = [
        'urlReducers',
        'detailReducers',
        'homeReducers',
        'layerReducers',
        'mapReducers',
        'pageReducers',
        'searchReducers',
        'straatbeeldReducers',
        'dataSelectionReducers',
        'printReducers'
    ];

    function reducerFactory (urlReducers,
        detailReducers,
        homeReducers,
                             layerReducers,
        mapReducers,
        pageReducers,
        searchReducers,
        straatbeeldReducers,
        dataSelectionReducers,
        printReducers) {

        return function (oldState, action) {
            var actions = angular.merge(
                urlReducers,
                detailReducers,
                homeReducers,
                layerReducers,
                mapReducers,
                pageReducers,
                searchReducers,
                straatbeeldReducers,
                dataSelectionReducers,
                printReducers
            );

            if (angular.isDefined(action) && angular.isDefined(actions[action.type])) {
                return actions[action.type](oldState, action.payload);
            } else {
                return oldState;
            }
        };
    }
})();<commit_msg>Indenting fixed<commit_after>(function () {
    'use strict';

    angular
        .module('atlas')
        .factory('reducer', reducerFactory);

    reducerFactory.$inject = [
        'urlReducers',
        'detailReducers',
        'homeReducers',
        'layerReducers',
        'mapReducers',
        'pageReducers',
        'searchReducers',
        'straatbeeldReducers',
        'dataSelectionReducers',
        'printReducers'
    ];

    function reducerFactory (urlReducers,
        detailReducers,
        homeReducers,
        layerReducers,
        mapReducers,
        pageReducers,
        searchReducers,
        straatbeeldReducers,
        dataSelectionReducers,
        printReducers) {

        return function (oldState, action) {
            var actions = angular.merge(
                urlReducers,
                detailReducers,
                homeReducers,
                layerReducers,
                mapReducers,
                pageReducers,
                searchReducers,
                straatbeeldReducers,
                dataSelectionReducers,
                printReducers
            );

            if (angular.isDefined(action) && angular.isDefined(actions[action.type])) {
                return actions[action.type](oldState, action.payload);
            } else {
                return oldState;
            }
        };
    }
})();<|endoftext|>


<commit_before>Jsonix.Model.Adapter = Jsonix.Class({
	initialize : function() {
	},
	unmarshal: function(typeInfo, context, input, scope)
	{
		return typeInfo.unmarshal(context, input, scope);
	},
	marshal: function(context, value, output, typeInfo)
	{
		typeInfo.marshal(context, value, output);
	},
	CLASS_NAME : "Jsonix.Model.Adapter"
});
Jsonix.Model.Adapter.INSTANCE = new Jsonix.Model.Adapter();
Jsonix.Model.Adapter.getAdapter = function (elementInfo)
{
	Jsonix.Util.Ensure.ensureObject(elementInfo);
	Jsonix.Util.Ensure.ensureObject(elementInfo.typeInfo);
	return Jsonix.Util.Type.exists(elementInfo.adapter) ? elementInfo.adapter : Jsonix.Model.Adapter.INSTANCE;
};<commit_msg>value, context, output, scope<commit_after>Jsonix.Model.Adapter = Jsonix.Class({
	initialize : function() {
	},
	unmarshal: function(typeInfo, context, input, scope)
	{
		return typeInfo.unmarshal(context, input, scope);
	},
	marshal: function(typeInfo, value, context, output, scope)
	{
		typeInfo.marshal(value, context, output, scope);
	},
	CLASS_NAME : "Jsonix.Model.Adapter"
});
Jsonix.Model.Adapter.INSTANCE = new Jsonix.Model.Adapter();
Jsonix.Model.Adapter.getAdapter = function (elementInfo)
{
	Jsonix.Util.Ensure.ensureObject(elementInfo);
	Jsonix.Util.Ensure.ensureObject(elementInfo.typeInfo);
	return Jsonix.Util.Type.exists(elementInfo.adapter) ? elementInfo.adapter : Jsonix.Model.Adapter.INSTANCE;
};<|endoftext|>


<commit_before>"use strict";

import Dispatcher     from "../dispatcher";
import Constants      from "../constants";
import StoreCommon    from "./store_common";
import assign         from "object-assign";

let _user = {};

// log the user in
function login(email, password){
  return true;
}

// Register
function register(user){
  return true;
}

// Extend User Store with EventEmitter to add eventing capabilities
let UserStore = assign({}, StoreCommon, {

  // Return current user
  current(){
    return _user;
  },

  loggedIn(){
    return _user.email !== undefined;
  },

  token(){
    return _user.token;
  }

});

// Register callback with Dispatcher
Dispatcher.register(function(payload) {
  let action = payload.action;

  switch(action){

    // Respond to LOGIN action
    case Constants.LOGIN:
      login(payload.email, payload.password);
      break;

    // Respond to REGISTER action
    case Constants.REGISTER:
      register(payload.user);
      break;

    default:
      return true;
  }

  // If action was responded to, emit change event
  UserStore.emitChange();

  return true;

});

export default UserStore;

<commit_msg>Use var instead of let for now<commit_after>"use strict";

import Dispatcher     from "../dispatcher";
import Constants      from "../constants";
import StoreCommon    from "./store_common";
import assign         from "object-assign";

var _user = {};

// log the user in
function login(email, password){
  return true;
}

// Register
function register(user){
  return true;
}

// Extend User Store with EventEmitter to add eventing capabilities
var UserStore = assign({}, StoreCommon, {

  // Return current user
  current(){
    return _user;
  },

  loggedIn(){
    return _user.email !== undefined;
  },

  token(){
    return _user.token;
  }

});

// Register callback with Dispatcher
Dispatcher.register(function(payload) {
  var action = payload.action;

  switch(action){

    // Respond to LOGIN action
    case Constants.LOGIN:
      login(payload.email, payload.password);
      break;

    // Respond to REGISTER action
    case Constants.REGISTER:
      register(payload.user);
      break;

    default:
      return true;
  }

  // If action was responded to, emit change event
  UserStore.emitChange();

  return true;

});

export default UserStore;

<|endoftext|>


<commit_before>var fs = require('fs');
var ursa = require('ursa');
var dgram = require('dgram');
var tls = require('tls');
var net = require('net');
var mongoose = require('mongoose');

mongoose.connect("mongodb://localhost/raspi");

json_scheme = {
	name : String,
	id : String
};

var raschi_data = mongoose.model("raschi_data", new mongoose.Schema(json_scheme) );

/**
 * 公開鍵と秘密鍵と証明書ファイルへのパスを指定します。
 *

 *
{@link children_client~create_tlsclient}
 *
{@link children_client~register_client_with_mongodb}
 *
{@link children_client~register_to_db}
 *
{@link children_client~start_udp_server}
 *
{@link children_client~send_to_mpserver}
 *
{@link children_client~connect_to_mpserver}
 *
{@link children_client~listen_tcp_server}
 *
{@link children_client~connect_to_children}
 *
{@link children_client~send_command_to_children}
 *
{@link children_client.message_parse}
 *
{@link children_client.start}
 *

 * @constructor
 * @classdesc 子機との通信を管理するクラス
 * @param {string} public_key_path - 公開鍵へのパス
 * @param {string} private_key_path - 秘密鍵へのパス
 * @param {string} crt_file_path - 証明書へのパス
 */
var children_client = function(public_key_path,private_key_path,crt_file_path){
	var th = this;

	/* -------------------------- SSL Module ----------------------*/
	//ssl module class

	/**
	 * 秘密鍵と公開鍵へのパスを指定します。
	 *

	 *
 {@link ssl_module.decrypt}
	 *
 {@link ssl_module.encrypt}
	 *

	 * @constructor
	 * @classdesc UDPの通信の際に送られてきたデータを復号化するクラスです。
	 * @param {string} pubpath - 公開鍵へのパス
	 * @param {string} pripath - 秘密鍵へのパス
	 */
	var ssl_module = function(pubpath,pripath){
		/**
		 * 復号化に利用する秘密鍵オブジェクト
		 */
		var key = ursa.createPrivateKey(fs.readFileSync(pripath));

		/**
		 * 暗号化に利用する公開鍵オブジェクト
		 */
		var crt = ursa.createPublicKey(fs.readFileSync(pubpath));

		/**
		 * メッセージを復号化する
		 * @param {string} msg - 復号化する文字列
		 * @return {string} 復号化した文字列
		 */
		this.decrypt = function(msg){
			return key.decrypt(msg,'base64','utf8');
		};

		/**
		 * メッセージを暗号化する
		 * @param {string} msg - 暗号化する文字列
		 * @return {string} 暗号化した文字列
		 */
		this.encrypt = function(msg){
			return crt.encrypt(msg,'utf8','base64');
		};
	};

	/**
	 * {@link ssl_module} のインスタンス
	 * @type {ssl_module}
	 */
	var sslm = new ssl_module(public_key_path,private_key_path);

	//---------------------------------------------------------------

	/*-------------------------- TLS CLient -----------------------*/
	//tls_client class
	//
	/**
	 * 子機に接続しているソケットとその子機のguidを指定します。
	 *

	 *
{@link tls_client.write}
	 *

	 * @constructor
	 * @classdesc 子機との通信をするTLSのクライアントのクラス
	 * @param {tls.TLSSocket} socket - [tls.TLSSocket]{@link http://u111u.info/mnHq} のインスタンス
	 * @param {string} guid - 接続している子機のguid
	 */
	var tls_client = function(socket,guid){
		/**
		 * tlsのソケット
		 */
		this.socket = socket;
		/**
		 * 接続状態の確認
		 */

		var connection = true;
		/**
		 * 子機のGUID
		 * @type {string}
		 */
		this.guid = guid;
		/**
		 * メッセージを送信します
		 * @param {string} str - 送信する文字列
		 */
		this.write = function(str){
			if(connection){
				try{
					this.socket.write(str,'utf-8');
				}catch(ex){
					console.log("[CHILDREN CLIENT] [TLS CLIENT] Message Write Error: " + ex.stack);
				}
			}
		};

		/**
		 * ソケットでエラーが発生した場合の関数
		 * @method
		 * @listens error
		 */
		this.socket.on("error",function(ex){
			console.log("[CHILDREN CLIENT] [TLS CLINET]  " + ex.stack);
		});

		/**
		 * ソケットがオープンした時
		 */
		var socket_this = this;
		this.socket.on("connect",function(ex){
			console.log("[CHILDREN CLIENT] [TLS CLINET]  Open Connection " + socket_this.guid);
		});

		/**
		 * ソケットがクローズした場合
		 */
		this.socket.on("close",function(ex){
			console.log("[CHILDREN CLIENT] [TLS CLINET] Close Connection to " + socket_this.guid);
			connection = false;
		});

		/**
		 * ソケットからデータが来た場合の関数
		 */
		this.socket.on('data',function(str){
			console.log("[CHILDREN CLIENT] [TLS CLIENT] Message recived:" + str);
			th.message_parse(str);
		});
	};

	/**
	 * tls_clientの設定
	 */
	var option = {
		ca: fs.readFileSync(crt_file_path),
		rejectUnauthorized:false
	};

	/**
	 * {@link tls_client}のインスタンス
	 */
	var tls_clients = {};
	/**
	 * tls_clientのguidの配列
	 * @type {Array.string}
	 */
	var client_list = [];
	/**
	 * 子機と接続するtls_clientを作成します
	 *
	 * @param {string} guid - 子機のguid
	 * @param {dgram.rinfo} rinfo - 子機のアドレス情報 {@link http://u111u.info/momf}
	 */
	var create_tlsclient = function(guid,rinfo){
		if(client_list.indexOf(guid) == -1){
			var socket = tls.connect(15000,rinfo.address,option);
			//TODO
			//子機に命令を送るときにtls_clientsのguidから判別するのではなくいい感じにtls_client.guidから判別したい
			tls_clients[guid] = new tls_client(socket,guid);
		}else{
			delete client_list[client_list.indexOf(guid)];
			var socket = tls.connect(15000,rinfo.address,option);
			//TODO
			//子機に命令を送るときにtls_clientsのguidから判別するのではなくいい感じにtls_client.guidから判別したい
			tls_clients[guid] = new tls_client(socket,guid);
		}
	};
	//-------------------------------------------------------------------

	/*------------------------- Mongoose -------------------------------*/

	/**
	 * 子機情報をmongodbに保存
	 * @param {Object} obj - 子機情報のjson
	 */
	var register_client_with_mongodb = function(obj){
		var item = new raschi_data(
				{name:obj["name"],id:obj["guid"]}
				);
		item.save(function(e){console.log("add:"+JSON.stringify(item));});
	};

	/**
	 * 子機情報をデータベースに保存するかどうかを判定する
	 * @param {Object} obj - 子機情報のjson
	 */
	var register_to_db = function(obj){
		raschi_data.find({},function(err,docs){
			var id = -1;
			for(var i=0,size =docs.length;i < size; ++i){
				if(docs[i].id == obj["guid"]) id = docs[i].id;
			}
			console.log(id);
			if(id == -1){
				register_client_with_mongodb(obj);
			}
		});
	};

	//--------------------------------------------------------------------

	/* ------------------------- UDP Server -----------------------------*/

	/**
	 * udpのサーバーのポート番号
	 * @type {num}
	 */
	var udp_server_port = 8000;
	/**
	 * udpのサーバーのインスタンス
	 */
	var udp_server = dgram.createSocket("udp4");

	/**
	 * udp_serverでエラーが起きた際のプログラム
	 */
	udp_server.on("error",function(err){
		console.log("[CHILDREN CLIENT] [UDP SERVER] Server error: " + err.stack);
	});

	/**
	 * updサーバーでメッセージを受け取った時のプログラム
	 */
	udp_server.on("message",function(msg,rinfo){
		console.log("[CHILDREN CLIENT] [UDP SERVER] message comming:");
		connect_to_children(msg,rinfo);
	});

	/**
	 * UDPサーバーをスタートさせます
	 */
	var start_udp_server = function(){
		udp_server.bind(8000,"0.0.0.0");
		console.log("[CHILDREN CLIENT] [UDP SERVER] OPEN UDP SERVER");
	};

	//--------------------------------------------------------------------

	/* ------------------ TCP Server And Client ----------------*/
	// Client

	/**
	 * メッセージサーバーのポート番号
	 * @type {num}
	 */
	var tcp_client_port = 12000;
	/**
	 * メッセージパーサーサーバーに接続するクライアント
	 */
	var tcp_client = new net.Socket({readable:true,writable:true});

	/**
	 * メッセージパーサーに接続するのが失敗した時
	 */
	tcp_client.on('error',function(error){
		tcp_client.connect({port:th.tcp_client_port});
	});

	/**
	 * メッセージサーバーにメッセージを送信するプログラム
	 *
	 * @param {string} str - 送信する文字列
	 */
	var send_to_mpserver = function(str){
		return tcp_client.write(str);
	};

	/**
	 * メッセージパーサーサーバーに接続します
	 */
	var connect_to_mpserver = function(){
		tcp_client.connect({port:tcp_client_port},function(){
			console.log("[CHILDREN CLIENT] [TCP CLIENT] CONNECT TO MPSERVER");
		});
	};

	// Server

	/**
	 * メッセージパーサからのクライアントを受け付けるサーバーのポート番号
	 * @type {num}
	 */
	var tcp_server_port = 20000;

	/**
	 * メッセージパーサー用TCPサーバーのインスタンス
	 */
	var tcp_server = new net.Server(function(socket){
		console.log("[CHILDREN CLIENT] [TCP SERVER] CONNECT CLIENT");
		connect_to_mpserver();
		socket.on('error',function(){
			console.log("[CHILDREN CLIENT] [TCP SERVER] SOCKET ERROR");
		});
		socket.on('data',function(str){
			send_command_to_children(str);
		});
	});

	/**
	 * メッセージサーバー用サーバーがエラーを起こした時
	 */
	tcp_server.on('error',function(){
		console.log("[CHILDREN CLIENT] [TCP SERVER] SERVER ERROR");
	});
	/**
	 * メッセージサーバー用TCPサーバーの待機を始める
	 */
	var listen_tcp_server = function(){
		tcp_server.listen(tcp_server_port,function(){
			console.log("[CHILDREN CLIENT] [TCP SERVER] SERVER LISTEN START");
		});
	};

	//-------------------------------------------------------------

	/**
	 * UDPサーバーで受け取ったデータを元に子機に接続する
	 *
	 * @param {string} str - UDPで受信したメッセージ
	 * @param {dgram.rinfo} client_info - 子機のアドレス情報 {@link http://u111u.info/momf}
	 */
	var connect_to_children = function(str,client_info){
		json_str = sslm.decrypt(str.toString('utf8',0,client_info.size));
		obj = JSON.parse(json_str);
		register_to_db(obj);
		create_tlsclient(obj.guid,client_info);
	};
	/**
	 * 子機に命令を送信する
	 *
	 * @param {string} str - 子機に送る命令の文字列
	 */
	var send_command_to_children = function(str){
		json_obj = JSON.parse(str);
		message = JSON.stringify(json_obj["message"]);
		tls_clients[json_obj["id"]].write(message);
	};

	/**
	 * メッセージをパースする
	 *
	 * @param {string} str - パースする文字列
	 */
	this.message_parse = function(str){
		send_to_mpserver(str);
	};

	/**
	 * UDPサーバーとTCPサーバーをスタートさせる
	 */
	this.start = function(){
		start_udp_server();
		listen_tcp_server();
	};
};

module.exports = children_client;
<commit_msg>return error object when tls_client send can't send object<commit_after>var fs = require('fs');
var ursa = require('ursa');
var dgram = require('dgram');
var tls = require('tls');
var net = require('net');
var mongoose = require('mongoose');

mongoose.connect("mongodb://localhost/raspi");

json_scheme = {
	name : String,
	id : String
};

var raschi_data = mongoose.model("raschi_data", new mongoose.Schema(json_scheme) );

/**
 * 公開鍵と秘密鍵と証明書ファイルへのパスを指定します。
 *

 *
{@link children_client~create_tlsclient}
 *
{@link children_client~register_client_with_mongodb}
 *
{@link children_client~register_to_db}
 *
{@link children_client~start_udp_server}
 *
{@link children_client~send_to_mpserver}
 *
{@link children_client~connect_to_mpserver}
 *
{@link children_client~listen_tcp_server}
 *
{@link children_client~connect_to_children}
 *
{@link children_client~send_command_to_children}
 *
{@link children_client.message_parse}
 *
{@link children_client.start}
 *

 * @constructor
 * @classdesc 子機との通信を管理するクラス
 * @param {string} public_key_path - 公開鍵へのパス
 * @param {string} private_key_path - 秘密鍵へのパス
 * @param {string} crt_file_path - 証明書へのパス
 */
var children_client = function(public_key_path,private_key_path,crt_file_path){
	var th = this;

	/* -------------------------- SSL Module ----------------------*/
	//ssl module class

	/**
	 * 秘密鍵と公開鍵へのパスを指定します。
	 *

	 *
 {@link ssl_module.decrypt}
	 *
 {@link ssl_module.encrypt}
	 *

	 * @constructor
	 * @classdesc UDPの通信の際に送られてきたデータを復号化するクラスです。
	 * @param {string} pubpath - 公開鍵へのパス
	 * @param {string} pripath - 秘密鍵へのパス
	 */
	var ssl_module = function(pubpath,pripath){
		/**
		 * 復号化に利用する秘密鍵オブジェクト
		 */
		var key = ursa.createPrivateKey(fs.readFileSync(pripath));

		/**
		 * 暗号化に利用する公開鍵オブジェクト
		 */
		var crt = ursa.createPublicKey(fs.readFileSync(pubpath));

		/**
		 * メッセージを復号化する
		 * @param {string} msg - 復号化する文字列
		 * @return {string} 復号化した文字列
		 */
		this.decrypt = function(msg){
			return key.decrypt(msg,'base64','utf8');
		};

		/**
		 * メッセージを暗号化する
		 * @param {string} msg - 暗号化する文字列
		 * @return {string} 暗号化した文字列
		 */
		this.encrypt = function(msg){
			return crt.encrypt(msg,'utf8','base64');
		};
	};

	/**
	 * {@link ssl_module} のインスタンス
	 * @type {ssl_module}
	 */
	var sslm = new ssl_module(public_key_path,private_key_path);

	//---------------------------------------------------------------

	/*-------------------------- TLS CLient -----------------------*/
	//tls_client class
	//
	/**
	 * 子機に接続しているソケットとその子機のguidを指定します。
	 *

	 *
{@link tls_client.write}
	 *

	 * @constructor
	 * @classdesc 子機との通信をするTLSのクライアントのクラス
	 * @param {tls.TLSSocket} socket - [tls.TLSSocket]{@link http://u111u.info/mnHq} のインスタンス
	 * @param {string} guid - 接続している子機のguid
	 */
	var tls_client = function(socket,guid){
		/**
		 * tlsのソケット
		 */
		this.socket = socket;
		/**
		 * 接続状態の確認
		 */

		var connection = true;
		/**
		 * 子機のGUID
		 * @type {string}
		 */
		this.guid = guid;
		/**
		 * メッセージを送信します
		 * @param {string} str - 送信する文字列
		 */
		this.write = function(str){
			if(connection){
				try{
					this.socket.write(str,'utf-8');
				}catch(ex){
					console.log("[CHILDREN CLIENT] [TLS CLIENT] Message Write Error: " + ex.stack);
				}
			}
			return connection;
		};

		/**
		 * ソケットでエラーが発生した場合の関数
		 * @method
		 * @listens error
		 */
		this.socket.on("error",function(ex){
			console.log("[CHILDREN CLIENT] [TLS CLINET]  " + ex.stack);
		});

		/**
		 * ソケットがオープンした時
		 */
		var socket_this = this;
		this.socket.on("connect",function(ex){
			console.log("[CHILDREN CLIENT] [TLS CLINET]  Open Connection " + socket_this.guid);
		});

		/**
		 * ソケットがクローズした場合
		 */
		this.socket.on("close",function(ex){
			console.log("[CHILDREN CLIENT] [TLS CLINET] Close Connection to " + socket_this.guid);
			connection = false;
		});

		/**
		 * ソケットからデータが来た場合の関数
		 */
		this.socket.on('data',function(str){
			console.log("[CHILDREN CLIENT] [TLS CLIENT] Message recived:" + str);
			th.message_parse(str);
		});
	};

	/**
	 * tls_clientの設定
	 */
	var option = {
		ca: fs.readFileSync(crt_file_path),
		rejectUnauthorized:false
	};

	/**
	 * {@link tls_client}のインスタンス
	 */
	var tls_clients = {};
	/**
	 * tls_clientのguidの配列
	 * @type {Array.string}
	 */
	var client_list = [];
	/**
	 * 子機と接続するtls_clientを作成します
	 *
	 * @param {string} guid - 子機のguid
	 * @param {dgram.rinfo} rinfo - 子機のアドレス情報 {@link http://u111u.info/momf}
	 */
	var create_tlsclient = function(guid,rinfo){
		if(client_list.indexOf(guid) == -1){
			var socket = tls.connect(15000,rinfo.address,option);
			//TODO
			//子機に命令を送るときにtls_clientsのguidから判別するのではなくいい感じにtls_client.guidから判別したい
			tls_clients[guid] = new tls_client(socket,guid);
		}else{
			delete client_list[client_list.indexOf(guid)];
			var socket = tls.connect(15000,rinfo.address,option);
			//TODO
			//子機に命令を送るときにtls_clientsのguidから判別するのではなくいい感じにtls_client.guidから判別したい
			tls_clients[guid] = new tls_client(socket,guid);
		}
	};
	//-------------------------------------------------------------------

	/*------------------------- Mongoose -------------------------------*/

	/**
	 * 子機情報をmongodbに保存
	 * @param {Object} obj - 子機情報のjson
	 */
	var register_client_with_mongodb = function(obj){
		var item = new raschi_data(
				{name:obj["name"],id:obj["guid"]}
				);
		item.save(function(e){console.log("add:"+JSON.stringify(item));});
	};

	/**
	 * 子機情報をデータベースに保存するかどうかを判定する
	 * @param {Object} obj - 子機情報のjson
	 */
	var register_to_db = function(obj){
		raschi_data.find({},function(err,docs){
			var id = -1;
			for(var i=0,size =docs.length;i < size; ++i){
				if(docs[i].id == obj["guid"]) id = docs[i].id;
			}
			console.log(id);
			if(id == -1){
				register_client_with_mongodb(obj);
			}
		});
	};

	/**
	 * guidから子機の名前を取り出します
	 * @param {string} guid - 子機のid
	 */
	var search_name_from_db = function(guid){
		raschi_data.find({},function(err,docs){
			var name = "";
			for(var i=0;size = docs.length; i< size; ++i){
				if(docs[i].id = guid) name = docs[i].name;
			}
			return name;
		}
	};

	//--------------------------------------------------------------------

	/* ------------------------- UDP Server -----------------------------*/

	/**
	 * udpのサーバーのポート番号
	 * @type {num}
	 */
	var udp_server_port = 8000;
	/**
	 * udpのサーバーのインスタンス
	 */
	var udp_server = dgram.createSocket("udp4");

	/**
	 * udp_serverでエラーが起きた際のプログラム
	 */
	udp_server.on("error",function(err){
		console.log("[CHILDREN CLIENT] [UDP SERVER] Server error: " + err.stack);
	});

	/**
	 * updサーバーでメッセージを受け取った時のプログラム
	 */
	udp_server.on("message",function(msg,rinfo){
		console.log("[CHILDREN CLIENT] [UDP SERVER] message comming:");
		connect_to_children(msg,rinfo);
	});

	/**
	 * UDPサーバーをスタートさせます
	 */
	var start_udp_server = function(){
		udp_server.bind(8000,"0.0.0.0");
		console.log("[CHILDREN CLIENT] [UDP SERVER] OPEN UDP SERVER");
	};

	//--------------------------------------------------------------------

	/* ------------------ TCP Server And Client ----------------*/
	// Client

	/**
	 * メッセージサーバーのポート番号
	 * @type {num}
	 */
	var tcp_client_port = 12000;
	/**
	 * メッセージパーサーサーバーに接続するクライアント
	 */
	var tcp_client = new net.Socket({readable:true,writable:true});

	/**
	 * メッセージパーサーに接続するのが失敗した時
	 */
	tcp_client.on('error',function(error){
		tcp_client.connect({port:th.tcp_client_port});
	});

	/**
	 * メッセージサーバーにメッセージを送信するプログラム
	 *
	 * @param {string} str - 送信する文字列
	 */
	var send_to_mpserver = function(str){
		return tcp_client.write(str);
	};

	/**
	 * メッセージパーサーサーバーに接続します
	 */
	var connect_to_mpserver = function(){
		tcp_client.connect({port:tcp_client_port},function(){
			console.log("[CHILDREN CLIENT] [TCP CLIENT] CONNECT TO MPSERVER");
		});
	};

	// Server

	/**
	 * メッセージパーサからのクライアントを受け付けるサーバーのポート番号
	 * @type {num}
	 */
	var tcp_server_port = 20000;

	/**
	 * メッセージパーサー用TCPサーバーのインスタンス
	 */
	var tcp_server = new net.Server(function(socket){
		console.log("[CHILDREN CLIENT] [TCP SERVER] CONNECT CLIENT");
		connect_to_mpserver();
		socket.on('error',function(){
			console.log("[CHILDREN CLIENT] [TCP SERVER] SOCKET ERROR");
		});
		socket.on('data',function(str){
			send_command_to_children(str);
		});
	});

	/**
	 * メッセージサーバー用サーバーがエラーを起こした時
	 */
	tcp_server.on('error',function(){
		console.log("[CHILDREN CLIENT] [TCP SERVER] SERVER ERROR");
	});
	/**
	 * メッセージサーバー用TCPサーバーの待機を始める
	 */
	var listen_tcp_server = function(){
		tcp_server.listen(tcp_server_port,function(){
			console.log("[CHILDREN CLIENT] [TCP SERVER] SERVER LISTEN START");
		});
	};

	//-------------------------------------------------------------

	/**
	 * UDPサーバーで受け取ったデータを元に子機に接続する
	 *
	 * @param {string} str - UDPで受信したメッセージ
	 * @param {dgram.rinfo} client_info - 子機のアドレス情報 {@link http://u111u.info/momf}
	 */
	var connect_to_children = function(str,client_info){
		json_str = sslm.decrypt(str.toString('utf8',0,client_info.size));
		obj = JSON.parse(json_str);
		register_to_db(obj);
		create_tlsclient(obj.guid,client_info);
	};
	/**
	 * 子機に命令を送信する
	 *
	 * @param {string} str - 子機に送る命令の文字列
	 */
	var send_command_to_children = function(str){
		json_obj = JSON.parse(str);
		message = JSON.stringify(json_obj["message"]);
		if(!tls_clients[json_obj.id].write(message)){
			var error_obj = new Error("Connection Refused");
			var name = search_name_from_db(json_obj.id);
			var obj = {
					"type" : "result",
					"value" {
						"id" : json_obj.id,
						"name" : name,
						"value" : {
							"functionName" : json_obj.function,
							"hasError" : true,
							"cancelled" : true,
							"error" : error_obj,
							"result" : undefined
						}
					}
			};
			send_to_mpserver(JSON.stringify(obj));
		}
	};

	/**
	 * メッセージをパースする
	 *
	 * @param {string} str - パースする文字列
	 */
	this.message_parse = function(str){
		send_to_mpserver(str);
	};

	/**
	 * UDPサーバーとTCPサーバーをスタートさせる
	 */
	this.start = function(){
		start_udp_server();
		listen_tcp_server();
	};
};

module.exports = children_client;
<|endoftext|>


<commit_before>/**
 * Provides functionality to place a view inside of a flyout-pane.
 */
define([
    'backbone.marionette', 'jquery', 'jquery.hammer', 'communicator', 'underscore'
  ],

  function( Marionette, $, jQueryHammer, Communicator, _ ) {
    'use strict';

    return Marionette.Region.extend({

      // Element to which this view's containing region is attached.
      $container: null,

      onShownWrapper: null,
      onHiddenWrapper: null,

      initialize: function() {
        this.onShownWrapper = _.bind( this.onShown, this );
        this.onHiddenWrapper = _.bind( this.onHidden, this );
      },

      onShow: function() {
        this.$el.on( 'transitionend', this.onShownWrapper );

        if (this.options.el == '#flyout-detail') {
          this.$el.hammer().bind('swiperight', _.bind(this.hideFlyout, this));
        }

        this.$el.addClass('visible');
        this.$container = this.$el;
        this.$body = $('body');
        this.$body.addClass( this.$container.attr('id') + '-visible' );
      },

      onShown: function() {
        this.$el.off( 'transitionend', this.onShownWrapper );
      },

      hideFlyout: function() {
        if (this.$container && this.currentView) {
          this.currentView.trigger('hide');
          this.$el.on( 'transitionend', this.onHiddenWrapper );

          this.$body.removeClass( this.$container.attr('id') + '-visible' );
          this.$container.removeClass( 'visible' );
        }
      },

      onHidden: function() {
        if (!this.$el) return;
        this.$el.off( 'transitionend', this.onHiddenWrapper );
        this.reset();
      },

      onBeforeDestroy: function() {
        if (this.$container) {
          this.$body.removeClass( this.$container.attr('id') + '-visible' );
        }
      },

      isVisible: function() {
        if (!this.$el) return false;
        return this.$container.hasClass('visible');
      }

    })

  }
);
<commit_msg>functions to collapse/expand flyout without destroying the contained view<commit_after>/**
 * Provides functionality to place a view inside of a flyout-pane.
 */
define([
    'backbone.marionette', 'jquery', 'jquery.hammer', 'communicator', 'underscore'
  ],

  function( Marionette, $, jQueryHammer, Communicator, _ ) {
    'use strict';

    return Marionette.Region.extend({

      // Element to which this view's containing region is attached.
      $container: null,

      onShownWrapper: null,
      onHiddenWrapper: null,

      initialize: function() {
        this.onShownWrapper = _.bind( this.onShown, this );
        this.onHiddenWrapper = _.bind( this.onHidden, this );
      },

      /**
       * Does not destroy the view.
       */
      collapse: function() {
        this.$body.removeClass( this.$container.attr('id') + '-visible' );
        this.$container.removeClass( 'visible' );
      },

      /**
       * Does not destroy the view.
       */
      expand: function() {
        this.$body.addClass( this.$container.attr('id') + '-visible' );
        this.$container.addClass( 'visible' );
      },

      hideFlyout: function() {
        if (this.$container && this.currentView) {
          this.currentView.trigger('hide');
          this.$el.on( 'transitionend', this.onHiddenWrapper );
          this.collapse();
        }
      },

      isVisible: function() {
        if (!this.$el) return false;
        return this.$container.hasClass('visible');
      },

      onBeforeDestroy: function() {
        if (this.$container) {
          this.$body.removeClass( this.$container.attr('id') + '-visible' );
        }
      },

      onHidden: function() {
        if (!this.$el) return;
        this.$el.off( 'transitionend', this.onHiddenWrapper );
      },

      onShow: function() {
        this.$el.on( 'transitionend', this.onShownWrapper );
        if (this.options.el == '#flyout-detail') {
          this.$el.hammer().bind('swiperight', _.bind(this.hideFlyout, this));
        }
        this.$container = this.$el;
        this.$body = $('body');
        this.expand();
      },

      onShown: function() {
        this.$el.off( 'transitionend', this.onShownWrapper );
      }

    })

  }
);
<|endoftext|>


<commit_before>  module.exports = {
    startUpload: function (successCb, errorCb, params) {

      // if (params[0] == null) {
      //   return errorCb("invalid payload");
      // }

      var payload = params[0];
      if (payload.serverUrl == null) {
      //   return errorCb("server url is required");
      // }

      // if (payload.serverUrl.trim() == '') {
      //   return errorCb("invalid server url");
      // }

      // if (payload.file == null) {
      //   return errorCb("file is required");
      // }

      var request = window.superagent;
      request.post('https://api.cloudinary.com/v1_1/tyets/upload')
        .set(payload.headers != null ? payload.headers : {})
        .field(payload.parameters != null ? payload.parameters : {})
        //.field('upload_preset', 'my2rjjsk')
        .on('progress', function (e) {
          console.log('Percentage done: ', e.percent);
          if (e.percent != null && e.percent != undefined)
            successCb({
              progress: e.percent
            });
        })
        .attach('file', payload.filePath)
        .end(function (err, res) {
          console.log(res.req);
          //console.log(res);
          if (err != null) {
            errorCb(err);
          } else {
            successCb(res);
          }
        });
    }
  };

  require("cordova/exec/proxy").add("FileTransferBackground", module.exports);<commit_msg>fixed typo<commit_after>  module.exports = {
    startUpload: function (successCb, errorCb, params) {

      // if (params[0] == null) {
      //   return errorCb("invalid payload");
      // }

      var payload = params[0];
      //if (payload.serverUrl == null) {
      //   return errorCb("server url is required");
      // }

      // if (payload.serverUrl.trim() == '') {
      //   return errorCb("invalid server url");
      // }

      // if (payload.file == null) {
      //   return errorCb("file is required");
      // }

      var request = window.superagent;
      request.post('https://api.cloudinary.com/v1_1/tyets/upload')
        .set(payload.headers != null ? payload.headers : {})
        .field(payload.parameters != null ? payload.parameters : {})
        //.field('upload_preset', 'my2rjjsk')
        .on('progress', function (e) {
          console.log('Percentage done: ', e.percent);
          if (e.percent != null && e.percent != undefined)
            successCb({
              progress: e.percent
            });
        })
        .attach('file', payload.filePath)
        .end(function (err, res) {
          console.log(res.req);
          //console.log(res);
          if (err != null) {
            errorCb(err);
          } else {
            successCb(res);
          }
        });
    }
  };

  require("cordova/exec/proxy").add("FileTransferBackground", module.exports);<|endoftext|>


<commit_before>// pump.js
//
// Entrypoint for the pump.io client UI
//
// Copyright 2011-2012, E14N https://e14n.com/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Make sure this exists

if (!window.Pump) {
    window.Pump = {};
}

(function(_, $, Backbone, Pump) {

    // This is overwritten by inline script in layout.utml

    Pump.config = {};

    // Main entry point

    $(document).ready(function() {

        // Set up router

        Pump.router   = new Pump.Router();

        // Set up initial view

        Pump.body     = new Pump.BodyView({el: $("body")});
        Pump.body.nav = new Pump.AnonymousNav({el: ".navbar-inner .container"});

        // XXX: Make this more complete

        Pump.initialContentView();

        $("abbr.easydate").easydate();

        Backbone.history.start({pushState: true, silent: true});

        Pump.setupWysiHTML5();

        // Refresh the streams automatically every 60 seconds
        // This is a fallback in case something gets lost in the
        // SockJS conversation

        Pump.refreshStreamsID = setInterval(Pump.refreshStreams, 60000);

        // Connect to current server

        if (Pump.config.sockjs) {
            Pump.setupSocket();
        }

        Pump.setupInfiniteScroll();

        if (Pump.principalUser) {
            Pump.principalUser = Pump.User.unique(Pump.principalUser);
            Pump.principal = Pump.Person.unique(Pump.principal);
            Pump.body.nav = new Pump.UserNav({el: Pump.body.$(".navbar-inner .container"),
                                              model: Pump.principalUser,
                                              data: {
                                                  messages: Pump.principalUser.majorDirectInbox,
                                                  notifications: Pump.principalUser.minorDirectInbox
                                              }});
        } else if (Pump.principal) {
            Pump.principal = Pump.Person.unique(Pump.principal);
            Pump.body.nav = new Pump.RemoteNav({el: Pump.body.$(".navbar-inner .container"),
                                                model: Pump.principal});
        } else {
            // Check if we have stored OAuth credentials

            Pump.ensureCred(function(err, cred) {

                var nickname, pair;

                if (err) {
                    Pump.error(err.message);
                    return;
                }

                pair = Pump.getUserCred();

                if (pair) {

                    // We need to renew the session, for images and objects and so on.

                    Pump.renewSession(function(err, data) {

                        var user, major, minor;

                        if (err) {
                            Pump.error(err);
                            Pump.clearUserCred();
                            return;
                        }

                        user = Pump.principalUser = Pump.User.unique(data);
                        Pump.principal = Pump.principalUser.profile;

                        major = user.majorDirectInbox;
                        minor = user.minorDirectInbox;

                        Pump.fetchObjects([major, minor], function(err, objs) {
                            var sp, continueTo;

                            if (err) {
                                Pump.clearUserCred();
                                Pump.error(err);
                                return;
                            }

                            Pump.principalUser = user;

                            Pump.body.nav = new Pump.UserNav({el: ".navbar-inner .container",
                                                              model: user,
                                                              data: {
                                                                  messages: major,
                                                                  notifications: minor
                                                              }});
                            Pump.body.nav.render();

                            // If we're on the login page, and there's a current
                            // user, redirect to the actual page

                            switch (window.location.pathname) {
                            case "/main/login":
                                Pump.body.content = new Pump.LoginContent();
                                continueTo = Pump.getContinueTo();
                                Pump.router.navigate(continueTo, true);
                                break;
                            case "/":
                                Pump.router.home();
                                break;
                            }
                        });
                    });
                }
            });
        }
    });

    // Renew the cookie session

    Pump.renewSession = function(callback) {

        var options = {
            dataType: "json",
            type: "POST",
            url: "/main/renew",
            success: function(data, textStatus, jqXHR) {
                callback(null, data);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                callback(new Error("Failed to renew"), null);
            }
        };

        Pump.ajax(options);
    };

    // When errors happen, and you don't know what to do with them,
    // send them here and I'll figure it out.

    Pump.error = function(err) {
        console.log(err);
        if (err.stack) {
            console.log(err.stack);
        }
    };

    // Given a relative URL like /main/register, make a fully-qualified
    // URL on the current server

    Pump.fullURL = function(url) {

        var here = window.location;

        if (url.indexOf(':') == -1) {
            if (url.substr(0, 1) == '/') {
                url = here.protocol + '//' + here.host + url;
            } else {
                url = here.href.substr(0, here.href.lastIndexOf('/') + 1) + url;
            }
        }

        return url;
    };

    // Add some OAuth magic to the arguments for a $.ajax() call

    Pump.oauthify = function(options) {

        options.url = Pump.fullURL(options.url);

        var message = {action: options.url,
                       method: options.type,
                       parameters: [["oauth_version", "1.0"],
                                    ["oauth_consumer_key", options.consumerKey]]};

        if (options.token) {
            message.parameters.push(["oauth_token", options.token]);
        }

        OAuth.setTimestampAndNonce(message);
        OAuth.SignatureMethod.sign(message,
                                   {consumerSecret: options.consumerSecret,
                                    tokenSecret: options.tokenSecret});

        var header =  OAuth.getAuthorizationHeader("OAuth", message.parameters);

        options.headers = {Authorization: header};

        return options;
    };

    Pump.fetchObjects = function(orig, callback) {
        var fetched = 0,
            objs = (orig.length) > 0 ? orig.slice(0) : [], // make a dupe in case arg is changed
            count = objs.length,
            done = false,
            onSuccess = function() {
                if (!done) {
                    fetched++;
                    if (fetched >= count) {
                        done = true;
                        callback(null, objs);
                    }
                }
            },
            onError = function(xhr, status, thrown) {
                if (!done) {
                    done = true;
                    if (thrown) {
                        callback(thrown, null);
                    } else {
                        callback(new Error(status), null);
                    }
                }
            };

        _.each(objs, function(obj) {
            try {
                if (_.isFunction(obj.prevLink) && obj.prevLink()) {
                    obj.getPrev(function(err) {
                        if (err) {
                            onError(null, null, err);
                        } else {
                            onSuccess();
                        }
                    });
                } else {
                    obj.fetch({update: true,
                               success: onSuccess,
                               error: onError});
                }
            } catch (e) {
                onError(null, null, e);
            }
        });
    };

    // Not the most lovely, but it works
    // XXX: change this to use UTML templating instead

    Pump.wysihtml5Tmpl = {
        "emphasis": function(locale) {
            return "
" +
                "
" +
                "" +
                "" +
                "_" +
                "
" +
                "
";
        }
    };

    // Most long-form descriptions and notes use this lib for editing

    Pump.setupWysiHTML5 = function() {

        // Set wysiwyg defaults

        $.fn.wysihtml5.defaultOptions["font-styles"] = false;
        $.fn.wysihtml5.defaultOptions["image"] = false;
        $.fn.wysihtml5.defaultOptions["customTemplates"] = Pump.wysihtml5Tmpl;
    };

    // Turn the querystring into an object

    Pump.searchParams = function(str) {
        var params = {},
            pl     = /\+/g,
            decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
            pairs;

        if (!str) {
            str = window.location.search;
        }

        pairs = str.substr(1).split("&");

        _.each(pairs, function(pairStr) {
            var pair = pairStr.split("=", 2),
                key = decode(pair[0]),
                value = (pair.length > 1) ? decode(pair[1]) : null;

            params[key] = value;
        });

        return params;
    };

    Pump.continueTo = null;

    // Get the "continue" param

    Pump.getContinueTo = function() {
        var sp = Pump.searchParams(),
            continueTo = (_.has(sp, "continue")) ? sp["continue"] : null;

        if (continueTo && continueTo.length > 0 && continueTo[0] == "/") {
            return continueTo;
        } else if (Pump.continueTo) {
            continueTo = Pump.continueTo;
            return continueTo;
        } else {
            return "";
        }
    };

    Pump.saveContinueTo = function() {
        Pump.continueTo = window.location.pathname + window.location.search;
    };

    Pump.clearContinueTo = function() {
        Pump.continueTo = null;
    };

    // We clear out cached stuff when login state changes

    Pump.clearCaches = function() {
        Pump.Model.clearCache();
        Pump.User.clearCache();
    };

    Pump.ajax = function(options) {
        // For remote users, we use session auth
        if (Pump.principal && !Pump.principalUser && options.type == "GET") {
            $.ajax(options);
        } else {
            Pump.ensureCred(function(err, cred) {
                var pair;
                if (err) {
                    Pump.error("Couldn't get OAuth credentials. :(");
                } else {
                    options.consumerKey = cred.clientID;
                    options.consumerSecret = cred.clientSecret;
                    pair = Pump.getUserCred();

                    if (pair) {
                        options.token = pair.token;
                        options.tokenSecret = pair.secret;
                    }

                    options = Pump.oauthify(options);
                    $.ajax(options);
                }
            });
        }
    };

    Pump.setupInfiniteScroll = function() {

        var didScroll = false;

        // scroll fires too fast, so just use the handler
        // to set a flag, and check that flag with an interval

        // From http://ejohn.org/blog/learning-from-twitter/

        $(window).scroll(function() {
            didScroll = true;
        });

        setInterval(function() {
            var streams;
            if (didScroll) {
                didScroll = false;
                if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
                    streams = Pump.getStreams();
                    if (streams.major && streams.major.nextLink) {
                        Pump.body.startLoad();
                        streams.major.getNext(function() {
                            Pump.body.endLoad();
                        });
                    }
                }
            }
        }, 250);
    };

    // XXX: this is cheeseball.

    Pump.rel = function(url) {

        var a = document.createElement('a'),
            pathname;

        a.href = url;
        pathname = a.pathname;

        return pathname;
    };

    Pump.htmlEncode = function(value) {
        return $('
').text(value).html();
    };

    Pump.htmlDecode = function(value) {
        return $('
').html(value).text();
    };

    // Sets up the initial view and sub-views

    Pump.initialContentView = function() {

        var $content = $("#content"),
            selectorToView = {
                "#main": {View: Pump.MainContent},
                "#loginpage": {View: Pump.LoginContent},
                "#register": {View: Pump.RegisterContent},
                "#inbox": {View: Pump.InboxContent, models: {major: Pump.ActivityStream, minor: Pump.ActivityStream}},
                ".object-page": {View: Pump.ObjectContent, models: {object: Pump.ActivityObject}},
                ".major-activity-page": {View: Pump.ActivityContent, models: {activity: Pump.Activity}},
                ".user-activities": {View: Pump.UserPageContent, models: {profile: Pump.Person,
                                                                          major: Pump.ActivityStream,
                                                                          minor: Pump.ActivityStream}},
                ".user-favorites": {View: Pump.FavoritesContent, models: {profile: Pump.Person,
                                                                          favorites: Pump.ActivityObjectStream}},
                ".user-followers": {View: Pump.FollowersContent, models: {profile: Pump.Person,
                                                                          followers: Pump.PeopleStream}},
                ".user-following": {View: Pump.FollowingContent, models: {profile: Pump.Person,
                                                                          following: Pump.PeopleStream}},
                ".user-lists": {View: Pump.ListsContent, models: {profile: Pump.Person,
                                                                  lists: Pump.ActivityObjectStream}},
                ".user-list": {View: Pump.ListContent, models: {profile: Pump.Person,
                                                                lists: Pump.ActivityObjectStream,
                                                                list: Pump.ActivityObject}}
            },
            selector,
            $el,
            model,
            options,
            def,
            data,
            View;

        // When I say "view" the crowd say "selector"

        for (selector in selectorToView) {
            if (_.has(selectorToView, selector)) {
                $el = $content.find(selector);
                if ($el.length > 0) {
                    def = selectorToView[selector];
                    View = def.View;
                    options = {el: $el, data: {}};
                    data = Pump.initialData;
                    _.each(data, function(value, name) {
                        if (name == View.prototype.modelName) {
                            options.model = def.models[name].unique(value);
                        } else if (def.models[name]) {
                            options.data[name] = def.models[name].unique(value);
                        } else {
                            options.data[name] = value;
                        }
                    });
                    Pump.body.content = new View(options);
                    Pump.initialData = null;
                    break;
                }
            }
        }

        // XXX: set up initial data
    };

    Pump.newMinorActivity = function(act, callback) {
        if (Pump.principalUser) {
            Pump.addToStream(Pump.principalUser.minorStream, act, callback);
        } else {
            Pump.proxyActivity(act, callback);
        }
    };

    Pump.newMajorActivity = function(act, callback) {
        if (Pump.principalUser) {
            Pump.addToStream(Pump.principalUser.majorStream, act, callback);
        } else {
            Pump.proxyActivity(act, callback);
        }
    };

    Pump.addToStream = function(stream, act, callback) {
        stream.items.create(act, {
            success: function(act) {
                callback(null, act);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                var type, response;
                type = jqXHR.getResponseHeader("Content-Type");
                if (type && type.indexOf("application/json") !== -1) {
                    response = JSON.parse(jqXHR.responseText);
                    callback(new Error(response.error), null);
                } else {
                    callback(new Error(errorThrown), null);
                }
            }
        });
    };

    // XXX: This POSTs with session auth; subject to XSS.

    Pump.proxyActivity = function(act, callback) {
        $.ajax({
            contentType: "application/json",
            data: JSON.stringify(act),
            dataType: "json",
            type: "POST",
            url: "/main/proxy",
            success: function(act) {
                callback(null, act);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                var type, response;
                type = jqXHR.getResponseHeader("Content-Type");
                if (type && type.indexOf("application/json") !== -1) {
                    response = JSON.parse(jqXHR.responseText);
                    callback(new Error(response.error), null);
                } else {
                    callback(new Error(errorThrown), null);
                }
            }
        });
    };

    Pump.setTitle = function(title) {
        $("title").html(title + " - " + Pump.config.site);
    };

})(window._, window.$, window.Backbone, window.Pump);
<commit_msg>Get the error from getNext()<commit_after>// pump.js
//
// Entrypoint for the pump.io client UI
//
// Copyright 2011-2012, E14N https://e14n.com/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Make sure this exists

if (!window.Pump) {
    window.Pump = {};
}

(function(_, $, Backbone, Pump) {

    // This is overwritten by inline script in layout.utml

    Pump.config = {};

    // Main entry point

    $(document).ready(function() {

        // Set up router

        Pump.router   = new Pump.Router();

        // Set up initial view

        Pump.body     = new Pump.BodyView({el: $("body")});
        Pump.body.nav = new Pump.AnonymousNav({el: ".navbar-inner .container"});

        // XXX: Make this more complete

        Pump.initialContentView();

        $("abbr.easydate").easydate();

        Backbone.history.start({pushState: true, silent: true});

        Pump.setupWysiHTML5();

        // Refresh the streams automatically every 60 seconds
        // This is a fallback in case something gets lost in the
        // SockJS conversation

        Pump.refreshStreamsID = setInterval(Pump.refreshStreams, 60000);

        // Connect to current server

        if (Pump.config.sockjs) {
            Pump.setupSocket();
        }

        Pump.setupInfiniteScroll();

        if (Pump.principalUser) {
            Pump.principalUser = Pump.User.unique(Pump.principalUser);
            Pump.principal = Pump.Person.unique(Pump.principal);
            Pump.body.nav = new Pump.UserNav({el: Pump.body.$(".navbar-inner .container"),
                                              model: Pump.principalUser,
                                              data: {
                                                  messages: Pump.principalUser.majorDirectInbox,
                                                  notifications: Pump.principalUser.minorDirectInbox
                                              }});
        } else if (Pump.principal) {
            Pump.principal = Pump.Person.unique(Pump.principal);
            Pump.body.nav = new Pump.RemoteNav({el: Pump.body.$(".navbar-inner .container"),
                                                model: Pump.principal});
        } else {
            // Check if we have stored OAuth credentials

            Pump.ensureCred(function(err, cred) {

                var nickname, pair;

                if (err) {
                    Pump.error(err.message);
                    return;
                }

                pair = Pump.getUserCred();

                if (pair) {

                    // We need to renew the session, for images and objects and so on.

                    Pump.renewSession(function(err, data) {

                        var user, major, minor;

                        if (err) {
                            Pump.error(err);
                            Pump.clearUserCred();
                            return;
                        }

                        user = Pump.principalUser = Pump.User.unique(data);
                        Pump.principal = Pump.principalUser.profile;

                        major = user.majorDirectInbox;
                        minor = user.minorDirectInbox;

                        Pump.fetchObjects([major, minor], function(err, objs) {
                            var sp, continueTo;

                            if (err) {
                                Pump.clearUserCred();
                                Pump.error(err);
                                return;
                            }

                            Pump.principalUser = user;

                            Pump.body.nav = new Pump.UserNav({el: ".navbar-inner .container",
                                                              model: user,
                                                              data: {
                                                                  messages: major,
                                                                  notifications: minor
                                                              }});
                            Pump.body.nav.render();

                            // If we're on the login page, and there's a current
                            // user, redirect to the actual page

                            switch (window.location.pathname) {
                            case "/main/login":
                                Pump.body.content = new Pump.LoginContent();
                                continueTo = Pump.getContinueTo();
                                Pump.router.navigate(continueTo, true);
                                break;
                            case "/":
                                Pump.router.home();
                                break;
                            }
                        });
                    });
                }
            });
        }
    });

    // Renew the cookie session

    Pump.renewSession = function(callback) {

        var options = {
            dataType: "json",
            type: "POST",
            url: "/main/renew",
            success: function(data, textStatus, jqXHR) {
                callback(null, data);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                callback(new Error("Failed to renew"), null);
            }
        };

        Pump.ajax(options);
    };

    // When errors happen, and you don't know what to do with them,
    // send them here and I'll figure it out.

    Pump.error = function(err) {
        console.log(err);
        if (err.stack) {
            console.log(err.stack);
        }
    };

    // Given a relative URL like /main/register, make a fully-qualified
    // URL on the current server

    Pump.fullURL = function(url) {

        var here = window.location;

        if (url.indexOf(':') == -1) {
            if (url.substr(0, 1) == '/') {
                url = here.protocol + '//' + here.host + url;
            } else {
                url = here.href.substr(0, here.href.lastIndexOf('/') + 1) + url;
            }
        }

        return url;
    };

    // Add some OAuth magic to the arguments for a $.ajax() call

    Pump.oauthify = function(options) {

        options.url = Pump.fullURL(options.url);

        var message = {action: options.url,
                       method: options.type,
                       parameters: [["oauth_version", "1.0"],
                                    ["oauth_consumer_key", options.consumerKey]]};

        if (options.token) {
            message.parameters.push(["oauth_token", options.token]);
        }

        OAuth.setTimestampAndNonce(message);
        OAuth.SignatureMethod.sign(message,
                                   {consumerSecret: options.consumerSecret,
                                    tokenSecret: options.tokenSecret});

        var header =  OAuth.getAuthorizationHeader("OAuth", message.parameters);

        options.headers = {Authorization: header};

        return options;
    };

    Pump.fetchObjects = function(orig, callback) {
        var fetched = 0,
            objs = (orig.length) > 0 ? orig.slice(0) : [], // make a dupe in case arg is changed
            count = objs.length,
            done = false,
            onSuccess = function() {
                if (!done) {
                    fetched++;
                    if (fetched >= count) {
                        done = true;
                        callback(null, objs);
                    }
                }
            },
            onError = function(xhr, status, thrown) {
                if (!done) {
                    done = true;
                    if (thrown) {
                        callback(thrown, null);
                    } else {
                        callback(new Error(status), null);
                    }
                }
            };

        _.each(objs, function(obj) {
            try {
                if (_.isFunction(obj.prevLink) && obj.prevLink()) {
                    obj.getPrev(function(err) {
                        if (err) {
                            onError(null, null, err);
                        } else {
                            onSuccess();
                        }
                    });
                } else {
                    obj.fetch({update: true,
                               success: onSuccess,
                               error: onError});
                }
            } catch (e) {
                onError(null, null, e);
            }
        });
    };

    // Not the most lovely, but it works
    // XXX: change this to use UTML templating instead

    Pump.wysihtml5Tmpl = {
        "emphasis": function(locale) {
            return "
" +
                "
" +
                "" +
                "" +
                "_" +
                "
" +
                "
";
        }
    };

    // Most long-form descriptions and notes use this lib for editing

    Pump.setupWysiHTML5 = function() {

        // Set wysiwyg defaults

        $.fn.wysihtml5.defaultOptions["font-styles"] = false;
        $.fn.wysihtml5.defaultOptions["image"] = false;
        $.fn.wysihtml5.defaultOptions["customTemplates"] = Pump.wysihtml5Tmpl;
    };

    // Turn the querystring into an object

    Pump.searchParams = function(str) {
        var params = {},
            pl     = /\+/g,
            decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
            pairs;

        if (!str) {
            str = window.location.search;
        }

        pairs = str.substr(1).split("&");

        _.each(pairs, function(pairStr) {
            var pair = pairStr.split("=", 2),
                key = decode(pair[0]),
                value = (pair.length > 1) ? decode(pair[1]) : null;

            params[key] = value;
        });

        return params;
    };

    Pump.continueTo = null;

    // Get the "continue" param

    Pump.getContinueTo = function() {
        var sp = Pump.searchParams(),
            continueTo = (_.has(sp, "continue")) ? sp["continue"] : null;

        if (continueTo && continueTo.length > 0 && continueTo[0] == "/") {
            return continueTo;
        } else if (Pump.continueTo) {
            continueTo = Pump.continueTo;
            return continueTo;
        } else {
            return "";
        }
    };

    Pump.saveContinueTo = function() {
        Pump.continueTo = window.location.pathname + window.location.search;
    };

    Pump.clearContinueTo = function() {
        Pump.continueTo = null;
    };

    // We clear out cached stuff when login state changes

    Pump.clearCaches = function() {
        Pump.Model.clearCache();
        Pump.User.clearCache();
    };

    Pump.ajax = function(options) {
        // For remote users, we use session auth
        if (Pump.principal && !Pump.principalUser && options.type == "GET") {
            $.ajax(options);
        } else {
            Pump.ensureCred(function(err, cred) {
                var pair;
                if (err) {
                    Pump.error("Couldn't get OAuth credentials. :(");
                } else {
                    options.consumerKey = cred.clientID;
                    options.consumerSecret = cred.clientSecret;
                    pair = Pump.getUserCred();

                    if (pair) {
                        options.token = pair.token;
                        options.tokenSecret = pair.secret;
                    }

                    options = Pump.oauthify(options);
                    $.ajax(options);
                }
            });
        }
    };

    Pump.setupInfiniteScroll = function() {

        var didScroll = false;

        // scroll fires too fast, so just use the handler
        // to set a flag, and check that flag with an interval

        // From http://ejohn.org/blog/learning-from-twitter/

        $(window).scroll(function() {
            didScroll = true;
        });

        setInterval(function() {
            var streams;
            if (didScroll) {
                didScroll = false;
                if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
                    streams = Pump.getStreams();
                    if (streams.major && streams.major.nextLink) {
                        Pump.body.startLoad();
                        streams.major.getNext(function(err) {
                            Pump.body.endLoad();
                        });
                    }
                }
            }
        }, 250);
    };

    // XXX: this is cheeseball.

    Pump.rel = function(url) {

        var a = document.createElement('a'),
            pathname;

        a.href = url;
        pathname = a.pathname;

        return pathname;
    };

    Pump.htmlEncode = function(value) {
        return $('
').text(value).html();
    };

    Pump.htmlDecode = function(value) {
        return $('
').html(value).text();
    };

    // Sets up the initial view and sub-views

    Pump.initialContentView = function() {

        var $content = $("#content"),
            selectorToView = {
                "#main": {View: Pump.MainContent},
                "#loginpage": {View: Pump.LoginContent},
                "#register": {View: Pump.RegisterContent},
                "#inbox": {View: Pump.InboxContent, models: {major: Pump.ActivityStream, minor: Pump.ActivityStream}},
                ".object-page": {View: Pump.ObjectContent, models: {object: Pump.ActivityObject}},
                ".major-activity-page": {View: Pump.ActivityContent, models: {activity: Pump.Activity}},
                ".user-activities": {View: Pump.UserPageContent, models: {profile: Pump.Person,
                                                                          major: Pump.ActivityStream,
                                                                          minor: Pump.ActivityStream}},
                ".user-favorites": {View: Pump.FavoritesContent, models: {profile: Pump.Person,
                                                                          favorites: Pump.ActivityObjectStream}},
                ".user-followers": {View: Pump.FollowersContent, models: {profile: Pump.Person,
                                                                          followers: Pump.PeopleStream}},
                ".user-following": {View: Pump.FollowingContent, models: {profile: Pump.Person,
                                                                          following: Pump.PeopleStream}},
                ".user-lists": {View: Pump.ListsContent, models: {profile: Pump.Person,
                                                                  lists: Pump.ActivityObjectStream}},
                ".user-list": {View: Pump.ListContent, models: {profile: Pump.Person,
                                                                lists: Pump.ActivityObjectStream,
                                                                list: Pump.ActivityObject}}
            },
            selector,
            $el,
            model,
            options,
            def,
            data,
            View;

        // When I say "view" the crowd say "selector"

        for (selector in selectorToView) {
            if (_.has(selectorToView, selector)) {
                $el = $content.find(selector);
                if ($el.length > 0) {
                    def = selectorToView[selector];
                    View = def.View;
                    options = {el: $el, data: {}};
                    data = Pump.initialData;
                    _.each(data, function(value, name) {
                        if (name == View.prototype.modelName) {
                            options.model = def.models[name].unique(value);
                        } else if (def.models[name]) {
                            options.data[name] = def.models[name].unique(value);
                        } else {
                            options.data[name] = value;
                        }
                    });
                    Pump.body.content = new View(options);
                    Pump.initialData = null;
                    break;
                }
            }
        }

        // XXX: set up initial data
    };

    Pump.newMinorActivity = function(act, callback) {
        if (Pump.principalUser) {
            Pump.addToStream(Pump.principalUser.minorStream, act, callback);
        } else {
            Pump.proxyActivity(act, callback);
        }
    };

    Pump.newMajorActivity = function(act, callback) {
        if (Pump.principalUser) {
            Pump.addToStream(Pump.principalUser.majorStream, act, callback);
        } else {
            Pump.proxyActivity(act, callback);
        }
    };

    Pump.addToStream = function(stream, act, callback) {
        stream.items.create(act, {
            success: function(act) {
                callback(null, act);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                var type, response;
                type = jqXHR.getResponseHeader("Content-Type");
                if (type && type.indexOf("application/json") !== -1) {
                    response = JSON.parse(jqXHR.responseText);
                    callback(new Error(response.error), null);
                } else {
                    callback(new Error(errorThrown), null);
                }
            }
        });
    };

    // XXX: This POSTs with session auth; subject to XSS.

    Pump.proxyActivity = function(act, callback) {
        $.ajax({
            contentType: "application/json",
            data: JSON.stringify(act),
            dataType: "json",
            type: "POST",
            url: "/main/proxy",
            success: function(act) {
                callback(null, act);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                var type, response;
                type = jqXHR.getResponseHeader("Content-Type");
                if (type && type.indexOf("application/json") !== -1) {
                    response = JSON.parse(jqXHR.responseText);
                    callback(new Error(response.error), null);
                } else {
                    callback(new Error(errorThrown), null);
                }
            }
        });
    };

    Pump.setTitle = function(title) {
        $("title").html(title + " - " + Pump.config.site);
    };

})(window._, window.$, window.Backbone, window.Pump);
<|endoftext|>