<commit_before>/*
    Date: 2015-12-25
*/

var app = {
    self : {},

    onDeviceReady : function () {
        //alert("device ready.");
        if (device.platform === "iOS") {
            alert("got iOS.");
            // hide Exit button. They don't have one on iOS devices.
            // http://www.mzcart.com/javascript-how-to-addremove-css-class-from-a-dom-element/
            document.getElementById('exitApp').classList.add("hidden");
            // deals with post-iOS-7 change that covers the status bar
            // http://coenraets.org/blog/2013/09/phonegap-and-cordova-with-ios-7/
            document.body.style.marginTop = "20px";
            // hide the Splash Screen for iOS only
            navigator.splashscreen.hide();
        } else if (device.platform == 'Android') {
            // Get rid of 300ms delay
            document.addEventListener('DOMContentLoaded', function() { FastClick.attach(document.body); }, false);
            //
            document.getElementById('exitApp').addEventListener('click', function() {
                app.exit();
            });
        } else if (device.platform == 'browser') {
            document.getElementById('exitApp').addEventListener('click', function() {
                app.exit();
            });
        }
        plugin.test();
    },
    exit : function () {
        console.log('Called app.exit()');
        if ('app' in navigator) {
            navigator.app.exitApp();
        } else {
            alert('exit button hit.');
        }
    }
};

//
// Wait for PhoneGap to load
document.addEventListener("deviceready", app.onDeviceReady, false);

var plugin = {
    self        : {},
    directories : {},

    // Is API available?
    test : function () {
        console.log("app.test");
        $('#isavailable').html(plugin.isAvailable('requestFileSystem'));
    },
    // Open/Close
    test2 : function (data) {
        $('#resultPlugin').html(data);
    },
    // Support directory constants (on device)
    test3 : function (data) {
        $('#resultPlugin').html(data);
        var url  = cordova.file.applicationDirectory + "www/index.html";
        var url2 = cordova.file.applicationStorageDirectory;
        var url3 = cordova.file.dataDirectory;
        var url4 = cordova.file.cacheDirectory;
        window.resolveLocalFileSystemURL(url, function (fileEntry) {
            $('#resultPlugin').html(fileEntry.fullPath + ":"  +  fileEntry.isFile);

            window.resolveLocalFileSystemURL(url2, function (fileEntry) {
                $('#resultPlugin').html($('#resultPlugin').html() + "
" + fileEntry.fullPath  + ":"  +  fileEntry.isDirectory);

                window.resolveLocalFileSystemURL(url3, function (fileEntry) {
                    $('#resultPlugin').html($('#resultPlugin').html() + "
" + fileEntry.fullPath  + ":"  +  fileEntry.isDirectory);

                    window.resolveLocalFileSystemURL(url4, function (fileEntry) {
                        $('#resultPlugin').html($('#resultPlugin').html() + "
" + fileEntry.fullPath  + ":"  +  fileEntry.isDirectory);
                    });
                });
            });
        });
    },
    // Support directory constants (on device external)
    test4 : function (data) {
        $('#resultPlugin').html(data);
        var url5 = cordova.file.externalApplicationStorageDirectory;
        var url6 = cordova.file.externalDataDirectory;
        var url7 = cordova.file.externalCacheDirectory;
        var url8 = cordova.file.externalRootDirectory;
        window.resolveLocalFileSystemURL(url5, function (fileEntry) {
            $('#resultPlugin').html(fileEntry.fullPath + ":"  +  fileEntry.isDirectory);

            window.resolveLocalFileSystemURL(url6, function (fileEntry) {
                $('#resultPlugin').html($('#resultPlugin').html() + "
" + fileEntry.fullPath  + ":"  +  fileEntry.isDirectory);

                window.resolveLocalFileSystemURL(url7, function (fileEntry) {
                    $('#resultPlugin').html($('#resultPlugin').html() + "
" + fileEntry.fullPath  + ":"  +  fileEntry.isDirectory);

                    window.resolveLocalFileSystemURL(url8, function (fileEntry) {
                        $('#resultPlugin').html($('#resultPlugin').html() + "
" + fileEntry.fullPath  + ":"  +  fileEntry.isDirectory);
                    });
                });
            });
        });
    },
    // Read File
    test5 : function (data) {
        $('#resultPlugin').html(data);
        var url  = cordova.file.applicationDirectory + "www/README.md";

        window.resolveLocalFileSystemURL(url, function (fileEntry) {
            fileEntry.file(function(file) {

                var reader = new FileReader();

                reader.onloadend = function(e) {
                    //document.querySelector("#textArea").innerHTML = this.result;
                    $('#outputData').html(this.result);
                }

                reader.readAsText(file);
            });
        });
    },
    // write File
    test6 : function (data) {
        $('#resultPlugin').html(data);
        var url  = cordova.file.dataDirectory + "data.txt";

        var onInitFS = function(fs) {
            // $('#resultPlugin').html("onInitFS");
            url  = fs.root.nativeURL + "data.txt";
            $('#outputData').html("fs.root:" + JSON.stringify(fs.root));
            $('#resultPlugin').html("in fs.root:" + plugin.isThere('getFile', fs.root));
            $('#resultPlugin').html('url:' + url);

            fs.root.getFile(url, {create: true, exclusive: false}, function(fileEntry) {
                $('#resultPlugin').html("getFile");

                // Create a FileWriter object for our FileEntry (log.txt).
                fileEntry.createWriter(function(fileWriter) {
                    $('#resultPlugin').html("createWriter");

                    fileWriter.onwriteend = function(e) {
                        $('#resultPlugin').html('Write completed.');
                        //alert('Write completed.');
                    };

                    fileWriter.onerror = function(e) {
                        $('#outputError').html('Write failed: ' + e.toString());
                        //alert('Write failed: ' + e.toString());
                    };

                    // Create a new Blob and write it to log.txt.
                    var blob = new Blob(['Lorem Ipsum'], {type: 'text/plain'});

                    fileWriter.write(blob);
                }, plugin.handleError);
            }, plugin.handleError);
        };

        window.requestFileSystem(window.PERSISTENT, 1024, onInitFS, plugin.handleError)
        $('#resultPlugin').html('requestFileSystem completed.');
    },
    handleError : function (e) {
        $('#outputError').html('handleError');
        $('#outputError').addClass('error');
        $('#outputError').html(plugin.errorDecode(e));
        console.log(plugin.errorDecode(e));
        //alert(plugin.errorDecode(e));
    },
    errorDecode : function (e) {
        var msg = '';

        switch (e.code) {
          case FileError.QUOTA_EXCEEDED_ERR:
            msg = 'QUOTA_EXCEEDED_ERR';
          break;
          case FileError.NOT_FOUND_ERR:
            msg = 'NOT_FOUND_ERR';
          break;
          case FileError.SECURITY_ERR:
            msg = 'SECURITY_ERR';
          break;
          case FileError.INVALID_MODIFICATION_ERR:
             msg = 'INVALID_MODIFICATION_ERR';
          break;
          case FileError.INVALID_STATE_ERR:
             msg = 'INVALID_STATE_ERR';
          break;
          default:
            msg = 'Unknown Error';
          break;
        };
        return msg;
    },
    isThere : function (type, object) {
        return (type in object) ?  true : false;
    },
    // See alternate method: http://code.tutsplus.com/tutorials/working-with-indexeddb--net-34673 under "Let's Get Started"
    isAvailable : function (type) {
        return (type in window) ?  true : false;
    }
};

<commit_msg>change blob()<commit_after>/*
    Date: 2015-12-25
*/

var app = {
    self : {},

    onDeviceReady : function () {
        //alert("device ready.");
        if (device.platform === "iOS") {
            alert("got iOS.");
            // hide Exit button. They don't have one on iOS devices.
            // http://www.mzcart.com/javascript-how-to-addremove-css-class-from-a-dom-element/
            document.getElementById('exitApp').classList.add("hidden");
            // deals with post-iOS-7 change that covers the status bar
            // http://coenraets.org/blog/2013/09/phonegap-and-cordova-with-ios-7/
            document.body.style.marginTop = "20px";
            // hide the Splash Screen for iOS only
            navigator.splashscreen.hide();
        } else if (device.platform == 'Android') {
            // Get rid of 300ms delay
            document.addEventListener('DOMContentLoaded', function() { FastClick.attach(document.body); }, false);
            //
            document.getElementById('exitApp').addEventListener('click', function() {
                app.exit();
            });
        } else if (device.platform == 'browser') {
            document.getElementById('exitApp').addEventListener('click', function() {
                app.exit();
            });
        }
        plugin.test();
    },
    exit : function () {
        console.log('Called app.exit()');
        if ('app' in navigator) {
            navigator.app.exitApp();
        } else {
            alert('exit button hit.');
        }
    }
};

//
// Wait for PhoneGap to load
document.addEventListener("deviceready", app.onDeviceReady, false);

var plugin = {
    self        : {},
    directories : {},

    // Is API available?
    test : function () {
        console.log("app.test");
        $('#isavailable').html(plugin.isAvailable('requestFileSystem'));
    },
    // Open/Close
    test2 : function (data) {
        $('#resultPlugin').html(data);
    },
    // Support directory constants (on device)
    test3 : function (data) {
        $('#resultPlugin').html(data);
        var url  = cordova.file.applicationDirectory + "www/index.html";
        var url2 = cordova.file.applicationStorageDirectory;
        var url3 = cordova.file.dataDirectory;
        var url4 = cordova.file.cacheDirectory;
        window.resolveLocalFileSystemURL(url, function (fileEntry) {
            $('#resultPlugin').html(fileEntry.fullPath + ":"  +  fileEntry.isFile);

            window.resolveLocalFileSystemURL(url2, function (fileEntry) {
                $('#resultPlugin').html($('#resultPlugin').html() + "
" + fileEntry.fullPath  + ":"  +  fileEntry.isDirectory);

                window.resolveLocalFileSystemURL(url3, function (fileEntry) {
                    $('#resultPlugin').html($('#resultPlugin').html() + "
" + fileEntry.fullPath  + ":"  +  fileEntry.isDirectory);

                    window.resolveLocalFileSystemURL(url4, function (fileEntry) {
                        $('#resultPlugin').html($('#resultPlugin').html() + "
" + fileEntry.fullPath  + ":"  +  fileEntry.isDirectory);
                    });
                });
            });
        });
    },
    // Support directory constants (on device external)
    test4 : function (data) {
        $('#resultPlugin').html(data);
        var url5 = cordova.file.externalApplicationStorageDirectory;
        var url6 = cordova.file.externalDataDirectory;
        var url7 = cordova.file.externalCacheDirectory;
        var url8 = cordova.file.externalRootDirectory;
        window.resolveLocalFileSystemURL(url5, function (fileEntry) {
            $('#resultPlugin').html(fileEntry.fullPath + ":"  +  fileEntry.isDirectory);

            window.resolveLocalFileSystemURL(url6, function (fileEntry) {
                $('#resultPlugin').html($('#resultPlugin').html() + "
" + fileEntry.fullPath  + ":"  +  fileEntry.isDirectory);

                window.resolveLocalFileSystemURL(url7, function (fileEntry) {
                    $('#resultPlugin').html($('#resultPlugin').html() + "
" + fileEntry.fullPath  + ":"  +  fileEntry.isDirectory);

                    window.resolveLocalFileSystemURL(url8, function (fileEntry) {
                        $('#resultPlugin').html($('#resultPlugin').html() + "
" + fileEntry.fullPath  + ":"  +  fileEntry.isDirectory);
                    });
                });
            });
        });
    },
    // Read File
    test5 : function (data) {
        $('#resultPlugin').html(data);
        var url  = cordova.file.applicationDirectory + "www/README.md";

        window.resolveLocalFileSystemURL(url, function (fileEntry) {
            fileEntry.file(function(file) {

                var reader = new FileReader();

                reader.onloadend = function(e) {
                    //document.querySelector("#textArea").innerHTML = this.result;
                    $('#outputData').html(this.result);
                }

                reader.readAsText(file);
            });
        });
    },
    // write File
    test6 : function (data) {
        $('#resultPlugin').html(data);
        var url  = cordova.file.dataDirectory + "data.txt";

        var onInitFS = function(fs) {
            // $('#resultPlugin').html("onInitFS");
            url  = fs.root.nativeURL + "data.txt";
            $('#outputData').html("fs.root:" + JSON.stringify(fs.root));
            $('#resultPlugin').html("in fs.root:" + plugin.isThere('getFile', fs.root));
            $('#resultPlugin').html('url:' + url);

            fs.root.getFile(url, {create: true, exclusive: false}, function(fileEntry) {
                $('#resultPlugin').html("getFile");

                // Create a FileWriter object for our FileEntry (log.txt).
                fileEntry.createWriter(function(fileWriter) {
                    $('#resultPlugin').html("createWriter");

                    fileWriter.onwriteend = function(e) {
                        $('#resultPlugin').html('Write completed.');
                        //alert('Write completed.');
                    };

                    fileWriter.onerror = function(e) {
                        $('#outputError').html('Write failed: ' + e.toString());
                        //alert('Write failed: ' + e.toString());
                    };

                    // Create a new Blob and write it to log.txt.
                    //var blob = new Blob(['Lorem Ipsum'], {type: 'text/plain'});
                    var blob = new Blob(['Lorem Ipsum']);

                    fileWriter.write(blob);
                }, plugin.handleError);
            }, plugin.handleError);
        };

        window.requestFileSystem(window.PERSISTENT, 1024, onInitFS, plugin.handleError)
        $('#resultPlugin').html('requestFileSystem completed.');
    },
    handleError : function (e) {
        $('#outputError').html('handleError');
        $('#outputError').addClass('error');
        $('#outputError').html(plugin.errorDecode(e));
        console.log(plugin.errorDecode(e));
        //alert(plugin.errorDecode(e));
    },
    errorDecode : function (e) {
        var msg = '';

        switch (e.code) {
          case FileError.QUOTA_EXCEEDED_ERR:
            msg = 'QUOTA_EXCEEDED_ERR';
          break;
          case FileError.NOT_FOUND_ERR:
            msg = 'NOT_FOUND_ERR';
          break;
          case FileError.SECURITY_ERR:
            msg = 'SECURITY_ERR';
          break;
          case FileError.INVALID_MODIFICATION_ERR:
             msg = 'INVALID_MODIFICATION_ERR';
          break;
          case FileError.INVALID_STATE_ERR:
             msg = 'INVALID_STATE_ERR';
          break;
          default:
            msg = 'Unknown Error';
          break;
        };
        return msg;
    },
    isThere : function (type, object) {
        return (type in object) ?  true : false;
    },
    // See alternate method: http://code.tutsplus.com/tutorials/working-with-indexeddb--net-34673 under "Let's Get Started"
    isAvailable : function (type) {
        return (type in window) ?  true : false;
    }
};

<|endoftext|>


<commit_before>var vows = require('vows');
var assert = require('assert');
var util = require('util');
var url = require('url');
var FacebookStrategy = require('passport-facebook/strategy');

vows.describe('FacebookStrategy').addBatch({

  'strategy': {
    topic: function() {
      return new FacebookStrategy({
        clientID: 'ABC123',
        clientSecret: 'secret'
      },
      function() {});
    },

    'should be named facebook': function (strategy) {
      assert.equal(strategy.name, 'facebook');
    },
  },

  'strategy when redirecting for authorization': {
    topic: function () {
      var strategy = new FacebookStrategy({
        clientID: 'ABC123',
        clientSecret: 'secret'
      });

      return strategy;
    },

    'and display not set': {
      topic: function (strategy) {
        var mockRequest = {},
            url;

        // Stub strategy.redirect()
        var self = this;
        strategy.redirect = function (location) {
          self.callback(null, location)
        };
        strategy.authenticate(mockRequest);
      },

      'does not set authorization param': function(err, location) {
        var params = url.parse(location, true).query;
        assert.isUndefined(params.display);
      }
    },

    'and display set to mobile': {
      topic: function (strategy) {
        var mockRequest = {},
            url;

        // Stub strategy.redirect()
        var self = this;
        strategy.redirect = function (location) {
          self.callback(null, location)
        };
        strategy.authenticate(mockRequest, { display: 'mobile' });
      },

      'sets authorization param to mobile': function(err, location) {
        var params = url.parse(location, true).query;
        assert.equal(params.display, 'mobile');
      }
    }
  },

  'strategy when loading user profile': {
    topic: function() {
      var strategy = new FacebookStrategy({
        clientID: 'ABC123',
        clientSecret: 'secret'
      },
      function() {});

      // mock
      strategy._oauth2.getProtectedResource = function(url, accessToken, callback) {
        var body = '{"id":"500308595","name":"Jared Hanson","first_name":"Jared","last_name":"Hanson","link":"http:\\/\\/www.facebook.com\\/jaredhanson","username":"jaredhanson","gender":"male","email":"jaredhanson\\u0040example.com"}';

        callback(null, body, undefined);
      }

      return strategy;
    },

    'when told to load user profile': {
      topic: function(strategy) {
        var self = this;
        function done(err, profile) {
          self.callback(err, profile);
        }

        process.nextTick(function () {
          strategy.userProfile('access-token', done);
        });
      },

      'should not error' : function(err, req) {
        assert.isNull(err);
      },
      'should load profile' : function(err, profile) {
        assert.equal(profile.provider, 'facebook');
        assert.equal(profile.id, '500308595');
        assert.equal(profile.username, 'jaredhanson');
        assert.equal(profile.displayName, 'Jared Hanson');
        assert.equal(profile.name.familyName, 'Hanson');
        assert.equal(profile.name.givenName, 'Jared');
        assert.equal(profile.gender, 'male');
        assert.equal(profile.profileUrl, 'http://www.facebook.com/jaredhanson');
        assert.lengthOf(profile.emails, 1);
        assert.equal(profile.emails[0].value, 'jaredhanson@example.com');
      },
      'should set raw property' : function(err, profile) {
        assert.isString(profile._raw);
      },
      'should set json property' : function(err, profile) {
        assert.isObject(profile._json);
      },
    },
  },

  'strategy when loading user profile and encountering an error': {
    topic: function() {
      var strategy = new FacebookStrategy({
        clientID: 'ABC123',
        clientSecret: 'secret'
      },
      function() {});

      // mock
      strategy._oauth2.getProtectedResource = function(url, accessToken, callback) {
        callback(new Error('something-went-wrong'));
      }

      return strategy;
    },

    'when told to load user profile': {
      topic: function(strategy) {
        var self = this;
        function done(err, profile) {
          self.callback(err, profile);
        }

        process.nextTick(function () {
          strategy.userProfile('access-token', done);
        });
      },

      'should error' : function(err, req) {
        assert.isNotNull(err);
      },
      'should wrap error in InternalOAuthError' : function(err, req) {
        assert.equal(err.constructor.name, 'InternalOAuthError');
      },
      'should not load profile' : function(err, profile) {
        assert.isUndefined(profile);
      },
    },
  },

  'strategy when configured to load specific profile fields': {
    topic: function() {
      var strategy = new FacebookStrategy({
        clientID: 'ABC123',
        clientSecret: 'secret',
        profileFields: ['id', 'photos']
      },
      function() {});

      // mock
      strategy._oauth2.getProtectedResource = function(url, accessToken, callback) {
        var body = '{"id":"500308595","picture":"http://profile.ak.fbcdn.net/blahblahblah.jpg"}';

        callback(null, body, undefined);
      }

      return strategy;
    },

    'when converting field names to facebook api': {
      topic: function(strategy) {
        this.callback(null, strategy._convertProfileFields(strategy.profileFields));
      },

      'should return a string of comma-separated field names': function(err, fields) {
        assert.equal(fields, 'id,picture');
      }
    },

    'when told to load user profile': {
      topic: function(strategy) {
        var self = this;
        function done(err, profile) {
          self.callback(err, profile);
        }

        process.nextTick(function () {
          strategy.userProfile('access-token', done);
        });
      },

      'should not error' : function(err, req) {
        assert.isNull(err);
      },
      'should load specific fields': function(err, profile) {
        assert.equal(profile.provider, 'facebook');
        assert.equal(profile.id, '500308595');
        assert.isUndefined(profile.username);
        assert.isUndefined(profile.displayName);
        assert.isUndefined(profile.name);
        assert.isUndefined(profile.gender);
        assert.isUndefined(profile.profileUrl);
        assert.isUndefined(profile.emails);
        assert.deepEqual(profile.photos, [{value: 'http://profile.ak.fbcdn.net/blahblahblah.jpg' }]);
      }
    }

  },

}).export(module);
<commit_msg>Test cases for profile parsing (with mapped profile fields).<commit_after>var vows = require('vows');
var assert = require('assert');
var util = require('util');
var url = require('url');
var FacebookStrategy = require('passport-facebook/strategy');

vows.describe('FacebookStrategy').addBatch({

  'strategy': {
    topic: function() {
      return new FacebookStrategy({
        clientID: 'ABC123',
        clientSecret: 'secret'
      },
      function() {});
    },

    'should be named facebook': function (strategy) {
      assert.equal(strategy.name, 'facebook');
    },
  },

  'strategy when redirecting for authorization': {
    topic: function () {
      var strategy = new FacebookStrategy({
        clientID: 'ABC123',
        clientSecret: 'secret'
      });

      return strategy;
    },

    'and display not set': {
      topic: function (strategy) {
        var mockRequest = {},
            url;

        // Stub strategy.redirect()
        var self = this;
        strategy.redirect = function (location) {
          self.callback(null, location)
        };
        strategy.authenticate(mockRequest);
      },

      'does not set authorization param': function(err, location) {
        var params = url.parse(location, true).query;
        assert.isUndefined(params.display);
      }
    },

    'and display set to mobile': {
      topic: function (strategy) {
        var mockRequest = {},
            url;

        // Stub strategy.redirect()
        var self = this;
        strategy.redirect = function (location) {
          self.callback(null, location)
        };
        strategy.authenticate(mockRequest, { display: 'mobile' });
      },

      'sets authorization param to mobile': function(err, location) {
        var params = url.parse(location, true).query;
        assert.equal(params.display, 'mobile');
      }
    }
  },

  'strategy when loading user profile': {
    topic: function() {
      var strategy = new FacebookStrategy({
        clientID: 'ABC123',
        clientSecret: 'secret'
      },
      function() {});

      // mock
      strategy._oauth2.getProtectedResource = function(url, accessToken, callback) {
        if (url == 'https://graph.facebook.com/me') {
          var body = '{"id":"500308595","name":"Jared Hanson","first_name":"Jared","last_name":"Hanson","link":"http:\\/\\/www.facebook.com\\/jaredhanson","username":"jaredhanson","gender":"male","email":"jaredhanson\\u0040example.com"}';
          callback(null, body, undefined);
        } else {
          callback(new Error('Incorrect user profile URL'));
        }
      }

      return strategy;
    },

    'when told to load user profile': {
      topic: function(strategy) {
        var self = this;
        function done(err, profile) {
          self.callback(err, profile);
        }

        process.nextTick(function () {
          strategy.userProfile('access-token', done);
        });
      },

      'should not error' : function(err, req) {
        assert.isNull(err);
      },
      'should load profile' : function(err, profile) {
        assert.equal(profile.provider, 'facebook');
        assert.equal(profile.id, '500308595');
        assert.equal(profile.username, 'jaredhanson');
        assert.equal(profile.displayName, 'Jared Hanson');
        assert.equal(profile.name.familyName, 'Hanson');
        assert.equal(profile.name.givenName, 'Jared');
        assert.equal(profile.gender, 'male');
        assert.equal(profile.profileUrl, 'http://www.facebook.com/jaredhanson');
        assert.lengthOf(profile.emails, 1);
        assert.equal(profile.emails[0].value, 'jaredhanson@example.com');
        assert.isUndefined(profile.photos);
      },
      'should set raw property' : function(err, profile) {
        assert.isString(profile._raw);
      },
      'should set json property' : function(err, profile) {
        assert.isObject(profile._json);
      },
    },
  },

  'strategy when loading user profile with mapped profile fields': {
    topic: function() {
      var strategy = new FacebookStrategy({
        clientID: 'ABC123',
        clientSecret: 'secret',
        profileFields: ['id', 'username', 'displayName', 'name', 'gender', 'profileUrl', 'emails', 'photos']
      },
      function() {});

      // mock
      strategy._oauth2.getProtectedResource = function(url, accessToken, callback) {
        if (url == 'https://graph.facebook.com/me?fields=id,username,name,last_name,first_name,middle_name,gender,link,email,picture') {
          var body = '{"id":"500308595","name":"Jared Hanson","first_name":"Jared","last_name":"Hanson","link":"http:\\/\\/www.facebook.com\\/jaredhanson","username":"jaredhanson","gender":"male","email":"jaredhanson\\u0040example.com"}';
          callback(null, body, undefined);
        } else {
          callback(new Error('Incorrect user profile URL: ' + url));
        }
      }

      return strategy;
    },

    'when told to load user profile': {
      topic: function(strategy) {
        var self = this;
        function done(err, profile) {
          self.callback(err, profile);
        }

        process.nextTick(function () {
          strategy.userProfile('access-token', done);
        });
      },

      'should not error' : function(err, req) {
        assert.isNull(err);
      },
      'should load profile' : function(err, profile) {
        assert.equal(profile.provider, 'facebook');
        assert.equal(profile.id, '500308595');
        assert.equal(profile.username, 'jaredhanson');
      },
      'should set raw property' : function(err, profile) {
        assert.isString(profile._raw);
      },
      'should set json property' : function(err, profile) {
        assert.isObject(profile._json);
      },
    },
  },

  'strategy when loading user profile with id and photos': {
    topic: function() {
      var strategy = new FacebookStrategy({
        clientID: 'ABC123',
        clientSecret: 'secret',
        profileFields: ['id', 'photos']
      },
      function() {});

      // mock
      strategy._oauth2.getProtectedResource = function(url, accessToken, callback) {
        if (url == 'https://graph.facebook.com/me?fields=id,picture') {
          var body = '{"id":"500308595","picture":"http:\/\/profile.ak.fbcdn.net\/hprofile-ak-prn1\/example.jpg"}';
          callback(null, body, undefined);
        } else {
          callback(new Error('Incorrect user profile URL: ' + url));
        }
      }

      return strategy;
    },

    'when told to load user profile': {
      topic: function(strategy) {
        var self = this;
        function done(err, profile) {
          self.callback(err, profile);
        }

        process.nextTick(function () {
          strategy.userProfile('access-token', done);
        });
      },

      'should not error' : function(err, req) {
        assert.isNull(err);
      },
      'should load profile' : function(err, profile) {
        assert.equal(profile.provider, 'facebook');
        assert.equal(profile.photos[0].value, 'http://profile.ak.fbcdn.net/hprofile-ak-prn1/example.jpg');
      },
      'should set raw property' : function(err, profile) {
        assert.isString(profile._raw);
      },
      'should set json property' : function(err, profile) {
        assert.isObject(profile._json);
      },
    },
  },

  'strategy when loading user profile with id and photos using October 2012 Breaking Changes': {
    topic: function() {
      var strategy = new FacebookStrategy({
        clientID: 'ABC123',
        clientSecret: 'secret',
        profileFields: ['id', 'photos']
      },
      function() {});

      // mock
      strategy._oauth2.getProtectedResource = function(url, accessToken, callback) {
        if (url == 'https://graph.facebook.com/me?fields=id,picture') {
          var body = '{"id":"500308595","picture":{"data":{"url":"http:\/\/profile.ak.fbcdn.net\/hprofile-ak-prn1\/example.jpg","is_silhouette":false}}}';
          callback(null, body, undefined);
        } else {
          callback(new Error('Incorrect user profile URL: ' + url));
        }
      }

      return strategy;
    },

    'when told to load user profile': {
      topic: function(strategy) {
        var self = this;
        function done(err, profile) {
          self.callback(err, profile);
        }

        process.nextTick(function () {
          strategy.userProfile('access-token', done);
        });
      },

      'should not error' : function(err, req) {
        assert.isNull(err);
      },
      'should load profile' : function(err, profile) {
        assert.equal(profile.provider, 'facebook');
        assert.equal(profile.photos[0].value, 'http://profile.ak.fbcdn.net/hprofile-ak-prn1/example.jpg');
      },
      'should set raw property' : function(err, profile) {
        assert.isString(profile._raw);
      },
      'should set json property' : function(err, profile) {
        assert.isObject(profile._json);
      },
    },
  },

  'strategy when loading user profile and encountering an error': {
    topic: function() {
      var strategy = new FacebookStrategy({
        clientID: 'ABC123',
        clientSecret: 'secret'
      },
      function() {});

      // mock
      strategy._oauth2.getProtectedResource = function(url, accessToken, callback) {
        callback(new Error('something-went-wrong'));
      }

      return strategy;
    },

    'when told to load user profile': {
      topic: function(strategy) {
        var self = this;
        function done(err, profile) {
          self.callback(err, profile);
        }

        process.nextTick(function () {
          strategy.userProfile('access-token', done);
        });
      },

      'should error' : function(err, req) {
        assert.isNotNull(err);
      },
      'should wrap error in InternalOAuthError' : function(err, req) {
        assert.equal(err.constructor.name, 'InternalOAuthError');
      },
      'should not load profile' : function(err, profile) {
        assert.isUndefined(profile);
      },
    },
  },

}).export(module);
<|endoftext|>


<commit_before>// The translations in this file can be added with:
//   #registerTranslations('de', require('counterpart/locales/de');

module.exports = {
  counterpart: {
    names: require('date-names/de'),
    pluralize: require('pluralizers/de'),

    formats: {
      date: {
        default:  '%a, %e. %b %Y',
        long:     '%A, %e. %B %Y',
        short:    '%d.%m.%y'
      },

      time: {
        default:  '%H:%M Uhr',
        long:     '%H:%M:%S %z',
        short:    '%H:%M'
      },

      datetime: {
        default:  '%a, %e. %b %Y, %H:%M Uhr',
        long:     '%A, %e. %B %Y, %H:%M:%S %z',
        short:    '%d.%m.%y %H:%M'
      }
    }
  }
};
<commit_msg>quote 'default' keyword when used as object property, #6<commit_after>// The translations in this file can be added with:
//   #registerTranslations('de', require('counterpart/locales/de');

module.exports = {
  counterpart: {
    names: require('date-names/de'),
    pluralize: require('pluralizers/de'),

    formats: {
      date: {
        'default':  '%a, %e. %b %Y',
        long:     '%A, %e. %B %Y',
        short:    '%d.%m.%y'
      },

      time: {
        'default':  '%H:%M Uhr',
        long:     '%H:%M:%S %z',
        short:    '%H:%M'
      },

      datetime: {
        'default':  '%a, %e. %b %Y, %H:%M Uhr',
        long:     '%A, %e. %B %Y, %H:%M:%S %z',
        short:    '%d.%m.%y %H:%M'
      }
    }
  }
};
<|endoftext|>


<commit_before>/*yeoman-test*/
const helpers = require('yeoman-test');
const assert = require('yeoman-assert');
const fs = require('fs');
const fsextra = require('fs-extra');
const path = require('path');

const basedir = path.join(__dirname, '../generators/app');

describe('yo:phaser-h5', () => {

    let tmpdir;

    beforeEach(() => {
        return helpers.run(basedir)
            .inTmpDir(dir => {
                tmpdir = dir;
            })
            .withPrompts({ projectName: 'temp', projectDesc: ' ', projectLicense: 'MIT', projectSass: true });
    });

    afterEach(() => fsextra.remove(tmpdir));

    it('creates expected files', () => {

        const expected = [
            // add files you expect to exist here.
            'gulpfile.js',
            '.jshintrc',
            'src/index.html',
            'package.json',
            'src/assets/js/main.js',
            'src/assets/js/entities/Gesture.js',
            'src/assets/js/entities/MovieClip.js',
            'src/assets/js/entities/VideoConfig.js',
            'src/assets/js/states/boot.js',
            'src/assets/js/states/state1.js',
            'src/assets/js/states/preloader.js',
            'src/assets/css/sass.scss'
        ];
        const files = expected.map(i => path.join(tmpdir, i));
        assert.file(files);
    });
});<commit_msg>:white_check_mark: Fixing tests<commit_after>/*yeoman-test*/
const helpers = require('yeoman-test');
const assert = require('yeoman-assert');
const fs = require('fs');
const fsextra = require('fs-extra');
const path = require('path');
const chalk = require('chalk');

const basedir = path.join(__dirname, '../generators/app');
const name = 'test projectName';
const description = 'test projectDesc';

describe(chalk.bold.cyan('generator-phaser-h5'), () => {

            let tmpdir;

            beforeEach(() => {
                return helpers.run(basedir)
                    .inTmpDir(dir => {
                        tmpdir = dir;
                    })
                    .withPrompts({ projectName: name, projectDesc: description, projectLicense: 'MIT', projectSass: true });
            });

            afterEach(() => fsextra.remove(tmpdir));

            it('creates expected files', () => checkAssets().then(checkConfig).then(checkReadme).then(checkScripts);;

                function checkConfig() {
                    assert.file([
                        'gulpfile.js',
                        '.jshintrc'
                    ]);
                    assert.fileContent([
                        ['package.json', `"name": ${JSON.stringify(name)}`],
                        ['package.json', `"description": ${JSON.stringify(description)}`]
                    ]);
                }

                function checkReadme() {
                    assert.fileContent([
                        ['README.md', `# [${name}]`],
                        ['README.md', `${description}`]
                    ]);
                }

                function checkScripts() {
                    assert.file([
                        'src/assets/js/main.js',
                        'src/assets/js/entities/Gesture.js',
                        'src/assets/js/entities/MovieClip.js',
                        'src/assets/js/entities/VideoConfig.js',
                        'src/assets/js/states/boot.js',
                        'src/assets/js/states/state1.js',
                        'src/assets/js/states/preloader.js'
                    ]);
                }

                function checkAssets() {
                    // const expected = [
                    //     'src/index.html',
                    //     'src/LICENSE',
                    //     'src/assets/css/sass.scss',
                    //     'src/assets/img/favicon.ico'
                    // ];
                    // const files = expected.map(i => path.join(tmpdir, i));
                    assert.file([
                        'src/index.html',
                        'src/LICENSE',
                        'src/assets/css/sass.scss',
                        'src/assets/img/favicon.ico'
                    ]);
                }
            });<|endoftext|>


<commit_before>// Limited driver used purely to compute and emit computed values in separate process

'use strict';

var customError    = require('es5-ext/error/custom')
  , setPrototypeOf = require('es5-ext/object/set-prototype-of')
  , d              = require('d')
  , deferred       = require('deferred')
  , Storage        = require('../../storage')

  , stringify = JSON.stringify
  , resolved = deferred(undefined);

var RecomputeStorage = Object.defineProperties(function (driver, name) {
	if (!(this instanceof RecomputeStorage)) return new RecomputeStorage(driver, name);
	Storage.call(this, driver, name);
}, {
	defaultAutoSaveFilter: d(function (event) { return false; })
});
setPrototypeOf(RecomputeStorage, Storage);
module.exports = RecomputeStorage;

RecomputeStorage.prototype = Object.create(Storage.prototype, {
	constructor: d(RecomputeStorage),
	_handleStoreComputed: d(function (ns, path, value, stamp) {
		this.driver.emit('computedUpdate',
			{ name: this.name, ns: ns, path: path, value: value, stamp: stamp });
		return resolved;
	}),

	_trackSize: d(function (name, conf) {
		if (this._indexes[name]) {
			throw customError("Index of " + stringify(name) + " was already registered",
				'DUPLICATE_INDEX');
		}
		this._indexes[name] = conf.meta;
		return resolved;
	}),

	// Connection related
	__close: d(function () { return resolved; }) // Nothing to close
});
<commit_msg>Remove rejection filter<commit_after>// Limited driver used purely to compute and emit computed values in separate process

'use strict';

var customError    = require('es5-ext/error/custom')
  , setPrototypeOf = require('es5-ext/object/set-prototype-of')
  , d              = require('d')
  , deferred       = require('deferred')
  , Storage        = require('../../storage')

  , stringify = JSON.stringify
  , resolved = deferred(undefined);

var RecomputeStorage = function (driver, name) {
	if (!(this instanceof RecomputeStorage)) return new RecomputeStorage(driver, name);
	Storage.call(this, driver, name);
};
setPrototypeOf(RecomputeStorage, Storage);
module.exports = RecomputeStorage;

RecomputeStorage.prototype = Object.create(Storage.prototype, {
	constructor: d(RecomputeStorage),
	_handleStoreComputed: d(function (ns, path, value, stamp) {
		this.driver.emit('computedUpdate',
			{ name: this.name, ns: ns, path: path, value: value, stamp: stamp });
		return resolved;
	}),

	_trackSize: d(function (name, conf) {
		if (this._indexes[name]) {
			throw customError("Index of " + stringify(name) + " was already registered",
				'DUPLICATE_INDEX');
		}
		this._indexes[name] = conf.meta;
		return resolved;
	}),

	// Connection related
	__close: d(function () { return resolved; }) // Nothing to close
});
<|endoftext|>


<commit_before><commit_msg>new test<commit_after>var test = require('tape');
var VK = require('../');

test('deferring calls for multiple execution', function (t) {
	var vk = new VK();
	var exec = vk.execution();

	exec.push('hello', {foo: 'bar'}).push('world');

	t.is(exec.code(), 'return [API.hello({"foo":"bar"}), API.world({})];', '#code() renders proper code');

	t.end();
});
<|endoftext|>


<commit_before>udefine(['root', '../graphics', '../graphics/rootelement'], function(root, Graphics, createRootElement) {
  'use strict';

  var pixelize = function(num) {
    return num + 'px';
  };

  var unpixelize = function(str) {
    return parseFloat(str) || 0;
  };

  Graphics.renderer = 'DOM';

  var rootElement = null;

  Graphics.on('initialize', function(Game) {
    rootElement = createRootElement.call(Game, 'div', function(rootElement) {
      rootElement.style.backgroundColor = this.color;
      rootElement.style.overflow = 'hidden';
      rootElement.style.cursor = 'default';
      rootElement.style.userSelect = rootElement.style.mozUserSelect = rootElement.style.webkitUserSelect = 'none';
    });
  });

  Graphics.on('add', function(obj) {
    var elementId = obj.id.toLowerCase();

    // Remove previous elements of the same id
    if (document.getElementById(elementId) != null) {
      (function() {
        var parentId = obj.parent.id.toLowerCase();

        var parentElem = document.getElementById(parentId);
        parentElem.removeChild(document.getElementId(elementId));
      })();
    }

    var parent = obj.parent;

    var parentElem = (function() {
      if ((parent && parent.isRoot) || parent == null) {
        return rootElement;
      } else {
        var parentId = obj.parent.id.toLowerCase();
        var element = document.getElementById(parentId);
        if (element == null) {
          return rootElement;
        } else {
          return element;
        }
      }
    })();

    var element = document.createElement('div');
    element.id = elementId;
    element.className = [obj.type.toLowerCase(), obj.name.toLowerCase()].join(' ');
    element.style.position = 'absolute';

    switch (obj.type) {
    case 'Scene':
      element.style.width = pixelize(obj.parent.width);
      element.style.height = pixelize(obj.parent.height);
      break;
    case 'GameObject':
      element.style.left = pixelize(obj.x);
      element.style.top = pixelize(obj.y);
      element.style.width = pixelize(obj.width);
      element.style.height = pixelize(obj.height);

      // TODO: Normalize events
      root.addEventListener('click', function(evt) {
        obj.trigger('click', evt);
      }, true);

      root.addEventListener('mousedown', function(evt) {
        obj.trigger('mousedown', evt);
      }, true);

      root.addEventListener('mouseup', function(evt) {
        obj.trigger('mouseup', evt);
      }, true);

      root.addEventListener('mouseenter', function(evt) {
        obj.trigger('mouseenter', evt);
      }, true);

      root.addEventListener('mouseleave', function(evt) {
        obj.trigger('mouseleave', evt);
      }, true);

      root.addEventListener('mouseover', function(evt) {
        obj.trigger('mouseover', evt);
      }, true);
      break;
    default:
      break;
    }

    parentElem.appendChild(element);
  });

  Graphics.on('texture-image-loaded', function(obj, texture) {
    var element = document.getElementById(obj.id.toLowerCase());

    if (element != null) {
      element.style.backgroundImage = 'url(' + texture.image.filename + ')';
      element.style.width = pixelize(obj.width);
      element.style.height = pixelize(obj.height);
    }
  });

  Graphics.on('texture-label-loaded', function(obj, texture) {
    var element = document.getElementById(obj.id.toLowerCase());

    if (element != null) {
      element.style.width = pixelize(obj.width);
      element.style.height = pixelize(obj.height);
    }
  });

  var dirtyObjects = {};

  Graphics.after('render', function(obj) {
    var objId = obj.id.toLowerCase();

    dirtyObjects[objId] = obj;
  });

  Graphics.on('render', function(obj) {
    var objId = obj.id.toLowerCase();

    // Update element attributes
    var element = document.getElementById(objId);

    if (element != null) {
      var prevObj = dirtyObjects[objId] || {};

      switch (obj.type) {
      case 'GameObject':
        var elemVisible = element.style.display === 'block';

        if (elemVisible !== obj.visible) {
          element.style.display = (obj.visible) ? 'block' : 'hidden';
        }

        if (!elemVisible) {
          return;
        }

        var elemX = unpixelize(element.style.left);
        var elemY = unpixelize(element.style.top);
        var elemWidth = unpixelize(element.style.width);
        var elemHeight = unpixelize(element.style.height);

        if (elemX !== obj.x) {
          element.style.left = pixelize(obj.x);
        }

        if (elemY !== obj.y) {
          element.style.top = pixelize(obj.y);
        }

        if (elemWidth !== obj.width) {
          element.style.width = pixelize(obj.width);
        }

        if (elemHeight !== obj.height) {
          element.style.height = pixelize(obj.height);
        }

        if (obj.angle) {
          element.style.transform = element.style.mozTransform = element.style.webkitTransform = 'rotate(' + obj.angle + 'deg)';
        }

        if (obj.alpha !== 1) {
          element.style.opacity = obj.alpha;
        }

        // Set background color
        element.style.backgroundColor = obj.texture.color;

        // Set border
        if (obj.border.width > 0) {
          element.style.borderWidth = pixelize(obj.border.width);
          element.style.borderStyle = 'solid';
          element.style.borderColor = obj.border.color;

          if (obj.border.radius > 0) {
            element.style.borderRadius = pixelize(obj.border.radius);
          }
        }

        if (obj.texture.image.filename) {
          if (obj.texture.image.offset.x !== 0) {
            element.style.backgroundPositionX = obj.texture.image.offset.x * (-1) + 'px';
          }

          if (obj.texture.image.offset.y !== 0) {
            element.style.backgroundPositionY = obj.texture.image.offset.y * (-1) + 'px';
          }
        }

        if (obj.texture.label.text) {
          element.innerText = obj.texture.label.text;

          element.style.whiteSpace = 'nowrap';

          if (obj.texture.label.font.size) {
            element.style.fontSize = pixelize(obj.texture.label.font.size);
          }

          if (obj.texture.label.font.color) {
            element.style.color = obj.texture.label.font.color;
          }

          if (obj.texture.label.font.name) {
            element.style.fontFamily = obj.texture.label.font.name;
          }

          obj.texture.label.font.decoration.forEach(function(decoration) {
            switch (decoration) {
            case 'bold':
              element.style.fontWeight = 'bold';
              break;
            case 'italic':
              element.style.fontStyle = 'italic';
              break;
            case 'underline':
              element.style.textDecoration = 'underline';
              break;
            default:
              break;
            }
          });
        }

        break;
      case 'Scene':
        var elemVisibleStyle = element.style.display;

        if (obj.parent.activeScene !== obj.name) {
          if (elemVisibleStyle !== 'hidden') {
            element.style.display = 'hidden';
          }
        } else {
          if (elemVisibleStyle !== 'block') {
            element.style.display = 'block';
          }
        }
        break;
      default:
        break;
      }

    }

  });

  return Graphics;

});
<commit_msg>Use drawable properties in DOM renderer<commit_after>udefine(['root', '../graphics', '../graphics/rootelement'], function(root, Graphics, createRootElement) {
  'use strict';

  var pixelize = function(num) {
    return num + 'px';
  };

  var unpixelize = function(str) {
    return parseFloat(str) || 0;
  };

  Graphics.renderer = 'DOM';

  var rootElement = null;

  Graphics.on('initialize', function(Game) {
    rootElement = createRootElement.call(Game, 'div', function(rootElement) {
      rootElement.style.backgroundColor = this.color;
      rootElement.style.overflow = 'hidden';
      rootElement.style.cursor = 'default';
      rootElement.style.userSelect = rootElement.style.mozUserSelect = rootElement.style.webkitUserSelect = 'none';
    });
  });

  Graphics.on('add', function(obj) {
    var elementId = obj.id.toLowerCase();

    // Remove previous elements of the same id
    if (document.getElementById(elementId) != null) {
      (function() {
        var parentId = obj.parent.id.toLowerCase();

        var parentElem = document.getElementById(parentId);
        parentElem.removeChild(document.getElementId(elementId));
      })();
    }

    var parent = obj.parent;

    var parentElem = (function() {
      if ((parent && parent.isRoot) || parent == null) {
        return rootElement;
      } else {
        var parentId = obj.parent.id.toLowerCase();
        var element = document.getElementById(parentId);
        if (element == null) {
          return rootElement;
        } else {
          return element;
        }
      }
    })();

    var element = document.createElement('div');
    element.id = elementId;
    element.className = [obj.type.toLowerCase(), obj.name.toLowerCase()].join(' ');
    element.style.position = 'absolute';

    switch (obj.type) {
    case 'Scene':
      element.style.width = pixelize(obj.parent.width);
      element.style.height = pixelize(obj.parent.height);
      break;
    case 'GameObject':
      element.style.left = pixelize(obj.x);
      element.style.top = pixelize(obj.y);
      element.style.width = pixelize(obj.width);
      element.style.height = pixelize(obj.height);

      // TODO: Normalize events
      root.addEventListener('click', function(evt) {
        obj.trigger('click', evt);
      }, true);

      root.addEventListener('mousedown', function(evt) {
        obj.trigger('mousedown', evt);
      }, true);

      root.addEventListener('mouseup', function(evt) {
        obj.trigger('mouseup', evt);
      }, true);

      root.addEventListener('mouseenter', function(evt) {
        obj.trigger('mouseenter', evt);
      }, true);

      root.addEventListener('mouseleave', function(evt) {
        obj.trigger('mouseleave', evt);
      }, true);

      root.addEventListener('mouseover', function(evt) {
        obj.trigger('mouseover', evt);
      }, true);
      break;
    default:
      break;
    }

    parentElem.appendChild(element);
  });

  Graphics.on('texture-image-loaded', function(obj, texture) {
    var element = document.getElementById(obj.id.toLowerCase());

    if (element != null) {
      element.style.backgroundImage = 'url(' + texture.image.filename + ')';
      element.style.width = pixelize(obj.width);
      element.style.height = pixelize(obj.height);
    }
  });

  Graphics.on('texture-label-loaded', function(obj, texture) {
    var element = document.getElementById(obj.id.toLowerCase());

    if (element != null) {
      element.style.width = pixelize(obj.width);
      element.style.height = pixelize(obj.height);
    }
  });

  var dirtyObjects = {};

  Graphics.after('render', function(obj) {
    var objId = obj.id.toLowerCase();

    dirtyObjects[objId] = obj;
  });

  Graphics.on('render', function(obj) {
    var objId = obj.id.toLowerCase();

    // Update element attributes
    var element = document.getElementById(objId);

    if (element != null) {
      var prevObj = dirtyObjects[objId] || {};

      switch (obj.type) {
      case 'GameObject':
        var elemVisible = element.style.display === 'block';

        if (elemVisible !== obj.visible) {
          element.style.display = (obj.visible) ? 'block' : 'hidden';
        }

        if (!elemVisible) {
          return;
        }

        var elemX = unpixelize(element.style.left);
        var elemY = unpixelize(element.style.top);
        var elemWidth = unpixelize(element.style.width);
        var elemHeight = unpixelize(element.style.height);

        if (elemX !== obj.x) {
          element.style.left = pixelize(obj.x);
        }

        if (elemY !== obj.y) {
          element.style.top = pixelize(obj.y);
        }

        if (elemWidth !== obj.width) {
          element.style.width = pixelize(obj.width);
        }

        if (elemHeight !== obj.height) {
          element.style.height = pixelize(obj.height);
        }

        if (obj.angle) {
          element.style.transform = element.style.mozTransform = element.style.webkitTransform = 'rotate(' + obj.angle + 'deg)';
        }

        if (obj.alpha !== 1) {
          element.style.opacity = obj.alpha;
        }

        // Set background color
        element.style.backgroundColor = obj.texture.color;

        // Set border
        if (obj.border.width > 0) {
          element.style.borderWidth = pixelize(obj.border.width);
          element.style.borderStyle = 'solid';
          element.style.borderColor = obj.border.color;

          if (obj.border.radius > 0) {
            element.style.borderRadius = pixelize(obj.border.radius);
          }
        }

        if (obj.texture.image.drawable) {
          if (obj.texture.image.offset.x !== 0) {
            element.style.backgroundPositionX = obj.texture.image.offset.x * (-1) + 'px';
          }

          if (obj.texture.image.offset.y !== 0) {
            element.style.backgroundPositionY = obj.texture.image.offset.y * (-1) + 'px';
          }
        }

        if (obj.texture.label.drawable) {
          element.innerText = obj.texture.label.text;

          element.style.whiteSpace = 'nowrap';

          if (obj.texture.label.font.size) {
            element.style.fontSize = pixelize(obj.texture.label.font.size);
          }

          if (obj.texture.label.font.color) {
            element.style.color = obj.texture.label.font.color;
          }

          if (obj.texture.label.font.name) {
            element.style.fontFamily = obj.texture.label.font.name;
          }

          obj.texture.label.font.decoration.forEach(function(decoration) {
            switch (decoration) {
            case 'bold':
              element.style.fontWeight = 'bold';
              break;
            case 'italic':
              element.style.fontStyle = 'italic';
              break;
            case 'underline':
              element.style.textDecoration = 'underline';
              break;
            default:
              break;
            }
          });
        }

        break;
      case 'Scene':
        var elemVisibleStyle = element.style.display;

        if (obj.parent.activeScene !== obj.name) {
          if (elemVisibleStyle !== 'hidden') {
            element.style.display = 'hidden';
          }
        } else {
          if (elemVisibleStyle !== 'block') {
            element.style.display = 'block';
          }
        }
        break;
      default:
        break;
      }

    }

  });

  return Graphics;

});
<|endoftext|>


<commit_before>var http = require('http');
var path = require('path');
var fs = require('filesystem');
var gitHubWebhookHandler = require('github-webhook-handler');
var settings = {};
settings.localPath = 'c:\\blaa';

var iFLicksHandler = gitHubWebhookHandler({ path: '/i-flicks', secret: 'lorcanvida' });
var gitHubPullerHandler = gitHubWebhookHandler({ path: '/gitHubPuller', secret: 'lorcanvida' });

http.createServer(function (req, res) {
    gitHubPullerHandler(req, res, function (err) {
        res.statusCode = 404;
        res.end('no such location');
    });
}).listen(7777);
function errorHandler(err, location, res) {
    console.log('Error at ', location, '.', 'Message: ', err.message);
    if (res) {
        res.status(500);
        res.end();
    }
}
gitHubPullerHandler.on('error', function (err) {
    console.error('Error:', err.message);
});

gitHubPullerHandler.on('push', function (event) {
	var added =event.payload.commits.added,
	    removed =event.payload.commits.removed,
	    changed =event.payload.commits.changed,
	    remotePath =event.payload.url,
	    i;

	for (i = 0; i < added.length; i++) {
		http.get(remotePath + '/' + added[i], function(err, res) {
			if (err) { errorHandler('push1', err); return; )
			fs.write(path.join(settings.localPath, added[i]), res.body, function(err) {
                if (err) { errorHandler('push2', err); return; )
            }
		}
	}

    console.log('Received a push event for %s to %s',
        event.payload.repository.name,
        event.payload.ref);
    /// get https://github.com/seethespark/i-flicks/archive/master.zip
});

gitHubPullerHandler.on('issues', function (event) {
    console.log('Received an issue event for %s action=%s: #%d %s',
        event.payload.repository.name,
        event.payload.action,
        event.payload.issue.number,
        event.payload.issue.title);
});<commit_msg>add hook paths as setting and thenloop through<commit_after>var http = require('http');
var path = require('path');
var fs = require('filesystem');
var gitHubWebhookHandler = require('github-webhook-handler');
var settings = {};
settings.localPath = 'c:\\blaa';
settings.hooks = [{name: 'gitHubPuller', localPath: ''}];

for (var i = 0; i < settings.hooks.length; i++) {
	var handler = gitHubWebhookHandler({ path: settings.hooks[i].name, secret: 'lorcanvida' });
	handler.on('push', function (event) {
		var added =event.payload.head_commit.added,
	    removed =event.payload.head_commit.removed,
	    modified =event.payload.head_commit.modified,
	    remotePath =event.payload.url,
	    i;

	for (i = 0; i < added.length; i++) {
		http.get(remotePath + '/' + added[i], function(err, res) {
			if (err) { errorHandler('push1', err); return; )
			fs.write(path.join(settings.localPath, added[i]), res.body, function(err) {
                if (err) { errorHandler('push2', err); return; )
            }
		}
	}

    console.log('Received a push event for %s to %s',
        event.payload.repository.name,
        event.payload.ref);
    /// get https://github.com/seethespark/i-flicks/archive/master.zip
	});
    handler.on('error', function (err) {
        console.error('Error:', err.message);
    });

    settings.hooks[i].handler = handler;
}
http.createServer(function (req, res) {
	for (var i = 0; i < settings.hooks.length; i++) {
		settings.hooks[i].handler(req, res, function (err) {
	        res.statusCode = 404;
	        res.end('no such location');
	    });
	}
}).listen(7777);

function errorHandler(err, location, res) {
    console.log('Error at ', location, '.', 'Message: ', err.message);
    if (res) {
        res.status(500);
        res.end();
    }
}

/*
gitHubPullerHandler.on('issues', function (event) {
    console.log('Received an issue event for %s action=%s: #%d %s',
        event.payload.repository.name,
        event.payload.action,
        event.payload.issue.number,
        event.payload.issue.title);
});*/<|endoftext|>


<commit_before>var assert = require('assert'),
    fs = require('fs'),
    path = require('path'),
    nodeunit = require('../lib/nodeunit');

var setup = function (fn) {
    return function (test) {
        process.chdir(__dirname);
        var env = {
            mock_module1: require(__dirname + '/fixtures/mock_module1'),
            mock_module2: require(__dirname + '/fixtures/mock_module2'),
            mock_module3: require(__dirname + '/fixtures/dir/mock_module3'),
            mock_module4: require(__dirname + '/fixtures/dir/mock_module4')
        };
        fn.call(env, test);
    };
};

exports.testRunFiles = setup(function (test) {
    test.expect(28);
    var runModule_copy = nodeunit.runModule;

    var runModule_calls = [];
    var modules = [];

    var opts = {
        moduleStart: function () {
            return 'moduleStart';
        },
        testDone: function () {
            return 'testDone';
        },
        testReady: function () {
            return 'testReady';
        },
        testStart: function () {
            return 'testStart';
        },
        log: function () {
            return 'log';
        },
        done: function (assertions) {
            test.equals(assertions.failures(), 0, 'failures');
            test.equals(assertions.length, 4, 'length');
            test.ok(typeof assertions.duration === "number");

            var called_with = function (name) {
                return runModule_calls.some(function (m) {
                    return m.name === name;
                });
            };
            test.ok(called_with('mock_module1'), 'mock_module1 ran');
            test.ok(called_with('mock_module2'), 'mock_module2 ran');
            test.ok(called_with('mock_module3'), 'mock_module3 ran');
            test.ok(called_with('mock_module4'), 'mock_module4 ran');
            test.equals(runModule_calls.length, 4);

            nodeunit.runModule = runModule_copy;
            test.done();
        }
    };

    nodeunit.runModule = function (name, mod, options, callback) {
        test.equals(options.testDone, opts.testDone);
        test.equals(options.testReady, opts.testReady);
        test.equals(options.testStart, opts.testStart);
        test.equals(options.log, opts.log);
        test.ok(typeof name === "string");
        runModule_calls.push(mod);
        var m = [{failed: function () {
            return false;
        }}];
        modules.push(m);
        callback(null, m);
    };

    nodeunit.runFiles(
        [__dirname + '/fixtures/mock_module1.js',
         __dirname + '/fixtures/mock_module2.js',
         __dirname + '/fixtures/dir'],
        opts
    );
});

exports.testRunFilesEmpty = function (test) {
    test.expect(3);
    nodeunit.runFiles([], {
        moduleStart: function () {
            test.ok(false, 'should not be called');
        },
        testDone: function () {
            test.ok(false, 'should not be called');
        },
        testReady: function () {
            test.ok(false, 'should not be called');
        },
        testStart: function () {
            test.ok(false, 'should not be called');
        },
        log: function () {
            test.ok(false, 'should not be called');
        },
        done: function (assertions) {
            test.equals(assertions.failures(), 0, 'failures');
            test.equals(assertions.length, 0, 'length');
            test.ok(typeof assertions.duration === "number");
            test.done();
        }
    });
};

exports.testEmptyDir = function (test) {
    var dir2 = __dirname + '/fixtures/dir2';

    // git doesn't like empty directories, so we have to create one
    path.exists(dir2, function (exists) {
        if (!exists) {
            fs.mkdirSync(dir2, 0777);
        }

        // runFiles on empty directory:
        nodeunit.runFiles([dir2], {
            moduleStart: function () {
                test.ok(false, 'should not be called');
            },
            testDone: function () {
                test.ok(false, 'should not be called');
            },
            testReady: function () {
                test.ok(false, 'should not be called');
            },
            testStart: function () {
                test.ok(false, 'should not be called');
            },
            log: function () {
                test.ok(false, 'should not be called');
            },
            done: function (assertions) {
                test.equals(assertions.failures(), 0, 'failures');
                test.equals(assertions.length, 0, 'length');
                test.ok(typeof assertions.duration === "number");
                test.done();
            }
        });
    });
};

var CoffeeScript;
try {
    CoffeeScript = require('coffee-script');
    if (CoffeeScript.register != null) {
        CoffeeScript.register();
    }
} catch (e) {
}

if (CoffeeScript) {
    exports.testCoffeeScript = function (test) {
        process.chdir(__dirname);
        var env = {
            mock_coffee_module: require(__dirname +
                                        '/fixtures/coffee/mock_coffee_module')
        };

        test.expect(10);
        var runModule_copy = nodeunit.runModule;

        var runModule_calls = [];
        var modules = [];

        var opts = {
            moduleStart: function () {
                return 'moduleStart';
            },
            testDone: function () {
                return 'testDone';
            },
            testReady: function () {
                return 'testReady';
            },
            testStart: function () {
                return 'testStart';
            },
            log: function () {
                return 'log';
            },
            done: function (assertions) {
                test.equals(assertions.failures(), 0, 'failures');
                test.equals(assertions.length, 1, 'length');
                test.ok(typeof assertions.duration === "number");

                var called_with = function (name) {
                    return runModule_calls.some(function (m) {
                        return m.name === name;
                    });
                };
                test.ok(
                    called_with('mock_coffee_15'),
                    'mock_coffee_module ran'
                );
                test.equals(runModule_calls.length, 1);

                nodeunit.runModule = runModule_copy;
                test.done();
            }
        };

        nodeunit.runModule = function (name, mod, options, callback) {
            test.equals(options.testDone, opts.testDone);
            test.equals(options.testReady, opts.testReady);
            test.equals(options.testStart, opts.testStart);
            test.equals(options.log, opts.log);
            test.ok(typeof name === "string");
            runModule_calls.push(mod);
            var m = [{failed: function () {
                return false;
            }}];
            modules.push(m);
            callback(null, m);
        };

        nodeunit.runFiles(
            [__dirname + '/fixtures/coffee/mock_coffee_module.coffee'],
            opts
        );
    };
}
<commit_msg>test: Update deprecated "path.exists" to "fs.access"<commit_after>var assert = require('assert'),
    fs = require('fs'),
    path = require('path'),
    nodeunit = require('../lib/nodeunit');

var setup = function (fn) {
    return function (test) {
        process.chdir(__dirname);
        var env = {
            mock_module1: require(__dirname + '/fixtures/mock_module1'),
            mock_module2: require(__dirname + '/fixtures/mock_module2'),
            mock_module3: require(__dirname + '/fixtures/dir/mock_module3'),
            mock_module4: require(__dirname + '/fixtures/dir/mock_module4')
        };
        fn.call(env, test);
    };
};

exports.testRunFiles = setup(function (test) {
    test.expect(28);
    var runModule_copy = nodeunit.runModule;

    var runModule_calls = [];
    var modules = [];

    var opts = {
        moduleStart: function () {
            return 'moduleStart';
        },
        testDone: function () {
            return 'testDone';
        },
        testReady: function () {
            return 'testReady';
        },
        testStart: function () {
            return 'testStart';
        },
        log: function () {
            return 'log';
        },
        done: function (assertions) {
            test.equals(assertions.failures(), 0, 'failures');
            test.equals(assertions.length, 4, 'length');
            test.ok(typeof assertions.duration === "number");

            var called_with = function (name) {
                return runModule_calls.some(function (m) {
                    return m.name === name;
                });
            };
            test.ok(called_with('mock_module1'), 'mock_module1 ran');
            test.ok(called_with('mock_module2'), 'mock_module2 ran');
            test.ok(called_with('mock_module3'), 'mock_module3 ran');
            test.ok(called_with('mock_module4'), 'mock_module4 ran');
            test.equals(runModule_calls.length, 4);

            nodeunit.runModule = runModule_copy;
            test.done();
        }
    };

    nodeunit.runModule = function (name, mod, options, callback) {
        test.equals(options.testDone, opts.testDone);
        test.equals(options.testReady, opts.testReady);
        test.equals(options.testStart, opts.testStart);
        test.equals(options.log, opts.log);
        test.ok(typeof name === "string");
        runModule_calls.push(mod);
        var m = [{failed: function () {
            return false;
        }}];
        modules.push(m);
        callback(null, m);
    };

    nodeunit.runFiles(
        [__dirname + '/fixtures/mock_module1.js',
         __dirname + '/fixtures/mock_module2.js',
         __dirname + '/fixtures/dir'],
        opts
    );
});

exports.testRunFilesEmpty = function (test) {
    test.expect(3);
    nodeunit.runFiles([], {
        moduleStart: function () {
            test.ok(false, 'should not be called');
        },
        testDone: function () {
            test.ok(false, 'should not be called');
        },
        testReady: function () {
            test.ok(false, 'should not be called');
        },
        testStart: function () {
            test.ok(false, 'should not be called');
        },
        log: function () {
            test.ok(false, 'should not be called');
        },
        done: function (assertions) {
            test.equals(assertions.failures(), 0, 'failures');
            test.equals(assertions.length, 0, 'length');
            test.ok(typeof assertions.duration === "number");
            test.done();
        }
    });
};

exports.testEmptyDir = function (test) {
    var dir2 = __dirname + '/fixtures/dir2';

    // git doesn't like empty directories, so we have to create one
    fs.access(dir2, function (err) {
        if (err) {
            fs.mkdirSync(dir2, 0777);
        }

        // runFiles on empty directory:
        nodeunit.runFiles([dir2], {
            moduleStart: function () {
                test.ok(false, 'should not be called');
            },
            testDone: function () {
                test.ok(false, 'should not be called');
            },
            testReady: function () {
                test.ok(false, 'should not be called');
            },
            testStart: function () {
                test.ok(false, 'should not be called');
            },
            log: function () {
                test.ok(false, 'should not be called');
            },
            done: function (assertions) {
                test.equals(assertions.failures(), 0, 'failures');
                test.equals(assertions.length, 0, 'length');
                test.ok(typeof assertions.duration === "number");
                test.done();
            }
        });
    });
};

var CoffeeScript;
try {
    CoffeeScript = require('coffee-script');
    if (CoffeeScript.register != null) {
        CoffeeScript.register();
    }
} catch (e) {
}

if (CoffeeScript) {
    exports.testCoffeeScript = function (test) {
        process.chdir(__dirname);
        var env = {
            mock_coffee_module: require(__dirname +
                                        '/fixtures/coffee/mock_coffee_module')
        };

        test.expect(10);
        var runModule_copy = nodeunit.runModule;

        var runModule_calls = [];
        var modules = [];

        var opts = {
            moduleStart: function () {
                return 'moduleStart';
            },
            testDone: function () {
                return 'testDone';
            },
            testReady: function () {
                return 'testReady';
            },
            testStart: function () {
                return 'testStart';
            },
            log: function () {
                return 'log';
            },
            done: function (assertions) {
                test.equals(assertions.failures(), 0, 'failures');
                test.equals(assertions.length, 1, 'length');
                test.ok(typeof assertions.duration === "number");

                var called_with = function (name) {
                    return runModule_calls.some(function (m) {
                        return m.name === name;
                    });
                };
                test.ok(
                    called_with('mock_coffee_15'),
                    'mock_coffee_module ran'
                );
                test.equals(runModule_calls.length, 1);

                nodeunit.runModule = runModule_copy;
                test.done();
            }
        };

        nodeunit.runModule = function (name, mod, options, callback) {
            test.equals(options.testDone, opts.testDone);
            test.equals(options.testReady, opts.testReady);
            test.equals(options.testStart, opts.testStart);
            test.equals(options.log, opts.log);
            test.ok(typeof name === "string");
            runModule_calls.push(mod);
            var m = [{failed: function () {
                return false;
            }}];
            modules.push(m);
            callback(null, m);
        };

        nodeunit.runFiles(
            [__dirname + '/fixtures/coffee/mock_coffee_module.coffee'],
            opts
        );
    };
}
<|endoftext|>


<commit_before>var fs = require('fs');
var bodyParser = require('body-parser');
var EventEmitter = require('events').EventEmitter;
var tmp = require('tmp');
tmp.setGracefulCleanup();

// Load custom crypto functions
var my_crypto = require('./my_crypto.js');

// Load KeePassIO functions
var kp = require('./kp_functions.js');

// Load express
var express = require('express');
var app = express();
app.use(bodyParser()); // support for URL-encoded bodies in posts

/*
 *            Application Logic
 *
 */

var passwords = [];
var clear_key = false;
var login_attempts = 0;
var login_pause = false;
var lockout = false;
var logfile = './log.txt';
var lockfile = './lockfile';
var prefix;
var server;

/*
 * Writes data to a tmp file
 * Currently, tmp file does not seem to be cleaned up properly automagically
 * I manually delete the tmp file later
 * This is used to pass the KDBX key to keepassio, since it only accepts
 * it as a file
 */

var write_tmp_file = function (data, next) {
  tmp.file(function _tempFileCreated(err, path, fd) {
    if (err) throw err;

    console.log("File: ", path);
    console.log("File descriptor: ", fd);

    fs.writeFileSync(path, data, 'utf8');
    next(path);
  });
};

/*
 * Generates the list of KeePass accounts
 */

var list_accts = function(key, keyfile, next) {
  kp.get_accts('./keepass/test.kdbx', key, keyfile, function(error, accts, pass) {
    var html = "";
    if (error) {
      bad_login();
      html="Incorrect Password
Wait 2 seconds before retrying";
      log("KDBX unlock failed");
    }
    else {
      accts.forEach(function(entry) {
        html += "
" + entry + "
";
      });
      passwords = pass;
      log('***KDBX unlock success***');
    }
  fs.unlink(keyfile, function (err) {
    if (err) {
      throw err;
    }
    console.log("Deleted: " + keyfile);
  });
  next(html);
  });
};

var bad_login = function() {
  login_attempts += 1;
  login_pause = true;

  setTimeout(function() {
    login_pause = false;
  }, 2000);

  if (login_attempts > 2) {
    lockout = true;
    server.close();
    fs.writeFile('./lockfile', 'Server locked', function write(err) {
      if (err)
        throw err;
    });
    log('Server locked');
  }
};

var log = function() {
  var logstring = new Date();
  for (var i in arguments) {
    logstring += '\n' + arguments[i];
  }
  logstring += '\n\n';
  fs.appendFile(logfile, logstring, function (err) {
    if (err)
    throw err;
  });
};

/*
 *
 *        Routing
 *
 */

// If we're in production mode, only accept https requests
// x-forwarded-proto is a heroku specific header
app.all('*', function(req, res, next) {
  if (lockout === false && login_pause === false) {
    if (process.env.NODE_ENV == "production") {
      if (req.headers['x-forwarded-proto']=='https') {
        next();
      }
    } else {
      next();
    }
  }
});

app.get('/', function (req, res) {
  res.sendfile('./public/index.html');
});

app.get('/style.css', function(req, res) {
  res.sendfile('./public/style.css');
});

app.get('/index.js', function(req, res) {
  res.sendfile('./public/index.js');
});

app.get('/jquery-1.11.0.min.js', function(req, res) {
  res.sendfile('./public/jquery-1.11.0.min.js');
});

// Show password
app.post('/show', function(req, res) {

  // Index from html account list
  var index= req.body.index;

  var html = "Password: " + passwords[index] +"";
  passwords = [];
  res.send(html);
});

// Show account list
app.post('/list', function(req, res) {
  var kdbx_pass = req.body.pass;
  var emitter = new EventEmitter();

  var render = function(html) {
    res.send(html);
  };

  write_tmp_file(clear_key, function next(path) {
    emitter.emit("file", path);
  });

  // Emits when the tmp file is ready
  emitter.on("file", function (path) {
    list_accts(kdbx_pass, path, function next(html) {
      render(html);
    });
  });
});

/*
 * Check if the supplied key properly decrypts the KDBX keyfile
 */

app.post('/auth', function(req, res) {
  var key = req.body.key;

  var logreq = req.ip + ': Decryption request';
  var logdata = 'Supplied key: ' + key;

  var cryptfile = "";

  // Try to decrypt each of the 5 key files
  for (var i = 0; i<5; i++) {
    cryptfile = prefix + 'key' + i + ".crypt";

    // false if decyption fails
    var test_key = my_crypto.decrypt_phrase(key, cryptfile);
    if (test_key) {
      clear_key = test_key;
      console.log(clear_key);
      break;
    }
    else {
      // Must set this explicitly to avoid memory
      clear_key = false;
    }
  }

  // Was the key properly decrypted?
  if (clear_key) {
    logdata += '\n***Decryption success***';
    log(logreq, logdata);

    fs.unlink(cryptfile, function (err) {
      if (err) {
        throw err;
      }
      console.log("Deleted: " + cryptfile);
    });
    res.send("true");
  }
  else {
    logdata += '\nDecryption failed';
    log(logreq, logdata);
    bad_login();
    res.send("false");
  }

});

/*
 *
 *        Start the server
 *
 */

try {
  fs.readFileSync('./lockfile');
    console.log("locked");
} catch (err) {
  // Only start the server if the file doesn't exist

  if (process.env.NODE_ENV == "production")
  {
    // Use the production keys
    prefix = "./keys/";

    // Trust heroku's forwarding -- note that this can be spoofed easily
    app.enable('trust proxy');

    server = app.listen(process.env.PORT || 5000);
    console.log("Server started");
  }
  else
  {
    // This is for testing locally
    prefix = "./testing/";
    var https = require('https');
    var privateKey  = fs.readFileSync('sslcert/backup_pass-key.pem');
    var certificate = fs.readFileSync('sslcert/public-cert.pem');
    var credentials = {key: privateKey, cert: certificate};
    var httpsServer = https.createServer(credentials, app);
    server = httpsServer.listen(8443);
    console.log("Server started");
  }

}
<commit_msg>Deletes event delegation<commit_after>var fs = require('fs');
var bodyParser = require('body-parser');
var tmp = require('tmp');
tmp.setGracefulCleanup();

// Load custom crypto functions
var my_crypto = require('./my_crypto.js');

// Load KeePassIO functions
var kp = require('./kp_functions.js');

// Load express
var express = require('express');
var app = express();
app.use(bodyParser()); // support for URL-encoded bodies in posts

/*
 *            Application Logic
 *
 */

var passwords = [];
var clear_key = false;
var login_attempts = 0;
var login_pause = false;
var lockout = false;
var logfile = './log.txt';
var lockfile = './lockfile';
var prefix;
var server;

/*
 * Writes data to a tmp file
 * Currently, tmp file does not seem to be cleaned up properly automagically
 * I manually delete the tmp file later
 * This is used to pass the KDBX key to keepassio, since it only accepts
 * it as a file
 */

var write_tmp_file = function (data, next) {
  tmp.file(function _tempFileCreated(err, path, fd) {
    if (err) throw err;

    console.log("File: ", path);
    console.log("File descriptor: ", fd);

    fs.writeFileSync(path, data, 'utf8');
    next(path);
  });
};

/*
 * Generates the list of KeePass accounts
 */

var list_accts = function(key, keyfile, next) {
  kp.get_accts('./keepass/test.kdbx', key, keyfile, function(error, accts, pass) {
    var html = "";
    if (error) {
      bad_login();
      html="Incorrect Password
Wait 2 seconds before retrying";
      log("KDBX unlock failed");
    }
    else {
      accts.forEach(function(entry) {
        html += "
" + entry + "
";
      });
      passwords = pass;
      log('***KDBX unlock success***');
    }
  fs.unlink(keyfile, function (err) {
    if (err) {
      throw err;
    }
    console.log("Deleted: " + keyfile);
  });
  next(html);
  });
};

var bad_login = function() {
  login_attempts += 1;
  login_pause = true;

  setTimeout(function() {
    login_pause = false;
  }, 2000);

  if (login_attempts > 2) {
    lockout = true;
    server.close();
    fs.writeFile('./lockfile', 'Server locked', function write(err) {
      if (err)
        throw err;
    });
    log('Server locked');
  }
};

var log = function() {
  var logstring = new Date();
  for (var i in arguments) {
    logstring += '\n' + arguments[i];
  }
  logstring += '\n\n';
  fs.appendFile(logfile, logstring, function (err) {
    if (err)
    throw err;
  });
};

/*
 *
 *        Routing
 *
 */

// If we're in production mode, only accept https requests
// x-forwarded-proto is a heroku specific header
app.all('*', function(req, res, next) {
  if (lockout === false && login_pause === false) {
    if (process.env.NODE_ENV == "production") {
      if (req.headers['x-forwarded-proto']=='https') {
        next();
      }
    } else {
      next();
    }
  }
});

app.get('/', function (req, res) {
  res.sendfile('./public/index.html');
});

app.get('/style.css', function(req, res) {
  res.sendfile('./public/style.css');
});

app.get('/index.js', function(req, res) {
  res.sendfile('./public/index.js');
});

app.get('/jquery-1.11.0.min.js', function(req, res) {
  res.sendfile('./public/jquery-1.11.0.min.js');
});

// Show password
app.post('/show', function(req, res) {

  // Index from html account list
  var index= req.body.index;

  var html = "Password: " + passwords[index] +"";
  passwords = [];
  res.send(html);
});

// Show account list
app.post('/list', function(req, res) {
  var kdbx_pass = req.body.pass;

  var render = function(html) {
    res.send(html);
  };

  write_tmp_file(clear_key, function next(path) {
    list_accts(kdbx_pass, path, render);
  });

});

/*
 * Check if the supplied key properly decrypts the KDBX keyfile
 */

app.post('/auth', function(req, res) {
  var key = req.body.key;

  var logreq = req.ip + ': Decryption request';
  var logdata = 'Supplied key: ' + key;

  var cryptfile = "";

  // Try to decrypt each of the 5 key files
  for (var i = 0; i<5; i++) {
    cryptfile = prefix + 'key' + i + ".crypt";

    // false if decyption fails
    var test_key = my_crypto.decrypt_phrase(key, cryptfile);
    if (test_key) {
      clear_key = test_key;
      console.log(clear_key);
      break;
    }
    else {
      // Must set this explicitly to avoid memory
      clear_key = false;
    }
  }

  // Was the key properly decrypted?
  if (clear_key) {
    logdata += '\n***Decryption success***';
    log(logreq, logdata);

    fs.unlink(cryptfile, function (err) {
      if (err) {
        throw err;
      }
      console.log("Deleted: " + cryptfile);
    });
    res.send("true");
  }
  else {
    logdata += '\nDecryption failed';
    log(logreq, logdata);
    bad_login();
    res.send("false");
  }

});

/*
 *
 *        Start the server
 *
 */

try {
  fs.readFileSync('./lockfile');
    console.log("locked");
} catch (err) {
  // Only start the server if the file doesn't exist

  if (process.env.NODE_ENV == "production")
  {
    // Use the production keys
    prefix = "./keys/";

    // Trust heroku's forwarding -- note that this can be spoofed easily
    app.enable('trust proxy');

    server = app.listen(process.env.PORT || 5000);
    console.log("Server started");
  }
  else
  {
    // This is for testing locally
    prefix = "./testing/";
    var https = require('https');
    var privateKey  = fs.readFileSync('sslcert/backup_pass-key.pem');
    var certificate = fs.readFileSync('sslcert/public-cert.pem');
    var credentials = {key: privateKey, cert: certificate};
    var httpsServer = https.createServer(credentials, app);
    server = httpsServer.listen(8443);
    console.log("Server started");
  }

}
<|endoftext|>


<commit_before>/// colorizing text for command line
String.prototype.col = function(col) {
    switch(col) {
        case 'black':
            return '\033[30m' + this + '\033[0m';
        case 'red':
            return '\033[31m' + this + '\033[0m';
        case 'green':
            return '\033[32m' + this + '\033[0m';
        case 'yellow':
            return '\033[33m' + this + '\033[0m';
        case 'blue':
            return '\033[34m' + this + '\033[0m';
        case 'magenta':
            return '\033[35m' + this + '\033[0m';
        case 'cyan':
            return '\033[36m' + this + '\033[0m';
        case 'white':
            return '\033[37m' + this + '\033[0m';
        default:
            return this;
    }
};

module.exports = (function () {
    'use strict';
    var path = require('path'),
        fs = require('fs');

    var _initGit = function (rootPath) {
        var sys = require('sys'),
            exec = require('child_process').exec;

        exec("git init " + rootPath, function (err, stdout, stderr) {
            if(err) {
                throw err;
            }
            console.log('initializing git...'.col('blue'));
            sys.puts(stdout);
            sys.puts(stderr);
        });
    };

    var _initPackageJSON = function (rootPath, projectName) {
        var pkg = '';
        pkg += '{\n';
        pkg += '    "name": "' + projectName + '",\n';
        pkg += '    "description": "",\n';
        pkg += '    "version: "0.0.0",\n';
        pkg += '    "private": true,\n';
        pkg += '    "author": "",\n';
        pkg += '    "license": "",\n';
        pkg += '    "dependencies": {},\n';
        pkg += '    "repository": {\n';
        pkg += '        "type": "",\n';
        pkg += '        "url": ""\n';
        pkg += '    }\n';
        pkg += "}";

        console.log('creating... '.col('blue') + path.join(rootPath, 'package.json'));
        fs.writeFile(path.join(rootPath, 'package.json'), pkg, function (err) {
            if(err) {
                throw err;
            }
        });
    };

    var _initReadme = function (rootPath, projectName) {
        var str = '# ' + projectName;

        console.log('creating... '.col('blue') + path.join(rootPath, 'README.md'));
        fs.writeFile(path.join(rootPath, 'README.md'), str, function (err) {
            if(err) {
                throw err;
            }
        });
    };

    var _initAppJS = function (rootPath) {
        console.log('creating... '.col('blue') + path.join(rootPath, 'app.js'));
        fs.open(path.join(rootPath, 'app.js'), 'w', function (err) {
            if(err) {
                throw err;
            }
        });
    };

    var _initGitIgnore = function (rootPath) {
        var str = 'node_modules/';

        console.log('creating... '.col('blue') + path.join(rootPath, '.gitignore'));
        fs.writeFile(path.join(rootPath, '.gitignore'), str, function (err) {
            if(err) {
                throw err;
            }

        });
    };

    var _initLicense = function (rootPath) {
        console.log('creating... '.col('blue') + path.join(rootPath, 'LICENSE'));
        fs.open(path.join(rootPath, 'LICENSE'), 'w', function (err) {
            if(err) {
                throw err;
            }
        });
    };

    var _mainFunc = function (argv) {

        var rootPath, projectName, rootDir;

        if(argv.length < 3) {
            console.log('error: expected another argument for root path');
            return;
        }

        projectName = argv[2];
        rootDir = argv[3] || '.';
        rootPath = path.join(__dirname, rootDir, projectName);

        if(fs.existsSync(rootPath)) {
            console.log('exists... '.col('red') + rootPath);
        }
        else {
            console.log('creating... '.col('blue') + rootPath);
            fs.mkdirSync(rootPath);
        }

        // creating default files... files to be created could be read from a config file
        _initReadme(rootPath, projectName);
        _initPackageJSON(rootPath, projectName);
        _initAppJS(rootPath);
        _initGitIgnore(rootPath);
        _initLicense(rootPath);

        _initGit(rootPath);
    };

    return _mainFunc;
}());
<commit_msg>read config file from default location<commit_after>/// colorizing text for command line
String.prototype.col = function(col) {
    switch(col) {
        case 'black':
            return '\033[30m' + this + '\033[0m';
        case 'red':
            return '\033[31m' + this + '\033[0m';
        case 'green':
            return '\033[32m' + this + '\033[0m';
        case 'yellow':
            return '\033[33m' + this + '\033[0m';
        case 'blue':
            return '\033[34m' + this + '\033[0m';
        case 'magenta':
            return '\033[35m' + this + '\033[0m';
        case 'cyan':
            return '\033[36m' + this + '\033[0m';
        case 'white':
            return '\033[37m' + this + '\033[0m';
        default:
            return this;
    }
};

module.exports = (function () {
    'use strict';
    var path = require('path'),
        fs = require('fs'),
        home_folder = process.env.USERPROFILE || process.env.HOME || process.env.HOMEPATH,
        config_path = path.join(home_folder, '.bisss.conf'),
        configJSON;

    var _initGit = function (rootPath) {
        var sys = require('sys'),
            exec = require('child_process').exec;

        exec("git init " + rootPath, function (err, stdout, stderr) {
            if(err) {
                throw err;
            }
            console.log('initializing git...'.col('blue'));
            sys.puts(stdout);
            sys.puts(stderr);
        });
    };

    var _initPackageJSON = function (rootPath, projectName) {
        var pkg = '';
        pkg += '{\n';
        pkg += '    "name": "' + projectName + '",\n';
        pkg += '    "description": "",\n';
        pkg += '    "version: "0.0.0",\n';
        pkg += '    "private": true,\n';
        pkg += '    "author": "",\n';
        pkg += '    "license": "",\n';
        pkg += '    "dependencies": {},\n';
        pkg += '    "repository": {\n';
        pkg += '        "type": "",\n';
        pkg += '        "url": ""\n';
        pkg += '    }\n';
        pkg += "}";

        console.log('creating... '.col('blue') + path.join(rootPath, 'package.json'));
        fs.writeFile(path.join(rootPath, 'package.json'), pkg, function (err) {
            if(err) {
                throw err;
            }
        });
    };

    var _initReadme = function (rootPath, projectName) {
        var str = '# ' + projectName;

        console.log('creating... '.col('blue') + path.join(rootPath, 'README.md'));
        fs.writeFile(path.join(rootPath, 'README.md'), str, function (err) {
            if(err) {
                throw err;
            }
        });
    };

    var _initAppJS = function (rootPath) {
        console.log('creating... '.col('blue') + path.join(rootPath, 'app.js'));
        fs.open(path.join(rootPath, 'app.js'), 'w', function (err) {
            if(err) {
                throw err;
            }
        });
    };

    var _initGitIgnore = function (rootPath) {
        var str = 'node_modules/';

        console.log('creating... '.col('blue') + path.join(rootPath, '.gitignore'));
        fs.writeFile(path.join(rootPath, '.gitignore'), str, function (err) {
            if(err) {
                throw err;
            }

        });
    };

    var _initLicense = function (rootPath) {
        console.log('creating... '.col('blue') + path.join(rootPath, 'LICENSE'));
        fs.open(path.join(rootPath, 'LICENSE'), 'w', function (err) {
            if(err) {
                throw err;
            }
        });
    };

    var _readConfigJSON = function (configPath) {
        if(fs.existsSync(configPath)) {
            var configText = fs.readFileSync(configPath, { encoding: 'utf8'});
            return JSON.parse(configText);
        }
        else {
            // create json
            return {
                "author": "",
                "license": "MIT"
            };
        }
    };

    var _mainFunc = function (argv) {

        var rootPath, projectName, rootDir;

        if(argv.length < 3) {
            console.log('error: expected another argument for root path');
            return;
        }

        projectName = argv[2];
        rootDir = argv[3] || '.';
        rootPath = path.join(__dirname, rootDir, projectName);

        configJSON = _readConfigJSON(config_path);

        if(fs.existsSync(rootPath)) {
            console.log('exists... '.col('red') + rootPath);
        }
        else {
            console.log('creating... '.col('blue') + rootPath);
            fs.mkdirSync(rootPath);
        }

        // creating default files... files to be created could be read from a config file
        _initReadme(rootPath, projectName);
        _initPackageJSON(rootPath, projectName);
        _initAppJS(rootPath);
        _initGitIgnore(rootPath);
        _initLicense(rootPath);

        _initGit(rootPath);
    };

    return _mainFunc;
}());
<|endoftext|>