<commit_before>const mongoClient = require('mongodb').MongoClient;
const fs = require('fs');

/*// Environment file
var env = require('node-env-file');
env(__dirname + '/.env');*/

var url = 'mongodb://' + process.env.MONGO_DB_TOKEN + '@aslandb-shard-00-01-yened.mongodb.net:27017/grandlyon?ssl=true&authSource=admin';
const GrandLyonCollection = "grandlyonData";

exports.getData = function(table, query, callback) {
  // Connexion au serveur avec la méthode connect
  mongoClient.connect(url, function (err, db) {
    try{
      if (err) {
          return console.log('Connection failed', err);
      }
      console.log('Connexion successful on', "aslandb-shard-00-01-yened.mongodb.net:27017");
      console.log('Connected on db:', db.databaseName);

      // Nous allons travailler ici ...
      /*db.collection(table).find(query).toArray(function(err, collections) {
          if (err) {
            console.log(err);
          } else {
            return collections;
          }
      });*/
    db.collection(table).find(query).toArray(callback);

    } catch(error) {
      console.log("error");
      console.log(error);
    }
  });
}

exports.loadJSonData = function(filePath) {
  // Connexion au serveur avec la méthode connect
  mongoClient.connect(url, function (err, db) {
    try{
      if (err) {
          return console.log('Connection failed', err);
      }
        fs.readFile(filePath, 'utf8', function (err, data) {
          if (err) throw err;

          var json = JSON.parse(data);

          db.collection(GrandLyonCollection).insert(json, function(err, doc) {
              console.log("Load done");
          if(err) throw err;
          });
        });
    } catch(error) {
      console.log(error);
    }
  });
}

exports.replaceDocument = function (filePath) {
    // Connexion au serveur avec la méthode connect
    mongoClient.connect(url, function (err, db) {
        try {
            if (err) {
                return console.log('Connection failed', err);
            }
            fs.readFile(filePath, 'utf8', function (err, data) {
                if (err) throw err;

                var json = JSON.parse(data);

                db.collection(GrandLyonCollection).findOneAndReplace({ "doc_id": json.doc_id}, json, function (err, doc) {
                    console.log("Load done");
                    if (err) throw err;
                });
            });
        } catch (error) {
            console.log(error);
        }
    });
}

exports.insertData = function(table, object, callback) {
    // Connexion au serveur avec la méthode connect
    mongoClient.connect(url, function (err, db) {
        try{
            if (err) {
                callback(err, null);
                return console.log('Connection failed', err);
            } else {
                console.log('Connexion successful on', "aslandb-shard-00-01-yened.mongodb.net:27017");
                console.log('Connected on db:', db.databaseName);
                db.collection(table).insert(object, null, callback);
            }
        } catch(error) {
            console.log("error");
            console.log(error);
            callback(error, null);
        }
    });
}
<commit_msg>Correction fonction insert<commit_after>const mongoClient = require('mongodb').MongoClient;
const fs = require('fs');

/*// Environment file
var env = require('node-env-file');
env(__dirname + '/.env');*/

var url = 'mongodb://' + process.env.MONGO_DB_TOKEN + '@aslandb-shard-00-01-yened.mongodb.net:27017/grandlyon?ssl=true&authSource=admin';
const GrandLyonCollection = "grandlyonData";

exports.getData = function(table, query, callback) {
  // Connexion au serveur avec la méthode connect
  mongoClient.connect(url, function (err, db) {
    try{
      if (err) {
          return console.log('Connection failed', err);
      }
      console.log('Connexion successful on', "aslandb-shard-00-01-yened.mongodb.net:27017");
      console.log('Connected on db:', db.databaseName);

      // Nous allons travailler ici ...
      /*db.collection(table).find(query).toArray(function(err, collections) {
          if (err) {
            console.log(err);
          } else {
            return collections;
          }
      });*/
    db.collection(table).find(query).toArray(callback);

    } catch(error) {
      console.log("error");
      console.log(error);
    }
  });
}

exports.loadJSonData = function(filePath) {
  // Connexion au serveur avec la méthode connect
  mongoClient.connect(url, function (err, db) {
    try{
      if (err) {
          return console.log('Connection failed', err);
      }
        fs.readFile(filePath, 'utf8', function (err, data) {
          if (err) throw err;

          var json = JSON.parse(data);

          db.collection(GrandLyonCollection).insert(json, function(err, doc) {
              console.log("Load done");
          if(err) throw err;
          });
        });
    } catch(error) {
      console.log(error);
    }
  });
}

exports.replaceDocument = function (filePath) {
    // Connexion au serveur avec la méthode connect
    mongoClient.connect(url, function (err, db) {
        try {
            if (err) {
                return console.log('Connection failed', err);
            }
            fs.readFile(filePath, 'utf8', function (err, data) {
                if (err) throw err;

                var json = JSON.parse(data);

                db.collection(GrandLyonCollection).findOneAndReplace({ "doc_id": json.doc_id}, json, function (err, doc) {
                    console.log("Load done");
                    if (err) throw err;
                });
            });
        } catch (error) {
            console.log(error);
        }
    });
}

exports.insertData = function(table, object, callback) {
    // Connexion au serveur avec la méthode connect
    mongoClient.connect(url, function (err, db) {
        try{
            if (err) {
                callback(err, null);
                return console.log('Connection failed', err);
            } else {
                console.log('Connexion successful on', "aslandb-shard-00-01-yened.mongodb.net:27017");
                console.log('Connected on db:', db.databaseName);
                db.collection(table).insert(object, callback);
            }
        } catch(error) {
            console.log("error");
            console.log(error);
            callback(error, null);
        }
    });
}
<|endoftext|>


<commit_before>// BabblerDataFlow.js

var React = require('react');

import {red200, lime900, deepPurple900} from 'material-ui/styles/colors';

var BabblerDataFlow = React.createClass({
    getInitialState: function() {
        return {
            deviceStatus: this.props.babblerDevice.deviceStatus(),
            dataFlow: []
        };
    },

    componentDidMount: function() {
        // слушаем статус устройства
        this.babblerDeviceListener = function onStatusChange(status) {
            this.setState({deviceStatus: status});
        }.bind(this);
        this.props.babblerDevice.addOnStatusChangeListener(this.babblerDeviceListener);

        // слушаем данные от устройства
        this.dataListener = function onData(data, dir) {
            var mark = (dir == BBLR_DATA_FLOW_IN ? "in>>" : "out<<");
            var style = (dir == BBLR_DATA_FLOW_IN ? {color: deepPurple900} : {color: lime900});

            var logElem =

                    {mark}{data}

                ;
            if(!this.props.reverseOrder) {
                // последнее событие в конец массива
                this.state.dataFlow.push(logElem);
            } else {
                // последнее событие в начало массива
                this.state.dataFlow.splice(0, 0, logElem);
            }
            // перерисовать
            this.setState({dataFlow: this.state.dataFlow});
        }.bind(this);
        this.props.babblerDevice.addOnDataListener(this.dataListener);

        // слушаем ошибки разбора данных устройства
        this.dataErrorListener = function(data, error, dir) {
            var mark = (dir == BBLR_DATA_FLOW_IN ? "err>>" : "err<<");
            var style = {color: red200};
            var logElem =

                    {mark}{error.toString()}:

                    {data.toString()}

                ;
            if(!this.props.reverseOrder) {
                // последнее событие в конец массива
                this.state.dataFlow.push(logElem);
            } else {
                // последнее событие в начало массива
                this.state.dataFlow.splice(0, 0, logElem);
            }
            // перерисовать
            this.setState({dataFlow: this.state.dataFlow});
        }.bind(this);
        this.props.babblerDevice.addOnDataErrorListener(this.dataErrorListener);
    },

    componentWillUnmount: function() {
        // почистим слушателей
        this.props.babblerDevice.removeOnStatusChangeListener(this.babblerDeviceListener);
        this.props.babblerDevice.removeOnDataListener(this.dataListener);
        this.props.babblerDevice.removeOnDataErrorListener(this.dataParseErrorListener);
    },

    render: function() {
        var connected = this.state.deviceStatus === BBLR_STATUS_CONNECTED ? true : false;
        return (

                {this.state.dataFlow}

        );
    },
});

// отправляем компонент на публику
module.exports = BabblerDataFlow;

<commit_msg>Отображать события очереди команд<commit_after>// BabblerDataFlow.js

var React = require('react');

import {red200, lime900, deepPurple900, yellow900} from 'material-ui/styles/colors';

var BabblerDataFlow = React.createClass({
    getInitialState: function() {
        return {
            deviceStatus: this.props.babblerDevice.deviceStatus(),
            dataFlow: []
        };
    },

    componentDidMount: function() {
        // слушаем статус устройства
        this.babblerDeviceListener = function onStatusChange(status) {
            this.setState({deviceStatus: status});
        }.bind(this);
        this.props.babblerDevice.addOnStatusChangeListener(this.babblerDeviceListener);

        // слушаем данные от устройства
        this.dataListener = function onData(data, dir) {
            var mark;
            var style;
            if(dir == BBLR_DATA_FLOW_IN) {
                mark = "in>>";
                style = {color: deepPurple900};
            } else if(dir == BBLR_DATA_FLOW_OUT) {
                mark = "out<<";
                style = {color: lime900};
            } else {//if(dir == BBLR_DATA_FLOW_QUEUE) {
                mark = "queue<<";
                style = {color: yellow900};
            }

            var logElem =

                    {mark}{data}

                ;
            if(!this.props.reverseOrder) {
                // последнее событие в конец массива
                this.state.dataFlow.push(logElem);
            } else {
                // последнее событие в начало массива
                this.state.dataFlow.splice(0, 0, logElem);
            }
            // перерисовать
            this.setState({dataFlow: this.state.dataFlow});
        }.bind(this);
        this.props.babblerDevice.addOnDataListener(this.dataListener);

        // слушаем ошибки разбора данных устройства
        this.dataErrorListener = function(data, error, dir) {
            var mark = (dir == BBLR_DATA_FLOW_IN ? "err>>" : "err<<");
            var style = {color: red200};
            var logElem =

                    {mark}{error.toString()}:

                    {data.toString()}

                ;
            if(!this.props.reverseOrder) {
                // последнее событие в конец массива
                this.state.dataFlow.push(logElem);
            } else {
                // последнее событие в начало массива
                this.state.dataFlow.splice(0, 0, logElem);
            }
            // перерисовать
            this.setState({dataFlow: this.state.dataFlow});
        }.bind(this);
        this.props.babblerDevice.addOnDataErrorListener(this.dataErrorListener);
    },

    componentWillUnmount: function() {
        // почистим слушателей
        this.props.babblerDevice.removeOnStatusChangeListener(this.babblerDeviceListener);
        this.props.babblerDevice.removeOnDataListener(this.dataListener);
        this.props.babblerDevice.removeOnDataErrorListener(this.dataParseErrorListener);
    },

    render: function() {
        var connected = this.state.deviceStatus === BBLR_STATUS_CONNECTED ? true : false;
        return (

                {this.state.dataFlow}

        );
    },
});

// отправляем компонент на публику
module.exports = BabblerDataFlow;

<|endoftext|>


<commit_before>
this.init = function(index, gameServer) {
  this.gameServer = gameServer;
this.index = index;
this.default = 0;
}

this.beforespawn = function (player,gameServer) {
if (!player.auth && gameServer.auon == 1) {
  player.frozen = true;
  if (this.index.config.allowregister != 1 && this.index.config.requirelogin != 1) this.default = 1;

  if (!player.astage) player.astage = this.default;
  if (player.astage == 0) {
    if (this.index.config.reservename == 1) {
      var ok = true;
      for (var i in gameServer.account) {
        var account = gameServer.account[i];
        if (account.username == player.name) {
          ok = false;
          player.mupa = account.pass;
          break;
        }
      }
      if (ok) {
        if (this.index.config.allowregister == 1) {
          player.un = player.name;
        player.name = 'Account Unregistered, press w to register it!';
        if (this.index.config.requirelogin != 1) player.name = player.name + ', Press q to play as guest';
        player.astage = 99;
        } else {
          player.astage = 100;
          player.frozen = false;
          player.auth = true;
          return true;
        }
      } else {
       player.un = player.name;
       player.name = 'Account registered, Press w to login';
       player.astage = 30;
      }

    } else {

    player.aname = player.name;
  var name = 'w = login';
  if (this.index.config.allowregister == 1) {
    name = name + ', Space = register';
  }
  if (this.index.config.requirelogin != 1) {
    name = name + ', q = playasguest';
  }
  player.name = name;
    }
  } else if (player.astage == 97) {
    player.pas = player.name;
    player.name = 'Press w to confirm';
  } else if (player.astage == 31) {
    player.pas = player.name;
    player.name = 'Press w to confirm'
  } else if (player.astage == 1) {
    player.name = 'Login, Username: (press w)';

  } else if (player.astage == 2) {
    player.un = player.name;
    player.name = 'pass: (press w)';

  } else if (player.astage == 3) {
    player.pa = player.name;
    player.name = 'Press w to confirm';
  } else if (player.astage == 5) {
    player.name = 'Username (press w)';

  } else if (player.astage == 6) {
    var ok = true;
    for (var i in gameServer.account) {
      if (gameServer.account[i].username == player.name) {
        ok = false
        break;
      }

    }
    if (ok) {
    player.un = player.name;
    player.name = 'Pass: (pres w)';
    player.astage = 7;
    } else {
      player.name = 'Username taken (press w)';
      player.astage = 50;
    }

  } else if (player.astage == 8) {
    player.pass = player.name;
    player.astage = 9;
    var ac = {
      username: player.un,
      pass: player.pass,

    };
    var re = gameServer.onregister(player);
    for (var i in re) ac[i] = re[i];
    gameServer.account.push(ac);

    player.name = 'Success!, Press w to login'
    player.astage = 50;
  }

  return true;
}
if (!player.spawna) gameServer.afterauth(player);
player.spawna = true;
return true;

};
this.beforeeject = function(player, gameServer) {
  if (player.cells && player.cells.length > 0 && gameServer.auon == 1) {
  if (player.astage = 0) {

  player.name = 'Username: (press w)';
  player.astage = 2
  return false;
 } else if (player.astage > 0 && player.astage < 3) {
  player.cells.forEach((cell)=>gameServer.removeNode(cell));
  player.astage ++;
  return false;
 } else if (player.astage == 30) {
   player.name = 'Pass: (press w)';
   player.astage = 31;
   return false;
 } else if (player.astage == 31) {
   player.cells.forEach((cell)=>gameServer.removeNode(cell));
   player.astage = 32;
   return false;
 } else if (player.astage == 33) {
   player.frozen = false;
   player.name = player.un;
   return false;
 } else if (player.astage == 32) {
   var ok = false;
   for (var i in gameServer.account) {
     if (gameServer.account[i].username == player.un && gameServer.account[i].pass == player.pas) {
       ok = true;
       player.accountid = i;
       player.auth = true;
       player.astage = 33;
       player.name = 'success! press w';
     }

   }
   if (!ok) {
     player.name = 'login fail, press w'
     player.astage = 50;
   }
   return false;
 } else if (player.astage == 99) {
  player.name = 'Password: (pressw)';
  player.astage = 98;
  return false;
 } else if (player.astage == 98) {
   player.cells.forEach((cell)=>gameServer.removeNode(cell));
   player.astage = 97;
   return false;
 } else if (player.astage == 97) {
   var p = {
     username: player.un,
     pass: player.pas,
   }
    var re = gameServer.onregister(player);
    for (var i in re) p[i] = re[i];
   gameServer.account.push(p);
   player.name = 'Success! Press w to log in';
   player.astage == 96
   return false;
 } else if (player.astage == 95) {
   player.name = 'Pass: (pressw)';
   player.astage = 30;
   return false;
} else if (player.astage == 3) {
  var ok = false;
  for (var i in gameServer.account) {
    var account = gameServer.account[i];
   if (account && account.pass == player.pa && account.un == account.username) {
     ok = true;
     player.accountid = i;
     break;
   }
  }
  if (!ok) {
    player.name = 'Wrong pass or username , press w';
    player.astage = 50;
  } else {
    player.name = 'Success, press w'
    player.astage = 4;
    player.auth = true;
  }
  return false
} else if (player.astage == 4) {
  player.frozen = false;
  player.name = player.aname;
  player.astage = 100;
  return false
} else if (player.astage == 5) {
player.cells.forEach((cell)=>gameServer.removeNode(cell));
player.astage = 6;
} else if (player.astage == 50) {
  player.cells.forEach((cell)=>gameServer.removeNode(cell));
  player.astage = this.default;
} else if (player.astage == 7) {
  player.cells.forEach((cell)=>gameServer.removeNode(cell));
  player.astage = 8;
  } else {
  return true;
}
}
return false;

};
this.beforesplit = function(player,gameServer) {
   if (player.cells && player.cells.length > 0 && gameServer.auon == 1) {
if (player.astage == 0 && this.index.config.allowregister == 1) {
  player.name = 'Username: (press w)'
  player.astage = 6;
} else {
  return true;
}
}
return false;
};
this.beforeq = function(player, gameServer) {
   if (player.cells && player.cells.length > 0 && gameServer.auon == 1) {
  if (player.astage == 0 && this.index.config.requirelogin != 1) {
    player.frozen = false;
    player.name = player.aname;
    player.astage = 50
    player.auth = true;
    player.guest = true;
  } else if (player.astage > 0 && player.astage < 100) {
    player.cells.forEach((cell)=>gameServer.removeNode(cell));
  player.astage = this.default;

  }

   }
};
module.exports = this;

<commit_msg>Update auth.js<commit_after>
this.init = function(index, gameServer) {
  this.gameServer = gameServer;
this.index = index;
this.default = 0;
}

this.beforespawn = function (player,gameServer) {
if (!player.auth && gameServer.auon == 1) {
  player.frozen = true;
  if (this.index.config.allowregister != 1 && this.index.config.requirelogin != 1) this.default = 1;

  if (!player.astage) player.astage = this.default;
  if (player.astage == 0) {
    if (this.index.config.reservename == 1) {
      var ok = true;
      for (var i in gameServer.account) {
        var account = gameServer.account[i];
        if (account.username == player.name) {
          ok = false;
          player.mupa = account.pass;
          break;
        }
      }
      if (ok) {
        if (this.index.config.allowregister == 1) {
          player.un = player.name;
        player.name = 'Account Unregistered, press w to register it!';
        if (this.index.config.requirelogin != 1) player.name = player.name + ', Press q to play as guest';
        player.astage = 99;
        } else {
          player.astage = 100;
          player.frozen = false;
          player.auth = true;
          return true;
        }
      } else {
       player.un = player.name;
       player.name = 'Account registered, Press w to login';
       player.astage = 30;
      }

    } else {

    player.aname = player.name;
  var name = 'w = login';
  if (this.index.config.allowregister == 1) {
    name = name + ', Space = register';
  }
  if (this.index.config.requirelogin != 1) {
    name = name + ', q = playasguest';
  }
  player.name = name;
    }
  } else if (player.astage == 97) {
    player.pas = player.name;
    player.name = 'Press w to confirm';
  } else if (player.astage == 31) {
    player.pas = player.name;
    player.name = 'Press w to confirm'
  } else if (player.astage == 1) {
    player.name = 'Login, Username: (press w)';

  } else if (player.astage == 2) {
    player.un = player.name;
    player.name = 'pass: (press w)';

  } else if (player.astage == 3) {
    player.pa = player.name;
    player.name = 'Press w to confirm';
  } else if (player.astage == 5) {
    player.name = 'Username (press w)';

  } else if (player.astage == 6) {
    var ok = true;
    for (var i in gameServer.account) {
      if (gameServer.account[i].username == player.name) {
        ok = false
        break;
      }

    }
    if (ok) {
    player.un = player.name;
    player.name = 'Pass: (pres w)';
    player.astage = 7;
    } else {
      player.name = 'Username taken (press w)';
      player.astage = 50;
    }

  } else if (player.astage == 8) {
    player.pass = player.name;
    player.astage = 9;
    var ac = {
      username: player.un,
      pass: player.pass,

    };
    var re = gameServer.onregister(player);
    for (var i in re) ac[i] = re[i];
    gameServer.account.push(ac);

    player.name = 'Success!, Press w to login'
    player.astage = 50;
  }

  return true;
}
if (!player.spawna) gameServer.afterauth(player);
player.spawna = true;
return true;

};
this.beforeeject = function(player, gameServer) {
  if (player.cells && player.cells.length > 0 && gameServer.auon == 1) {
  if (player.astage == 0) {

  player.name = 'Username: (press w)';
  player.astage = 2
  return false;
 } else if (player.astage > 0 && player.astage < 3) {
  player.cells.forEach((cell)=>gameServer.removeNode(cell));
  player.astage ++;
  return false;
 } else if (player.astage == 30) {
   player.name = 'Pass: (press w)';
   player.astage = 31;
   return false;
 } else if (player.astage == 31) {
   player.cells.forEach((cell)=>gameServer.removeNode(cell));
   player.astage = 32;
   return false;
 } else if (player.astage == 33) {
   player.frozen = false;
   player.name = player.un;
   return false;
 } else if (player.astage == 32) {
   var ok = false;
   for (var i in gameServer.account) {
     if (gameServer.account[i].username == player.un && gameServer.account[i].pass == player.pas) {
       ok = true;
       player.accountid = i;
       player.auth = true;
       player.astage = 33;
       player.name = 'success! press w';
     }

   }
   if (!ok) {
     player.name = 'login fail, press w'
     player.astage = 50;
   }
   return false;
 } else if (player.astage == 99) {
  player.name = 'Password: (pressw)';
  player.astage = 98;
  return false;
 } else if (player.astage == 98) {
   player.cells.forEach((cell)=>gameServer.removeNode(cell));
   player.astage = 97;
   return false;
 } else if (player.astage == 97) {
   var p = {
     username: player.un,
     pass: player.pas,
   }
    var re = gameServer.onregister(player);
    for (var i in re) p[i] = re[i];
   gameServer.account.push(p);
   player.name = 'Success! Press w to log in';
   player.astage == 96
   return false;
 } else if (player.astage == 95) {
   player.name = 'Pass: (pressw)';
   player.astage = 30;
   return false;
} else if (player.astage == 3) {
  var ok = false;
  for (var i in gameServer.account) {
    var account = gameServer.account[i];
   if (account && account.pass == player.pa && account.un == account.username) {
     ok = true;
     player.accountid = i;
     break;
   }
  }
  if (!ok) {
    player.name = 'Wrong pass or username , press w';
    player.astage = 50;
  } else {
    player.name = 'Success, press w'
    player.astage = 4;
    player.auth = true;
  }
  return false
} else if (player.astage == 4) {
  player.frozen = false;
  player.name = player.aname;
  player.astage = 100;
  return false
} else if (player.astage == 5) {
player.cells.forEach((cell)=>gameServer.removeNode(cell));
player.astage = 6;
} else if (player.astage == 50) {
  player.cells.forEach((cell)=>gameServer.removeNode(cell));
  player.astage = this.default;
} else if (player.astage == 7) {
  player.cells.forEach((cell)=>gameServer.removeNode(cell));
  player.astage = 8;
  } else {
  return true;
}
}
return false;

};
this.beforesplit = function(player,gameServer) {
   if (player.cells && player.cells.length > 0 && gameServer.auon == 1) {
if (player.astage == 0 && this.index.config.allowregister == 1) {
  player.name = 'Username: (press w)'
  player.astage = 6;
} else {
  return true;
}
}
return false;
};
this.beforeq = function(player, gameServer) {
   if (player.cells && player.cells.length > 0 && gameServer.auon == 1) {
  if (player.astage == 0 && this.index.config.requirelogin != 1) {
    player.frozen = false;
    player.name = player.aname;
    player.astage = 50
    player.auth = true;
    player.guest = true;
  } else if (player.astage > 0 && player.astage < 100) {
    player.cells.forEach((cell)=>gameServer.removeNode(cell));
  player.astage = this.default;

  }

   }
};
module.exports = this;

<|endoftext|>


<commit_before>/*global $:false */
'use strict';

var MovieApp = MovieApp || {
    url: 'http://localhost:3000'
};

MovieApp.getParams = function(){
	var params = window.location.search;
	var re = /\d/;
	return re.exec(params).join('');
};

MovieApp.getMovie = function(){
	var id = MovieApp.getParams();
	$.ajax({
		url: MovieApp.url + '/movies/' + id,
		type: 'GET'
	}).done(function(data){
		MovieApp.renderHTML(data);
	}).fail(function(jqXHR, textStatus, errorThrown){
		console.log(jqXHR, textStatus, errorThrown);
	});
};

MovieApp.renderHTML = function(movie){
	var html = '

'+movie.title+'
<button id="editBtn">Edit</button>
'+movie.rating+'

'+movie.release+'

'+movie.description+'

';
		if (movie.reviews){
			for (var i=0; i<movie.reviews.length; i++){
				html += '

'+movie.reviews[i].reviewer+'

'+movie.reviews[i].stars+'

'+movie.reviews[i].comment+'

';
			}
		}

	$('#movieShow').html(html);
	$('#editBtn').on('click', function(event){
		MovieApp.renderEditForm(event, movie);
	});
};

$(document).ready(function(){
  console.log('movie_show loaded');
  MovieApp.getMovie();
});
<commit_msg>resolved conflict<commit_after>/*global $:false */
'use strict';

var MovieApp = MovieApp || {
    url: 'http://localhost:3000'
};

MovieApp.getParams = function(){
	var params = window.location.search;
	var re = /\d/;
	return re.exec(params).join('');
};

MovieApp.getMovie = function(){
	var id = MovieApp.getParams();
	$.ajax({
		url: MovieApp.url + '/movies/' + id,
		type: 'GET'
	}).done(function(data){
		MovieApp.renderHTML(data);
	}).fail(function(jqXHR, textStatus, errorThrown){
		console.log(jqXHR, textStatus, errorThrown);
	});
};

MovieApp.getAverage = function(movie){
	if (movie.reviews) {
		var sum = movie.reviews.reduce(function(count, review) {return count + review.stars; }, 0);
		var withStars = movie.reviews.reduce(function(count, review){
			if (review.stars){
				return count + 1;
			} else {
				return count;
			}
		}, 0);
		return (sum/withStars).toFixed(1);
	} else {
		return 'No reviews yet'
	}
};

MovieApp.renderHTML = function(movie){
	var html = '

'+movie.title+'

'+movie.rating+'

'+movie.release+ '
Average User Stars: '+MovieApp.getAverage(movie)+'
'       +'

'+movie.description+'

';
		if (movie.reviews){
			for (var i=0; i<movie.reviews.length; i++){
				html += '

'+movie.reviews[i].reviewer+'

'+movie.reviews[i].stars+'

'+movie.reviews[i].comment+'

';
			}
		}

	$('#movieShow').html(html);
	$('#editBtn').on('click', function(event){
		MovieApp.renderEditForm(event, movie);
	});
};

$(document).ready(function(){
  console.log('movie_show loaded');
  MovieApp.getMovie();
});
<|endoftext|>


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

module.exports = function(router) {
  router.get('/system', auth, function(req, res, next) {
    res.json({ status: "ok" });
  });
}
<commit_msg>test again<commit_after>var auth = require('../helper/auth');

module.exports = function(router) {
  router.get('/system', auth, function(req, res, next) {
    res.json({ status: "okay" });
  });
}
<|endoftext|>


<commit_before>/* @flow */

import { StatusBar } from 'react-native';
import { Immersive } from 'react-native-immersive';

import { APP_STATE_CHANGED } from '../background';
import {
    CONFERENCE_FAILED,
    CONFERENCE_LEFT,
    CONFERENCE_WILL_JOIN,
    SET_AUDIO_ONLY
} from '../../base/conference';
import { HIDE_DIALOG } from '../../base/dialog';
import { Platform } from '../../base/react';
import { MiddlewareRegistry } from '../../base/redux';

/**
 * Middleware that captures conference actions and activates or deactivates the
 * full screen mode. On iOS it hides the status bar, and on Android it uses the
 * immersive mode:
 * https://developer.android.com/training/system-ui/immersive.html
 * In immersive mode the status and navigation bars are hidden and thus the
 * entire screen will be covered by our application.
 *
 * @param {Store} store - The redux store.
 * @returns {Function}
 */
MiddlewareRegistry.register(({ getState }) => next => action => {
    const result = next(action);

    let fullScreen = null;

    switch (action.type) {
    case APP_STATE_CHANGED:
    case CONFERENCE_WILL_JOIN:
    case HIDE_DIALOG:
    case SET_AUDIO_ONLY: {
        // Check if we just came back from the background and re-enable full
        // screen mode if necessary.
        const { appState } = action;

        if (typeof appState !== 'undefined' && appState !== 'active') {
            break;
        }

        const { audioOnly, conference }
            = getState()['features/base/conference'];

        fullScreen = conference || action.conference ? !audioOnly : false;
        break;
    }

    case CONFERENCE_FAILED:
    case CONFERENCE_LEFT:
        fullScreen = false;
        break;
    }

    if (fullScreen !== null) {
        _setFullScreen(fullScreen)
            .catch(err =>
                console.warn(`Failed to set full screen mode: ${err}`));
    }

    return result;
});

/**
 * Activates/deactivates the full screen mode. On iOS it will hide the status
 * bar, and on Android it will turn immersive mode on.
 *
 * @param {boolean} fullScreen - True to set full screen mode, false to
 * deactivate it.
 * @private
 * @returns {Promise}
 */
function _setFullScreen(fullScreen: boolean) {
    // XXX The React Native module Immersive is only implemented on Android and
    // throws on other platforms.
    if (Platform.OS === 'android') {
        return fullScreen ? Immersive.on() : Immersive.off();
    }

    // On platforms other than Android go with whatever React Native itself
    // supports.
    StatusBar.setHidden(fullScreen, 'slide');

    return Promise.resolve();
}
<commit_msg>[RN] Fix setting full-screen when joining a conference<commit_after>/* @flow */

import { StatusBar } from 'react-native';
import { Immersive } from 'react-native-immersive';

import { APP_STATE_CHANGED } from '../background';
import {
    CONFERENCE_FAILED,
    CONFERENCE_LEFT,
    CONFERENCE_WILL_JOIN,
    SET_AUDIO_ONLY
} from '../../base/conference';
import { HIDE_DIALOG } from '../../base/dialog';
import { Platform } from '../../base/react';
import { MiddlewareRegistry } from '../../base/redux';

/**
 * Middleware that captures conference actions and activates or deactivates the
 * full screen mode. On iOS it hides the status bar, and on Android it uses the
 * immersive mode:
 * https://developer.android.com/training/system-ui/immersive.html
 * In immersive mode the status and navigation bars are hidden and thus the
 * entire screen will be covered by our application.
 *
 * @param {Store} store - The redux store.
 * @returns {Function}
 */
MiddlewareRegistry.register(({ getState }) => next => action => {
    const result = next(action);

    let fullScreen = null;

    switch (action.type) {
    case APP_STATE_CHANGED:
    case CONFERENCE_WILL_JOIN:
    case HIDE_DIALOG:
    case SET_AUDIO_ONLY: {
        // Check if we just came back from the background and re-enable full
        // screen mode if necessary.
        const { appState } = action;

        if (typeof appState !== 'undefined' && appState !== 'active') {
            break;
        }

        const { audioOnly, conference, joining }
            = getState()['features/base/conference'];

        fullScreen = conference || joining ? !audioOnly : false;
        break;
    }

    case CONFERENCE_FAILED:
    case CONFERENCE_LEFT:
        fullScreen = false;
        break;
    }

    if (fullScreen !== null) {
        _setFullScreen(fullScreen)
            .catch(err =>
                console.warn(`Failed to set full screen mode: ${err}`));
    }

    return result;
});

/**
 * Activates/deactivates the full screen mode. On iOS it will hide the status
 * bar, and on Android it will turn immersive mode on.
 *
 * @param {boolean} fullScreen - True to set full screen mode, false to
 * deactivate it.
 * @private
 * @returns {Promise}
 */
function _setFullScreen(fullScreen: boolean) {
    // XXX The React Native module Immersive is only implemented on Android and
    // throws on other platforms.
    if (Platform.OS === 'android') {
        return fullScreen ? Immersive.on() : Immersive.off();
    }

    // On platforms other than Android go with whatever React Native itself
    // supports.
    StatusBar.setHidden(fullScreen, 'slide');

    return Promise.resolve();
}
<|endoftext|>


<commit_before>
this.init = function(index, gameServer) {
  this.gameServer = gameServer;
this.index = index;
this.default = 0;
};

this.beforespawn = function (player,gameServer) {

  if (player.name == player.olname && gameServer.auon == 1) {
    player.name = player.un;
  }
if ((!player.auth || (this.index.config.reservename == 1 && player.name != player.un)) && gameServer.auon == 1) {
  player.frozen = true;
  if (this.index.config.reservename == 1 && player.name != player.un && player.astage == 100) player.astage = this.default;
  if (this.index.config.allowregister != 1 && this.index.config.requirelogin != 1) this.default = 1;

  if (!player.astage) player.astage = this.default;
  if (player.astage == 0) {
    if (this.index.config.reservename == 1) {
      var ok = true;
      for (var i in gameServer.account) {
        var account = gameServer.account[i];
        if (account.username == player.name) {
          ok = false;
          player.mupa = account.pass;
          break;
        }
      }
      if (ok) {
        if (this.index.config.allowregister == 1) {
          player.un = player.name;
          player.aname = player.name;
        player.name = 'Account Unregistered, press w to register it!';
        if (this.index.config.requirelogin != 1) player.name = player.name + ', Press q to play as guest';
        player.astage = 99;
        } else {
          player.astage = 100;
          player.frozen = false;
          player.auth = true;
          return true;
        }
      } else {
       player.un = player.name;
       player.name = 'Account registered, Press w to login';
       player.astage = 30;
      }

    } else {

    player.aname = player.name;
  var name = 'w = login';
  if (this.index.config.allowregister == 1) {
    name = name + ', Space = register';
  }
  if (this.index.config.requirelogin != 1) {
    name = name + ', q = playasguest';
  }
  player.name = name;
    }
  } else if (player.astage == 97) {
    player.olname = player.name;
    player.pas = player.name;
    player.name = 'Press w to confirm';
  } else if (player.astage == 32) {
    player.olname = player.name;
    player.pas = player.name;
    player.name = 'Press w to confirm';
  } else if (player.astage == 1) {
    player.name = 'Login, Username: (press w)';

  } else if (player.astage == 2) {
    player.un = player.name;
    player.name = 'pass: (press w)';

  } else if (player.astage == 3) {
    player.olname = player.name;
    player.pa = player.name;
    player.name = 'Press w to confirm';
  } else if (player.astage == 5) {
    player.name = 'Username (press w)';

  } else if (player.astage == 6) {
    var ok = true;
    for (var i in gameServer.account) {
      if (gameServer.account[i].username == player.name) {
        ok = false;
        break;
      }

    }
    if (ok) {
    player.un = player.name;
    player.name = 'Pass: (pres w)';
    player.astage = 7;
    } else {
      player.name = 'Username taken (press w)';
      player.astage = 50;
    }

  } else if (player.astage == 32) {
    player.name = 'press w to confirm';
  } else if (player.astage == 8) {
    player.pass = player.name;
    player.astage = 9;
    var ac = {
      username: player.un,
      pass: player.pass,

    };
    gameServer.onregister(player);
    var re = gameServer.extraregpar;
    for (var i in re) ac[i] = re[i];
    gameServer.account.push(ac);

    player.name = 'Success!, Press w to login';
    player.astage = 50;
  }

  return true;
}
if (!player.spawna) gameServer.afterauth(player);
player.spawna = true;
return true;

};
this.beforeeject = function(player, gameServer) {
  if (player.cells && player.cells.length > 0 && gameServer.auon == 1) {
  if (player.astage == 0) {

  player.name = 'Username: (press w)';
  player.astage = 1;
  return false;
 } else if (player.astage > 0 && player.astage < 3) {
  player.cells.forEach((cell)=>gameServer.removeNode(cell));
  player.astage ++;
  return false;
 } else if (player.astage == 30) {
   player.name = 'Pass: (press w)';
   player.astage = 31;
   return false;
 } else if (player.astage == 31) {
   player.cells.forEach((cell)=>gameServer.removeNode(cell));
   player.astage = 32;
   return false;
 } else if (player.astage == 33) {
   player.frozen = false;
   player.name = player.un;
   player.astage = 100;
   return false;
 } else if (player.astage == 32) {
   var ok = false;
   for (var i in gameServer.account) {
     if (gameServer.account[i].username == player.un && gameServer.account[i].pass == player.pas) {
       ok = true;
       player.accountid = i;
       player.auth = true;
       player.astage = 33;
       player.name = 'success! press w';
     }

   }
   if (!ok) {
     player.name = 'login fail, press w';
     player.astage = 50;
   }
   return false;
 } else if (player.astage == 99) {
  player.name = 'Password: (pressw)';
  player.astage = 98;
  return false;
 } else if (player.astage == 98) {
   player.cells.forEach((cell)=>gameServer.removeNode(cell));
   player.astage = 97;
   return false;
 } else if (player.astage == 97) {
   var p = {
     username: player.un,
     pass: player.pas,
   };
    gameServer.onregister(player);
    var re = gameServer.extraregpar;
    for (var i in re) p[i] = re[i];
   gameServer.account.push(p);
   player.name = 'Success! Press w to log in';
   player.astage = 50;
   return false;
 } else if (player.astage == 95) {
   player.name = 'Pass: (pressw)';
   player.astage = 30;
   return false;
} else if (player.astage == 3) {
  var ok = false;
  for (var i in gameServer.account) {
    var account = gameServer.account[i];
   if (account && account.pass == player.pa && account.un == account.username) {
     ok = true;
     player.accountid = i;
     break;
   }
  }
  if (!ok) {
    player.name = 'Wrong pass or username , press w';
    player.astage = 50;
  } else {
    player.name = 'Success, press w';
    player.astage = 4;
    player.auth = true;
  }
  return false;
} else if (player.astage == 4) {
  player.frozen = false;
  player.name = player.aname;
  player.astage = 100;
  return false;
} else if (player.astage == 5) {
player.cells.forEach((cell)=>gameServer.removeNode(cell));
player.astage = 6;
} else if (player.astage == 50) {
  player.cells.forEach((cell)=>gameServer.removeNode(cell));
  player.astage = this.default;
} else if (player.astage == 7) {
  player.cells.forEach((cell)=>gameServer.removeNode(cell));
  player.astage = 8;
  } else {
  return true;
}
}
return false;

};
this.beforesplit = function(player,gameServer) {
   if (player.cells && player.cells.length > 0 && gameServer.auon == 1) {
if (player.astage == 0 && this.index.config.allowregister == 1) {
  player.name = 'Username: (press w)';
  player.astage = 5;
} else {
  return true;
}
}
return false;
};
this.beforeq = function(player, gameServer) {
   if (player.cells && player.cells.length > 0 && gameServer.auon == 1 && !player.auth) {
if ((player.astage == 0 || player.astage == 99) && this.index.config.requirelogin != 1) {
    player.frozen = false;
    player.name = player.aname;
    player.astage = 100;
    player.auth = true;
    player.guest = true;
  } else if (player.astage > 0 && player.astage < 100) {
    player.cells.forEach((cell)=>gameServer.removeNode(cell));
  player.astage = this.default;

  }
  return false;
   } else {
     return true;
   }
};
module.exports = this;

<commit_msg>Update auth.js<commit_after>
this.init = function(index, gameServer) {
  this.gameServer = gameServer;
this.index = index;
this.default = 0;
};

this.beforespawn = function (player,gameServer) {

  if (player.name == player.olname && gameServer.auon == 1) {
    player.name = player.un;
  }
if ((!player.auth || (this.index.config.reservename == 1 && player.name != player.un)) && gameServer.auon == 1) {
  player.frozen = true;
  if (this.index.config.reservename == 1 && player.name != player.un && player.astage == 100) player.astage = this.default;
  if (this.index.config.allowregister != 1 && this.index.config.requirelogin != 1) this.default = 1;

  if (!player.astage) player.astage = this.default;
  if (player.astage == 0) {
    if (this.index.config.reservename == 1) {
      var ok = true;
      for (var i in gameServer.account) {
        var account = gameServer.account[i];
        if (account.username == player.name) {
          ok = false;
          player.mupa = account.pass;
          break;
        }
      }
      if (ok) {
        if (this.index.config.allowregister == 1) {
          player.un = player.name;
          player.aname = player.name;
        player.name = 'Account Unregistered, press w to register it!';
        if (this.index.config.requirelogin != 1) player.name = player.name + ', Press q to play as guest';
        player.astage = 99;
        } else {
          player.astage = 100;
          player.frozen = false;
          player.auth = true;
          return true;
        }
      } else {
       player.un = player.name;
       player.name = 'Account registered, Press w to login';
       player.astage = 30;
      }

    } else {

    player.aname = player.name;
  var name = 'w = login';
  if (this.index.config.allowregister == 1) {
    name = name + ', Space = register';
  }
  if (this.index.config.requirelogin != 1) {
    name = name + ', q = playasguest';
  }
  player.name = name;
    }
  } else if (player.astage == 97) {
    player.olname = player.name;
    player.pas = player.name;
    player.name = 'Press w to confirm';
  } else if (player.astage == 32) {
    player.olname = player.name;
    player.pas = player.name;
    player.name = 'Press w to confirm';
  } else if (player.astage == 1) {
    player.name = 'Login, Username: (press w)';

  } else if (player.astage == 2) {
    player.un = player.name;
    player.name = 'pass: (press w)';

  } else if (player.astage == 3) {
    player.olname = player.name;
    player.pa = player.name;
    player.name = 'Press w to confirm';
  } else if (player.astage == 5) {
    player.name = 'Username (press w)';

  } else if (player.astage == 6) {
    var ok = true;
    for (var i in gameServer.account) {
      if (gameServer.account[i].username == player.name) {
        ok = false;
        break;
      }

    }
    if (ok) {
    player.un = player.name;
    player.name = 'Pass: (pres w)';
    player.astage = 7;
    } else {
      player.name = 'Username taken (press w)';
      player.astage = 50;
    }

  } else if (player.astage == 32) {
    player.name = 'press w to confirm';
  } else if (player.astage == 8) {
    player.pass = player.name;
    player.astage = 9;
    var ac = {
      username: player.un,
      pass: player.pass,

    };
    gameServer.onregister(player);
    var re = gameServer.extraregpar;
    for (var i in re) ac[i] = re[i];
    gameServer.account.push(ac);

    player.name = 'Success!, Press w to login';
    player.astage = 50;
  }

  return true;
}
if (!player.spawna) gameServer.afterauth(player);
player.spawna = true;
return true;

};
this.beforeeject = function(player, gameServer) {
  if (player.cells && player.cells.length > 0 && gameServer.auon == 1) {
  if (player.astage == 0) {

  player.name = 'Username: (press w)';
  player.astage = 1;
  return false;
 } else if (player.astage > 0 && player.astage < 3) {
  player.cells.forEach((cell)=>gameServer.removeNode(cell));
  player.astage ++;
  return false;
 } else if (player.astage == 30) {
   player.name = 'Pass: (press w)';
   player.astage = 31;
   return false;
 } else if (player.astage == 31) {
   player.cells.forEach((cell)=>gameServer.removeNode(cell));
   player.astage = 32;
   return false;
 } else if (player.astage == 33) {
   player.frozen = false;
   player.name = player.un;
   player.astage = 100;
   return false;
 } else if (player.astage == 32) {
   var ok = false;
   for (var i in gameServer.account) {
     if (gameServer.account[i].username == player.un && gameServer.account[i].pass == player.pas) {
       ok = true;
       player.accountid = i;
       player.auth = true;
       player.astage = 33;
       player.name = 'success! press w';
     }

   }
   if (!ok) {
     player.name = 'login fail, press w';
     player.astage = 50;
   }
   return false;
 } else if (player.astage == 99) {
  player.name = 'Password: (pressw)';
  player.astage = 98;
  return false;
 } else if (player.astage == 98) {
   player.cells.forEach((cell)=>gameServer.removeNode(cell));
   player.astage = 97;
   return false;
 } else if (player.astage == 97) {
   var p = {
     username: player.un,
     pass: player.pas,
   };
    gameServer.onregister(player);
    var re = gameServer.extraregpar;
    for (var i in re) p[i] = re[i];
   gameServer.account.push(p);
   player.name = 'Success! Press w to log in';
   player.astage = 50;
   return false;
 } else if (player.astage == 95) {
   player.name = 'Pass: (pressw)';
   player.astage = 30;
   return false;
} else if (player.astage == 3) {
  var ok = false;
  for (var i in gameServer.account) {
    var account = gameServer.account[i];
   if (account && account.pass == player.pa && player.un == account.username) {
     ok = true;
     player.accountid = i;
     break;
   }
  }
  if (!ok) {
    player.name = 'Wrong pass or username , press w';
    player.astage = 50;
  } else {
    player.name = 'Success, press w';
    player.astage = 4;
    player.auth = true;
  }
  return false;
} else if (player.astage == 4) {
  player.frozen = false;
  player.name = player.aname;
  player.astage = 100;
  return false;
} else if (player.astage == 5) {
player.cells.forEach((cell)=>gameServer.removeNode(cell));
player.astage = 6;
} else if (player.astage == 50) {
  player.cells.forEach((cell)=>gameServer.removeNode(cell));
  player.astage = this.default;
} else if (player.astage == 7) {
  player.cells.forEach((cell)=>gameServer.removeNode(cell));
  player.astage = 8;
  } else {
  return true;
}
}
return false;

};
this.beforesplit = function(player,gameServer) {
   if (player.cells && player.cells.length > 0 && gameServer.auon == 1) {
if (player.astage == 0 && this.index.config.allowregister == 1) {
  player.name = 'Username: (press w)';
  player.astage = 5;
} else {
  return true;
}
}
return false;
};
this.beforeq = function(player, gameServer) {
   if (player.cells && player.cells.length > 0 && gameServer.auon == 1 && !player.auth) {
if ((player.astage == 0 || player.astage == 99) && this.index.config.requirelogin != 1) {
    player.frozen = false;
    player.name = player.aname;
    player.astage = 100;
    player.auth = true;
    player.guest = true;
  } else if (player.astage > 0 && player.astage < 100) {
    player.cells.forEach((cell)=>gameServer.removeNode(cell));
  player.astage = this.default;

  }
  return false;
   } else {
     return true;
   }
};
module.exports = this;

<|endoftext|>


<commit_before>/**
 // Copyright Aaron K. Saunders and other contributors. 2015
 //
 // Primarily based on work by Stephen Feather - https://gist.github.com/sfeather/4400387
 // with additions listed below
 // - added promise functionality (https://github.com/kriskowal/q), and removing callbacks
 // - added url query param support to allow for more interesting queries
 // - added promises notify to support in progress information from http request
 // - added init function to extract credentials from the library
 // - fare number of the user functions are not correct
 // - clean up parameter naming
 //
 // Permission is hereby granted, free of charge, to any person obtaining a
 // copy of this software and associated documentation files (the
 // "Software"), to deal in the Software without restriction, including
 // without limitation the rights to use, copy, modify, merge, publish,
 // distribute, sublicense, and/or sell copies of the Software, and to permit
 // persons to whom the Software is furnished to do so, subject to the
 // following conditions:
 //
 // The above copyright notice and this permission notice shall be included
 // in all copies or substantial portions of the Software.
 //
 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
 // USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

/**
 * Usage:
 * var Parse = require('parse');
 *
 * Parse.getObjects('myClass', '{urlParams:{}}');
 *
 * Notes: Some folks like to do their error handling/forking in the Library.
 * I don't. So I only pass one callback into each function.
 * if you want a specific error function, add another param.
 *
 * Push notification registration borrowed/modified from Matt Berg (https://gist.github.com/3761738).
 *
 */

// will use this for promises
var Q = require('q');

var baseURL = 'https://api.parse.com/1/',
    appId,
    apiRESTKey;

// Be sure to use your REST API key and NOT your master as bad stuff can happen.

function ParseClient() {

}

ParseClient.prototype.init = function(_config) {
    _config = _config || {};
    appId = _config.appId || Ti.App.Properties.getString('Parse_AppId');
    apiRESTKey = _config.apiRESTKey || Ti.App.Properties.getString('Parse_RESTAPIKey');
    if (!appId || !apiRESTKey) {
        Ti.API.error('ParseClient Missing Credentials');
        alert('ParseClient Missing Credentials');
    }
};
ParseClient.prototype.saveUserRecord = function(user) {
    Ti.App.Properties.setObject('parseUser', user);
};

ParseClient.prototype.removeUserRecord = function(user) {
    Ti.App.Properties.removeObject('parseUser');
};

ParseClient.prototype.setSessionToken = function(token) {
    if (!token) {
        Ti.App.Properties.removeProperty('parseSessionToken');
        console.log("removed session token");
    } else {
        Ti.App.Properties.setString('parseSessionToken', token);
    }
};

ParseClient.prototype.getSessionToken = function() {
    return Ti.App.Properties.getString('parseSessionToken');
};

ParseClient.prototype.createObject = function(_class, data, callback) {
    var url = baseURL + 'classes/' + _class;
    var params = {
        method : 'POST',
        body : data
    };

    return this._request(url, params, callback);
};

ParseClient.prototype.updateObject = function(_class, _objectID, data, callback) {
    var url = baseURL + 'classes/' + _class + '/' + _objectID;
    var params = {
        method : 'PUT',
        body : data
    };

    return this._request(url, params, callback);
};

ParseClient.prototype.getObjects = function(_class, _params, callback) {
    var url = baseURL + 'classes/' + _class;
    var params = {
        method : 'GET',
        body : _params
    };

    params = _.extend(params, _params);

    return this._request(url, params, callback);
};

ParseClient.prototype.getObject = function(_class, _objectID, callback) {
    var url = baseURL + 'classes/' + _class + '/' + _objectID;
    return this._request(url, callback);
};

ParseClient.prototype.deleteObject = function(_class, _objectID, callback) {
    var url = baseURL + 'classes/' + _class + '/' + _objectID;
    var params = {
        method : 'DELETE'
    };

    return this._request(url, params, callback);
};

ParseClient.prototype.createUser = function(data, callback) {
    var url = baseURL + 'users';
    var params = {
        method : 'POST',
        body : data
    };

    function cb(success, response, code) {
        if (success === 1) {
            response = JSON.parse(response);
            parse.setSessionToken(response.sessionToken);
            callback(success, response, code);
        } else {
            callback(success, response, code);
        }
    }

    return this._request(url, params, cb);
};

ParseClient.prototype.getUsers = function(_params, callback) {
    var url = baseURL + 'users';
    var params = {
        method : 'GET',
    };

    params = _.extend(params, _params);

    return this._request(url, params, callback);
};

/**
 * @TODO - not updating saved user object
 */
ParseClient.prototype.getUser = function(_userId, callback) {
    var url = baseURL + 'users/' + _userId;
    return this._request(url, callback);
};

ParseClient.prototype.restoreUser = function() {
    var url = baseURL + 'users/me';
    return this._request(url);
};

ParseClient.prototype.loginUser = function(_username, _password) {
    var deferred = Q.defer();

    var url = baseURL + 'login?username=' + _username + '&password=' + _password;

    this._request(url, null).then(function(_response) {
        var response = _response.response;
        parse.setSessionToken(response.sessionToken);
        parse.saveUserRecord(response);
        return deferred.resolve(response);
    }, function(_error) {
        return deferred.reject(_error);
    });

    return deferred.promise;
};

ParseClient.prototype.logoutUser = function() {
    var deferred = Q.defer();

    var url = baseURL + 'logout';

    var params = {
        method : "POST"
    };

    this._request(url, params, null).then(function(_response) {
        var response = _response.response;
        parse.setSessionToken(null);
        parse.saveUserRecord(null);
        return deferred.resolve(response);
    }, function(_error) {
        return deferred.reject(_error);
    });

    return deferred.promise;
};

/**
 * @TODO - not updating saved user object
 */
ParseClient.prototype.updateUser = function(_userObject, data, callback) {
    var url = baseURL + 'users/' + _userObject;

    var params = {
        method : 'PUT',
        body : data
    };

    return this._request(url, params, callback);
};

ParseClient.prototype.deleteUser = function(_userObject, callback) {
    var url = baseURL + 'users/' + _userObject;
    var params = {
        method : 'DELETE'
    };

    return this._request(url, params, callback);
};

ParseClient.prototype.passwordReset = function(_email, callback) {
    var url = baseURL + 'requestPasswordReset';
    _email = {
        email : _email
    };

    var params = {
        method : 'POST',
        body : _email
    };

    return this._request(url, params, callback);
};

ParseClient.prototype.uploadFile = function(_contentType, _filename, _blob, callback) {

    console.log("_filename: " + _filename);

    var url = baseURL + 'files/' + _filename;
    var params = {
        method : 'POST',
        type : 'image',
        body : _blob,
        headers : {}
    };
    params.headers['Content-Type'] = _contentType;
    //Ti.API.error(params);
    return this._request(url, params, callback);
};

// -- functions below here not fully functional/tested --
// @TODO - clean this up!!

/**
 *
 *
 * Provide Callbacks for Android interaction
 *  _params.notificationReceive
 *  _params.notificationOpen
 */
ParseClient.prototype.registerPush = function(_params, callback) {

    var url = baseURL + 'installations';

    var params = {};

    if (OS_IOS) {
        return this._request(url, {
            method : "POST",
            body : _params.body
        });
    } else {

        // Android Parse Integration
        // This requires an Android Module to be included
        //  gittio install eu.rebelcorp.parse
        // or https://github.com/timanrebel/Parse/tree/master/android
        Parse = require('eu.rebelcorp.parse');

        Parse.start();

        Parse.enablePush();

        Parse.addEventListener('notificationreceive', function(e) {
            _params.notificationReceive && _params.notificationReceive(e);
        });

        Parse.addEventListener('notificationopen', function(e) {
            _params.notificationOpen && _params.notificationOpen(e);
        });

        if (_params.body.channels) {
            Ti.API.debug('Channels ' + JSON.stringify(_params.body.channels));
            _params.body.channels.map(function(_c) {
                Ti.API.debug('subscribeChannel ' + _c);
                Parse.subscribeChannel(_c);
            });
        }
        callback && callback();

        return Q.when({});
    }

};

// -- functions below here not fully functional/tested  send push notification --
// @TODO - clean this up!!
// @TODO - add support for where queries
ParseClient.prototype.sendPush = function(_params, callback) {

    var url = baseURL + 'push';

    console.log("url: " + url);
    console.log("sendPush _params: " + JSON.stringify(_params));

    var params = {
        method : "POST",
        body : {
            "channels" : _params.channel || [],
            "data" : {
                "alert" : _params.alert,
                "badge" : "Increment"
            }

        }
    };

    return this._request(url, params);
};

/**
 *
 * @param {Object} url
 * @param {Object} params
 * @param {Object} callback
 */
ParseClient.prototype._request = function(url, params, callback) {

    console.log(params);

    var Q = require('q');
    var deferred = Q.defer();

    if ( typeof params === 'function') {
        callback = params;
        params = {};
    }

    params = params || {};

    // Clean up the call type, defaulting to GET if no method set
    params.method = params.method || 'GET';

    params.method = params.method.toUpperCase();

    // If not specified, use a 20 second timeout
    params.timeout = ('timeout' in params) ? params.timeout : 15000;
    params.body = params.body || {};
    params.query = params.query || {};
    params.url = url || baseURL;
    //params.url += url;
    params.headers = params.headers || {};
    params.headers['X-Parse-Application-Id'] = Ti.App.Properties.getString('Parse_AppId');
    params.headers['X-Parse-REST-API-Key'] = Ti.App.Properties.getString('Parse_RESTAPIKey');
    params.headers['X-Parse-Revocable-Session'] = 1;
    if (!params.headers['Content-Type']) {
        params.headers['Content-Type'] = 'application/json';
    }
    params.headers['Accept'] = params.headers['Accept'] || 'application/json';

    if (parse.getSessionToken()) {
        params.headers['X-Parse-Session-Token'] = parse.getSessionToken();
    }

    // Need to clear some properties depending on method
    if ((params.method === 'GET') || (params.method === 'DELETE')) {
        params.body = null;
    } else {
        if (params.type === 'image') {
            params.body = params.body;
        } else {
            params.body = params.body ? JSON.stringify(params.body) : null;
        }
        params.query = null;
    }

    var xhr = Ti.Network.createHTTPClient({
        onsendstream : function(e) {
            //Ti.API.debug("progress: " + JSON.stringify(e));
            deferred.notify(e.progress);
        }
    });

    xhr.setTimeout(params.timeout);
    OS_ANDROID ? xhr.autoEncodeUrl = true : xhr.autoEncodeUrl = true;

    xhr.onerror = function(e) {
        Ti.API.error("error: " + JSON.stringify(e));
        callback && callback(0, xhr.responseText, xhr.status, xhr);

        return deferred.reject({
            error : xhr.responseText ? JSON.parse(xhr.responseText) : {},
            status : xhr.status
        });
    };

    xhr.onload = function(e) {
        Ti.API.info('this.responseText ' + xhr.responseText);
        callback && callback(1, xhr.responseText, xhr.status);
        return deferred.resolve({
            response : (xhr.responseText ? JSON.parse(xhr.responseText) : {}),
            status : xhr.status
        });
    };

    // @TODO find a better solution...
    // when urlparams has "where" encodeData function not working properly.
    // Below if statement code will make this query call.
    if (params.urlparams && params.urlparams.where) {

        // save the where stuff
        var whereParams = params.urlparams.where;
        delete params.urlparams['where'];

        // encode the rest of the url
        params.url = encodeData(params.urlparams, params.url);

        // add the where stuff to the url
        params.url = params.url + "&" + "where=" + JSON.stringify(whereParams);
    } else {
        params.url = encodeData(params.urlparams, params.url);
    }

    Ti.API.debug('params.url: ' + params.url);
    console.log('params.url: ' + params.url);

    xhr.open(params.method, params.url);

    for (var key in params.headers) {
        xhr.setRequestHeader(key, params.headers[key]);
    }

    xhr.send(params.body);

    return deferred.promise;
};

function encodeData(_params, _url) {

    var str = [];

    for (var p in _params) {
        //str.push(Ti.Network.encodeURIComponent(p) + "=" + Ti.Network.encodeURIComponent(_params[p]));
        str.push(p + "=" + _params[p]);
    }

    if (_.indexOf(_url, "?") == -1) {
        return _url + "?" + str.join("&");
    } else {
        return _url + "&" + str.join("&");
    }
}

var parse = new ParseClient();
module.exports = parse;
<commit_msg>force the removal of the parse cookies when the user is logged out<commit_after>/**
 // Copyright Aaron K. Saunders and other contributors. 2015
 //
 // Primarily based on work by Stephen Feather - https://gist.github.com/sfeather/4400387
 // with additions listed below
 // - added promise functionality (https://github.com/kriskowal/q), and removing callbacks
 // - added url query param support to allow for more interesting queries
 // - added promises notify to support in progress information from http request
 // - added init function to extract credentials from the library
 // - fare number of the user functions are not correct
 // - clean up parameter naming
 //
 // Permission is hereby granted, free of charge, to any person obtaining a
 // copy of this software and associated documentation files (the
 // "Software"), to deal in the Software without restriction, including
 // without limitation the rights to use, copy, modify, merge, publish,
 // distribute, sublicense, and/or sell copies of the Software, and to permit
 // persons to whom the Software is furnished to do so, subject to the
 // following conditions:
 //
 // The above copyright notice and this permission notice shall be included
 // in all copies or substantial portions of the Software.
 //
 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
 // USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

/**
 * Usage:
 * var Parse = require('parse');
 *
 * Parse.getObjects('myClass', '{urlParams:{}}');
 *
 * Notes: Some folks like to do their error handling/forking in the Library.
 * I don't. So I only pass one callback into each function.
 * if you want a specific error function, add another param.
 *
 * Push notification registration borrowed/modified from Matt Berg (https://gist.github.com/3761738).
 *
 */

// will use this for promises
var Q = require('q');

var baseURL = 'https://api.parse.com/1/',
    appId,
    apiRESTKey;

// Be sure to use your REST API key and NOT your master as bad stuff can happen.

function ParseClient() {

}

ParseClient.prototype.init = function(_config) {
	_config = _config || {};
	appId = _config.appId || Ti.App.Properties.getString('Parse_AppId');
	apiRESTKey = _config.apiRESTKey || Ti.App.Properties.getString('Parse_RESTAPIKey');
	if (!appId || !apiRESTKey) {
		Ti.API.error('ParseClient Missing Credentials');
		alert('ParseClient Missing Credentials');
	}
};
ParseClient.prototype.saveUserRecord = function(user) {
	Ti.App.Properties.setObject('parseUser', user);
};

ParseClient.prototype.removeUserRecord = function(user) {
	Ti.App.Properties.removeObject('parseUser');
};

ParseClient.prototype.setSessionToken = function(token) {
	if (!token) {
		Ti.App.Properties.removeProperty('parseSessionToken');
		console.log("removed session token");
	} else {
		Ti.App.Properties.setString('parseSessionToken', token);
	}
};

ParseClient.prototype.getSessionToken = function() {
	return Ti.App.Properties.getString('parseSessionToken');
};

ParseClient.prototype.createObject = function(_class, data, callback) {
	var url = baseURL + 'classes/' + _class;
	var params = {
		method : 'POST',
		body : data
	};

	return this._request(url, params, callback);
};

ParseClient.prototype.updateObject = function(_class, _objectID, data, callback) {
	var url = baseURL + 'classes/' + _class + '/' + _objectID;
	var params = {
		method : 'PUT',
		body : data
	};

	return this._request(url, params, callback);
};

ParseClient.prototype.getObjects = function(_class, _params, callback) {
	var url = baseURL + 'classes/' + _class;
	var params = {
		method : 'GET',
		body : _params
	};

	params = _.extend(params, _params);

	return this._request(url, params, callback);
};

ParseClient.prototype.getObject = function(_class, _objectID, callback) {
	var url = baseURL + 'classes/' + _class + '/' + _objectID;
	return this._request(url, callback);
};

ParseClient.prototype.deleteObject = function(_class, _objectID, callback) {
	var url = baseURL + 'classes/' + _class + '/' + _objectID;
	var params = {
		method : 'DELETE'
	};

	return this._request(url, params, callback);
};

ParseClient.prototype.createUser = function(data, callback) {
	var url = baseURL + 'users';
	var params = {
		method : 'POST',
		body : data
	};

	function cb(success, response, code) {
		if (success === 1) {
			response = JSON.parse(response);
			parse.setSessionToken(response.sessionToken);
			callback(success, response, code);
		} else {
			callback(success, response, code);
		}
	}

	return this._request(url, params, cb);
};

ParseClient.prototype.getUsers = function(_params, callback) {
	var url = baseURL + 'users';
	var params = {
		method : 'GET',
	};

	params = _.extend(params, _params);

	return this._request(url, params, callback);
};

/**
 * @TODO - not updating saved user object
 */
ParseClient.prototype.getUser = function(_userId, callback) {
	var url = baseURL + 'users/' + _userId;
	return this._request(url, callback);
};

ParseClient.prototype.restoreUser = function() {
	var url = baseURL + 'users/me';
	return this._request(url);
};

ParseClient.prototype.loginUser = function(_username, _password) {
	var deferred = Q.defer();

	var url = baseURL + 'login?username=' + _username + '&password=' + _password;

	this._request(url, null).then(function(_response) {
		var response = _response.response;
		parse.setSessionToken(response.sessionToken);
		parse.saveUserRecord(response);
		return deferred.resolve(response);
	}, function(_error) {
		return deferred.reject(_error);
	});

	return deferred.promise;
};

ParseClient.prototype.logoutUser = function() {
	var deferred = Q.defer();

	var url = baseURL + 'logout';

	var params = {
		method : "POST"
	};

	this._request(url, params, null).then(function(_response) {
		var response = _response.response;
		parse.setSessionToken(null);
		parse.saveUserRecord(null);

		Ti.Network.removeHTTPCookiesForDomain("parse.com");
		Ti.Network.removeHTTPCookiesForDomain("api.parse.com");

		return deferred.resolve(response);
	}, function(_error) {
		return deferred.reject(_error);
	});

	return deferred.promise;
};

/**
 * @TODO - not updating saved user object
 */
ParseClient.prototype.updateUser = function(_userObject, data, callback) {
	var url = baseURL + 'users/' + _userObject;

	var params = {
		method : 'PUT',
		body : data
	};

	return this._request(url, params, callback);
};

ParseClient.prototype.deleteUser = function(_userObject, callback) {
	var url = baseURL + 'users/' + _userObject;
	var params = {
		method : 'DELETE'
	};

	return this._request(url, params, callback);
};

ParseClient.prototype.passwordReset = function(_email, callback) {
	var url = baseURL + 'requestPasswordReset';
	_email = {
		email : _email
	};

	var params = {
		method : 'POST',
		body : _email
	};

	return this._request(url, params, callback);
};

ParseClient.prototype.uploadFile = function(_contentType, _filename, _blob, callback) {

	console.log("_filename: " + _filename);

	var url = baseURL + 'files/' + _filename;
	var params = {
		method : 'POST',
		type : 'image',
		body : _blob,
		headers : {}
	};
	params.headers['Content-Type'] = _contentType;
	//Ti.API.error(params);
	return this._request(url, params, callback);
};

// -- functions below here not fully functional/tested --
// @TODO - clean this up!!

/**
 *
 *
 * Provide Callbacks for Android interaction
 *  _params.notificationReceive
 *  _params.notificationOpen
 */
ParseClient.prototype.registerPush = function(_params, callback) {

	var url = baseURL + 'installations';

	var params = {};

	if (OS_IOS) {
		return this._request(url, {
			method : "POST",
			body : _params.body
		});
	} else {

		// Android Parse Integration
		// This requires an Android Module to be included
		//  gittio install eu.rebelcorp.parse
		// or https://github.com/timanrebel/Parse/tree/master/android
		Parse = require('eu.rebelcorp.parse');

		Parse.start();

		Parse.enablePush();

		Parse.addEventListener('notificationreceive', function(e) {
			_params.notificationReceive && _params.notificationReceive(e);
		});

		Parse.addEventListener('notificationopen', function(e) {
			_params.notificationOpen && _params.notificationOpen(e);
		});

		if (_params.body.channels) {
			Ti.API.debug('Channels ' + JSON.stringify(_params.body.channels));
			_params.body.channels.map(function(_c) {
				Ti.API.debug('subscribeChannel ' + _c);
				Parse.subscribeChannel(_c);
			});
		}
		callback && callback();

		return Q.when({});
	}

};

// -- functions below here not fully functional/tested  send push notification --
// @TODO - clean this up!!
// @TODO - add support for where queries
ParseClient.prototype.sendPush = function(_params, callback) {

	var url = baseURL + 'push';

	console.log("url: " + url);
	console.log("sendPush _params: " + JSON.stringify(_params));

	var params = {
		method : "POST",
		body : {
			"channels" : _params.channel || [],
			"data" : {
				"alert" : _params.alert,
				"badge" : "Increment"
			}

		}
	};

	return this._request(url, params);
};

/**
 *
 * @param {Object} url
 * @param {Object} params
 * @param {Object} callback
 */
ParseClient.prototype._request = function(url, params, callback) {

	console.log(params);

	var Q = require('q');
	var deferred = Q.defer();

	if ( typeof params === 'function') {
		callback = params;
		params = {};
	}

	params = params || {};

	// Clean up the call type, defaulting to GET if no method set
	params.method = params.method || 'GET';

	params.method = params.method.toUpperCase();

	// If not specified, use a 20 second timeout
	params.timeout = ('timeout' in params) ? params.timeout : 15000;
	params.body = params.body || {};
	params.query = params.query || {};
	params.url = url || baseURL;
	//params.url += url;
	params.headers = params.headers || {};
	params.headers['X-Parse-Application-Id'] = Ti.App.Properties.getString('Parse_AppId');
	params.headers['X-Parse-REST-API-Key'] = Ti.App.Properties.getString('Parse_RESTAPIKey');
	params.headers['X-Parse-Revocable-Session'] = 1;
	if (!params.headers['Content-Type']) {
		params.headers['Content-Type'] = 'application/json';
	}
	params.headers['Accept'] = params.headers['Accept'] || 'application/json';

	if (parse.getSessionToken()) {
		params.headers['X-Parse-Session-Token'] = parse.getSessionToken();
	}

	// Need to clear some properties depending on method
	if ((params.method === 'GET') || (params.method === 'DELETE')) {
		params.body = null;
	} else {
		if (params.type === 'image') {
			params.body = params.body;
		} else {
			params.body = params.body ? JSON.stringify(params.body) : null;
		}
		params.query = null;
	}

	var xhr = Ti.Network.createHTTPClient({
		onsendstream : function(e) {
			//Ti.API.debug("progress: " + JSON.stringify(e));
			deferred.notify(e.progress);
		}
	});

	xhr.setTimeout(params.timeout);
	OS_ANDROID ? xhr.autoEncodeUrl = true : xhr.autoEncodeUrl = true;

	xhr.onerror = function(e) {
		Ti.API.error("error: " + JSON.stringify(e));
		callback && callback(0, xhr.responseText, xhr.status, xhr);

		return deferred.reject({
			error : xhr.responseText ? JSON.parse(xhr.responseText) : {},
			status : xhr.status
		});
	};

	xhr.onload = function(e) {
		Ti.API.info('this.responseText ' + xhr.responseText);
		callback && callback(1, xhr.responseText, xhr.status);
		return deferred.resolve({
			response : (xhr.responseText ? JSON.parse(xhr.responseText) : {}),
			status : xhr.status
		});
	};

	// @TODO find a better solution...
	// when urlparams has "where" encodeData function not working properly.
	// Below if statement code will make this query call.
	if (params.urlparams && params.urlparams.where) {

		// save the where stuff
		var whereParams = params.urlparams.where;
		delete params.urlparams['where'];

		// encode the rest of the url
		params.url = encodeData(params.urlparams, params.url);

		// add the where stuff to the url
		params.url = params.url + "&" + "where=" + JSON.stringify(whereParams);
	} else {
		params.url = encodeData(params.urlparams, params.url);
	}

	Ti.API.debug('params.url: ' + params.url);
	console.log('params.url: ' + params.url);

	xhr.open(params.method, params.url);

	for (var key in params.headers) {
		xhr.setRequestHeader(key, params.headers[key]);
	}

	xhr.send(params.body);

	return deferred.promise;
};

function encodeData(_params, _url) {

	var str = [];

	for (var p in _params) {
		//str.push(Ti.Network.encodeURIComponent(p) + "=" + Ti.Network.encodeURIComponent(_params[p]));
		str.push(p + "=" + _params[p]);
	}

	if (_.indexOf(_url, "?") == -1) {
		return _url + "?" + str.join("&");
	} else {
		return _url + "&" + str.join("&");
	}
}

var parse = new ParseClient();
module.exports = parse;
<|endoftext|>


<commit_before>'use strict';

var isObject = require('lodash/isObject');

var PcRequest = require('./private/pc-request.js');

/**
 * @class
 * @classdesc Fetches an array of datasources from PC.
 * @alias datasources
 */
module.exports = class Datasources {
  /**
   * Initialises datasources and makes a request to PC server fetching datasource data. Chainable.
   * @constructor
   * @returns {this}
   */
  constructor() {
    this.request = new PcRequest("metadata/datasources", false);
    this.data = this.fetch();
  }

  /**
   * Makes a fetch request to PC requesting data sources. If called after class initialization, purges existing data source cache and makes a call to PC to re-fetch data sources.
   * @method datasources#fetch
   * @returns {Promise<object>} - Returns promise containing either the data source array or null if data source is not available
   */
  fetch() {
    var dataPromise = this.request.fetch().then((response) => {
      var output = {};
      if (isObject(response)) {
        response
          .filter(source => source.notPathwayData == false)
          .map((ds) => {
            var name = (ds.name.length > 1) ? ds.name[1] : ds.name[0];
            output[ds.uri] = {
              id: ds.identifier,
              uri: ds.uri,
              name: name,
              description: ds.description,
              type: ds.type,
              iconUrl: ds.iconUrl
            };
          });
      } else {
        output = null;
      }
      return output;
    }).catch(() => {
      return null;
    });

    this.data = dataPromise;
    return dataPromise;
  }

  /**
   * Returns promise containing data sources from PC.
   * @method datasources#get
   * @returns {Promise<object>} - Returns cached promise from the fetch method
   */
  get(callback) {
    return this.data;
  }

  /**
   * Fetches the logo for the datasource using either datasources URI or name. Intended to be used to generate image tags for thumbnails.
   * @method datasources#lookupIcon
   * @param {string} dsUriOrName - Either URI or name of the data source
   * @return {Promise<string>} logoUrl - Promise containing URL of datasource in question, else undefined if datasource not found
   */
  lookupIcon(dsUriOrName) {
    dsUriOrName = dsUriOrName || "";
    return this.data.then((dataSources) => {
      for (var key in dataSources) {
        var ds = dataSources[key];
        if (ds.uri == dsUriOrName || ds.name.toLowerCase() == dsUriOrName.toLowerCase()) {
          return ds.iconUrl;
        }
      }
    });
  }
}
<commit_msg>Code clean up<commit_after>'use strict';

var isObject = require('lodash/isObject');

var PcRequest = require('./private/pc-request.js');

/**
 * @class
 * @classdesc Fetches an array of datasources from PC.
 * @alias datasources
 */
module.exports = class Datasources {
  /**
   * Initialises datasources and makes a request to PC server fetching datasource data. Chainable.
   * @constructor
   * @returns {this}
   */
  constructor() {
    this.request = new PcRequest("metadata/datasources", false);
    this.data = this.fetch();
  }

  /**
   * Makes a fetch request to PC requesting data sources. If called after class initialization, purges existing data source cache and makes a call to PC to re-fetch data sources.
   * @method datasources#fetch
   * @returns {Promise<object>} - Returns promise containing either the data source array or null if data source is not available
   */
  fetch() {
    var dataPromise = this.request.fetch().then((response) => {
      var output = {};
      if (isObject(response)) {
        response
          .filter(source => source.notPathwayData == false)
          .map((ds) => {
            var name = (ds.name.length > 1) ? ds.name[1] : ds.name[0];
            output[ds.uri] = {
              id: ds.identifier,
              uri: ds.uri,
              name: name,
              description: ds.description,
              type: ds.type,
              iconUrl: ds.iconUrl
            };
          });
      } else {
        output = null;
      }
      return output;
    }).catch(() => {
      return null;
    });

    this.data = dataPromise;
    return dataPromise;
  }

  /**
   * Returns promise containing data sources from PC.
   * @method datasources#get
   * @returns {Promise<object>} - Returns cached promise from the fetch method
   */
  get() {
    return this.data;
  }

  /**
   * Fetches the logo for the datasource using either datasources URI or name. Intended to be used to generate image tags for thumbnails.
   * @method datasources#lookupIcon
   * @param {string} dsUriOrName - Either URI or name of the data source
   * @return {Promise<string>} logoUrl - Promise containing URL of datasource in question, else undefined if datasource not found
   */
  lookupIcon(dsUriOrName) {
    dsUriOrName = dsUriOrName || "";
    return this.data.then((dataSources) => {
      for (var key in dataSources) {
        var ds = dataSources[key];
        if (ds.uri == dsUriOrName || ds.name.toLowerCase() == dsUriOrName.toLowerCase()) {
          return ds.iconUrl;
        }
      }
    });
  }
}
<|endoftext|>


<commit_before>var $ = function(expr, context) {
	return new $.init(expr, context);
};
$.init = function(expr,context) {
	if(expr.nodeName && !context) this[0] = expr;
	else {
		try { var el = (context||document)['querySelectorAll'](expr); }
		catch(err){ var el = expr; }
		[].push.apply(this,[].slice.call(el));
	}
};
$.init.prototype = {
	each: function(el) {
		for (var l=0;l<this.length;l++) el(this[l]);
	},
	css: function(prop, val) {
		if ('object' == typeof prop) this.each(function(val) {
			for(var i in prop) val.style[i] = prop[i];
		});
		else {
			prop = prop.replace(/-([a-z])/g, function(prop) { return prop[1].toUpperCase(); });
			var el = this[0];
			return 1 < arguments.length ? (1 < this.length ? this.each(function(el) {
				el.style[prop] = val;
			}) : el.style[prop] = val, "") : "" === el.style[prop] ? el.currentStyle ? el.currentStyle[prop] : document.defaultView.getComputedStyle(el, null).getPropertyValue(prop) : el.style[prop];
		}
	},
	on: function(evt, fn) {
		for (var l = this.length; l--;) {
			var el = this[l];
			el.addEventListener ? el.addEventListener(evt, fn, !1) : el.attachEvent("on" + evt, function() {
				return fn.call(el, window.event);
			});
		}
	}
};
<commit_msg>added offset position<commit_after>var $ = function(expr, context) {
	return new $.init(expr, context);
};
$.init = function(expr,context) {
	if(expr.nodeName && !context) this[0] = expr;
	else {
		try { var el = (context||document)['querySelectorAll'](expr); }
		catch(err){ var el = expr; }
		[].push.apply(this,[].slice.call(el));
	}
};
$.init.prototype = {
	each: function(el) {
		for (var l=0;l<this.length;l++) el(this[l]);
	},
	css: function(prop, val) {
		if ('object' == typeof prop) this.each(function(val) {
			for(var i in prop) val.style[i] = prop[i];
		});
		else {
			prop = prop.replace(/-([a-z])/g, function (g) { return g[1].toUpperCase(); });
			var el = this[0], lt = /(left||top)/.test(prop);
			if(arguments.length>1) return 1 < this.length ? this.each(function(o){o.style[prop] = val;}) : el.style[prop] = val,"";
			else return el.style[prop]==''?(
				el.currentStyle && !lt?
				el.currentStyle[prop]:(lt?
					Math.round(el.getBoundingClientRect()[prop]):
					document.defaultView.getComputedStyle(el, null).getPropertyValue(prop)
				)
			):el.style[prop];
		}
	},
	on: function(evt, fn) {
		for (var l = this.length; l--;) {
			var el = this[l];
			el.addEventListener ? el.addEventListener(evt, fn, !1) : el.attachEvent("on" + evt, function() {
				return fn.call(el, window.event);
			});
		}
	}
};
<|endoftext|>


<commit_before>/*
* Copyright (c) 2012-2015 S-Core Co., Ltd.
*
* 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.
*/

/**
 * Constructor
 * Workbench
 *
 * @see Page, EventEmitter, PartContainer, Part, Perspective
 * @since: 2015.07.12
 * @author: hw.shim
 */

// @formatter:off
define([
    'external/eventEmitter/EventEmitter',
    'webida-lib/util/genetic',
    'webida-lib/util/logger/logger-client',
    './CompatibleLayoutPane',
    './DataSourceRegistry',
    './LayoutPane',
    './Page',
    './WorkspaceModel'
], function(
    EventEmitter,
    genetic,
    Logger,
    CompatibleLayoutPane,
    DataSourceRegistry,
    LayoutPane,
    Page,
    WorkspaceModel
) {
    'use strict';
// @formatter:on

    /**
     * @typedef {Object.<Object, Object>} Map
     * @typedef {Object} DataSourceRegistry
     * @typedef {Object} Page
     * @typedef {Object} WorkbenchModel
     * @typedef {Object} WorkspaceModel
     */

    var logger = new Logger();
    //logger.setConfig('level', Logger.LEVELS.log);
    //logger.off();

    function Workbench() {
        logger.info('new Workbench()');
        /** @type {Page} */
        this.currentPage = null;
        /** @type {Map.<string, Page>} */
        this.pages = [];
        /** @type {DataSourceRegistry} */
        this.dataSourceRegistry = new DataSourceRegistry();
        /** @type {WorkspaceModel} */
        this.workspaceModel = new WorkspaceModel();
    }

    genetic.inherits(Workbench, EventEmitter, {

        /**
         * @param {Page} page
         */
        addPage: function(page) {
            this.pages.push(page);
            page.setParent(this);
        },

        /**
         * @param {Page} page
         */
        removePage: function(page) {
            var index = this.pages.indexOf(page);
            if (index >= 0) {
                page.setParent(null);
                this.pages.splice(index, 1);
            }
        },

        /**
         * @return {Page[]}
         */
        getPages: function() {
            return this.pages;
        },

        /**
         * @param {Page} page
         */
        setCurrentPage: function(page) {
            this.currentPage = page;
        },

        /**
         * @return {Page}
         */
        getCurrentPage: function() {
            return this.currentPage;
        },

        /**
         * @return {DataSourceRegistry}
         */
        getDataSourceRegistry: function() {
            return this.dataSourceRegistry;
        },

        /**
         * Return true if specified dataSource is used
         * @return {boolean}
         */
        isDataSourceUsed: function(dataSource) {
            var reg, parts;
            var pages = this.getPages();
            for (var i in pages) {
                reg = pages[i].getPartRegistry();
                parts = reg.getPartsByDataSource(dataSource);
                if (parts.length > 0) {
                    return true;
                }
            }
            return false;
        },

        /**
         * @param {Object} dataSourceId
         * @param {Function} callback
         */
        createDataSource: function(dataSourceId, callback) {
            logger.info('createDataSource(' + dataSourceId + ', callback)');
            var dsRegistry = this.getDataSourceRegistry();
            var wsModel = this.getWorkspaceModel();
            var factoryId = wsModel.getDataSourceFactory(dataSourceId);
            require([factoryId], function(DataSourceFactory) {
                var factory = new DataSourceFactory();
                var dataSource = factory.create(dataSourceId);
                dsRegistry.registerDataSource(dataSource);
                callback(dataSource);
            });
        },

        /**
         * @param {WorkspaceModel}
         */
        getWorkspaceModel: function() {
            return this.workspaceModel;
        },

        /**
         * @param {WorkbenchModel} model
         */
        parseModel: function(workbenchModel) {

            //TODO : if(!(model instanceof WorkbenchModel)){return;}

            function getLayoutTree(model) {
                var LayoutClass = {
                    'Page': Page,
                    'LayoutPane': LayoutPane,
                    'CompatibleLayoutPane': CompatibleLayoutPane
                }
                var layoutTree, split, children, child;
                if ('type' in model) {
                    layoutTree = new LayoutClass[model.type](model.id, model.name);
                    if ('split' in model) {
                        split = model.split;
                        layoutTree.setOrientation(split.orientation);
                        layoutTree.setRatio(split.ratio);
                    }
                    if ('children' in model) {
                        children = model.children;
                        for (var i in children) {
                            child = getLayoutTree(children[i]);
                            layoutTree.insertChild(child, i);
                        }
                    }
                    return layoutTree;
                }
                return null;
            }

            if ('pages' in workbenchModel) {
                var page = [], pages = workbenchModel.pages;
                for (var i in pages) {
                    page[i] = getLayoutTree(pages[i]);
                    this.addPage(page[i]);
                }
                this.setCurrentPage(page[0]);
            }
        }
    });

    Workbench.CREATE_DATA_SOURCE = 'createDataSource';

    return Workbench;
});
<commit_msg>[TASK] Workbench : Solves async creation of DataSource<commit_after>/*
* Copyright (c) 2012-2015 S-Core Co., Ltd.
*
* 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.
*/

/**
 * Constructor
 * Workbench
 *
 * @see Page, EventEmitter, PartContainer, Part, Perspective
 * @since: 2015.07.12
 * @author: hw.shim
 */

// @formatter:off
define([
    'external/eventEmitter/EventEmitter',
    'webida-lib/util/genetic',
    'webida-lib/util/logger/logger-client',
    './CompatibleLayoutPane',
    './DataSourceRegistry',
    './LayoutPane',
    './Page',
    './WorkspaceModel'
], function(
    EventEmitter,
    genetic,
    Logger,
    CompatibleLayoutPane,
    DataSourceRegistry,
    LayoutPane,
    Page,
    WorkspaceModel
) {
    'use strict';
// @formatter:on

    /**
     * @typedef {Object.<Object, Object>} Map
     * @typedef {Object} DataSourceRegistry
     * @typedef {Object} Page
     * @typedef {Object} WorkbenchModel
     * @typedef {Object} WorkspaceModel
     */

    var logger = new Logger();
    //logger.setConfig('level', Logger.LEVELS.log);
    //logger.off();

    function Workbench() {
        logger.info('new Workbench()');
        /** @type {Page} */
        this.currentPage = null;
        /** @type {Map.<string, Page>} */
        this.pages = [];
        /** @type {DataSourceRegistry} */
        this.dataSourceRegistry = new DataSourceRegistry();
        /** @type {WorkspaceModel} */
        this.workspaceModel = new WorkspaceModel();
    }

    genetic.inherits(Workbench, EventEmitter, {

        /**
         * @param {Page} page
         */
        addPage: function(page) {
            this.pages.push(page);
            page.setParent(this);
        },

        /**
         * @param {Page} page
         */
        removePage: function(page) {
            var index = this.pages.indexOf(page);
            if (index >= 0) {
                page.setParent(null);
                this.pages.splice(index, 1);
            }
        },

        /**
         * @return {Page[]}
         */
        getPages: function() {
            return this.pages;
        },

        /**
         * @param {Page} page
         */
        setCurrentPage: function(page) {
            this.currentPage = page;
        },

        /**
         * @return {Page}
         */
        getCurrentPage: function() {
            return this.currentPage;
        },

        /**
         * @return {DataSourceRegistry}
         */
        getDataSourceRegistry: function() {
            return this.dataSourceRegistry;
        },

        /**
         * Return true if specified dataSource is used
         * @return {boolean}
         */
        isDataSourceUsed: function(dataSource) {
            var reg, parts;
            var pages = this.getPages();
            for (var i in pages) {
                reg = pages[i].getPartRegistry();
                parts = reg.getPartsByDataSource(dataSource);
                if (parts.length > 0) {
                    return true;
                }
            }
            return false;
        },

        /**
         * @param {Object} dataSourceId
         * @param {Function} callback
         */
        createDataSource: function(dataSourceId, callback) {
            logger.info('createDataSource(' + dataSourceId + ', callback)');
            var dsRegistry = this.getDataSourceRegistry();
            var wsModel = this.getWorkspaceModel();
            var factoryId = wsModel.getDataSourceFactory(dataSourceId);
            require([factoryId], function(DataSourceFactory) {
                var dataSource;
                var existingDs = dsRegistry.getDataSourceById(dataSourceId);
                //To solve async creation of DataSource check exists again
                if (existingDs) {
                    dataSource = existingDs;
                } else {
                    var factory = new DataSourceFactory();
                    dataSource = factory.create(dataSourceId);
                    dsRegistry.registerDataSource(dataSource);
                }
                callback(dataSource);
            });
        },

        /**
         * @param {WorkspaceModel}
         */
        getWorkspaceModel: function() {
            return this.workspaceModel;
        },

        /**
         * @param {WorkbenchModel} model
         */
        parseModel: function(workbenchModel) {

            //TODO : if(!(model instanceof WorkbenchModel)){return;}

            function getLayoutTree(model) {
                var LayoutClass = {
                    'Page': Page,
                    'LayoutPane': LayoutPane,
                    'CompatibleLayoutPane': CompatibleLayoutPane
                }
                var layoutTree, split, children, child;
                if ('type' in model) {
                    layoutTree = new LayoutClass[model.type](model.id, model.name);
                    if ('split' in model) {
                        split = model.split;
                        layoutTree.setOrientation(split.orientation);
                        layoutTree.setRatio(split.ratio);
                    }
                    if ('children' in model) {
                        children = model.children;
                        for (var i in children) {
                            child = getLayoutTree(children[i]);
                            layoutTree.insertChild(child, i);
                        }
                    }
                    return layoutTree;
                }
                return null;
            }

            if ('pages' in workbenchModel) {
                var page = [], pages = workbenchModel.pages;
                for (var i in pages) {
                    page[i] = getLayoutTree(pages[i]);
                    this.addPage(page[i]);
                }
                this.setCurrentPage(page[0]);
            }
        }
    });

    Workbench.CREATE_DATA_SOURCE = 'createDataSource';

    return Workbench;
});
<|endoftext|>