<commit_before>var mongoose = require('mongoose');
var quickMsg = require('../db/models/quickMsg');
var QuickMsg = mongoose.model('QuickMsg');

module.exports = function(app) {
    app.get('/', function(req, res) {
        res.render('base');
    });
    app.get('/index', function(req, res) {
        res.render('index');
    });
    app.get('/faq', function(req, res) {
        res.render('faq');
    });
    app.get('/faqContent', function(req, res) {
        res.send('有什么问题请尽管提问吧 ヾ(o◕∀◕)ﾉ');
    });
    app.get('/contactMe', function(req, res) {
        res.render('contactMe');
    });
    app.get('/photos', function(req, res) {
        res.render('photos');
    });
    app.post('/sendQuickMsg', function(req, res) {
        console.log(req.body);
        var data = {
            name: '',
            email: '',
            message: '',
            date: ''
        };
        data.name = req.body.name;
        data.email = req.body.email;
        data.message = req.body.message;
        data.date = 'today';
        var quickMsg = new QuickMsg(data);
        quickMsg.save();
        res.send('ok');
    });
};<commit_msg>change routes.js<commit_after>var mongoose = require('mongoose');
var quickMsg = require('../db/models/quickMsg');
var QuickMsg = mongoose.model('QuickMsg');

module.exports = function(app) {
    app.get('/', function(req, res) {
        res.render('base');
    });
    app.get('/index', function(req, res) {
        res.render('index');
    });
    app.get('/faq', function(req, res) {
        res.render('faq');
    });
    app.get('/faqContent', function(req, res) {
        res.send('有什么问题请尽管提问吧 ヾ(o◕∀◕)ﾉ');
    });
    app.get('/contactMe', function(req, res) {
        res.render('contactMe');
    });
    app.get('/photos', function(req, res) {
        res.render('photos');
    });
    app.post('/sendQuickMsg', function(req, res) {
        req.body.date = new Date().toLocaleString();
        var quickMsg = new QuickMsg(req.body);
        quickMsg.save();
        res.send('ok');
    });
};<|endoftext|>


<commit_before>const express = require('express');
const router = express.Router();
const qp = require('./query_parser');
const agg = require('./aggregation');
// --------------------------------------------------------------------------------------
// get data based on query
// --------------------------------------------------------------------------------------
router.get('/', function(req, res, next) {
  var query = qp.parse_query_string(req.url,
    ['pn', 'timestamp', 'csi', 'result', 'realm', 'visinst'],
    qp.validate_interval,
    false);       // no timestamp may be present in valid query

  if(Object.keys(query.filter).length == 0) {   // empty filter
    var err = new Error("Neplatný dotaz!");
    err.status = 400;
    throw err;
  }

  search(req, res, next, query);
});
// --------------------------------------------------------------------------------------
// search for given query
// --------------------------------------------------------------------------------------
function search(req, res, next, query) {
  // exclude possible regex from
  var regex = agg.check_regex(query.filter);

  // ===================================================
  // construct base query
  var aggregate_query = [
    {
      $match : query.filter       // filter by query
    },
  ];

  if(Object.keys(regex).length > 0) {
    agg.add_stage(aggregate_query, { $match : regex });
  }

  agg.add_stage(aggregate_query, {
      $project :
        {
          timestamp : 1,
          realm : 1,
          viscountry : 1,
          visinst : 1,
          mac_address : "$csi",
          username : "$pn",
          result : 1,
          _id : 0
        }
    });

  // ===================================================
  // add other operators, if defined in query
  agg.add_ops(aggregate_query, query);

  // ===================================================
  // search

  var stream = req.db.logs.aggregate(aggregate_query).cursor({ batchSize: 1000 }).exec().stream();
  var data = [];

  stream.on('error', function (err1) {
    if(err1) {
      var err2 = new Error();      // just to detect where the original error happened
      console.error(err2);
      console.error(err1);
      next([err2, err1]);
      return;
    }
  });

  stream.on('data', function(item) {
    data.push(item);
  });

  stream.on('end', function(items) {
    respond(filter_data(req, convert(data)), res);
  });
}
// --------------------------------------------------------------------------------------
// filter results so each user can search only relevant records
// user: only his records
// realm admin: only records for all administered realms
// --------------------------------------------------------------------------------------
function filter_data(req, data)
{
  var ret = [];

  if(req.session.user.role == "user") {
    for(var item in data)
      if(data[item].username == req.session.user.username)
        ret.push(data[item]);
  }

  else if(req.session.user.role == "realm_admin") {
    for(var realm in req.session.user.administered_realms)
      for(var item in data)
        if(data[item].realm == req.session.user.administered_realms[realm])
          ret.push(data[item]);
  }

  else if(req.session.user.role == "admin")  // no filtration
    return data;

  return ret;
}
// --------------------------------------------------------------------------------------
// convert timestamp in data
// --------------------------------------------------------------------------------------
function convert(data)
{
  var ret = [];

  if(data.length != 0 && !data[0].timestamp)   // output is limited to fields
    return data;

  for(var item in data) {
    data[item].timestamp = convert_time(data[item].timestamp);
    ret.push(data[item]);
  }

  return ret;
}
// --------------------------------------------------------------------------------------
// convert UTC to localtime based on input
// --------------------------------------------------------------------------------------
function convert_time(date)
{
  d = new Date(date);
  d.setTime(d.getTime() + (-1 * d.getTimezoneOffset() * 60 * 1000));
  return d;
}
// --------------------------------------------------------------------------------------
// send data to user
// --------------------------------------------------------------------------------------
function respond(items, res) {
  res.json(items);
}
// --------------------------------------------------------------------------------------
module.exports = router;
<commit_msg>use eduroam identities when matching against user<commit_after>const express = require('express');
const router = express.Router();
const qp = require('./query_parser');
const agg = require('./aggregation');
// --------------------------------------------------------------------------------------
// get data based on query
// --------------------------------------------------------------------------------------
router.get('/', function(req, res, next) {
  var query = qp.parse_query_string(req.url,
    ['pn', 'timestamp', 'csi', 'result', 'realm', 'visinst'],
    qp.validate_interval,
    false);       // no timestamp may be present in valid query

  if(Object.keys(query.filter).length == 0) {   // empty filter
    var err = new Error("Neplatný dotaz!");
    err.status = 400;
    throw err;
  }

  search(req, res, next, query);
});
// --------------------------------------------------------------------------------------
// search for given query
// --------------------------------------------------------------------------------------
function search(req, res, next, query) {
  // exclude possible regex from
  var regex = agg.check_regex(query.filter);

  // ===================================================
  // construct base query
  var aggregate_query = [
    {
      $match : query.filter       // filter by query
    },
  ];

  if(Object.keys(regex).length > 0) {
    agg.add_stage(aggregate_query, { $match : regex });
  }

  agg.add_stage(aggregate_query, {
      $project :
        {
          timestamp : 1,
          realm : 1,
          viscountry : 1,
          visinst : 1,
          mac_address : "$csi",
          username : "$pn",
          result : 1,
          _id : 0
        }
    });

  // ===================================================
  // add other operators, if defined in query
  agg.add_ops(aggregate_query, query);

  // ===================================================
  // search

  var stream = req.db.logs.aggregate(aggregate_query).cursor({ batchSize: 1000 }).exec().stream();
  var data = [];

  stream.on('error', function (err1) {
    if(err1) {
      var err2 = new Error();      // just to detect where the original error happened
      console.error(err2);
      console.error(err1);
      next([err2, err1]);
      return;
    }
  });

  stream.on('data', function(item) {
    data.push(item);
  });

  stream.on('end', function(items) {
    respond(filter_data(req, convert(data)), res);
  });
}
// --------------------------------------------------------------------------------------
// filter results so each user can search only relevant records
// user: only his records
// realm admin: only records for all administered realms
// --------------------------------------------------------------------------------------
function filter_data(req, data)
{
  var ret = [];

  if(req.session.user.role == "user") {
    for(var item in data)
      for(var id in req.session.user.identities)
        if(data[item].username == req.session.user.identities[id])  // match against identities not username !
          ret.push(data[item]);
  }

  else if(req.session.user.role == "realm_admin") {
    for(var realm in req.session.user.administered_realms)
      for(var item in data)
        if(data[item].realm == req.session.user.administered_realms[realm])
          ret.push(data[item]);
  }

  else if(req.session.user.role == "admin")  // no filtration
    return data;

  return ret;
}
// --------------------------------------------------------------------------------------
// convert timestamp in data
// --------------------------------------------------------------------------------------
function convert(data)
{
  var ret = [];

  if(data.length != 0 && !data[0].timestamp)   // output is limited to fields
    return data;

  for(var item in data) {
    data[item].timestamp = convert_time(data[item].timestamp);
    ret.push(data[item]);
  }

  return ret;
}
// --------------------------------------------------------------------------------------
// convert UTC to localtime based on input
// --------------------------------------------------------------------------------------
function convert_time(date)
{
  d = new Date(date);
  d.setTime(d.getTime() + (-1 * d.getTimezoneOffset() * 60 * 1000));
  return d;
}
// --------------------------------------------------------------------------------------
// send data to user
// --------------------------------------------------------------------------------------
function respond(items, res) {
  res.json(items);
}
// --------------------------------------------------------------------------------------
module.exports = router;
<|endoftext|>


<commit_before>var _      = require('underscore')
var async  = require('async')
var op     = require('object-path')
var router = require('express').Router()

var entu   = require('../helpers/entu')

router.get('/requests', function(req, res) {
    var limit = req.query.limit || 5
    var days = req.query.days || 7

    var today = new Date();
    var lastWeek = new Date(today.getFullYear(), today.getMonth(), today.getDate() - days);

    async.waterfall([
        function(callback) {
            entu.dbConnection('entu', callback)
        },
        function(connection, callback) {
            connection.collection('request').aggregate([
            	{
            		'$match' : {
                		date: {
                    		$gt: lastWeek
                		}
            		}
            	},
            	{
            		'$group' : {
            			_id: {
                            host: '$host',
                            month: { $month: '$date' },
                            day: { $dayOfMonth: '$date' },
                            year: { $year: '$date' }
                        },
            			count: {
            				$sum: 1
            			}
            		}
            	}
            ]).toArray(callback)
        },
        function(result, callback) {

            var seriesData = {}
            for (var i in result) {
                if(!result.hasOwnProperty(i)) { continue }

                var host = op.get(result[i], '_id.host')
                var day = '00' + op.get(result[i], '_id.day')
                var day = day.substr(day.length - 2)
                var month = '00' + op.get(result[i], '_id.month')
                var month = month.substr(month.length - 2)
                var year = op.get(result[i], '_id.year')

                var date = [year, month, day].join('-')
                var count = op.get(result[i], 'count')

                op.set(seriesData, [host, 'sum'], op.get(seriesData, [host, 'sum'], 0) + count)
                op.set(seriesData, [host, 'name'], host)
                op.push(seriesData, [host, 'data'], [date, count])
                op.set(seriesData, [host, 'incomplete_from'], today.toISOString().substr(0, 10))
            }

            var seriesDataValues = _.values(seriesData)
            var seriesDataValuesSorted = _.sortBy(seriesDataValues, 'sum')
            var graphData = {
                x_axis: {
                    type: 'datetime'
                },
                series: seriesDataValuesSorted.slice(seriesDataValuesSorted.length - limit)
            }

            callback(null, graphData)
        },
    ], function(err, result) {
        if(err) {
            res.send({
                error: err,
                version: APP_VERSION,
                started: APP_STARTED
            })
        } else {
            res.send(result)
        }
    })
})

router.get('/test', function() {
    throw new Error('böö')
})

module.exports = router
<commit_msg>Better sort fix<commit_after>var _      = require('underscore')
var async  = require('async')
var op     = require('object-path')
var router = require('express').Router()

var entu   = require('../helpers/entu')

router.get('/requests', function(req, res) {
    var limit = req.query.limit || 5
    var days = req.query.days || 7

    var today = new Date();
    var lastWeek = new Date(today.getFullYear(), today.getMonth(), today.getDate() - days);

    async.waterfall([
        function(callback) {
            entu.dbConnection('entu', callback)
        },
        function(connection, callback) {
            connection.collection('request').aggregate([
            	{
            		'$match' : {
                		date: {
                    		$gt: lastWeek
                		}
            		}
            	},
            	{
            		'$group' : {
            			_id: {
                            host: '$host',
                            month: { $month: '$date' },
                            day: { $dayOfMonth: '$date' },
                            year: { $year: '$date' }
                        },
            			count: {
            				$sum: 1
            			}
            		}
            	}
            ]).toArray(callback)
        },
        function(result, callback) {

            var seriesData = {}
            for (var i in result) {
                if(!result.hasOwnProperty(i)) { continue }

                var host = op.get(result[i], '_id.host')
                var day = '00' + op.get(result[i], '_id.day')
                var day = day.substr(day.length - 2)
                var month = '00' + op.get(result[i], '_id.month')
                var month = month.substr(month.length - 2)
                var year = op.get(result[i], '_id.year')

                var date = [year, month, day].join('-')
                var count = op.get(result[i], 'count')

                op.set(seriesData, [host, 'sum'], op.get(seriesData, [host, 'sum'], 0) + count)
                op.set(seriesData, [host, 'name'], host)
                op.push(seriesData, [host, 'data'], [date, count])
                op.set(seriesData, [host, 'incomplete_from'], today.toISOString().substr(0, 10))
            }

            var graphData = {
                x_axis: {
                    type: 'datetime'
                },
                seriesData: seriesData,
                seriesDataValues: seriesDataValues,
                seriesDataValuesSorted: seriesDataValuesSorted,
                series: _.sortBy(_.values(seriesData), 'sum').reverse().slice(0, limit)
            }

            callback(null, graphData)
        },
    ], function(err, result) {
        if(err) {
            res.send({
                error: err,
                version: APP_VERSION,
                started: APP_STARTED
            })
        } else {
            res.send(result)
        }
    })
})

router.get('/test', function() {
    throw new Error('böö')
})

module.exports = router
<|endoftext|>


<commit_before>'use strict';

let app = require('../app');
let express = require('express');
let pg_tool = require('../bin/pg_tool');
let redis_tool = require('../bin/redis_tool');
let session_tool = require('../bin/session_tool');
const mdb_key = require('../bin/secret_settings').api_settings.mdb_key;
let checkInput = require('../bin/validator_tool').checkInput;
let multer  = require('multer');
let upload = multer({ dest: 'uploads/' });
let fs = require('fs');
let csv = require('csv-parse');

const state_re = /^[a-zA-Z]{2}$/;
const comment_re = /^(\w| |-|@|!|&|\(|\)|#|_|\+|%|\^|\$|\*|'|\"|\?|\.)*$/;
const file_re = /^\w(\w|-|\.| ){0,250}\.csv$/;

let router = express.Router();

router.get('/', function(req, res) {
  try {
    req.session.mdb_key = mdb_key;
    res.render('submit');
  }
  catch (error) {
    console.log(error);
    res.render('error');
  }
});

router.post('/', function(req, res) {
  let result;
  try {
    if (req.session.mdb_key === mdb_key) {
      if (checkInput(req.body.year,'number',null) && checkInput(req.body.state,'string',state_re) && checkInput(req.body.county,'number',null) && checkInput(req.body.species,'number',null) && checkInput(req.body.trap,'number',null) && checkInput(req.body.wnv_results,'number',null) && checkInput(req.body.pools,'number',null)) {
        let errs = 'Invalid Parameter(s): ';
        let curr_date = new Date();
        let year = Number(req.body.year);
        if (year < 1900 || year > curr_date.getFullYear()) {
          errs += 'year ';
        }
        let month = null;
        if (req.body.month) {
          if (checkInput(req.body.month,'number',null)) {
            month = Number(req.body.month);
            if (month < 1 || month > 12) {
              errs += 'month ';
            }
          }
          else {
            errs += 'month ';
          }
        }
        let week = null;
        if (req.body.week) {
          if (checkInput(req.body.week,'number',null)) {
            week = Number(req.body.week);
            if (week < 1 || week > 52) {
              errs += 'week ';
            }
          }
          else {
            errs += 'week ';
          }
        }
        let state = (req.body.state + '').toUpperCase();
        let county = Number(req.body.county);
        let species = Number(req.body.species);
        let trap = Number(req.body.trap);
        let pools = Number(req.body.pools);
        if (pools < 0) {
          errs += 'pools ';
        }
        let individuals = null;
        if (req.body.individuals) {
          if (checkInput(req.body.individuals,'number',null)) {
            individuals = Number(req.body.individuals);
            if (individuals < 0) {
              errs += 'individuals ';
            }
          }
          else {
            errs += 'individuals ';
          }
        }
        let nights = null;
        if (req.body.nights) {
          if (checkInput(req.body.nights,'number',null)) {
            nights = Number(req.body.nights);
            if (nights < 1 || nights > 32766) {
              errs += 'nights ';
            }
          }
          else {
            errs += 'nights ';
          }
        }
        let wnv = Number(req.body.wnv_results);
        if (wnv < 0) {
          errs += 'wnv_results ';
        }
        let comment = null;
        if (req.body.comment) {
          if (checkInput(req.body.comment,'string',comment_re)) {
            comment = req.body.comment + '';
          }
          else {
            errs += 'comment ';
          }
        }
        if (errs === 'Invalid Parameter(s): ') {
          pg_tool.query('insert_collection', [year,month,week,state,county,trap,species,pools,individuals,nights,wnv,comment], function(error, rows) {
            if (error) {
              result = {
                "status": 500,
                "error": 'Server Error'
              };
              res.status(result.status).send(result);
            }
            else {
              result = {
                "status": 201,
                "message": "Collection Successfully Submitted"
              }
              res.status(result.status).send(result);
            }
          });
        }
        else {
          result = {
            "status": 400,
            "error": errs.trim()
          }
          res.status(result.status).send(result);
        }
      }
      else {
        result = {
          "status": 400,
          "error": "Invalid Parameter(s): "
        }
        if (!checkInput(req.body.year,'number',null)) {
          result.error += 'year ';
        }
        if (!checkInput(req.body.state,'string',state_re)) {
          result.error += 'state ';
        }
        if (!checkInput(req.body.county,'number',null)) {
          result.error += 'county ';
        }
        if (!checkInput(req.body.species,'number',null)) {
          result.error += 'species ';
        }
        if (!checkInput(req.body.trap,'number',null)) {
          result.error += 'trap ';
        }
        if (!checkInput(req.body.pools,'number',null)) {
          result.error += 'pools ';
        }
        if (!checkInput(req.body.wnv_results,'number',null)) {
          result.error += 'wnv_results ';
        }
        result.error = result.error.trim();
        res.status(result.status).send(result);
      }
    }
    else {
      result = {
        "status": 401,
        "error": "Unauthorized Request"
      }
      res.status(result.status).send(result);
    }
  }
  catch (error) {
    console.log(error);
    result = {
      "status": 500,
      "error": "Server Error"
    };
    res.status(result.status).send(result);
  }
});

router.post('/upload', upload.single('mosquitoFile'), function (req, res) {
  let result;
  try {
    if (req.session.mdb_key === mdb_key) {
      if (req.file) {
        fs.createReadStream(req.file.path).pipe(csv()).on('data', function(line) {
          if (line) {
            let items = "Row: ";
            line.forEach(function(item) {
              items+=item;
            })
            console.log(items);
          }
        });
        fs.unlink(req.file.path, function(err) {
          console.log(err);
        });
        result = {
          "status": 202,
          "message": "File Successfully Submitted"
        };
        res.status(result.status).send(result);
      }
      else {
        result = {
          "status": 400,
          "error": "Missing File"
        };
        res.status(result.status).send(result);
      }
    }
    else {
      fs.unlink(req.file.path, function(err) {
        console.log(err);
      });
      result = {
        "status": 401,
        "error": "Unauthorized Request"
      }
      res.status(result.status).send(result);
    }
  }
  catch (error) {
    console.log(error);
    result = {
      "status": 500,
      "error": "Server Error"
    };
    res.status(result.status).send(result);
  }
});

module.exports = router;
<commit_msg>added handling for csv uploads<commit_after>'use strict';

let app = require('../app');
let express = require('express');
let pg_tool = require('../bin/pg_tool');
let redis_tool = require('../bin/redis_tool');
let session_tool = require('../bin/session_tool');
const mdb_key = require('../bin/secret_settings').api_settings.mdb_key;
let checkInput = require('../bin/validator_tool').checkInput;
let multer  = require('multer');
let upload = multer({ dest: 'uploads/' });
let fs = require('fs');
let csv = require('csv-parse');
let async_loop = require('node-async-loop');

const state_re = /^[a-zA-Z]{2}$/;
const comment_re = /^(\w| |-|@|!|&|\(|\)|#|_|\+|%|\^|\$|\*|'|\"|\?|\.)*$/;
const file_re = /^\w(\w|-|\.| ){0,250}\.csv$/;
const base_error = 'Invalid Parameter(s): ';

let router = express.Router();

router.get('/', function(req, res) {
  try {
    req.session.mdb_key = mdb_key;
    res.render('submit');
  }
  catch (error) {
    console.log(error);
    res.render('error');
  }
});

router.post('/', function(req, res) {
  let result;
  try {
    if (req.session.mdb_key === mdb_key) {
      if (checkInput(req.body.year,'number',null) && checkInput(req.body.state,'string',state_re) && checkInput(req.body.county,'number',null) && checkInput(req.body.species,'number',null) && checkInput(req.body.trap,'number',null) && checkInput(req.body.wnv_results,'number',null) && checkInput(req.body.pools,'number',null)) {
        let errs = base_error;
        let curr_date = new Date();
        let year = Number(req.body.year);
        if (year < 1900 || year > curr_date.getFullYear()) {
          errs += 'year ';
        }
        let month = null;
        if (req.body.month) {
          if (checkInput(req.body.month,'number',null)) {
            month = Number(req.body.month);
            if (month < 1 || month > 12) {
              errs += 'month ';
            }
          }
          else {
            errs += 'month ';
          }
        }
        let week = null;
        if (req.body.week) {
          if (checkInput(req.body.week,'number',null)) {
            week = Number(req.body.week);
            if (week < 1 || week > 52) {
              errs += 'week ';
            }
          }
          else {
            errs += 'week ';
          }
        }
        let state = (req.body.state + '').toUpperCase();
        let county = Number(req.body.county);
        let species = Number(req.body.species);
        let trap = Number(req.body.trap);
        let pools = Number(req.body.pools);
        if (pools < 0) {
          errs += 'pools ';
        }
        let individuals = null;
        if (req.body.individuals) {
          if (checkInput(req.body.individuals,'number',null)) {
            individuals = Number(req.body.individuals);
            if (individuals < 0) {
              errs += 'individuals ';
            }
          }
          else {
            errs += 'individuals ';
          }
        }
        let nights = null;
        if (req.body.nights) {
          if (checkInput(req.body.nights,'number',null)) {
            nights = Number(req.body.nights);
            if (nights < 1 || nights > 32766) {
              errs += 'nights ';
            }
          }
          else {
            errs += 'nights ';
          }
        }
        let wnv = Number(req.body.wnv_results);
        if (wnv < 0) {
          errs += 'wnv_results ';
        }
        let comment = null;
        if (req.body.comment) {
          if (checkInput(req.body.comment,'string',comment_re)) {
            comment = req.body.comment + '';
          }
          else {
            errs += 'comment ';
          }
        }
        if (errs === base_error) {
          pg_tool.query('insert_collection', [year,month,week,state,county,trap,species,pools,individuals,nights,wnv,comment], function(error, rows) {
            if (error) {
              result = {
                "status": 500,
                "error": 'Server Error'
              };
              res.status(result.status).send(result);
            }
            else {
              result = {
                "status": 201,
                "message": "Collection Successfully Submitted"
              }
              res.status(result.status).send(result);
            }
          });
        }
        else {
          result = {
            "status": 400,
            "error": errs.trim()
          }
          res.status(result.status).send(result);
        }
      }
      else {
        result = {
          "status": 400,
          "error": "Invalid Parameter(s): "
        }
        if (!checkInput(req.body.year,'number',null)) {
          result.error += 'year ';
        }
        if (!checkInput(req.body.state,'string',state_re)) {
          result.error += 'state ';
        }
        if (!checkInput(req.body.county,'number',null)) {
          result.error += 'county ';
        }
        if (!checkInput(req.body.species,'number',null)) {
          result.error += 'species ';
        }
        if (!checkInput(req.body.trap,'number',null)) {
          result.error += 'trap ';
        }
        if (!checkInput(req.body.pools,'number',null)) {
          result.error += 'pools ';
        }
        if (!checkInput(req.body.wnv_results,'number',null)) {
          result.error += 'wnv_results ';
        }
        result.error = result.error.trim();
        res.status(result.status).send(result);
      }
    }
    else {
      result = {
        "status": 401,
        "error": "Unauthorized Request"
      }
      res.status(result.status).send(result);
    }
  }
  catch (error) {
    console.log(error);
    result = {
      "status": 500,
      "error": "Server Error"
    };
    res.status(result.status).send(result);
  }
});

router.post('/upload', upload.single('mosquitoFile'), function (req, res) {
  let result;
  try {
    if (req.session.mdb_key === mdb_key) {
      if (req.file) {
        let submissions = [];
        let errors = [];
        let line_num = 0;
        fs.createReadStream(req.file.path).pipe(csv())
        .on('data', function(line) {
          if (line && line[0] != 'year') {
            line_num++;
            try {
              let line_error = base_error;
              let submission = {
                "line": line_num,
                "year": null,
                "month": null,
                "week": null,
                "state": null,
                "county": null,
                "species": null,
                "trap": null,
                "pools": null,
                "individuals": null,
                "nights": null,
                "wnv": null,
                "comment": null
              };
              if (checkInput(line[0],'number',null)) {
                submission.year = Number(line[0]);
              }
              else {
                line_error += "year ";
              }
              if (line[1]) {
                if (checkInput(line[1],'number',null)) {
                  submission.month = Number(line[1]);
                }
                else {
                  line_error += "month ";
                }
              }
              if (line[2]) {
                if (checkInput(line[2],'number',null)) {
                  submission.week = Number(line[2]);
                }
                else {
                  line_error += "week ";
                }
              }
              if (checkInput(line[3].trim(),'string',state_re)) {
                submission.state = (line[3].trim() + "").toUpperCase();
              }
              else {
                line_error += "state ";
              }
              if (checkInput(line[4],'number',null)) {
                submission.county = Number(line[4]);
              }
              else {
                line_error += "county ";
              }
              if (checkInput(line[5],'number',null)) {
                submission.species = Number(line[5]);
              }
              else {
                line_error += "species ";
              }
              if (checkInput(line[6],'number',null)) {
                submission.trap = Number(line[6]);
              }
              else {
                line_error += "trap ";
              }
              if (checkInput(line[7],'number',null)) {
                submission.pools = Number(line[7]);
              }
              else {
                line_error += "pools ";
              }
              if (line[8]) {
                if (checkInput(line[8],'number',null)) {
                  submission.individuals = Number(line[8]);
                }
                else {
                  line_error += "individuals ";
                }
              }
              if (line[9]) {
                if (checkInput(line[9],'number',null)) {
                  submission.nights = Number(line[9]);
                }
                else {
                  line_error += "nights ";
                }
              }
              if (checkInput(line[10],'number',null)) {
                submission.wnv = Number(line[10]);
              }
              else {
                line_error += "wnv ";
              }
              if (line[11]) {
                if (checkInput(line[11],'string',comment_re)) {
                  submission.comment = line[11].trim() + "";
                }
                else {
                  line_error += "comment ";
                }
              }
              if (line_error === base_error) {
                submissions.push(submission);
              }
              else {
                errors.push({
                  line: line_num,
                  error: line_error
                });
              }
            }
            catch (err) {
              console.log(err);
              errors.push({
                line: line_num,
                error: 'Error Parsing Line'
              });
            }
          }
        })
        .on('end',function() {
          console.log('done reading csv');
          processSubmissions(submissions, function(errs) {
            for (let i = 0; i < errs.length; i++) {
              errors.push(errs[i]);
            }
            fs.unlink(req.file.path, function(err) {
              console.log(err);
            });
            result = {
              "status": 202,
              "message": "File Successfully Submitted",
              "errors": errors
            };
            res.status(result.status).send(result);
          });
        });
      }
      else {
        result = {
          "status": 400,
          "error": "Missing File"
        };
        res.status(result.status).send(result);
      }
    }
    else {
      fs.unlink(req.file.path, function(err) {
        console.log(err);
      });
      result = {
        "status": 401,
        "error": "Unauthorized Request"
      }
      res.status(result.status).send(result);
    }
  }
  catch (error) {
    console.log(error);
    result = {
      "status": 500,
      "error": "Server Error"
    };
    res.status(result.status).send(result);
  }
});

function processSubmissions(submissions, callback) {
  let errors = [];
  async_loop(submissions, function (submission, next) {
    if (submission) {
      try {
        pg_tool.query('insert_collection', [submission.year,submission.month,submission.week,submission.state,submission.county,submission.trap,submission.species,submission.pools,submission.individuals,submission.nights,submission.wnv,submission.comment], function(error, rows) {
          if (error) {
            console.log('CSV Insertion Error: ',error);
            let err = {
              "line": submission.line,
              "error": 'Insertion Error'
            };
            errors.push(err);
          }
          next();
        });
      }
      catch (error) {
        console.log('CSV Insertion Error: ',error);
        let err = {
          "line": submission.line,
          "error": 'Insertion Error'
        };
        errors.push(err);
        next();
      }
    }
  }, function () {
    callback(errors);
  });
}

module.exports = router;
<|endoftext|>


<commit_before>var operations = require('../operations');
var queueReq = operations.queueReq;
var multiparty = require('multiparty');
var express = require('express');
var upload = express.Router();
var Recaptcha = require('recaptcha').Recaptcha;
var rc_public = process.env.RECAPTCHA_PUBLIC_KEY;
var rc_secret = process.env.RECAPTCHA_SECRET_KEY;
var recaptcha = new Recaptcha(rc_public, rc_secret);
upload.get("/", function(req, res) {
    res.render("upload", {
        recaptcha_form: recaptcha.toHTML(),
    });
});
upload.post("/", function(req, res) {
    if (req.session.captcha_verified || process.env.NODE_ENV === "test") {
        req.session.captcha_verified = false; //Set back to false
        var form = new multiparty.Form();
        form.parse(req, function(err, fields, files) {
            if (err) {
                return close(err);
            }
            if (fields.match_id) {
                var match_id = Number(fields.match_id[0]);
                console.log(match_id);
                queueReq("api_details", {
                    match_id: match_id,
                    request: true,
                    priority: "high"
                }, close);
            }
            if (files.replay) {
                var fileName = files.replay[0].path;
                console.log(fileName);
                queueReq("parse", {
                    fileName: fileName,
                    upload: true,
                    priority: "high"
                }, close);
            }
        });
    }

    function close(err, job) {
        if (job && process.env.NODE_ENV !== "test") {
            console.log(job.data.payload);
            job.on("complete", function(result) {
                if (result.error) {
                    return res.render("upload", {
                        error:  result.error,
                        recaptcha_form: recaptcha.toHTML()
                    });
                }
                else {
                    return res.redirect("matches/" + result.match_id);
                }
            });
        }
        else {
            return res.render("upload", {
                error: err,
                recaptcha_form: recaptcha.toHTML()
            });
        }
    }
});
module.exports = upload;<commit_msg>clear cache on upload<commit_after>var operations = require('../operations');
var queueReq = operations.queueReq;
var multiparty = require('multiparty');
var express = require('express');
var redis = require('../redis').client;
var upload = express.Router();
var Recaptcha = require('recaptcha').Recaptcha;
var rc_public = process.env.RECAPTCHA_PUBLIC_KEY;
var rc_secret = process.env.RECAPTCHA_SECRET_KEY;
var recaptcha = new Recaptcha(rc_public, rc_secret);
upload.get("/", function(req, res) {
    res.render("upload", {
        recaptcha_form: recaptcha.toHTML(),
    });
});
upload.post("/", function(req, res) {
    if (req.session.captcha_verified || process.env.NODE_ENV === "test") {
        req.session.captcha_verified = false; //Set back to false
        var form = new multiparty.Form();
        form.parse(req, function(err, fields, files) {
            if (err) {
                return close(err);
            }
            if (fields.match_id) {
                var match_id = Number(fields.match_id[0]);
                console.log(match_id);
                queueReq("api_details", {
                    match_id: match_id,
                    request: true,
                    priority: "high"
                }, close);
            }
            if (files.replay) {
                var fileName = files.replay[0].path;
                console.log(fileName);
                queueReq("parse", {
                    fileName: fileName,
                    upload: true,
                    priority: "high"
                }, close);
            }
        });
    }

    function close(err, job) {
        if (job && process.env.NODE_ENV !== "test") {
            console.log(job.data.payload);
            job.on("complete", function(result) {
                if (result.error) {
                    return res.render("upload", {
                        error:  result.error,
                        recaptcha_form: recaptcha.toHTML()
                    });
                }
                else {
                    // clear the cache
                    redis.del("match:" + result.match_id, function(err, resp) {
                        return res.redirect("matches/" + result.match_id);
                    });
                }
            });
        }
        else {
            return res.render("upload", {
                error: err,
                recaptcha_form: recaptcha.toHTML()
            });
        }
    }
});
module.exports = upload;<|endoftext|>


<commit_before>var defer = require('promised-io/promise').defer;
var when = require('promised-io/promise').when;
var debug = require('debug')('p3api-server:msa');
var ChildProcess = require("child_process");
var config = require("../config");
var request = require('request');
var distributeURL = config.get("distributeURL");
var Temp = require('temp');
var fs = require('fs-extra');

function runQuery(query,opts){
	debug("Query: ", query)
	var def = new defer();

	debug("Send Request to distributeURL: ", distributeURL + "genome_feature");
	debug("runQuery: ", query);
	request.post({
		url: distributeURL + "genome_feature/",
		headers: {
			"content-type": "application/rqlquery+x-www-form-urlencoded",
			"accept": "text/tsv",
            "Authorization": opts.token || ""
		},
		body: query
	}, function(err,r,body){
		//debug("Distribute RESULTS: ", body);

		if (err){
			return def.reject(err);
		}

		//if (body && typeof body=="string"){
		//	body = JSON.parse(body)
		//}
		def.resolve(body);
	});

	return def.promise;
}

function buildGraph(annotations,opts){
	var def = new defer();
	var d = [];
	var errorClosed;

	debug("Run Panaconda");
	var child = ChildProcess.spawn("python", ["/Users/anwarren/projects/git_repos/cid_work/p3api/pangenome_graphs/fam_to_graph.py", "--"+opts.alpha, "--layout"],{
		stdio: [
			'pipe',
			'pipe', // pipe child's stdout to parent
      		'pipe'
      	]
    });

	child.stdout.on("data", function(data){
		debug("Panaconda done");
		d.push(data.toString());
	})

	child.stderr.on("data", function(errData){
		debug("Panaconda STDERR Data: ", errData.toString());
	})

	child.on("error", function(err){
		errorClosed = true;
		def.reject(err);
	})

	child.on('close', function(code){
		debug("Panaconda Process closed.", code);
		if (!errorClosed) {
			def.resolve(d.join(""));
		}
	})

	child.stdin.write(annotations,"utf8");
	child.stdin.end();

	return def.promise;
}

module.exports = {
	requireAuthentication: false,
	validate: function(params,req,res){
		//validate parameters here
		return params && params[0] && params[1] && params[0].length>1 && params[1].length>1;
	},
	execute: function(params,req,res){
		var def = new defer()
		// console.log("Execute MSA: ", params)
		var query = params[0];
        var alpha = params[1];
		var opts = {req: req, user: req.user, token:req.headers.authorization, alpha:alpha}

		when(runQuery(query,opts), function(annotations){
			when(buildGraph(annotations,opts), function(graph){
                    def.resolve({
                        graph: graph
                    })
			}, function(err){
			def.reject("Failure to build pg-graph: " + err);
		    })
		}, function(err){
			def.reject("Unable To retreive annotations for pg-graph: " + err);
		});
		return def.promise;
	}
}
<commit_msg>adding more parameters to panaconda analysis<commit_after>var defer = require('promised-io/promise').defer;
var when = require('promised-io/promise').when;
var debug = require('debug')('p3api-server:msa');
var ChildProcess = require("child_process");
var config = require("../config");
var request = require('request');
var distributeURL = config.get("distributeURL");
var Temp = require('temp');
var fs = require('fs-extra');

function runQuery(query,opts){
	debug("Query: ", query)
	var def = new defer();

	debug("Send Request to distributeURL: ", distributeURL + "genome_feature");
	debug("runQuery: ", query);
	request.post({
		url: distributeURL + "genome_feature/",
		headers: {
			"content-type": "application/rqlquery+x-www-form-urlencoded",
			"accept": "text/tsv",
            "Authorization": opts.token || ""
		},
		body: query
	}, function(err,r,body){
		//debug("Distribute RESULTS: ", body);

		if (err){
			return def.reject(err);
		}

		//if (body && typeof body=="string"){
		//	body = JSON.parse(body)
		//}
		def.resolve(body);
	});

	return def.promise;
}

function buildGraph(annotations,opts){
	var def = new defer();
	var d = [];
	var errorClosed;

	debug("Run Panaconda");
	var child = ChildProcess.spawn("python", ["/Users/anwarren/projects/git_repos/cid_work/p3api/pangenome_graphs/fam_to_graph.py",
            "--"+opts.alpha, "--layout", "--ksize",opts.ksize,"--diversity",opts.diversity,"--context",opts.context],{
		stdio: [
			'pipe',
			'pipe', // pipe child's stdout to parent
      		'pipe'
      	]
    });

	child.stdout.on("data", function(data){
		debug("Panaconda done");
		d.push(data.toString());
	})

	child.stderr.on("data", function(errData){
		debug("Panaconda STDERR Data: ", errData.toString());
	})

	child.on("error", function(err){
		errorClosed = true;
		def.reject(err);
	})

	child.on('close', function(code){
		debug("Panaconda Process closed.", code);
		if (!errorClosed) {
			def.resolve(d.join(""));
		}
	})

	child.stdin.write(annotations,"utf8");
	child.stdin.end();

	return def.promise;
}

module.exports = {
	requireAuthentication: false,
	validate: function(params,req,res){
		//validate parameters here
		return params && params[0] && params[1] && params[0].length>1 && params[1].length>1;
	},
	execute: function(params,req,res){
		var def = new defer()
		// console.log("Execute MSA: ", params)
		var query = params[0];
        var alpha = params[1];
        var ksize = params[2];
        var context = params[3];
        var diversity = params[4];
		var opts = {req: req, user: req.user, token:req.headers.authorization, alpha:alpha, ksize:ksize, context:context, diversity:diversity}

		when(runQuery(query,opts), function(annotations){
			when(buildGraph(annotations,opts), function(graph){
                    def.resolve({
                        graph: graph
                    })
			}, function(err){
			def.reject("Failure to build pg-graph: " + err);
		    })
		}, function(err){
			def.reject("Unable To retreive annotations for pg-graph: " + err);
		});
		return def.promise;
	}
}
<|endoftext|>


<commit_before>import seedClasses from '../utils/seed-classes';

const DEFAULT_OPTIONS = {
  combination: true,
  master: true,
  overwrite: false,
  frozen: false,
};

/**
 * Examples
 *
 *   var classFn = this.composeClasses('Foobar')
 *   div(class=classFn())
 *     div(class=classFn('&-buz))
 *     div(class=classFn('&-qux))
 *
 * Options
 *
 *   master: use the prop.className as the baseName if possible (default: true)
 *   combination: the component seed can be used together with a master baseName (default: true)
 *   overwrite: the master baseName overrules the component seed (default: false)
 *   frozen: the component seed overrules the master basename (default: false)
 *
 */

export function composeClasses(baseName, statuses, options) {
  if (process.env.NODE_ENV === 'development' && !baseName)
    return console.error('You must pass a `baseName`');

  var props = this.props;
  var classes = props.classes;
  var base = baseName;
  var opts = options
    ? Object.assign(DEFAULT_OPTIONS, options)
    : DEFAULT_OPTIONS;

  if (props.displayName) base = props.displayName;
  else if (opts.master && props.className) base = props.className;

  var fns = [];
  if (opts.frozen) {
    fns.push(seedClasses(baseName, statuses, classes));
  } else if (opts.overwrite) {
    fns.push(seedClasses(base, statuses, classes));
  } else {
    fns.push(seedClasses(base, statuses, classes));
    if (opts.combination && base !== baseName) {
      fns.push(seedClasses(baseName, statuses));
    }
  }

  return (n, sx) => filterUnique(fns.map((fn) => fn(n, sx))).join(' ');
}

function filterUnique(arr = []) {
  var u = {};
  return arr.filter(function (str) {
    if (u[str]) return false;
    return u[str] = 1;
  });
}

export default {composeClasses};
<commit_msg>use applyFns for de-duping<commit_after>import seedClasses from '../utils/seed-classes';

const DEFAULT_OPTIONS = {
  combination: true,
  master: true,
  overwrite: false,
  frozen: false,
};

/**
 * Examples
 *
 *   var classFn = this.composeClasses('Foobar')
 *   div(class=classFn())
 *     div(class=classFn('&-buz))
 *     div(class=classFn('&-qux))
 *
 * Options
 *
 *   master: use the prop.className as the baseName if possible (default: true)
 *   combination: the component seed can be used together with a master baseName (default: true)
 *   overwrite: the master baseName overrules the component seed (default: false)
 *   frozen: the component seed overrules the master basename (default: false)
 *
 */

export function composeClasses(baseName, statuses, options) {
  if (process.env.NODE_ENV === 'development' && !baseName)
    return console.error('You must pass a `baseName`');

  var props = this.props;
  var classes = props.classes;
  var base = baseName;
  var opts = options
    ? Object.assign(DEFAULT_OPTIONS, options)
    : DEFAULT_OPTIONS;

  if (props.displayName) base = props.displayName;
  else if (opts.master && props.className) base = props.className;

  var fns = [];
  if (opts.frozen) {
    fns.push(seedClasses(baseName, statuses, classes));
  } else if (opts.overwrite) {
    fns.push(seedClasses(base, statuses, classes));
  } else {
    fns.push(seedClasses(base, statuses, classes));
    if (opts.combination && base !== baseName) {
      fns.push(seedClasses(baseName, statuses));
    }
  }

  return applyFns.bind(null, fns);
}

function applyFns(fns, n, sx) {
  var classes = {};
  fns.forEach((fn) => classes[fn(n, sx)] = true);
  return Object.keys(classes).join(' ');
}

export default {composeClasses};
<|endoftext|>


<commit_before>var orm = require('../orm');

exports.findNotesByAuthor = function(userID, callback)
{
    var noteModel = orm.model('Note');

    noteModel.findAll({
        where: { author: userID }
    }).error(function(err)
        {
            return callback(err);
        }).success(function(notes)
        {
            return callback(null, notes);
        });
};

exports.findNotesByBoardID = function(boardID, callback)
{
    var noteModel = orm.model('Note');

    noteModel.findAll({
        where: { board_id: boardID }
    }).error(function(err)
        {
            return callback(err);
        }).success(function(notes)
        {
            return callback(null, notes);
        });
};

exports.createNote = function(boardID, title, body, userID, callback)
{
    var noteModel = orm.model('Note');

    noteModel.build({
        board_id: boardID,
        title: title,
        body: body,
        created: new Date(),
        author: userID
    }).save().error(function(err)
        {
            return callback(err);
        }).success(function(note)
        {
            return callback(null, note);
        });
}

exports.removeNoteByID = function(noteID, authorID, callback)
{
    var noteModel = orm.model('Note');

    noteModel.find({where: { id: noteID, author: authorID }}).error(function(error)
    {
        return callback(error);

    }).success(function(note)
        {
            if (!note)
            {
                return callback(null);
            }

            note.destroy().error(function(err)
            {
                return callback(err);

            }).success(function()
                {
                    return callback(null);
                })
        });
}

exports.updateNoteById = function(noteID, authorID, title, body, callback)
{
    var noteModel = orm.model('Note');

    var parameters =
    {
        title: title,
        body: body
    }

    var criteria =
    {
        id: noteID,
        author: authorID
    }

    noteModel.update(parameters, criteria).error(function(error)
    {
        return callback(error);

    }).success(function()
        {
            return callback(null);
        });
};<commit_msg>Fixed getting notes by author to only return private notes<commit_after>var orm = require('../orm');

exports.findNotesByAuthor = function(userID, callback)
{
    var noteModel = orm.model('Note');

    noteModel.findAll({
        where: { author: userID, board_id: null}
    }).error(function(err)
        {
            return callback(err);
        }).success(function(notes)
        {
            return callback(null, notes);
        });
};

exports.findNotesByBoardID = function(boardID, callback)
{
    var noteModel = orm.model('Note');

    noteModel.findAll({
        where: { board_id: boardID }
    }).error(function(err)
        {
            return callback(err);
        }).success(function(notes)
        {
            return callback(null, notes);
        });
};

exports.createNote = function(boardID, title, body, userID, callback)
{
    var noteModel = orm.model('Note');

    noteModel.build({
        board_id: boardID,
        title: title,
        body: body,
        created: new Date(),
        author: userID
    }).save().error(function(err)
        {
            return callback(err);
        }).success(function(note)
        {
            return callback(null, note);
        });
}

exports.removeNoteByID = function(noteID, authorID, callback)
{
    var noteModel = orm.model('Note');

    noteModel.find({where: { id: noteID, author: authorID }}).error(function(error)
    {
        return callback(error);

    }).success(function(note)
        {
            if (!note)
            {
                return callback(null);
            }

            note.destroy().error(function(err)
            {
                return callback(err);

            }).success(function()
                {
                    return callback(null);
                })
        });
}

exports.updateNoteById = function(noteID, authorID, title, body, callback)
{
    var noteModel = orm.model('Note');

    var parameters =
    {
        title: title,
        body: body
    }

    var criteria =
    {
        id: noteID,
        author: authorID
    }

    noteModel.update(parameters, criteria).error(function(error)
    {
        return callback(error);

    }).success(function()
        {
            return callback(null);
        });
};<|endoftext|>


<commit_before>if (Meteor.isClient) {

  Session.set('selectedhvaczone', null);
  Session.set('selectedlightingzone', null);

  hvaczones = function() {
    return _.uniq( _.filter( _.pluck(Rooms.find().fetch(), 'HVACZone'), function(o) { return o != null; }));
  };

  roomsForHVACZone = function(zone) {
    if (!zone) {
      return []
    }
    return _.pluck(Rooms.find({'HVACZone':zone}).fetch(), 'RoomNumber');
  };

  //TODO: where do we pull lighting zones from? there can be multiple in a room? What defines a lighting zone?
  lightingzones = function() {
    return _.uniq( _.filter( _.pluck(Rooms.find().fetch(), 'LightingZone'), function(o) { return o != null; }));
  };

  roomsForLightingZone = function(zone) {
    if (!zone) {
      return []
    }
    return _.pluck(Rooms.find({'LightingZone':zone}).fetch(), 'RoomNumber');
  };

  UI.registerHelper('fixPath', function(p) {
    return p.replace(/\//g,'_');
  });

  UI.registerHelper('hvaczones', function() {
    return hvaczones();
  });

  UI.registerHelper('lightingzones', function() {
    return lightingzones();
  });

  Template.status.sources = function() {
    /*
     * Grabs all the HVAC, Lighting and Monitoring points. These
     * have been configured, so we can read their metadata. Thanks
     * to the 'querysystem' function, thse are pre-aggregated by
     * their driver path instead of the individual timeseries
     */
    var sources = []
    sources.push.apply(sources, Lighting.find().fetch())
    sources.push.apply(sources, HVAC.find().fetch())
    sources.push.apply(sources, Monitoring.find().fetch())
    return sources;
  };

  Template.device.driverPath = function() {
    /*
     * From the driver module path (e.g. smap.drivers.lights.VirtualLightDriver),
     * we generate the URL to the code of the driver
     */
    var baseurl = "https://github.com/SoftwareDefinedBuildings/smap/tree/unitoftime/python";
    var components = this.driver.split('.');
    _.each(components, function(val, idx) {
      baseurl += '/' + val
    });
    baseurl += '.py';
    return baseurl;
  };

  //TODO: autopopulate with the current values
  Template.configuration.events({
    'click .btn-info': function(e) {
        var path = this.path;
        var fixedpath = this.path.replace(/\//g,'_');
    },

    'change .hvaczones': function(e, template) {
        Session.set('selectedhvaczone', template.find('.hvaczones').value);
    },

    'change .lightingzones': function(e, template) {
        Session.set('selectedlightingzone', template.find('.lightingzones').value);
    },

    'click .save': function(e, template) {
      //TODO: save this to mongo. `this` contains the mongo record, including ID
      var hvaczone = template.find('.hvaczones').value;
      var lightingzone = template.find('.lightingzones').value;
      var room = template.find('.rooms').value;
      var record = null;
      record = HVAC.findOne({'_id': this._id})
      if (record) {
        HVAC.update(this._id, {$set: {'zone': hvaczone, 'room': room}});
      }
      record = Lighting.findOne({'_id': this._id})
      if (record) {
        Lighting.update(this._id, {$set: {'zone': lightingzone, 'room': room}});
      }
      record = Monitoring.findOne({'_id': this._id})
      if (record) {
        Monitoring.update(this._id, {$set: {'lightingzone': lightingzone, 'hvaczone': hvaczone, 'room': room}});
      }
      //TODO: give notification of successful save

    }
  });

  Template.configuration.derivedrooms = function() {
    var ret = [];
    if (Session.get('selectedhvaczone') != null) {
      ret = roomsForHVACZone(Session.get('selectedhvaczone'));
    }
    return ret;
  };

  Template.contents.rendered = function() {
    $('#config_contents').empty();
    $('#config_contents').append("

");
    var items = [];
    _.each(this.data, function(val, idx) {
      items.push('
'+val+'
');
    });
    $('#config_contents').append(items.join(''));

  };

}
<commit_msg>save changes to mongo<commit_after>if (Meteor.isClient) {

  Session.set('selectedhvaczone', null);
  Session.set('selectedlightingzone', null);

  hvaczones = function() {
    return _.uniq( _.filter( _.pluck(Rooms.find().fetch(), 'HVACZone'), function(o) { return o != null; }));
  };

  roomsForHVACZone = function(zone) {
    if (!zone) {
      return []
    }
    return _.pluck(Rooms.find({'HVACZone':zone}).fetch(), 'RoomNumber');
  };

  //TODO: where do we pull lighting zones from? there can be multiple in a room? What defines a lighting zone?
  lightingzones = function() {
    return _.uniq( _.filter( _.pluck(Rooms.find().fetch(), 'LightingZone'), function(o) { return o != null; }));
  };

  roomsForLightingZone = function(zone) {
    if (!zone) {
      return []
    }
    return _.pluck(Rooms.find({'LightingZone':zone}).fetch(), 'RoomNumber');
  };

  UI.registerHelper('fixPath', function(p) {
    return p.replace(/\//g,'_');
  });

  UI.registerHelper('hvaczones', function() {
    return hvaczones();
  });

  UI.registerHelper('lightingzones', function() {
    return lightingzones();
  });

  Template.status.sources = function() {
    /*
     * Grabs all the HVAC, Lighting and Monitoring points. These
     * have been configured, so we can read their metadata. Thanks
     * to the 'querysystem' function, thse are pre-aggregated by
     * their driver path instead of the individual timeseries
     */
    var sources = []
    sources.push.apply(sources, Lighting.find().fetch())
    sources.push.apply(sources, HVAC.find().fetch())
    sources.push.apply(sources, Monitoring.find().fetch())
    return sources;
  };

  Template.device.driverPath = function() {
    /*
     * From the driver module path (e.g. smap.drivers.lights.VirtualLightDriver),
     * we generate the URL to the code of the driver
     */
    var baseurl = "https://github.com/SoftwareDefinedBuildings/smap/tree/unitoftime/python";
    var components = this.driver.split('.');
    _.each(components, function(val, idx) {
      baseurl += '/' + val
    });
    baseurl += '.py';
    return baseurl;
  };

  Template.configuration.events({
    'click .btn-info': function(e) {
        var path = this.path;
        var fixedpath = this.path.replace(/\//g,'_');
    },

    'change .hvaczones': function(e, template) {
        Session.set('selectedhvaczone', template.find('.hvaczones').value);
    },

    'change .lightingzones': function(e, template) {
        Session.set('selectedlightingzone', template.find('.lightingzones').value);
    },

    'click .save': function(e, template) {
      var hvaczone = template.find('.hvaczones').value;
      var lightingzone = template.find('.lightingzones').value;
      var room = template.find('.rooms').value;
      var record = null;
      record = HVAC.findOne({'_id': this._id})
      if (record) {
        HVAC.update(this._id, {$set: {'zone': hvaczone, 'room': room}});
      }
      record = Lighting.findOne({'_id': this._id})
      if (record) {
        Lighting.update(this._id, {$set: {'zone': lightingzone, 'room': room}});
      }
      record = Monitoring.findOne({'_id': this._id})
      if (record) {
        Monitoring.update(this._id, {$set: {'lightingzone': lightingzone, 'hvaczone': hvaczone, 'room': room}});
      }
      //TODO: give notification of successful save

    }
  });

  Template.configuration.rendered = function() {
      console.log("rendered",this);
      var myhvaczone = null;
      var mylightingzone = null;
      var path = this.data.path;
      record = HVAC.findOne({'_id': this.data._id})
      if (record) {
        myhvaczone = record.zone;
        mylightingzone = '';
      }
      record = Lighting.findOne({'_id': this.data._id})
      if (record) {
        myhvaczone = ''
        mylightingzone = record.zone;
      }
      record = Monitoring.findOne({'_id': this.data._id})
      if (record) {
        myhvaczone = record.hvaczone;
        mylightingzone = record.lightingzone;
      }
      console.log(myhvaczone, mylightingzone);
      $('.lightingzones').find('option').removeClass('selected')
      _.each($('.lightingzones').find('option'), function(val, idx) {
        if (val.value == mylightingzone) {
            mypath = path.replace(/\//g,'_');
            $('#device_'+mypath+' .lightingzones').val(val.value);
        }
      });
      $('.hvaczones').find('option').removeClass('selected')
      _.each($('.hvaczones').find('option'), function(val, idx) {
        if (val.value == myhvaczone) {
            mypath = path.replace(/\//g,'_');
            $('#device_'+mypath+' .hvaczones').val(val.value);
        }
      });
  };

  Template.configuration.derivedrooms = function() {
    var ret = [];
    if (Session.get('selectedhvaczone') != null) {
      ret = roomsForHVACZone(Session.get('selectedhvaczone'));
    }
    return ret;
  };

  Template.contents.rendered = function() {
    $('#config_contents').empty();
    $('#config_contents').append("

");
    var items = [];
    _.each(this.data, function(val, idx) {
      items.push('
'+val+'
');
    });
    $('#config_contents').append(items.join(''));

  };

}
<|endoftext|>


<commit_before>define(['Ti/_/browser', 'Ti/_/declare', 'Ti/_/UI/KineticScrollView', 'Ti/_/lang', 'Ti/_/dom', 'Ti/_/style', 'Ti/UI'],
	function(browser, declare, KineticScrollView, lang, dom, style, UI) {

	var setStyle = style.set,
		is = require.is,
		isDef = lang.isDef,
		unitize = dom.unitize,
		once = require.on.once,

		// Velocity bounds, used to make sure that animations don't become super long or super short
		minVelocity = 0.4,
		maxVelocity = 3,

		// This sets the minimum velocity that determines whether a swipe was a flick or a drag
		velocityThreshold = 0.4,

		// This determines the minimum distance scale (i.e. width divided by this value) before a flick requests a page turn
		minimumFlickDistanceScaleFactor = 200,

		// This determines the minimum distance scale (i.e. width divided by this value) before a drag requests a page turn
		minimumDragDistanceScaleFactor = 2;

	return declare('Ti.UI.ScrollableView', KineticScrollView, {

		constructor: function(){

			// Create the content container
			this._initKineticScrollView(UI.createView({
				left: 0,
				top: 0,
				width: UI.SIZE,
				height: '100%',
				layout: 'constrainingHorizontal'
			}), 'horizontal');

			// Create the paging control container
			this._add(this._pagingControlContainer = UI.createView({
				width: '100%',
				height: 20,
				bottom: 0,
				backgroundColor: 'black',
				opacity: 0,
				touchEnabled: false
			}));

			this._pagingControlContainer._add(this._pagingControlContentContainer = UI.createView({
				width: UI.SIZE,
				height: '100%',
				top: 0,
				touchEnabled: false,
				layout: 'constrainingHorizontal'
			}));

			// State variables
			this.properties.__values__.views = [];
			this._viewToRemoveAfterScroll = -1;

			require.on(this, 'postlayout', this._updateTranslation);
		},

		_handleDragStart: function() {
			var currentPage = this.currentPage;
			if (~currentPage) {
				this._showView(currentPage - 1);
				this._showView(currentPage);
				this._showView(currentPage + 1);
				this.fireEvent('dragstart');
				this._updatePagingControl(this.currentPage);
			}
		},

		_handleDrag: function(e) {
			var currentPage = this.currentPage,
				currentView = this.views[currentPage];
			if (currentView) {
				this.fireEvent('scroll', {
					currentPage: currentPage,
					currentPageAsFloat: currentPage - e.distanceX / currentView._measuredWidth,
					view: currentView
				});
				this._updatePagingControl(currentPage);
			}
		},

		_handleDragCancel: function() {
			var currentPage = this.currentPage;
			if (~currentPage) {
				this._hideView(currentPage - 1);
				this._showView(currentPage);
				this._hideView(currentPage + 1);
			}
		},

		_handleDragEnd: function(e, velocityX) {
			if (~this.currentPage && isDef(velocityX)) {
				velocityX = Math.max(minVelocity, Math.min(maxVelocity, velocityX));
				var self = this,
					views = self.views,
					currentPage = self.currentPage,
					distance = e.distanceX,
					normalizedWidth = views[currentPage]._measuredWidth / (Math.abs(velocityX) > velocityThreshold ?
						minimumFlickDistanceScaleFactor :
						minimumDragDistanceScaleFactor),
					destinationPosition,
					destination = views[currentPage],
					destinationIndex = currentPage;

				// Determine the animation characteristics
				if (distance > normalizedWidth && currentPage > 0) {
					// Previous page
					destinationIndex = currentPage - 1;
					distance = (destination = views[destinationIndex])._measuredLeft - self._currentTranslationX;
				} else if (distance < -normalizedWidth && currentPage < views.length - 1) {
					// Next page
					destinationIndex = currentPage + 1;
					distance = self._currentTranslationX - (destination = views[destinationIndex])._measuredLeft;
				}
				destinationPosition = -destination._measuredLeft;
				self._updatePagingControl(destinationIndex);

				// Fire the drag end event
				self.fireEvent('dragend', {
					currentPage: destinationIndex,
					view: destination
				});

				// Animate the view. Note: the 1.724 constance was calculated, not estimated. It is NOT for tweaking.
				// If tweaking is needed, tweak the velocity algorithm in KineticScrollView.
				self._animateToPosition(destinationPosition, 0, Math.abs(1.724 *
						(destinationPosition - self._currentTranslationX) / velocityX), UI.ANIMATION_CURVE_EASE_OUT, function(){
					destinationIndex !== currentPage - 1 && self._hideView(currentPage - 1);
					destinationIndex !== currentPage && self._hideView(currentPage);
					destinationIndex !== currentPage + 1 && self._hideView(currentPage + 1);
					self.properties.__values__.currentPage = destinationIndex;
					self._showView(destinationIndex);
					setTimeout(function(){
						self.fireEvent('scrollend',{
							currentPage: destinationIndex,
							view: destination
						});
					}, 1);
				});
			}
		},

		_hideView: function(index) {
			var views = this.views;
			index >= 0 && index < views.length && setStyle(views[index].domNode, 'display', 'none');
		},

		_showView: function(index) {
			var views = this.views;
			index >= 0 && index < views.length && setStyle(views[index].domNode, 'display', 'inherit');
		},

		addView: function(view){
			if (view) {
				this.views.push(view);
				this._contentContainer._add(view);
				if (this.views.length == 1) {
					this.properties.__values__.currentPage = 0;
				} else {
					setStyle(view.domNode, 'display', 'none');
				}
			}
		},

		removeView: function(view) {

			// Get and validate the location of the view
			var viewIndex = is(view,'Number') ? view : this.views.indexOf(view);
			if (viewIndex < 0 || viewIndex >= this.views.length) {
				return;
			}

			// Update the view if this view was currently visible
			if (viewIndex == this.currentPage && this.views.length !== 1) {
				this._viewToRemoveAfterScroll = viewIndex;
				this.scrollToView(viewIndex == this.views.length - 1 ? --viewIndex : ++viewIndex);
			} else {
				this._removeViewFromList(viewIndex);
			}
		},

		_removeViewFromList: function(viewIndex) {

			var contentContainer = this._contentContainer,
				self = this;

			// Update the current view if necessary once everything has been re-laid out.
			if (viewIndex < this.currentPage) {
				self.properties.__values__.currentPage--;
			}

			// Remove the view and update the paging control
			contentContainer._remove(self.views.splice(viewIndex,1)[0]);
			!self.views.length && (self.properties.__values__.currentPage = -1);
			once(UI, 'postlayout', function() {
				setTimeout(function(){
					self._updateTranslation();
				}, 1);
			});
			self._updatePagingControl(self.currentPage);
		},

		_updateTranslation: function() {
			~this.currentPage && this._setTranslation(-this.views[this.currentPage]._measuredLeft, 0);
		},

		scrollToView: function(view) {
			var viewIndex = is(view,'Number') ? view : this.views.indexOf(view),
				self = this;

			// Sanity check
			if (viewIndex < 0 || viewIndex >= this.views.length || viewIndex == this.currentPage) {
				return;
			}

			function scroll(){

				// Calculate the views to be scrolled
				var contentContainer = self._contentContainer,
					currentPage = self.currentPage,
					destination = -self.views[viewIndex]._measuredLeft,
					i,

					// Calculate a weighted duration so that larger views take longer to scroll.
					duration = 400 + 0.3 * (Math.abs(viewIndex - self.currentPage) * contentContainer._measuredWidth);

				// Make the views that will be seen visible
				if (currentPage < viewIndex) {
					for(i = currentPage + 1; i <= viewIndex; i++) {
						self._showView(i);
					}
				} else {
					for(i = viewIndex; i < currentPage; i++) {
						self._showView(i);
					}
				}

				// Animate the views
				self._updatePagingControl(viewIndex);
				self._animateToPosition(destination, 0, duration, UI.ANIMATION_CURVE_EASE_IN_OUT, function(){
					self.properties.__values__.currentPage = viewIndex;
					if (currentPage < viewIndex) {
						for(i = currentPage; i < viewIndex; i++) {
							self._hideView(i);
						}
					} else {
						for(i = viewIndex + 1; i <= currentPage; i++) {
							self._hideView(i);
						}
					}
					if (self._viewToRemoveAfterScroll !== -1) {
						destination += self.views[self._viewToRemoveAfterScroll]._measuredWidth;
						self._removeViewFromList(self._viewToRemoveAfterScroll);
						self._viewToRemoveAfterScroll = -1;
					}
					self.fireEvent('scrollend',{
						currentPage: viewIndex,
						view: self.views[viewIndex]
					});
				});
			}

			// If the scrollableView hasn't been laid out yet, we must wait until it is
			if (self._contentContainer.domNode.offsetWidth) {
				scroll();
			} else {
				once(self, 'postlayout', scroll);
			}
		},

		_showPagingControl: function() {
			if (!this.showPagingControl) {
				this._pagingControlContainer.opacity = 0;
				return;
			}
			if (this._isPagingControlActive) {
				return;
			}
			this._isPagingControlActive = true;
			this._pagingControlContainer.animate({
				duration: 250,
				opacity: 0.75
			});
			this.pagingControlTimeout > 0 && setTimeout(lang.hitch(this,function() {
				this._pagingControlContainer.animate({
					duration: 750,
					opacity: 0
				});
				this._isPagingControlActive = false;
			}),this.pagingControlTimeout);
		},

		_updatePagingControl: function(newIndex, hidePagingControl) {
			var contentContainer = this._pagingControlContentContainer,
				numViews = this.views.length,
				diameter = this.pagingControlHeight / 2;
			if (this.showPagingControl && (!this._isPagingControlActive || newIndex !== contentContainer._currentIndex ||
					numViews !== contentContainer._numViews || diameter !== contentContainer._diameter)) {
				contentContainer._currentIndex = newIndex;
				contentContainer._numViews = numViews;
				contentContainer._diameter = diameter;
				contentContainer._removeAllChildren();
				for (var i = 0; i < this.views.length; i++) {
					var indicator = UI.createView({
						width: diameter,
						height: diameter,
						left: 5,
						right: 5,
						backgroundColor: i === newIndex ? 'white' : 'grey',
						borderRadius: unitize(diameter / 2)
					});
					contentContainer._add(indicator);
				}
				hidePagingControl || this._showPagingControl();
			}
		},

		_defaultWidth: UI.FILL,

		_defaultHeight: UI.FILL,

		properties: {
			currentPage: {
				set: function(value, oldValue) {
					if (value >= 0 && value < this.views.length) {
						this.scrollToView(value);
						return value;
					}
					return oldValue;
				},
				value: -1
			},
			pagingControlColor: {
				set: function(value) {
					this._pagingControlContainer.backgroundColor = value;
					return value;
				},
				value: 'black'
			},
			pagingControlHeight: {
				set: function(value) {
					this._pagingControlContainer.height = value;
					return value;
				},
				value: 20
			},
			pagingControlTimeout: {
				set: function(value) {
					this.pagingControlTimeout === 0 && this._updatePagingControl();
					return value;
				},
				value: 1250
			},
			showPagingControl: {
				set: function(value) {
					this.pagingControlTimeout === 0 && this._updatePagingControl();
					return value;
				},
				value: false
			},
			views: {
				set: function(value) {

					// Value must be an array
					if (!is(value,'Array')) {
						return;
					}

					// Add the views to the content container
					var i = 0,
						len = value.length,
						contentContainer = this._contentContainer,
						view;
					contentContainer._removeAllChildren();
					for(; i < len; i++) {
						(view = value[i]).width = '100%';
						view.height = '100%';
						contentContainer._add(view);
					}
					this.properties.__values__.currentPage = len ? 0 : -1;

					return value;
				},
				post: function() {
					this._updatePagingControl(this.currentPage,true);
				}
			}
		}

	});

});<commit_msg>[TIMOB-12067] Replaced the old kinetic scrolling code with the new prototype code.<commit_after>define(['Ti/_/browser', 'Ti/_/declare', 'Ti/UI/View', 'Ti/_/lang', 'Ti/_/dom', 'Ti/_/style', 'Ti/UI'],
	function(browser, declare, View, lang, dom, style, UI) {

	var setStyle = style.set,
		is = require.is,
		unitize = dom.unitize,
		on = require.on,
		once = on.once,
		global = window,

		useTouch = 'ontouchstart' in global,

		// Maximum time that a gesture can be considered a flick
		maxFlickTime = 200,

		// Minimum distance that must be traveled to register the flick
		flickThreshold = 10;

	return declare('Ti.UI.ScrollableView', View, {

		constructor: function(){

			// Create the content container
			var containerDomNode,
				self = this;
			self._add(self._contentContainer = UI.createView({
				left: 0,
				top: 0,
				width: UI.SIZE,
				height: '100%',
				layout: 'constrainingHorizontal'
			}), 'horizontal');
			containerDomNode = self._contentContainer.domNode;

			// Create the paging control container
			self._add(self._pagingControlContainer = UI.createView({
				width: '100%',
				height: 20,
				bottom: 0,
				backgroundColor: 'black',
				opacity: 0,
				touchEnabled: false
			}));

			self._pagingControlContainer._add(self._pagingControlContentContainer = UI.createView({
				width: UI.SIZE,
				height: '100%',
				top: 0,
				touchEnabled: false,
				layout: 'constrainingHorizontal'
			}));

			// State variables
			self.properties.__values__.views = [];
			self._viewToRemoveAfterScroll = -1;

			on(self, 'postlayout', self._updateTranslation);

			on(containerDomNode, useTouch ? 'touchstart' : 'mousedown', function(e) {
				var startX = e.touches ? e.touches[0].clientX : e.clientX,
					startTime = Date.now(),
					currentX,
					mouseMoveListener = function(e) {
						var width = self._measuredWidth;
						e.preventDefault();
						currentX = e.touches ? e.touches[0].clientX : e.clientX;
						setStyle(containerDomNode, 'transform', 'translatez(0) translatex(' + ((self.currentPage * -width) + currentX - startX) + 'px)');
					},
					mouseUpListener = function(e) {
						var	now = Date.now(),
							isFlick = now - startTime < maxFlickTime,
							width = self._measuredWidth,
							currentPage = self.currentPage,
							thresholdMet = Math.abs(startX - currentX) > (isFlick ? flickThreshold : width / 2),
							props = self.properties.__values__;
						global.removeEventListener(useTouch ? 'touchmove' : 'mousemove', mouseMoveListener);
						global.removeEventListener(useTouch ? 'touchend' : 'mouseup', mouseUpListener);
						e.preventDefault();

						if (thresholdMet) {
							if (startX > currentX) {
								currentPage !== props.views.length - 1 && props.currentPage++;
							} else {
								currentPage !== 0 && props.currentPage--;
							}
						}
						setStyle(containerDomNode, 'transform', 'translatez(0) translatex(' + (self.currentPage * -width) + 'px)');
					};
				e.preventDefault();
				global.addEventListener(useTouch ? 'touchmove' : 'mousemove', mouseMoveListener);
				global.addEventListener(useTouch ? 'touchend' : 'mouseup', mouseUpListener);
			});
		},

		addView: function(view){
			if (view) {
				this.views.push(view);
				this._contentContainer._add(view);
				if (this.views.length == 1) {
					this.properties.__values__.currentPage = 0;
				} else {
					setStyle(view.domNode, 'display', 'none');
				}
			}
		},

		removeView: function(view) {

			// Get and validate the location of the view
			var viewIndex = is(view,'Number') ? view : this.views.indexOf(view);
			if (viewIndex < 0 || viewIndex >= this.views.length) {
				return;
			}

			// Update the view if this view was currently visible
			if (viewIndex == this.currentPage && this.views.length !== 1) {
				this._viewToRemoveAfterScroll = viewIndex;
				this.scrollToView(viewIndex == this.views.length - 1 ? --viewIndex : ++viewIndex);
			} else {
				this._removeViewFromList(viewIndex);
			}
		},

		_removeViewFromList: function(viewIndex) {

			var contentContainer = this._contentContainer,
				self = this;

			// Update the current view if necessary once everything has been re-laid out.
			if (viewIndex < this.currentPage) {
				self.properties.__values__.currentPage--;
			}

			// Remove the view and update the paging control
			contentContainer._remove(self.views.splice(viewIndex,1)[0]);
			!self.views.length && (self.properties.__values__.currentPage = -1);
			once(UI, 'postlayout', function() {
				setTimeout(function(){
					self._updateTranslation();
				}, 1);
			});
			self._updatePagingControl(self.currentPage);
		},

		scrollToView: function(view) {
			var viewIndex = is(view,'Number') ? view : this.views.indexOf(view),
				self = this;

			// Sanity check
			if (viewIndex < 0 || viewIndex >= this.views.length || viewIndex == this.currentPage) {
				return;
			}

			function scroll(){

				// Calculate the views to be scrolled
				var contentContainer = self._contentContainer,
					currentPage = self.currentPage,
					destination = -self.views[viewIndex]._measuredLeft,
					i,

					// Calculate a weighted duration so that larger views take longer to scroll.
					duration = 400 + 0.3 * (Math.abs(viewIndex - self.currentPage) * contentContainer._measuredWidth);

				// Make the views that will be seen visible
				if (currentPage < viewIndex) {
					for(i = currentPage + 1; i <= viewIndex; i++) {
						self._showView(i);
					}
				} else {
					for(i = viewIndex; i < currentPage; i++) {
						self._showView(i);
					}
				}

				// Animate the views
				self._updatePagingControl(viewIndex);
				self._animateToPosition(destination, 0, duration, UI.ANIMATION_CURVE_EASE_IN_OUT, function(){
					self.properties.__values__.currentPage = viewIndex;
					if (currentPage < viewIndex) {
						for(i = currentPage; i < viewIndex; i++) {
							self._hideView(i);
						}
					} else {
						for(i = viewIndex + 1; i <= currentPage; i++) {
							self._hideView(i);
						}
					}
					if (self._viewToRemoveAfterScroll !== -1) {
						destination += self.views[self._viewToRemoveAfterScroll]._measuredWidth;
						self._removeViewFromList(self._viewToRemoveAfterScroll);
						self._viewToRemoveAfterScroll = -1;
					}
					self.fireEvent('scrollend',{
						currentPage: viewIndex,
						view: self.views[viewIndex]
					});
				});
			}

			// If the scrollableView hasn't been laid out yet, we must wait until it is
			if (self._contentContainer.domNode.offsetWidth) {
				scroll();
			} else {
				once(self, 'postlayout', scroll);
			}
		},

		_showPagingControl: function() {
			if (!this.showPagingControl) {
				this._pagingControlContainer.opacity = 0;
				return;
			}
			if (this._isPagingControlActive) {
				return;
			}
			this._isPagingControlActive = true;
			this._pagingControlContainer.animate({
				duration: 250,
				opacity: 0.75
			});
			this.pagingControlTimeout > 0 && setTimeout(lang.hitch(this,function() {
				this._pagingControlContainer.animate({
					duration: 750,
					opacity: 0
				});
				this._isPagingControlActive = false;
			}),this.pagingControlTimeout);
		},

		_updatePagingControl: function(newIndex, hidePagingControl) {
			var contentContainer = this._pagingControlContentContainer,
				numViews = this.views.length,
				diameter = this.pagingControlHeight / 2;
			if (this.showPagingControl && (!this._isPagingControlActive || newIndex !== contentContainer._currentIndex ||
					numViews !== contentContainer._numViews || diameter !== contentContainer._diameter)) {
				contentContainer._currentIndex = newIndex;
				contentContainer._numViews = numViews;
				contentContainer._diameter = diameter;
				contentContainer._removeAllChildren();
				for (var i = 0; i < this.views.length; i++) {
					var indicator = UI.createView({
						width: diameter,
						height: diameter,
						left: 5,
						right: 5,
						backgroundColor: i === newIndex ? 'white' : 'grey',
						borderRadius: unitize(diameter / 2)
					});
					contentContainer._add(indicator);
				}
				hidePagingControl || this._showPagingControl();
			}
		},

		_defaultWidth: UI.FILL,

		_defaultHeight: UI.FILL,

		properties: {
			currentPage: {
				set: function(value, oldValue) {
					if (value >= 0 && value < this.views.length) {
						this.scrollToView(value);
						return value;
					}
					return oldValue;
				},
				value: -1
			},
			pagingControlColor: {
				set: function(value) {
					this._pagingControlContainer.backgroundColor = value;
					return value;
				},
				value: 'black'
			},
			pagingControlHeight: {
				set: function(value) {
					this._pagingControlContainer.height = value;
					return value;
				},
				value: 20
			},
			pagingControlTimeout: {
				set: function(value) {
					this.pagingControlTimeout === 0 && this._updatePagingControl();
					return value;
				},
				value: 1250
			},
			showPagingControl: {
				set: function(value) {
					this.pagingControlTimeout === 0 && this._updatePagingControl();
					return value;
				},
				value: false
			},
			views: {
				set: function(value) {

					// Value must be an array
					if (!is(value,'Array')) {
						return;
					}

					// Add the views to the content container
					var i = 0,
						len = value.length,
						contentContainer = this._contentContainer,
						view;
					contentContainer._removeAllChildren();
					for(; i < len; i++) {
						(view = value[i]).width = '100%';
						view.height = '100%';
						contentContainer._add(view);
					}
					this.properties.__values__.currentPage = len ? 0 : -1;

					return value;
				},
				post: function() {
					this._updatePagingControl(this.currentPage,true);
				}
			}
		}

	});

});<|endoftext|>


<commit_before>( function( mw, $ ) { "use strict";

mw.AdLoader = {
	// Vast response can return Wrapper that points to another vast
	// this varible holds the max number of redirects to follow
	maxRedirects: 5,
	currentCounter: 0,
	/**
	 * Get ad display configuration object from a url
	 *
	 * @param {string} adUrl
	 * 		The url which contains the xml ad payload
	 * @param {function} callback
	 * 		Function called with ad payload once ad content is loaded.
	 * @param {number} counter
	 * 		(optional) used to stop loading of ad after X redirects
	 */
	load: function( adUrl, callback, wrapped ){
		var _this = this;
		mw.log('AdLoader :: load Ad: ', adUrl);

		// Increase counter if the vast is wrapped, otherwise reset
		if( wrapped ) {
			this.currentCounter++;
		} else {
			this.currentCounter = 0;
		}

		// Stop loading of ad if the counter is bigger then max redirects
		if( this.currentCounter >= this.maxRedirects ) {
			mw.log("Error: Maximum nubmber of redirects is " + this.maxRedirects);
			callback({});
			return ;
		}

		// Make ajax request with fallback to proxy service
		new mw.ajaxProxy({
			url: adUrl,
			success: function( resultXML ) {
				_this.handleResult( resultXML, callback );
			},
			error: function( error ) {
				mw.log("Error: AdLoader failed to load:" + adUrl);
				callback({});
			}
		});
	},
	handleResult: function(data, callback ){
		var _this = this;
		// If our data is a string we need to parse it as XML
		if( typeof data === 'string' ) {
			// Clean everything before <?xml?> tag
			var xmlPosition = data.indexOf("<?xml");
			if( xmlPosition > 0 ) {
				var junk = data.substr(0,xmlPosition);
				data = data.replace(junk, '');
			}
			try{
				data = $.parseXML( data );
			} catch( error ){
				// error in parsing xml
			}
		}
		switch( _this.getAdFormat( data) ){
			case 'vast':
				// If we have lots of ad formats we could conditionally load them here:
				// 'mw.VastAdParser' is a dependency of adLoader
				mw.load( 'mw.VastAdParser', function(){
					mw.VastAdParser.parse( data, callback );
				});
				return ;
			break;
		}
		mw.log("Error: could not parse adFormat from add content: \n" + data);
		callback( false );
	},
	/**
	 * Get ad Format
	 * @param {string}
	 * 		The xml string of the ad contents
	 * @return
	 * @type {string}
	 * 		The type of string
	 */
	getAdFormat: function( xmlObject ){
		if( xmlObject.childNodes ){
			var rootNodeName = xmlObject.childNodes[0].nodeName;
		}
		if( rootNodeName && (
				rootNodeName.toLowerCase() == 'vast' ||
				rootNodeName.toLowerCase() == 'videoadservingtemplate' )
		){
			return 'vast';
		}
		return 'unknown';
	}
};
} )( window.mw, jQuery );
<commit_msg>modified comments<commit_after>( function( mw, $ ) { "use strict";

mw.AdLoader = {
	// Vast response can return Wrapper that points to another vast
	// this varible holds the max number of redirects to follow
	maxRedirects: 5,
	currentCounter: 0,
	/**
	 * Get ad display configuration object from a url
	 *
	 * @param {string} adUrl
	 * 		The url which contains the xml ad payload
	 * @param {function} callback
	 * 		Function called with ad payload once ad content is loaded.
	 * @param {boolean} wrapped
	 * 		(optional) used to increase the internal counter
	 */
	load: function( adUrl, callback, wrapped ){
		var _this = this;
		mw.log('AdLoader :: load Ad: ', adUrl);

		// Increase counter if the vast is wrapped, otherwise reset
		if( wrapped ) {
			this.currentCounter++;
		} else {
			this.currentCounter = 0;
		}

		// Stop loading of ad if the counter is bigger then max redirects
		if( this.currentCounter >= this.maxRedirects ) {
			mw.log("Error: The allowd number of redirects is " + this.maxRedirects);
			callback({});
			return ;
		}

		// Make ajax request with fallback to proxy service
		new mw.ajaxProxy({
			url: adUrl,
			success: function( resultXML ) {
				_this.handleResult( resultXML, callback );
			},
			error: function( error ) {
				mw.log("Error: AdLoader failed to load:" + adUrl);
				callback({});
			}
		});
	},
	handleResult: function(data, callback ){
		var _this = this;
		// If our data is a string we need to parse it as XML
		if( typeof data === 'string' ) {
			// Clean everything before <?xml?> tag
			var xmlPosition = data.indexOf("<?xml");
			if( xmlPosition > 0 ) {
				var junk = data.substr(0,xmlPosition);
				data = data.replace(junk, '');
			}
			try{
				data = $.parseXML( data );
			} catch( error ){
				// error in parsing xml
			}
		}
		switch( _this.getAdFormat( data) ){
			case 'vast':
				// If we have lots of ad formats we could conditionally load them here:
				// 'mw.VastAdParser' is a dependency of adLoader
				mw.load( 'mw.VastAdParser', function(){
					mw.VastAdParser.parse( data, callback );
				});
				return ;
			break;
		}
		mw.log("Error: could not parse adFormat from add content: \n" + data);
		callback( false );
	},
	/**
	 * Get ad Format
	 * @param {string}
	 * 		The xml string of the ad contents
	 * @return
	 * @type {string}
	 * 		The type of string
	 */
	getAdFormat: function( xmlObject ){
		if( xmlObject.childNodes ){
			var rootNodeName = xmlObject.childNodes[0].nodeName;
		}
		if( rootNodeName && (
				rootNodeName.toLowerCase() == 'vast' ||
				rootNodeName.toLowerCase() == 'videoadservingtemplate' )
		){
			return 'vast';
		}
		return 'unknown';
	}
};
} )( window.mw, jQuery );
<|endoftext|>