<commit_before>var express = require('express'),
	db = require('./app').db,
	ejsonHelper = require('./ejsonHelper'),
	adminDb = require('./app').admin,
	config = require('./app').config,
	metaCollection = require('./app').metaCollection

var DbCrud = function () {
	if (config.dbNames) {
		this.dbs = config.dbNames.map(function (name) {
			return {name: name, _id: name};
		});
	}

}

DbCrud.prototype._getDatabases = function (cb) {
	if (this.dbs) {
		cb(null,this.dbs);
	} else {
		adminDb.listDatabases(function (err, dbs) {
			if (err) {
				cb(err);
			} else {
				var mdbs = dbs.databases.map(function (mdb) {
					mdb.host = config.host;
					return mdb;
				});
				cb(null, mdbs);
			}
		});
	}
}

DbCrud.prototype.find = function (cb) {
	this._getDatabases(cb);
};

DbCrud.prototype.get = function (id, cb) {
	this.find(function (err, dbs) {
		if (err) return cb(err)
		var candidates = dbs.filter(function (db) {
			return db.name === id;
		})
		if (candidates.length === 1) {
			var db = candidates[0];
			metaCollection.find({db: db.name}, function (e, results) {
				if (e != null) {
					return next(e);
				} else {
					results.toArray(function (e, results) {
						if (e != null) {
							return next(e);
						} else {
							db.collections = results.map(function (coll) {
								return ejsonHelper.inflateId(coll._id);
							})
							cb(null, db);
						}
					});
				}
			})
		} else {
			cb(null, null)
		}
	});
}

DbCrud.prototype.synchronize = function (dbName, cb) {
	if (this.dbs) {
		return;
	}
	var adb = db(dbName);
	adb.collectionNames(null, {namesOnly: true}, function (e, collectionNames) {
		if (e) {
			cb(e);
		} else {
			var collection = {};
			collectionNames.forEach(function (name) {
				var shortName = name.substring(dbName.length + 1);
				collection[shortName] = false;
			})
			var existing = Object.keys(collection);
			metaCollection.find({db: dbName}, function (e, results) {
				results.toArray(function (e, metaNames) {
					if (e) {
						cb(e);
					} else {
						var removed = {};
						metaNames.forEach(function (meta) {
							removed[meta.collection] = true;
							delete collection[meta.collection];
						})
						existing.forEach(function (name) {
							delete removed[name];
						})
						if (Object.keys(removed).length > 0) {
							metaCollection.remove({
								db: dbName,
								collection: {$in: Object.keys(removed)}
							}, function (e, result) {
								console.log("removed " + result + " collections ");
							});
						}
						var metas = Object.keys(collection).map(function (collectionName) {
							return {
								collection: collectionName,
								name: collectionName,
								db: dbName,
								description: "generated on " + new Date() + "."
							};
						});
						if (metas.length > 0) {
							metaCollection.insert(metas, function (e, results) {
								if (e) {
									cb(e);
								} else {
									var newCollections = [];
									results.forEach(function (collection) {
										newCollections.push(ejsonHelper.inflate(collection));
									})
									cb({msg: "success", collections: newCollections});
								}
							});
						} else {
							cb({msg: "success", collections: []});
						}
					}
				});
			});
		}
	});
};

DbCrud.prototype.synchronizeAll = function (cb) {
	var me = this;
	this.find(function (e, dbs) {
		if (e) {
			cb(e);
		} else {
			var dbCount = dbs.length;
			dbs.forEach(function (db) {
				me.synchronize(db.name, function (e, result) {
					dbCount--;
					if (dbCount == 0) {
						if (cb) cb();
					}
				});
			});
		}
	})
}

module.exports = DbCrud;
<commit_msg>fix synchronize<commit_after>var express = require('express'),
	db = require('./app').db,
	ejsonHelper = require('./ejsonHelper'),
	adminDb = require('./app').admin,
	config = require('./app').config,
	metaCollection = require('./app').metaCollection

var DbCrud = function () {
	if (config.dbNames) {
		this.dbs = config.dbNames.map(function (name) {
			return {name: name, _id: name};
		});
	}

}

DbCrud.prototype._getDatabases = function (cb) {
	if (this.dbs) {
		cb(null, this.dbs);
	} else {
		adminDb.listDatabases(function (err, dbs) {
			if (err) {
				cb(err);
			} else {
				var mdbs = dbs.databases.map(function (mdb) {
					mdb.host = config.host;
					return mdb;
				});
				cb(null, mdbs);
			}
		});
	}
}

DbCrud.prototype.find = function (cb) {
	this._getDatabases(cb);
};

DbCrud.prototype.get = function (id, cb) {
	this.find(function (err, dbs) {
		if (err) return cb(err)
		var candidates = dbs.filter(function (db) {
			return db.name === id;
		})
		if (candidates.length === 1) {
			var db = candidates[0];
			metaCollection.find({db: db.name}, function (e, results) {
				if (e != null) {
					return next(e);
				} else {
					results.toArray(function (e, results) {
						if (e != null) {
							return next(e);
						} else {
							db.collections = results.map(function (coll) {
								return ejsonHelper.inflateId(coll._id);
							})
							cb(null, db);
						}
					});
				}
			})
		} else {
			cb(null, null)
		}
	});
}

DbCrud.prototype.synchronize = function (dbName, cb) {
	var adb = db(dbName);
	adb.collectionNames(null, {namesOnly: true}, function (e, collectionNames) {
		if (e) {
			cb(e);
		} else {
			var collection = {};
			collectionNames.forEach(function (name) {
				var shortName = name.substring(dbName.length + 1);
				collection[shortName] = false;
			})
			var existing = Object.keys(collection);
			metaCollection.find({db: dbName}, function (e, results) {
				results.toArray(function (e, metaNames) {
					if (e) {
						cb(e);
					} else {
						var removed = {};
						metaNames.forEach(function (meta) {
							removed[meta.collection] = true;
							delete collection[meta.collection];
						})
						existing.forEach(function (name) {
							delete removed[name];
						})
						if (Object.keys(removed).length > 0) {
							metaCollection.remove({
								db: dbName,
								collection: {$in: Object.keys(removed)}
							}, function (e, result) {
								console.log("removed " + result + " collections ");
							});
						}
						var metas = Object.keys(collection).map(function (collectionName) {
							return {
								collection: collectionName,
								name: collectionName,
								db: dbName,
								description: "generated on " + new Date() + "."
							};
						});
						if (metas.length > 0) {
							metaCollection.insert(metas, function (e, results) {
								if (e) {
									cb(e);
								} else {
									var newCollections = [];
									results.forEach(function (collection) {
										newCollections.push(ejsonHelper.inflate(collection));
									})
									cb(null, {msg: "success", collections: newCollections});
								}
							});
						} else {
							cb(null, {msg: "success", collections: []});
						}
					}
				});
			});
		}
	});
};

DbCrud.prototype.synchronizeAll = function (cb) {
	var me = this;
	this.find(function (e, dbs) {
		if (e) {
			cb(e);
		} else {
			var dbCount = dbs.length;
			dbs.forEach(function (db) {
				me.synchronize(db.name, function (e, result) {
					dbCount--;
					if (dbCount == 0) {
						if (cb) cb();
					}
				});
			});
		}
	})
}

module.exports = DbCrud;
<|endoftext|>


<commit_before>const async = require('async');
const Order_info_item_scrape = require('../models/Order_info_item_scrape.js');
const Message = require('../models/Message.js');
const passport = require('passport');
var PythonShell = require('python-shell');
var mongoose = require('mongoose');
var fs = require('fs');
const User = require('../models/User');
mongoose.Promise = require('bluebird');

var message_data = []

var google = require('googleapis');
var OAuth2 = google.auth.OAuth2;
var oauth2Client = new OAuth2(
  process.env.GOOGLE_ID,
  process.env.GOOGLE_SECRET,
  process.env.GOOGLE_URIS
);

var gmail = google.gmail({
  version: 'v1',
  auth: oauth2Client
});

//sub function to get message from gmail api
//**********//**********//**********//**********
function getMessage(i, email ,thread_id, callback) {
   gmail.users.messages.get({
     auth: oauth2Client,
     userId: email,
     id: thread_id.id,
     format: 'raw'
   },
     function(err, response2) {
       if (err) {
         console.log('The API returned an error: ' + err);
         return;
       }

       //for some reason i needed to create an _id to save to mongoose...:(
       var mongoose = require('mongoose');
       var ObjectId =  mongoose.Types.ObjectId;
       var x = new ObjectId();

       var date = new Date().getTime()
       const email_thread = new Message(
         {
           _id: x,
           email: email,
           date_extracted: date,
           thread_id: thread_id.id,
           encoded_message: response2['raw']
        }
       );
       email_thread.save();
       console.log('saved thread')
    })
    console.log('counter is ' + i)
 }

function getThreads(email, callback) {
  var retailers = ['contact@em.nordstrom.com']
  var key_words = '{subject:order subject:reciept subject:confirmation subject:purchase}'
  query = 'in: anywhere,' + retailers +','+ key_words

  gmail.users.threads.list({
    auth: oauth2Client,
    userId: email,
    q: query
  }, function(err, response) {
    if (err) {
      console.log('The API returned an error: ' + err);
      return;
    }

    var threads = response['threads']
    console.log(threads.length)
    if (threads.length == 0) {
      console.log('no threads found that match critera');
    } else {
      for (var i = 0; i < threads.length; i++) {
        var thread = threads[i];
        console.log(email)
        getMessage(i , email, thread)
      }
      if (i==threads.length){
        //callback(null);
      }
    }
  });
}

//**********//**********//**********//**********
//**********//**********//**********//**********

exports.getOrder = (req, res) => {
console.log(process.cwd())
  if(req.user){
    async.waterfall([

      function(callback) {
        //checking to see if the user has an initial status of need to scrape
        if (req.user.initial_scrape_state == 'need_initial') {
          console.log(req.user.tokens[0].accessToken)
          if (req.user.tokens[0].accessToken) {
              //setting oauth2Client credentials if user has a token set up
              oauth2Client.setCredentials({
              access_token: req.user.tokens[0].accessToken,
              refresh_token: req.user.refresh_token[0].refreshToken
            });
            //getThreads(req.user.email, callback);
            //callback(null, 'next1');

  ///*
            var retailers = ['contact@em.nordstrom.com']
            var key_words = '{subject:order subject:reciept subject:confirmation subject:purchase}'
            var lookback = ' newer_than:60d'
            query = 'in: anywhere,' + retailers +','+ key_words + ',' + lookback

            gmail.users.threads.list({
              auth: oauth2Client,
              userId: req.user.email,
              q: query
            }, function(err, response) {
              if (err) {
                console.log('The API returned an error: ' + err);
                return;
              }

              var threads = response['threads']
              if (threads.length == 0) {
                console.log('no threads found that match critera');
              } else {
                var j = 0
                for (var i = 0; i < threads.length; i++) {
                  var thread = threads[i];
                  console.log(req.user.email)

                  //getMessage(i , req.user.email, thread)
                  gmail.users.messages.get({
                    auth: oauth2Client,
                    userId: req.user.email,
                    id: thread.id,
                    format: 'raw'
                  },
                    function(err, response2) {
                      if (err) {
                        console.log('The API returned an error: ' + err);
                        return;
                      }
                      var mongoose = require('mongoose');
                      var ObjectId =  mongoose.Types.ObjectId;
                      var x = new ObjectId();

                      var date = new Date().getTime()
                      const email_thread = new Message(
                        {
                          _id: x,
                          email: req.user.email,
                          date_extracted: date,
                          thread_id: thread.id,
                          encoded_message: response2['raw'],
                          status: 'need to scrape'
                       }
                      );
                      email_thread.save();
                      j++;
                      console.log('saved thread')
                      console.log(j)
                      if (j==threads.length){
                        callback(null, 'next1');
                      }
                   })
                }
              }
            });
            //*/
          }
        }
        //else{
        //  callback(null, 'next1');
        //}

      },

      function(arg1, callback) {
        //in this subfunction i want to call the python scraper :D
        if (req.user.initial_scrape_state == 'need_initial') {

          var PythonShell = require('python-shell');
          var path = process.cwd()+'/public/test_scripts/'
          var pyshell = new PythonShell('test.py', {scriptPath:path, pythonOptions: ['-u']});
          pyshell.on('message', function (message) {
            // received a message sent from the Python script (a simple "print" statement)
            console.log(message);
          });
          // end the input stream and allow the process to exit
          pyshell.end(function (err) {
            if (err) throw err;
            console.log('finished first python scrape');
            console.log(arg1)
            callback(null, 'next3');
          });

        }
        else{
          callback(null, 'next1');
        }

      },

      function(arg1, callback) {
        //in this subfunction i want to call the python scraper :D
        if (req.user.initial_scrape_state == 'need_initial') {

          var PythonShell = require('python-shell');
          var path = process.cwd()+'/public/test_scripts/'
          var pyshell = new PythonShell('test_scrape_nordstrom.py',{scriptPath: path, pythonOptions: ['-u']});

          pyshell.on('message', function (message) {
            // received a message sent from the Python script (a simple "print" statement)
            console.log(message);

          });

          // end the input stream and allow the process to exit

          pyshell.end(function (err) {
            if (err) throw err;
            console.log('finished second python scrape');
            console.log(arg1)
            callback(null, 'next3');
          });

        }

        else{
          callback(null, 'next1');
        }

      },

      function(arg1, callback) {
          if (req.user.initial_scrape_state == 'need_initial') {
            User.update(
              {'email': req.user.email }
              ,{$set:{'initial_scrape_state':'complete'}}
              , function(err, result) {
                    if (err) {console.log(err);}
                    else {console.log('saved')}
                }
            )
          };
        console.log('task2')
        callback(null, 'next2');
      },
    ], function (err, arg1) {
      console.log(arg1)
      Order_info_item_scrape.find((err, docs) => {
          res.render('orders', {orders: docs});
      });
      console.log('result')
  });
  }
  else{

    res.render('orders')
  }

};
<commit_msg>cleaning up after the initial scrape is done, previously stalled<commit_after>const async = require('async');
const Order_info_item_scrape = require('../models/Order_info_item_scrape.js');
const Message = require('../models/Message.js');
const passport = require('passport');
var PythonShell = require('python-shell');
var mongoose = require('mongoose');
var fs = require('fs');
const User = require('../models/User');
mongoose.Promise = require('bluebird');

var message_data = []

var google = require('googleapis');
var OAuth2 = google.auth.OAuth2;
var oauth2Client = new OAuth2(
  process.env.GOOGLE_ID,
  process.env.GOOGLE_SECRET,
  process.env.GOOGLE_URIS
);

var gmail = google.gmail({
  version: 'v1',
  auth: oauth2Client
});

//sub function to get message from gmail api
//**********//**********//**********//**********
function getMessage(i, email ,thread_id, callback) {
   gmail.users.messages.get({
     auth: oauth2Client,
     userId: email,
     id: thread_id.id,
     format: 'raw'
   },
     function(err, response2) {
       if (err) {
         console.log('The API returned an error: ' + err);
         return;
       }

       //for some reason i needed to create an _id to save to mongoose...:(
       var mongoose = require('mongoose');
       var ObjectId =  mongoose.Types.ObjectId;
       var x = new ObjectId();

       var date = new Date().getTime()
       const email_thread = new Message(
         {
           _id: x,
           email: email,
           date_extracted: date,
           thread_id: thread_id.id,
           encoded_message: response2['raw']
        }
       );
       email_thread.save();
       console.log('saved thread')
    })
    console.log('counter is ' + i)
 }

function getThreads(email, callback) {
  var retailers = ['contact@em.nordstrom.com']
  var key_words = '{subject:order subject:reciept subject:confirmation subject:purchase}'
  query = 'in: anywhere,' + retailers +','+ key_words

  gmail.users.threads.list({
    auth: oauth2Client,
    userId: email,
    q: query
  }, function(err, response) {
    if (err) {
      console.log('The API returned an error: ' + err);
      return;
    }

    var threads = response['threads']
    console.log(threads.length)
    if (threads.length == 0) {
      console.log('no threads found that match critera');
    } else {
      for (var i = 0; i < threads.length; i++) {
        var thread = threads[i];
        console.log(email)
        getMessage(i , email, thread)
      }
      if (i==threads.length){
        //callback(null);
      }
    }
  });
}

//**********//**********//**********//**********
//**********//**********//**********//**********

exports.getOrder = (req, res) => {
console.log(process.cwd())
  if(req.user && req.user.initial_scrape_state == 'need_initial'){
    async.waterfall([

      function(callback) {
        //checking to see if the user has an initial status of need to scrape
          console.log(req.user.tokens[0].accessToken)
          if (req.user.tokens[0].accessToken) {
              //setting oauth2Client credentials if user has a token set up
              oauth2Client.setCredentials({
              access_token: req.user.tokens[0].accessToken,
              refresh_token: req.user.refresh_token[0].refreshToken
            });

            var retailers = ['contact@em.nordstrom.com']
            var key_words = '{subject:order subject:reciept subject:confirmation subject:purchase}'
            var lookback = ' newer_than:60d'
            query = 'in: anywhere,' + retailers +','+ key_words + ',' + lookback

            gmail.users.threads.list({
              auth: oauth2Client,
              userId: req.user.email,
              q: query
            }, function(err, response) {
              if (err) {
                console.log('The API returned an error: ' + err);
                return;
              }

              var threads = response['threads']
              if (threads.length == 0) {
                console.log('no threads found that match critera');
              } else {
                var j = 0
                for (var i = 0; i < threads.length; i++) {
                  var thread = threads[i];
                  console.log(req.user.email)

                  //getMessage(i , req.user.email, thread)
                  gmail.users.messages.get({
                    auth: oauth2Client,
                    userId: req.user.email,
                    id: thread.id,
                    format: 'raw'
                  },
                    function(err, response2) {
                      if (err) {
                        console.log('The API returned an error: ' + err);
                        return;
                      }
                      var mongoose = require('mongoose');
                      var ObjectId =  mongoose.Types.ObjectId;
                      var x = new ObjectId();

                      var date = new Date().getTime()
                      const email_thread = new Message(
                        {
                          _id: x,
                          email: req.user.email,
                          date_extracted: date,
                          thread_id: thread.id,
                          encoded_message: response2['raw'],
                          status: 'need to scrape'
                       }
                      );
                      email_thread.save();
                      j++;
                      console.log('saved thread')
                      console.log(j)
                      if (j==threads.length){
                        callback(null, 'next1');
                      }
                   })
                }
              }
            });
            //*/
          }

        //else{
        //  callback(null, 'next1');
        //}

      },

      function(arg1, callback) {
        //in this subfunction i want to call the python scraper :D

          var PythonShell = require('python-shell');
          var path = process.cwd()+'/public/test_scripts/'
          var pyshell = new PythonShell('test.py', {scriptPath:path, pythonOptions: ['-u']});
          pyshell.on('message', function (message) {
            // received a message sent from the Python script (a simple "print" statement)
            console.log(message);
          });
          // end the input stream and allow the process to exit
          pyshell.end(function (err) {
            if (err) throw err;
            console.log('finished first python scrape');
            console.log(arg1)
            callback(null, 'next3');
          });

      },

      function(arg1, callback) {
        //in this subfunction i want to call the python scraper :D

          var PythonShell = require('python-shell');
          var path = process.cwd()+'/public/test_scripts/'
          var pyshell = new PythonShell('test_scrape_nordstrom.py',{scriptPath: path, pythonOptions: ['-u']});

          pyshell.on('message', function (message) {
            // received a message sent from the Python script (a simple "print" statement)
            console.log(message);

          });

          // end the input stream and allow the process to exit

          pyshell.end(function (err) {
            if (err) throw err;
            console.log('finished second python scrape');
            console.log(arg1)
            callback(null, 'next3');
          });

      },

      function(arg1, callback) {

            User.update(
              {'email': req.user.email }
              ,{$set:{'initial_scrape_state':'complete'}}
              , function(err, result) {
                    if (err) {console.log(err);}
                    else {console.log('saved')}
                }
            )
        console.log('task2')
        callback(null, 'next2');
      },
    ], function (err, arg1) {
      console.log(arg1)
      Order_info_item_scrape.find((err, docs) => {
          res.render('orders', {orders: docs});
      });
      console.log('result')
  });
  }
  else{

    Order_info_item_scrape.find((err, docs) => {
        res.render('orders', {orders: docs});
    });
  }

};
<|endoftext|>


<commit_before>var facebook = {
    loginCallback: function(page){
        console.log('page: ' + page);
        if (page == 'index'){
            FB.getLoginStatus(function(response) {
                if (response.status === 'connected') {
                    // the user is logged in and has authenticated your
                    // app, and response.authResponse supplies
                    // the user's ID, a valid access token, a signed
                    // request, and the time the access token
                    // and signed request each expire
                    var uid = response.authResponse.userID;
                    var accessToken = response.authResponse.accessToken;
                    console.log('[response.status] connected, user: ' + uid);
                    console.log('[response.status] connected, token: ' + accessToken);
                    console.log('redirect to main page');
                    window.location = aboutme.path.main;

                } else if (response.status === 'not_authorized') {
                    // the user is logged in to Facebook,
                    // but has not authenticated your app
                    console.log('[response.status] not_authorized');
                } else {
                    // the user isn't logged in to Facebook.
                    console.log('[response.status] not logged in');
                }
            });

            // after user click login
            FB.Event.subscribe('auth.authResponseChange', function(response) {
                if (response.status === 'connected') {
                    var uid = response.authResponse.userID;
                    console.log('[authResponseChange, connected] user: ' + uid);
                    console.log('redirect to main page');
                    window.location = aboutme.path.main;
                }
            });

        } else if (page == 'main'){
            // Here we subscribe to the auth.authResponseChange JavaScript event. This event is fired
            // for any authentication related change, such as login, logout or session refresh. This means that
            // whenever someone who was previously logged out tries to log in again, the correct case below
            // will be handled.
            FB.Event.subscribe('auth.authResponseChange', function(response) {
                // Here we specify what we do with the response anytime this event occurs.
                if (response.status === 'connected') {
                    // The response object is returned with a status field that lets the app know the current
                    // login status of the person. In this case, we're handling the situation where they
                    // have logged in to the app.
                    var uid = response.authResponse.userID;
                    console.log('[authResponseChange, connected] user: ' + uid);
                    aboutme.login(uid);

                } else if (response.status === 'not_authorized') {
                    // In this case, the person is logged into Facebook, but not into the app, so we call
                    // FB.login() to prompt them to do so.
                    // In real-life usage, you wouldn't want to immediately prompt someone to login
                    // like this, for two reasons:
                    // (1) JavaScript created popup windows are blocked by most browsers unless they
                    // result from direct interaction from people using the app (such as a mouse click)
                    // (2) it is a bad experience to be continually prompted to login upon page load.
                    console.log('[authResponseChange, not_authorized] not_authorized, login');
                    FB.login();
                } else {
                    // In this case, the person is not logged into Facebook, so we call the login()
                    // function to prompt them to do so. Note that at this stage there is no indication
                    // of whether they are logged into the app. If they aren't then they'll see the Login
                    // dialog right after they log in to Facebook.
                    // The same caveats as above apply to the FB.login() call here.
                    console.log('[authResponseChange] seem logout');
                    window.location = '/';
                }
            });
        }
    },
    logout: function(response) {
        console.log(response);
    }
};

var aboutme = {
    domain: 'project.aboutme.com.hk',
    path: {
        main: '/app/main',
        upload_url: '/gapp/upload_url',
        photo_search: '/gapp/search',
        photo_view: '/gapp/view',
        photo_download: 'http://i-littlecircle.appspot.com/download/',
        event_query: '/app/event/query',
        event_create: '/app/event/create'
    },
    socket: null,
    socketPort: 3000,
    user: {
        getName: function(){
            var n = '';
            if (this.first_name) n += this.first_name;
            if (this.first_name && this.last_name) n += ' ';
            if (this.last_name) n += this.last_name;
            return n;
        },
        loadFromFacebook: function(fb){
            if (!fb){
                console.log('[loadFromFacebook] data is null');
                return;
            }
            var bday = moment(fb.birthday, 'MM/DD/YYYY');
            this.fb_id = fb.id;
            this.first_name = fb.first_name;
            this.last_name = fb.last_name;
            this.name = this.getName();
            this.gender = fb.gender;
            this.email = fb.email;
            this.birthday = bday.isValid()? bday.format('YYYY-MM-DD'): null;
        },
        logout: function(postAction){
            this.fb_id = null;
            this.first_name = null;
            this.last_name = null;
            this.gender = null;
            this.email = null;
            this.birthday = null;
            if (postAction) postAction();
        }
    },
    initFacebook: function(){
        FB.init({
            appId : '471865979603234',
            status: true, // check login status
            cookie: true, // enable cookies to allow the server to access the session
            xfbml : true  // parse XFBML
        });
    },
    index: function(){
        $.ajaxSetup({ cache: true });
        $.getScript('//connect.facebook.net/en_UK/all.js', function(){
            aboutme.initFacebook();
            FB.getLoginStatus(facebook.loginCallback('index'));
        });
    },
    main: function(){
        $.ajaxSetup({ cache: true });
        $.getScript('//connect.facebook.net/en_UK/all.js', function(){
            aboutme.initFacebook();
            FB.getLoginStatus(facebook.loginCallback('main'));
        });

        // prepare upload photo
        aboutme.upload.prepare();

        // web socket
        var socket = 'http://' + aboutme.domain + ':' + aboutme.socketPort;
        console.log('connect ' + socket);
        aboutme.socket = io.connect(socket);
        aboutme.socket.on('message', function (data) {
            console.log('message: ' + data);
            if (data) {
                $('div.chat_history').append(data + '
');
            }
        });
        /*
        aboutme.socket.on('alive', function() {
            aboutme.socket.emit('offline', aboutme.user);
            alert('emit offline: ' + JSON.stringify(aboutme.user));
        });
        */
        // load photo
        aboutme.photo.search({ event: '1'});
    },
    chat: function(){
        var msg = $('input.chat_message').val();
        if (msg){
            var send = {user: aboutme.user, message: msg};
            console.log(JSON.stringify(send));
            console.log(send.user.name + ': ' + send.message);
            aboutme.socket.emit('chat', send);
        }
    },
    login: function(uid){
        console.log('[login] loading user [' + uid + '] from facebook...');
//         FB.api('/me', function(response) {
//             console.log('[login] /me: ' + response.name + '.');
//         });
        FB.api('/' + uid, function(response) {
            console.log('[login] /' + uid + ': ' + JSON.stringify(response) + '.');
            aboutme.user.loadFromFacebook(response);
            console.log(aboutme.user.name + "'s birthday: " + aboutme.user.birthday);
            aboutme.socket.emit('online', aboutme.user);
            aboutme.loadEvent();
        });

//         console.log('loading friends');
//         FB.api("/me/friends", function (response) {
//             console.log('friends: ' + response.data.length);
//             if (response && !response.error) {
//                 // handle the result
//             }
//         });
    },
    loadEvent: function(){
        var html = '';
        if (aboutme.user.fb_id){
            console.log('[loadEvent] load from server');
            $.ajax({
                type: "GET",
                url: aboutme.path.event_query,
                data: {
                    user_id: aboutme.user.fb_id
                }
            }).done(function(data){
                if (!data){
                    alert(['Your request cannot be processed, please try again later.
Ref. #' + 500]);
                    return;
                }

                data.forEach(function(obj, idx){
                    html += obj.title + '@' + obj.location + '
';
                });
                $('div.event').html(html);
            });
        }
        $('div.event').html(html);
    },
    saveEvent: function(){
        var title = $('input.title')
          , location = $('input.location')
          , event = {
                title: title.val(),
                location: location.val(),
          };

        console.log(JSON.stringify(event));
        //aboutme.pushPost(event);
        console.log(aboutme.socket);
        aboutme.socket.emit('send', {message: event.title});

        $.ajax({
            type: "GET",
            url: aboutme.path.event_create,
            data: {
                user_id: aboutme.user.fb_id,
                event: event
            }
        }).done(function(data){
            if (!data){
                alert(['Your request cannot be processed, please try again later.
Ref. #' + 500]);
                return;
            }
            title.val(null);
            location.val(null);
            aboutme.loadEvent();
        });
    },
    pushPost: function(event){
        console.log('push post to facebook');
        var msg = aboutme.user.name + ' is ' + event.title + ' at ' + event.location;
        FB.api('/me/feed', 'post', {message: msg}, function(response){
            if (!response || response.error){
                console.log('[pushPost] error: ' + JSON.stringify(response.error));
            } else {
                console.log('[pushPost] success');
            }
        });
    },
    upload: {
        url: '',
        action: function(){
            confirm('are you sure');
            var formData = new FormData($('form.form_upload')[0]);
            $.ajax({
                url: aboutme.upload.url,
                type: 'POST',
                xhr: function() {
                    // Custom XMLHttpRequest
                    var myXhr = $.ajaxSettings.xhr();
                    // Check if upload property exists
                    if (myXhr.upload){
                        // For handling the progress of the upload
                        myXhr.upload.addEventListener('progress', aboutme.upload.progressCallback, false);
                    }
                    return myXhr;
                },
                // events
                // beforeSend: null,
                success: aboutme.upload.successCallback,
                error: aboutme.upload.errorCallback,
                // Form data
                data: formData,
                // Options to tell jQuery not to process data or worry about content-type.
                cache: false,
                contentType: false,
                processData: false
            });
        },
        prepare: function(){
            var form = $('form.form_upload');
            form.hide();
            $.ajax({
                type: "GET",
                url: aboutme.path.upload_url
            }).done(function(data){
                if (!data){
                    alert(['Your request cannot be processed, please try again later.
Ref. #' + 500]);
                    return;
                }
                aboutme.upload.url = data;
                form.show();
            });
        },
        validate: function(){
            /*
            $(':file').change(function(){
                var file = this.files[0];
                var name = file.name;
                var size = file.size;
                var type = file.type;
                alert(name);
            });
            */
        },
        progressCallback: function(e){
            //if (e.lengthComputable)
            //    $('progress').attr({value:e.loaded,max:e.total});
        },
        successCallback: function (data){
            if (!data){
                alert(['Your request cannot be processed, please try again later.
Ref. #' + 500]);
                return;
            }
            // append photo
            $('div.gallery').append(aboutme.photo.getPhotoLink(data, aboutme.photo.num));
            aboutme.photo.initFancyBox(aboutme.photo.num++);

            // get new upload URL
            aboutme.upload.prepare();
        },
        errorCallback: function (error){
            //alert('errorHandler: ' + JSON.stringify(error));
            alert(['Your request cannot be processed, please try again later.
Ref. #' + 500]);
        }
    },
    photo: {
        num: 0,
        search: function(data){
            $.ajax({
                type: "GET",
                url: aboutme.path.photo_search,
                data: data
            }).done(function(data){
                if (!data || data.length < 1){
                    return;
                }
                var div = $('div.gallery');
                data.forEach(function(o){
                    div.append(aboutme.photo.getPhotoLink(o.pkey, aboutme.photo.num));
                    aboutme.photo.initFancyBox(aboutme.photo.num++);
                });
            });
        },
        getPhotoLink: function(id, index){
            var
            p = aboutme.path.photo_view + '?id=' + id,
            d = aboutme.path.photo_download + id; // p + '&full=1';
            return '';
        },
        initFancyBox: function(index){
            $('a#img_' + index).fancybox({
                'type'          : 'image',
                'transitionIn'  : 'elastic',
                'transitionOut' : 'fade'
            });
        }
    }
};
<commit_msg>update the path in JavaScript<commit_after>var facebook = {
    loginCallback: function(page){
        console.log('page: ' + page);
        if (page == 'index'){
            FB.getLoginStatus(function(response) {
                if (response.status === 'connected') {
                    // the user is logged in and has authenticated your
                    // app, and response.authResponse supplies
                    // the user's ID, a valid access token, a signed
                    // request, and the time the access token
                    // and signed request each expire
                    var uid = response.authResponse.userID;
                    var accessToken = response.authResponse.accessToken;
                    console.log('[response.status] connected, user: ' + uid);
                    console.log('[response.status] connected, token: ' + accessToken);
                    console.log('redirect to main page');
                    window.location = aboutme.path.main;

                } else if (response.status === 'not_authorized') {
                    // the user is logged in to Facebook,
                    // but has not authenticated your app
                    console.log('[response.status] not_authorized');
                } else {
                    // the user isn't logged in to Facebook.
                    console.log('[response.status] not logged in');
                }
            });

            // after user click login
            FB.Event.subscribe('auth.authResponseChange', function(response) {
                if (response.status === 'connected') {
                    var uid = response.authResponse.userID;
                    console.log('[authResponseChange, connected] user: ' + uid);
                    console.log('redirect to main page');
                    window.location = aboutme.path.main;
                }
            });

        } else if (page == 'main'){
            // Here we subscribe to the auth.authResponseChange JavaScript event. This event is fired
            // for any authentication related change, such as login, logout or session refresh. This means that
            // whenever someone who was previously logged out tries to log in again, the correct case below
            // will be handled.
            FB.Event.subscribe('auth.authResponseChange', function(response) {
                // Here we specify what we do with the response anytime this event occurs.
                if (response.status === 'connected') {
                    // The response object is returned with a status field that lets the app know the current
                    // login status of the person. In this case, we're handling the situation where they
                    // have logged in to the app.
                    var uid = response.authResponse.userID;
                    console.log('[authResponseChange, connected] user: ' + uid);
                    aboutme.login(uid);

                } else if (response.status === 'not_authorized') {
                    // In this case, the person is logged into Facebook, but not into the app, so we call
                    // FB.login() to prompt them to do so.
                    // In real-life usage, you wouldn't want to immediately prompt someone to login
                    // like this, for two reasons:
                    // (1) JavaScript created popup windows are blocked by most browsers unless they
                    // result from direct interaction from people using the app (such as a mouse click)
                    // (2) it is a bad experience to be continually prompted to login upon page load.
                    console.log('[authResponseChange, not_authorized] not_authorized, login');
                    FB.login();
                } else {
                    // In this case, the person is not logged into Facebook, so we call the login()
                    // function to prompt them to do so. Note that at this stage there is no indication
                    // of whether they are logged into the app. If they aren't then they'll see the Login
                    // dialog right after they log in to Facebook.
                    // The same caveats as above apply to the FB.login() call here.
                    console.log('[authResponseChange] seem logout');
                    window.location = '/';
                }
            });
        }
    },
    logout: function(response) {
        console.log(response);
    }
};

var aboutme = {
    domain: 'project.aboutme.com.hk',
    path: {
        main: '/app/main',
        upload_url: '/gapp/upload_url',
        photo_search: '/gapp/search',
        photo_view: '/gapp/view',
        event_query: '/app/event/query',
        event_create: '/app/event/create'
    },
    socket: null,
    socketPort: 3000,
    user: {
        getName: function(){
            var n = '';
            if (this.first_name) n += this.first_name;
            if (this.first_name && this.last_name) n += ' ';
            if (this.last_name) n += this.last_name;
            return n;
        },
        loadFromFacebook: function(fb){
            if (!fb){
                console.log('[loadFromFacebook] data is null');
                return;
            }
            var bday = moment(fb.birthday, 'MM/DD/YYYY');
            this.fb_id = fb.id;
            this.first_name = fb.first_name;
            this.last_name = fb.last_name;
            this.name = this.getName();
            this.gender = fb.gender;
            this.email = fb.email;
            this.birthday = bday.isValid()? bday.format('YYYY-MM-DD'): null;
        },
        logout: function(postAction){
            this.fb_id = null;
            this.first_name = null;
            this.last_name = null;
            this.gender = null;
            this.email = null;
            this.birthday = null;
            if (postAction) postAction();
        }
    },
    initFacebook: function(){
        FB.init({
            appId : '471865979603234',
            status: true, // check login status
            cookie: true, // enable cookies to allow the server to access the session
            xfbml : true  // parse XFBML
        });
    },
    index: function(){
        $.ajaxSetup({ cache: true });
        $.getScript('//connect.facebook.net/en_UK/all.js', function(){
            aboutme.initFacebook();
            FB.getLoginStatus(facebook.loginCallback('index'));
        });
    },
    main: function(){
        $.ajaxSetup({ cache: true });
        $.getScript('//connect.facebook.net/en_UK/all.js', function(){
            aboutme.initFacebook();
            FB.getLoginStatus(facebook.loginCallback('main'));
        });

        // prepare upload photo
        aboutme.upload.prepare();

        // web socket
        var socket = 'http://' + aboutme.domain + ':' + aboutme.socketPort;
        console.log('connect ' + socket);
        aboutme.socket = io.connect(socket);
        aboutme.socket.on('message', function (data) {
            console.log('message: ' + data);
            if (data) {
                $('div.chat_history').append(data + '
');
            }
        });
        /*
        aboutme.socket.on('alive', function() {
            aboutme.socket.emit('offline', aboutme.user);
            alert('emit offline: ' + JSON.stringify(aboutme.user));
        });
        */
        // load photo
        aboutme.photo.search({ event: '1'});
    },
    chat: function(){
        var msg = $('input.chat_message').val();
        if (msg){
            var send = {user: aboutme.user, message: msg};
            console.log(JSON.stringify(send));
            console.log(send.user.name + ': ' + send.message);
            aboutme.socket.emit('chat', send);
        }
    },
    login: function(uid){
        console.log('[login] loading user [' + uid + '] from facebook...');
//         FB.api('/me', function(response) {
//             console.log('[login] /me: ' + response.name + '.');
//         });
        FB.api('/' + uid, function(response) {
            console.log('[login] /' + uid + ': ' + JSON.stringify(response) + '.');
            aboutme.user.loadFromFacebook(response);
            console.log(aboutme.user.name + "'s birthday: " + aboutme.user.birthday);
            aboutme.socket.emit('online', aboutme.user);
            aboutme.loadEvent();
        });

//         console.log('loading friends');
//         FB.api("/me/friends", function (response) {
//             console.log('friends: ' + response.data.length);
//             if (response && !response.error) {
//                 // handle the result
//             }
//         });
    },
    loadEvent: function(){
        var html = '';
        if (aboutme.user.fb_id){
            console.log('[loadEvent] load from server');
            $.ajax({
                type: "GET",
                url: aboutme.path.event_query,
                data: {
                    user_id: aboutme.user.fb_id
                }
            }).done(function(data){
                if (!data){
                    alert(['Your request cannot be processed, please try again later.
Ref. #' + 500]);
                    return;
                }

                data.forEach(function(obj, idx){
                    html += obj.title + '@' + obj.location + '
';
                });
                $('div.event').html(html);
            });
        }
        $('div.event').html(html);
    },
    saveEvent: function(){
        var title = $('input.title')
          , location = $('input.location')
          , event = {
                title: title.val(),
                location: location.val(),
          };

        console.log(JSON.stringify(event));
        //aboutme.pushPost(event);
        console.log(aboutme.socket);
        aboutme.socket.emit('send', {message: event.title});

        $.ajax({
            type: "GET",
            url: aboutme.path.event_create,
            data: {
                user_id: aboutme.user.fb_id,
                event: event
            }
        }).done(function(data){
            if (!data){
                alert(['Your request cannot be processed, please try again later.
Ref. #' + 500]);
                return;
            }
            title.val(null);
            location.val(null);
            aboutme.loadEvent();
        });
    },
    pushPost: function(event){
        console.log('push post to facebook');
        var msg = aboutme.user.name + ' is ' + event.title + ' at ' + event.location;
        FB.api('/me/feed', 'post', {message: msg}, function(response){
            if (!response || response.error){
                console.log('[pushPost] error: ' + JSON.stringify(response.error));
            } else {
                console.log('[pushPost] success');
            }
        });
    },
    upload: {
        url: '',
        action: function(){
            confirm('are you sure');
            var formData = new FormData($('form.form_upload')[0]);
            $.ajax({
                url: aboutme.upload.url,
                type: 'POST',
                xhr: function() {
                    // Custom XMLHttpRequest
                    var myXhr = $.ajaxSettings.xhr();
                    // Check if upload property exists
                    if (myXhr.upload){
                        // For handling the progress of the upload
                        myXhr.upload.addEventListener('progress', aboutme.upload.progressCallback, false);
                    }
                    return myXhr;
                },
                // events
                // beforeSend: null,
                success: aboutme.upload.successCallback,
                error: aboutme.upload.errorCallback,
                // Form data
                data: formData,
                // Options to tell jQuery not to process data or worry about content-type.
                cache: false,
                contentType: false,
                processData: false
            });
        },
        prepare: function(){
            var form = $('form.form_upload');
            form.hide();
            $.ajax({
                type: "GET",
                url: aboutme.path.upload_url
            }).done(function(data){
                if (!data){
                    alert(['Your request cannot be processed, please try again later.
Ref. #' + 500]);
                    return;
                }
                aboutme.upload.url = data;
                form.show();
            });
        },
        validate: function(){
            /*
            $(':file').change(function(){
                var file = this.files[0];
                var name = file.name;
                var size = file.size;
                var type = file.type;
                alert(name);
            });
            */
        },
        progressCallback: function(e){
            //if (e.lengthComputable)
            //    $('progress').attr({value:e.loaded,max:e.total});
        },
        successCallback: function (data){
            if (!data){
                alert(['Your request cannot be processed, please try again later.
Ref. #' + 500]);
                return;
            }
            // append photo
            $('div.gallery').append(aboutme.photo.getPhotoLink(data, aboutme.photo.num));
            aboutme.photo.initFancyBox(aboutme.photo.num++);

            // get new upload URL
            aboutme.upload.prepare();
        },
        errorCallback: function (error){
            //alert('errorHandler: ' + JSON.stringify(error));
            alert(['Your request cannot be processed, please try again later.
Ref. #' + 500]);
        }
    },
    photo: {
        num: 0,
        search: function(data){
            $.ajax({
                type: "GET",
                url: aboutme.path.photo_search,
                data: data
            }).done(function(data){
                if (!data || data.length < 1){
                    return;
                }
                var div = $('div.gallery');
                data.forEach(function(o){
                    div.append(aboutme.photo.getPhotoLink(o.pkey, aboutme.photo.num));
                    aboutme.photo.initFancyBox(aboutme.photo.num++);
                });
            });
        },
        getPhotoLink: function(id, index){
            var
            p = aboutme.path.photo_view + '?id=' + id,
            d = p + '&full=1';
            return '';
        },
        initFancyBox: function(index){
            $('a#img_' + index).fancybox({
                'type'          : 'image',
                'transitionIn'  : 'elastic',
                'transitionOut' : 'fade'
            });
        }
    }
};
<|endoftext|>


<commit_before>var webpackConfig = require('./webpack/webpack.config.js');

module.exports = function (config) {
  var configObject = {
    frameworks: ['jasmine'],
    basePath: '',
    files: [
      'node_modules/polyfill-function-prototype-bind/bind.js',
      'node_modules/es6-promise/dist/es6-promise.js',
      'src/modules/grid-spec-helper/matchers.js',
      'webpack/test-entry.js',
    ],
    preprocessors: {
      'webpack/test-entry.js': ['webpack', 'sourcemap'],
      'src/modules/grid-spec-helper/matchers.js': ['webpack', 'sourcemap'],
    },
    webpackMiddleware: {
      noInfo: true,
    },
    autoWatch: true,
    reporters: ['progress'],
    browsers: ['ChromeHeadlessNoSandbox'],
    customLaunchers: {
      ChromeHeadlessNoSandbox: {
        base: 'ChromeHeadless',
        flags: '--no-sandbox',
      },
    },
    junitReporter: {
      outputFile: 'test_out/unit.xml',
      suite: 'unit',
    },
    notifyReporter: {
      reportSuccess: false,
    },
    browserNoActivityTimeout: 3000000,
    reportSlowerThan: 250,
    webpack: require('./webpack/webpack.test'),
  };
  config.set(configObject);
};
<commit_msg>fix(build): flags is an array<commit_after>var webpackConfig = require('./webpack/webpack.config.js');

module.exports = function (config) {
  var configObject = {
    frameworks: ['jasmine'],
    basePath: '',
    files: [
      'node_modules/polyfill-function-prototype-bind/bind.js',
      'node_modules/es6-promise/dist/es6-promise.js',
      'src/modules/grid-spec-helper/matchers.js',
      'webpack/test-entry.js',
    ],
    preprocessors: {
      'webpack/test-entry.js': ['webpack', 'sourcemap'],
      'src/modules/grid-spec-helper/matchers.js': ['webpack', 'sourcemap'],
    },
    webpackMiddleware: {
      noInfo: true,
    },
    autoWatch: true,
    reporters: ['progress'],
    browsers: ['ChromeHeadlessNoSandbox'],
    customLaunchers: {
      ChromeHeadlessNoSandbox: {
        base: 'ChromeHeadless',
        flags: ['--no-sandbox'],
      },
    },
    junitReporter: {
      outputFile: 'test_out/unit.xml',
      suite: 'unit',
    },
    notifyReporter: {
      reportSuccess: false,
    },
    browserNoActivityTimeout: 3000000,
    reportSlowerThan: 250,
    webpack: require('./webpack/webpack.test'),
  };
  config.set(configObject);
};
<|endoftext|>


<commit_before>'use strict';

var express = require('express'),
	constants = require('./../config/constants'),
	config = require('./../config/config'),
	repository = require('./../util/repository'),
	logger = require('./../util/logger'),
	router = express.Router();

var auth = require('./../services/auth');

router
	.get(constants.SIGN_OUT_PATH, function (req, res) {
		var access_token = req.cookies[constants.AUTH_ACCESS_TOKEN_NAME];
    if (!access_token) {
	    res.set('www-authenticate', constants.NO_TOKEN);
	    res.send(401);
	    return;
    }
		function errorHandler(err) {
			res.clearCookie(constants.AUTH_ACCESS_TOKEN_NAME, { path: '/api' });
			res.send(500);
			logger.error(err);
		}
    repository.get(access_token).then(function (data) {
      try {
        data = JSON.parse(data);
        req._userId = data.user_id;
        auth.revokeRefreshToken(data.refresh_token).then(function () {
          repository.del(access_token);
          res.clearCookie(constants.AUTH_ACCESS_TOKEN_NAME, { path: '/api' });
          res.send(200);
        }, errorHandler);
      } catch (err) {
	      errorHandler(err);
      }
    }, errorHandler);
	})
	.get(constants.CLIENT_CONFIG_PATH, function (req, res) {
		res.send(200, config.clientConfig);
	})
	.post(constants.LOG_PATH, function (req, res) {
		var timestamp = Date.now(),
				startDate = new Date(timestamp),
				data = req.body;
		if (!data) {
			throw(new Error('No log data sent.'));
		}
		if (!data.message) {
			throw(new Error('Missing log message.'));
		}
		if (data.level && typeof logger[data.level] !== 'function') {
			throw(new Error('Invalid log level: ' + data.level));
		}
		if (!data.level) {
			data.level = 'error'; // Default logging level for CWA logs
		}
		res.send(200);
		logger[data.level](String(data.message), {
			appName: 'CWA',
			timestamp: timestamp,
			datetime: startDate,
			httpUserAgent: req.headers['user-agent'],
			httpClientIP: req.ip || req._remoteAddress || (req.connection && req.connection.remoteAddress),
			httpVia: req.headers.via,
			httpXForwardedFor: req.headers['x-forwarded-for'],
			stack: data.stack
		});
	});

module.exports = router;
<commit_msg>req.body is already set when bodyParser is used.<commit_after>'use strict';

var express = require('express'),
	constants = require('./../config/constants'),
	config = require('./../config/config'),
	repository = require('./../util/repository'),
	logger = require('./../util/logger'),
	router = express.Router();

var auth = require('./../services/auth');

router
	.get(constants.SIGN_OUT_PATH, function (req, res) {
		var access_token = req.cookies[constants.AUTH_ACCESS_TOKEN_NAME];
    if (!access_token) {
	    res.set('www-authenticate', constants.NO_TOKEN);
	    res.send(401);
	    return;
    }
		function errorHandler(err) {
			res.clearCookie(constants.AUTH_ACCESS_TOKEN_NAME, { path: '/api' });
			res.send(500);
			logger.error(err);
		}
    repository.get(access_token).then(function (data) {
      try {
        data = JSON.parse(data);
        req._userId = data.user_id;
        auth.revokeRefreshToken(data.refresh_token).then(function () {
          repository.del(access_token);
          res.clearCookie(constants.AUTH_ACCESS_TOKEN_NAME, { path: '/api' });
          res.send(200);
        }, errorHandler);
      } catch (err) {
	      errorHandler(err);
      }
    }, errorHandler);
	})
	.get(constants.CLIENT_CONFIG_PATH, function (req, res) {
		res.send(200, config.clientConfig);
	})
	.post(constants.LOG_PATH, function (req, res) {
		var timestamp = Date.now(),
				startDate = new Date(timestamp),
				data = req.body;
		if (!data || !data.message) {
			throw(new Error('Missing log message.'));
		}
		if (data.level && typeof logger[data.level] !== 'function') {
			throw(new Error('Invalid log level: ' + data.level));
		}
		if (!data.level) {
			data.level = 'error'; // Default logging level for CWA logs
		}
		res.send(200);
		logger[data.level](String(data.message), {
			appName: 'CWA',
			timestamp: timestamp,
			datetime: startDate,
			httpUserAgent: req.headers['user-agent'],
			httpClientIP: req.ip || req._remoteAddress || (req.connection && req.connection.remoteAddress),
			httpVia: req.headers.via,
			httpXForwardedFor: req.headers['x-forwarded-for'],
			stack: data.stack
		});
	});

module.exports = router;
<|endoftext|>


<commit_before>'use strict';

var createComponent = require('./createComponent');
var ContainerMixin = require('./ContainerMixin');
var LayerMixin = require('./LayerMixin');
var RenderLayer = require('./RenderLayer');

var Group = createComponent('Group', LayerMixin, ContainerMixin, {

  mountComponent: function (rootID, transaction, context) {
    var props = this._currentElement.props;
    var layer = this.node;

    this.applyLayerProps({}, props);
    this.mountAndInjectChildren(props.children, transaction, context);

    return layer;
  },

  receiveComponent: function (nextComponent, transaction, context) {
    var props = nextComponent.props;
    var prevProps = this._currentElement.props;
    this.applyLayerProps(prevProps, props);
    this.updateChildren(props.children, transaction, context);
    this._currentElement = nextComponent;
  },

  unmountComponent: function () {
    LayerMixin.unmountComponent.call(this);
    this.unmountChildren();
  }

});

module.exports = Group;
<commit_msg>Invalidate backing layer for <Group> on child updates.<commit_after>'use strict';

var createComponent = require('./createComponent');
var ContainerMixin = require('./ContainerMixin');
var LayerMixin = require('./LayerMixin');
var RenderLayer = require('./RenderLayer');

var Group = createComponent('Group', LayerMixin, ContainerMixin, {

  mountComponent: function (rootID, transaction, context) {
    var props = this._currentElement.props;
    var layer = this.node;

    this.applyLayerProps({}, props);
    this.mountAndInjectChildren(props.children, transaction, context);

    return layer;
  },

  receiveComponent: function (nextComponent, transaction, context) {
    var props = nextComponent.props;
    var prevProps = this._currentElement.props;
    this.applyLayerProps(prevProps, props);
    this.updateChildren(props.children, transaction, context);
    this._currentElement = nextComponent;
    this.node.invalidateLayout();
  },

  unmountComponent: function () {
    LayerMixin.unmountComponent.call(this);
    this.unmountChildren();
  }

});

module.exports = Group;
<|endoftext|>


<commit_before>/*
 * This file is part of Dependency-Track.
 *
 * Dependency-Track is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option) any
 * later version.
 *
 * Dependency-Track is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * Dependency-Track. If not, see http://www.gnu.org/licenses/.
 */

"use strict";

/**
 * Called by bootstrap table to format the data in the projects table.
 */
function formatProjectsTable(res) {
    for (let i=0; i<res.length; i++) {
        let projecturl = "../project?uuid=" + res[i].uuid;
        res[i].projecthref = "" + res[i].name + "";
    }
    return res;
}

/**
 * Service called when a project is created.
 */
function createProject() {
    const name = $("#createProjectNameInput").val();
    const version = $("#createProjectVersionInput").val();
    const description = $("#createProjectDescriptionInput").val();
    const tags = tagsStringToObjectArray($("#createProjectTagsInput").val());
    console.log("name: " + name);
    console.log("version: " + version);
    console.log("description: " + description);
    console.log("tags: " + tags);
    $.ajax({
        url: contextPath() + URL_PROJECT,
        contentType: CONTENT_TYPE_JSON,
        dataType: DATA_TYPE,
        type: METHOD_PUT,
        data: JSON.stringify({name: name, version: version, description: description, tags: tags}),
        statusCode: {
            201: function(data) {
                $("#projectsTable").bootstrapTable("refresh", {silent: true});
            }
        },
        error: function(xhr, ajaxOptions, thrownError) {
            console.log("failed");
        }
    });
    clearInputFields();
}

/**
 * Given a comma-separated string of tags, creates an
 * array of tag objects.
 */
function tagsStringToObjectArray(tagsString) {
    let tagsArray = [];
    if (!isEmpty(tagsString)) {
        let tmpArray = tagsString.split(",");
        for (let i in tmpArray) {
            tagsArray.push({name: tmpArray[i]});
        }
    }
    return tagsArray;
}

/**
 * Clears all the input fields from the modal.
 */
function clearInputFields() {
    $("#createProjectNameInput").val("");
    $("#createProjectVersionInput").val("");
    $("#createProjectDescriptionInput").val("");
    $("#createProjectTagsInput").val("");
}

/**
 * Service called when a project is updated.
 */
function updateProject() {
    const uuid = $(this).data("project-uuid");
    const name = $("#inputProjectName-" + uuid).val();
    const version = $("#inputProjectVersion-" + uuid).val();
    const description = $("#inputProjectDescription-" + uuid).val();
    const tags = $("#inputProjectTags-" + uuid).val();
    $.ajax({
        url: contextPath() + URL_PROJECT,
        contentType: CONTENT_TYPE_JSON,
        dataType: DATA_TYPE,
        type: METHOD_POST,
        data: JSON.stringify({uuid: uuid, name: name, version: version, description: description, tags: tags}),
        statusCode: {
            200: function(data) {
                $("#projectsTable").bootstrapTable("refresh", {silent: true});
            },
            404: function(data) {
                //todo: the uuid of the project could not be found
            }
        },
        error: function(xhr, ajaxOptions, thrownError){
            console.log("failed");
        }
    });
}

/**
 * Service called when a project is deleted.
 */
function deleteProject() {
    const uuid = $(this).data("project-uuid");
    $.ajax({
        url: contextPath() + URL_PROJECT,
        contentType: CONTENT_TYPE_JSON,
        type: METHOD_DELETE,
        data: JSON.stringify({uuid: uuid}),
        statusCode: {
            204: function(data) {
                const projectsTable = $('#projectsTable');
                projectsTable.expanded = false;
                projectsTable.bootstrapTable("collapseAllRows");
                projectsTable.bootstrapTable("refresh", {silent: true});
            },
            404: function(data) {
                //todo: the uuid of the project could not be found
            }
        },
        error: function(xhr, ajaxOptions, thrownError){
            console.log("failed");
        }
    });
}

/**
 * Setup events and trigger other stuff when the page is loaded and ready
 */
$(document).ready(function () {

    // Initialize all tooltips
    $('[data-toggle="tooltip"]').tooltip();

    // Listen for if the button to create a project is clicked
    $("#createProjectCreateButton").on("click", createProject);

    // When modal closes, clear out the input fields
    $("#modalCreateProject").on("hidden.bs.modal", function () {
        $("#createProjectNameInput").val("");
    });

});<commit_msg>removed unused function<commit_after>/*
 * This file is part of Dependency-Track.
 *
 * Dependency-Track is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option) any
 * later version.
 *
 * Dependency-Track is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * Dependency-Track. If not, see http://www.gnu.org/licenses/.
 */

"use strict";

/**
 * Called by bootstrap table to format the data in the projects table.
 */
function formatProjectsTable(res) {
    for (let i=0; i<res.length; i++) {
        let projecturl = "../project?uuid=" + res[i].uuid;
        res[i].projecthref = "" + res[i].name + "";
    }
    return res;
}

/**
 * Service called when a project is created.
 */
function createProject() {
    const name = $("#createProjectNameInput").val();
    const version = $("#createProjectVersionInput").val();
    const description = $("#createProjectDescriptionInput").val();
    const tags = tagsStringToObjectArray($("#createProjectTagsInput").val());
    console.log("name: " + name);
    console.log("version: " + version);
    console.log("description: " + description);
    console.log("tags: " + tags);
    $.ajax({
        url: contextPath() + URL_PROJECT,
        contentType: CONTENT_TYPE_JSON,
        dataType: DATA_TYPE,
        type: METHOD_PUT,
        data: JSON.stringify({name: name, version: version, description: description, tags: tags}),
        statusCode: {
            201: function(data) {
                $("#projectsTable").bootstrapTable("refresh", {silent: true});
            }
        },
        error: function(xhr, ajaxOptions, thrownError) {
            console.log("failed");
        }
    });
    clearInputFields();
}

/**
 * Given a comma-separated string of tags, creates an
 * array of tag objects.
 */
function tagsStringToObjectArray(tagsString) {
    let tagsArray = [];
    if (!isEmpty(tagsString)) {
        let tmpArray = tagsString.split(",");
        for (let i in tmpArray) {
            tagsArray.push({name: tmpArray[i]});
        }
    }
    return tagsArray;
}

/**
 * Clears all the input fields from the modal.
 */
function clearInputFields() {
    $("#createProjectNameInput").val("");
    $("#createProjectVersionInput").val("");
    $("#createProjectDescriptionInput").val("");
    $("#createProjectTagsInput").val("");
}

/**
 * Setup events and trigger other stuff when the page is loaded and ready
 */
$(document).ready(function () {

    // Initialize all tooltips
    $('[data-toggle="tooltip"]').tooltip();

    // Listen for if the button to create a project is clicked
    $("#createProjectCreateButton").on("click", createProject);

    // When modal closes, clear out the input fields
    $("#modalCreateProject").on("hidden.bs.modal", function () {
        $("#createProjectNameInput").val("");
    });

});<|endoftext|>


<commit_before>var rest = require('restler');
var cheerio = require('cheerio');
var geolib = require('geolib');
var parseString = require('xml2js').parseString;
var util = require('./util');
var nusbusstops = require('./nusbusstops.json');
var ltaCredentials = require('./private/lta_credentials.json');

var busStops = [19059, 19051, 17099, 17091];
var defaultBusStop = 19059;

var busStopUrl =
    'http://datamall2.mytransport.sg/ltaodataservice/BusArrival?BusStopID=';

var busStopHeaders = {
    'AccountKey': ltaCredentials.AccountKey,
    'UniqueUserID': ltaCredentials.UniqueUserID
};

function busStop(id, callback) {
    if (callback === undefined) {
        callback = console.log;
    }
    var reqUrl = busStopUrl + id.toString();
    var reqOptions = {
        'headers': busStopHeaders,
        'timeout': 5000
    };
    var response = send(reqUrl, reqOptions, callback);
    return response;
}

function send(reqUrl, reqOptions, callback) {
    return rest.get(reqUrl, reqOptions).on('timeout', function() {
        callback("LTA service is busy at the moment. Please try again in a few minutes 😊");
    }).on('complete', function(data) {
        processInfo(data, callback);
    });
}

function processInfo(data, callback) {
    if (data.hasOwnProperty("odata.error")) {
        return callback("Invalid Bus Stop ID :(\nTry again.");
        // return callback(data["odata.error"].message.value);
    }

    var busTimingsList = "";
    var header;
    data.Services.forEach(function(bus) {
        if (bus.Status === 'In Operation') {
            var nextBusTime = new Date(bus.NextBus.EstimatedArrival);
            var subseqBusTime = new Date(bus.SubsequentBus.EstimatedArrival);
            busTimingsList += bus.ServiceNo + ' - ' +
                util.timeLeftMin(nextBusTime) + ', ' +
                util.timeLeftMin(subseqBusTime) + '\n';
        }
    });
    header = (busTimingsList === "") ? "Go walk home 😜" : "Buses in operation:";
    busTimingsList = (busTimingsList) ? busTimingsList : "";
    callback(header + '\n' + busTimingsList);
}

function nusbus(callback, busstop_name, location) {
    var busstopMap = {
        "utown": "UTown",
        "computing": "COM2",
        "central library": "CENLIB",
        "computer centre": "COMCEN",
        "science": "LT29",
        "business": "HSSML-OPP",
        "kent ridge mrt": "KR-MRT",
        "bukit timah campus": "BUKITTIMAH-BTC2",
        "pgp terminal": "PGPT"
    };

    var busstop;
    if (location) {
        busstop = nearestNUSBustop(location);
    } else {
        busstop = busstopMap[busstop_name];
    }
    if (!busstop) {
        return callback("❗ Invalid Bus Stop Chosen. Send location or choose again ", null);
    }

    var reqURL = "http://nextbus.comfortdelgro.com.sg//testMethod.asmx/GetShuttleService?busstopname=" + busstop;
    rest.get(reqURL, {
        timeout: 5000
    }).on('timeout', function() {
        callback("NUS Bus Service is busy at the moment. Please try again in a few minutes 😊");
    }).on('complete', function(data) {
        parseString(data, function(err, result) {
            if (!err) {
                var busdata = JSON.parse(result.string._);
                var list = "";
                if (location) {
                    list = "From your location, I have identified: " + "_" + busstop + "_" + " as the nearest bus stop\n\n";
                } else {
                    list = "Your selected location is " + "_" + busstop + "_" + "\n\n";
                }
                list += "Here are the Buses and the respective timings:\n";
                busdata.ShuttleServiceResult.shuttles.forEach(function(shuttle) {
                    var shuttleMessage = "";
                    var shuttleNextMessage = "";
                    if ((shuttle.arrivalTime === "-") || (shuttle.arrivalTime === "N.A")) {
                        if ((shuttle.nextArrivalTime === "-") || (shuttle.nextArrivalTime === "N.A")) {
                            shuttleMessage += " 🚫 The Service is *Not* Available ";
                        } else {
                            shuttleNextMessage += shuttle.nextArrivalTime + " min";
                        }
                    } else if ((shuttle.arrivalTime === "Arr") || (shuttle.nextArrivalTime === "Arr")) {
                        shuttleMessage += shuttle.arrivalTime + " , ";
                        shuttleNextMessage += shuttle.nextArrivalTime + " ";
                    } else {
                        shuttleMessage += shuttle.arrivalTime + " min, ";
                        shuttleNextMessage += shuttle.nextArrivalTime + " min";
                    }

                    list += "*" + shuttle.name + "*" + ": ";
                    list += shuttleMessage;
                    list += shuttleNextMessage + "\n";
                });
                return callback(null, list);
            }
        });
    });
}

function nearestNUSBustop(start) {
    var minDist = Infinity;
    var minLoc = "UTown";
    for (var i = 0; i < nusbusstops.length; i++) {
        var dist = geolib.getDistance(start, nusbusstops[i]);
        if (dist < minDist) {
            minDist = dist;
            minLoc = nusbusstops[i].name;
        }
    }
    return minLoc;
}

module.exports = {
    'busStopQuery': busStop,
    'defaultBusStop': defaultBusStop,
    'nusbus': nusbus
};
<commit_msg>fixed formatting for invalid case<commit_after>var rest = require('restler');
var cheerio = require('cheerio');
var geolib = require('geolib');
var parseString = require('xml2js').parseString;
var util = require('./util');
var nusbusstops = require('./nusbusstops.json');
var ltaCredentials = require('./private/lta_credentials.json');

var busStops = [19059, 19051, 17099, 17091];
var defaultBusStop = 19059;

var busStopUrl =
    'http://datamall2.mytransport.sg/ltaodataservice/BusArrival?BusStopID=';

var busStopHeaders = {
    'AccountKey': ltaCredentials.AccountKey,
    'UniqueUserID': ltaCredentials.UniqueUserID
};

function busStop(id, callback) {
    if (callback === undefined) {
        callback = console.log;
    }
    var reqUrl = busStopUrl + id.toString();
    var reqOptions = {
        'headers': busStopHeaders,
        'timeout': 5000
    };
    var response = send(reqUrl, reqOptions, callback);
    return response;
}

function send(reqUrl, reqOptions, callback) {
    return rest.get(reqUrl, reqOptions).on('timeout', function() {
        callback("LTA service is busy at the moment. Please try again in a few minutes 😊");
    }).on('complete', function(data) {
        processInfo(data, callback);
    });
}

function processInfo(data, callback) {
    if (data.hasOwnProperty("odata.error")) {
        return callback("Invalid Bus Stop ID :(\nTry again.");
        // return callback(data["odata.error"].message.value);
    }

    var busTimingsList = "";
    var header;
    data.Services.forEach(function(bus) {
        if (bus.Status === 'In Operation') {
            var nextBusTime = new Date(bus.NextBus.EstimatedArrival);
            var subseqBusTime = new Date(bus.SubsequentBus.EstimatedArrival);
            busTimingsList += bus.ServiceNo + ' - ' +
                util.timeLeftMin(nextBusTime) + ', ' +
                util.timeLeftMin(subseqBusTime) + '\n';
        }
    });
    header = (busTimingsList === "") ? "Go walk home 😜" : "Buses in operation:";
    busTimingsList = (busTimingsList) ? busTimingsList : "";
    callback(header + '\n' + busTimingsList);
}

function nusbus(callback, busstop_name, location) {
    var busstopMap = {
        "utown": "UTown",
        "computing": "COM2",
        "central library": "CENLIB",
        "computer centre": "COMCEN",
        "science": "LT29",
        "business": "HSSML-OPP",
        "kent ridge mrt": "KR-MRT",
        "bukit timah campus": "BUKITTIMAH-BTC2",
        "pgp terminal": "PGPT"
    };

    var busstop;
    if (location) {
        busstop = nearestNUSBustop(location);
    } else {
        busstop = busstopMap[busstop_name];
    }
    if (!busstop) {
        return callback("Invalid Bus Stop Chosen. Send location or choose again", null);
    }

    var reqURL = "http://nextbus.comfortdelgro.com.sg//testMethod.asmx/GetShuttleService?busstopname=" + busstop;
    rest.get(reqURL, {
        timeout: 5000
    }).on('timeout', function() {
        callback("NUS Bus Service is busy at the moment. Please try again in a few minutes 😊");
    }).on('complete', function(data) {
        parseString(data, function(err, result) {
            if (!err) {
                var busdata = JSON.parse(result.string._);
                var list = "";
                if (location) {
                    list = "From your location, I have identified: " + "_" + busstop + "_" + " as the nearest bus stop\n\n";
                } else {
                    list = "Your selected location is " + "_" + busstop + "_" + "\n\n";
                }
                list += "Here are the Buses and the respective timings:\n";
                busdata.ShuttleServiceResult.shuttles.forEach(function(shuttle) {
                    var shuttleMessage = "";
                    var shuttleNextMessage = "";
                    if ((shuttle.arrivalTime === "-") || (shuttle.arrivalTime === "N.A")) {
                        if ((shuttle.nextArrivalTime === "-") || (shuttle.nextArrivalTime === "N.A")) {
                            shuttleMessage += " 🚫 The Service is *Not* Available ";
                        } else {
                            shuttleNextMessage += shuttle.nextArrivalTime + " min";
                        }
                    } else if ((shuttle.arrivalTime === "Arr") || (shuttle.nextArrivalTime === "Arr")) {
                        shuttleMessage += shuttle.arrivalTime + " , ";
                        shuttleNextMessage += shuttle.nextArrivalTime + " ";
                    } else {
                        shuttleMessage += shuttle.arrivalTime + " min, ";
                        shuttleNextMessage += shuttle.nextArrivalTime + " min";
                    }

                    list += "*" + shuttle.name + "*" + ": ";
                    list += shuttleMessage;
                    list += shuttleNextMessage + "\n";
                });
                return callback(null, list);
            }
        });
    });
}

function nearestNUSBustop(start) {
    var minDist = Infinity;
    var minLoc = "UTown";
    for (var i = 0; i < nusbusstops.length; i++) {
        var dist = geolib.getDistance(start, nusbusstops[i]);
        if (dist < minDist) {
            minDist = dist;
            minLoc = nusbusstops[i].name;
        }
    }
    return minLoc;
}

module.exports = {
    'busStopQuery': busStop,
    'defaultBusStop': defaultBusStop,
    'nusbus': nusbus
};
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import Carousel from 'nuka-carousel';
import VideoThumb from './VideoThumb';
import SmallDropdownButton from './SmallDropdownButton';

class PlaylistCarousel extends Component {
  renderThumbs () {
    const { playlist } = this.props;
    let index = 0;
    return playlist.map(thumb => {
      return (
        <VideoThumb key={index++} video={{
          videocode: thumb.videocode,
          title: thumb.video_title,
          uploadername: thumb.video_uploader
        }} />
      )
    })
  }

  onEditTitle() {

  }

  onDeleteClick() {

  }

  render () {
    const { title, uploader, editable } = this.props;
    const menuProps = [
      {
        label: 'Edit Title',
        onClick: this.onEditTitle.bind(this)
      },
      {
        label: 'Change Videos',
        onClick: this.onEditTitle.bind(this)
      },
      {
        label: 'Reorder Videos',
        onClick: this.onEditTitle.bind(this)
      },
      {
        separator: true
      },
      {
        label: 'Remove Playlist',
        onClick: this.onDeleteClick.bind(this)
      }
    ]
    return (

            {title} by {uploader}

          {
            editable && <SmallDropdownButton
              menuProps={menuProps}
              rightMargin="1em"
            />
          }

        <Carousel slidesToShow={5} slidesToScroll={5} cellSpacing={20}>
          { this.renderThumbs() }
        </Carousel>

    )
  }
}

export default PlaylistCarousel;
<commit_msg>Adding playlist title edit feature<commit_after>import React, { Component } from 'react';
import Carousel from 'nuka-carousel';
import VideoThumb from './VideoThumb';
import SmallDropdownButton from './SmallDropdownButton';

class PlaylistCarousel extends Component {
  state = {
    onEdit: false
  }

  renderThumbs () {
    const { playlist } = this.props;
    let index = 0;
    return playlist.map(thumb => {
      return (
        <VideoThumb key={index++} video={{
          videocode: thumb.videocode,
          title: thumb.video_title,
          uploadername: thumb.video_uploader
        }} />
      )
    })
  }

  onEditTitle() {
    this.setState({onEdit: true})
  }

  onDeleteClick() {

  }

  render () {
    const { onEdit } = this.state;
    const { title, uploader, editable } = this.props;
    const menuProps = [
      {
        label: 'Edit Title',
        onClick: this.onEditTitle.bind(this)
      },
      {
        label: 'Change Videos',
        onClick: this.onEditTitle.bind(this)
      },
      {
        label: 'Reorder Videos',
        onClick: this.onEditTitle.bind(this)
      },
      {
        separator: true
      },
      {
        label: 'Remove Playlist',
        onClick: this.onDeleteClick.bind(this)
      }
    ]
    return (

          {
            onEdit ?

              <form>
                <input
                  ref="editTitleInput"
                  type="text"
                  className="form-control"
                  placeholder="Enter Title..."
                />
              </form>

            :

              {title} by {uploader}

          }
          {
            editable && <SmallDropdownButton
              menuProps={menuProps}
              rightMargin="1em"
            />
          }

        <Carousel slidesToShow={5} slidesToScroll={5} cellSpacing={20}>
          { this.renderThumbs() }
        </Carousel>

    )
  }
}

export default PlaylistCarousel;
<|endoftext|>


<commit_before>#!/usr/bin/env node --harmony

'use strict';

var Mocha = require('mocha');
var childProcess = require('child_process');
var fs = require('fs');
var jsonfile = require('jsonfile');
var packageInfo = require('../package.json');
var path = require('path');
var prompt = require('prompt');
var spawn = require('child_process').spawn;

jsonfile.spaces = 2;

prompt.colors = false;
prompt.message = '';
prompt.delimiter = '';
prompt.start();

var curVersion = packageInfo.version;
var defaultRelease = curVersion.replace(/-SNAPSHOT$/, '');

if (curVersion === defaultRelease) {
  throw new Error('Not a SNAPSHOT version!');
}

function doRelease() {
  var packagePath = path.resolve(__dirname, '..', 'package.json');

  prompt.get({
    properties: {
      releaseVersion: {
        description: 'Release version [' + defaultRelease + ']: ',
        pattern: /[0-9]+[.][0-9]+[.][0-9]/
      }
    }
  }, function(err, result) {
    if (err) {
      throw err;
    }

    var releaseVersion = result.releaseVersion || defaultRelease;
    var splitVersion = releaseVersion.split('.').map(function(s) {
      return parseInt(s, 10);
    });

    splitVersion[2] += 1;
    var defaultNext = splitVersion.join('.') + '-SNAPSHOT';

    prompt.get({
      properties: {
        nextVersion: {
          description: 'Next version[' + defaultNext + ']:',
          pattern: /[0-9]+[.][0-9]+[.][0-9]-SNAPSHOT/
        }
      }
    }, function(nErr, nResult) {
      if (err) {
        throw err;
      }

      var nextVersion = nResult.nextVersion || defaultNext;

      packageInfo.version = releaseVersion;
      jsonfile.writeFileSync(packagePath, packageInfo);

      childProcess.execSync('git add ' + packagePath);
      childProcess.execSync('git commit -m "Setting version to ' +
        releaseVersion +
        '"');
      childProcess.execSync('git tag v' + releaseVersion);

      packageInfo.version = nextVersion;
      jsonfile.writeFileSync(packagePath, packageInfo);

      childProcess.execSync('git add ' + packagePath);
      childProcess.execSync('git commit -m "Setting version to ' +
        nextVersion +
        '"');
      prompt.get({
        properties: {
          doPush: {
            description: 'Push changes to the remote repository (y/n)? ' + '[y]:'
          }
        }
      }, function(pErr, pResult) {
        if (pErr) {
          throw pErr;
        }

        if (pResult.doPush.toLowerCase() === 'y') {
          console.log('pushing changes...');
          childProcess.execSync('git push', {stdio: 'inherit'});
          childProcess.execSync('git push --tags', {stdio: 'inherit'});
          console.log('Done.');
        }
      });
    });
  });
}

// var test = spawn('npm', ['test'], {cwd: __dirname + '/..', stdio: 'inherit'});
// test.on('close', function(code) {
//   if (code !== 0) throw new Error("Exited with code " + code);
//   doRelease();
// });

doRelease();<commit_msg>Actually push if you accept the default behavior<commit_after>#!/usr/bin/env node --harmony

'use strict';

var Mocha = require('mocha');
var childProcess = require('child_process');
var fs = require('fs');
var jsonfile = require('jsonfile');
var packageInfo = require('../package.json');
var path = require('path');
var prompt = require('prompt');
var spawn = require('child_process').spawn;

jsonfile.spaces = 2;

prompt.colors = false;
prompt.message = '';
prompt.delimiter = '';
prompt.start();

var curVersion = packageInfo.version;
var defaultRelease = curVersion.replace(/-SNAPSHOT$/, '');

if (curVersion === defaultRelease) {
  throw new Error('Not a SNAPSHOT version!');
}

function doRelease() {
  var packagePath = path.resolve(__dirname, '..', 'package.json');

  prompt.get({
    properties: {
      releaseVersion: {
        description: 'Release version [' + defaultRelease + ']: ',
        pattern: /[0-9]+[.][0-9]+[.][0-9]/
      }
    }
  }, function(err, result) {
    if (err) {
      throw err;
    }

    var releaseVersion = result.releaseVersion || defaultRelease;
    var splitVersion = releaseVersion.split('.').map(function(s) {
      return parseInt(s, 10);
    });

    splitVersion[2] += 1;
    var defaultNext = splitVersion.join('.') + '-SNAPSHOT';

    prompt.get({
      properties: {
        nextVersion: {
          description: 'Next version[' + defaultNext + ']:',
          pattern: /[0-9]+[.][0-9]+[.][0-9]-SNAPSHOT/
        }
      }
    }, function(nErr, nResult) {
      if (err) {
        throw err;
      }

      var nextVersion = nResult.nextVersion || defaultNext;

      packageInfo.version = releaseVersion;
      jsonfile.writeFileSync(packagePath, packageInfo);

      childProcess.execSync('git add ' + packagePath);
      childProcess.execSync('git commit -m "Setting version to ' +
        releaseVersion +
        '"');
      childProcess.execSync('git tag v' + releaseVersion);

      packageInfo.version = nextVersion;
      jsonfile.writeFileSync(packagePath, packageInfo);

      childProcess.execSync('git add ' + packagePath);
      childProcess.execSync('git commit -m "Setting version to ' +
        nextVersion +
        '"');
      prompt.get({
        properties: {
          doPush: {
            description: 'Push changes to the remote repository (y/n)? ' + '[y]:'
          }
        }
      }, function(pErr, pResult) {
        if (pErr) {
          throw pErr;
        }

        var doPush = pResult.doPush.toLowerCase() || 'y';

        if (doPush === 'y') {
          console.log('pushing changes...');
          childProcess.execSync('git push', {stdio: 'inherit'});
          childProcess.execSync('git push --tags', {stdio: 'inherit'});
          console.log('Done.');
        }
      });
    });
  });
}

// var test = spawn('npm', ['test'], {cwd: __dirname + '/..', stdio: 'inherit'});
// test.on('close', function(code) {
//   if (code !== 0) throw new Error("Exited with code " + code);
//   doRelease();
// });

doRelease();
<|endoftext|>