<commit_before>'use strict';

const mongoURI = process.env.MONGODB_URI;

var fs = require('fs'),
	readline = require('readline'),
	MongoClient = require('mongodb').MongoClient,
	assert = require('assert'),
	codeCounter = "codeCounter",
	dict = "dict";
function showTest(){
	console.log("showTest");
	console.log("Dict: " + dict);
	console.log("codeCounter: " + codeCounter)
}
function init(){
	MongoClient.connect(mongoURI , function(err, db){
		if(err){
			console.log("GET CURRCODE: OPENING", err);
		} else {
			var collection = db.collection('codeCounter');
			collection.find().toArray(function(err, res) {
				if(err){
					console.log("GET CURRCODE: READING", err);
				} else{
					console.log(res[0]);
					codeCounter = JSON.parse(JSON.stringify(res[0].codeCounter));
					showTest();
					//
				}
			})
		}
	});

	fs.readFile('dict.json', 'utf8', function (err, data) {
		if(err) throw err;
		console.log(JSON.parse(data));
		dict = JSON.parse(data);
		showTest();
	});
}
init();

//IDK Why the latter dont work but im sure this part does
/*module.exports.codeCounter = {};
module.exports.dict = {};
module.exports.initf = false;*/
/*var codeCounter = [];
var dict = [];
var initf = false;

var init = function() {
	//get codeCounter
	console.log("initing");//
	console.log(init);
	if(this.initf) {
		return; //
	}
	initf = true;
	MongoClient.connect(mongoURI , function(err, db){
		if(err){
			console.log("GET CURRCODE: OPENING", err);
		} else {
			var collection = db.collection('codeCounter');
			collection.find().toArray(function(err, res) {
				if(err){
					console.log("GET CURRCODE: READING", err);
				} else{
					console.log(res[0]);
					codeCounter = (res[0].codeCounter);
					//
				}
			})
		}
	});

	//getDict
	fs.readFile('dict.json', 'utf8', function (err, data) {
		if(err) throw err;
		console.log(JSON.parse(data));
		dict = JSON.parse(data);
	})
}
*/

/*
function getCurrCode(){
	return new Promise(function (resolve, reject){
		MongoClient.connect(mongoURI , function(err, db){
			if(err){
				console.log("GET CURRCODE: OPENING", err);
				reject(err);
			} else {
					var collection = db.collection('codeCounter');
					collection.find().toArray(function(err, res) {
					if(err){
						console.log("GET CURRCODE: READING", err);
					} else{
						console.log(res[0]);
						resolve(res[0].codeCounter);
						//
					}
					})
				}
			});
	});
}*/

/*limitation, if codeCounter exceeds [n,n,n,n], where n
is dictSize, counter does not change*/
var makeNewCode = function(){
		//I wonder if there is going to be any async issues, if u run two of these at the same time hmm
		var isFinished = false;
		var curr = codeCounter.length;
		console.log("makeNewCode");
		console.log(this);
		codeCounter[curr]++;
		while (!isFinished && curr > 0) {
			if (codeCounter[curr] > (dict.length - 1)){
				codeCounter[curr] = 0;
				curr--;
				if (curr < 0 ){
					throw "Code Counter Overflowed, I.E Game Limit Reached";
				}
				else {
					codeCounter[curr - 1]++;
				}
			}
			else {
				isFinished = true;
			}
		}

		MongoClient.connect(mongoURI , function(err, db){
			if(err){
				console.log("WRITING CURRCODE TO DB: ", err);
				reject(err);
			} else {
					var collection = db.collection('codeCounter');
					collection.updateOne({}, {"codeCounter" : codeCounter}, function(err, res) {
					if(err){
						console.log("WRITING CURRCODE TO DB: ", err);
					} else{
						console.log("WRITING CURRCODE TO DB: Success");
					}
					})
				}
		});
		return codeCounter;
}

function genCode(){
	console.log("genCode");
	console.log("fs: " + fs);
	console.log("codeCounter: " + codeCounter);

	return new Promise(function(resolve, reject){
		//var makeCode = makeNewCode.bind(codeCounter, dict.length);
		resolve(makeNewCode());
	});
}

/*needs the mongoURI and the local dictionary JSON file path
chose to take in mongoURI rather than get from process because this is module*/
/*exports.genCode = genCode;*/
/*var Game = function (){

	MongoClient.connect(mongoURI , function(err, db){
		if(err){
			console.log("GET CURRCODE: OPENING", err);
		} else {
			var collection = db.collection('codeCounter');
			collection.find().toArray(function(err, res) {
				if(err){
					console.log("GET CURRCODE: READING", err);
				} else{
					console.log(res[0]);
					codeCounter = (res[0].codeCounter);
					//
				}
			})
		}
	});

	//getDict
	fs.readFile('dict.json', 'utf8', function (err, data) {
		if(err) throw err;
		console.log(JSON.parse(data));
		dict = JSON.parse(data);
	})

	this.dict = dict;
	this.codeCounter = codeCounter;
};

Game.prototype.makeNewCode = makeNewCode;
Game.prototype.genCode = genCode;*/
module.exports.genCode = genCode;<commit_msg>ARRRGH<commit_after>'use strict';

const mongoURI = process.env.MONGODB_URI;

var fs = require('fs'),
	readline = require('readline'),
	MongoClient = require('mongodb').MongoClient,
	assert = require('assert'),
	codeCounter = "codeCounter",
	dict = "dict";
function showTest(){
	console.log("showTest");
	console.log("Dict: " + dict);
	console.log("codeCounter: " + codeCounter)
}
function init(){
	MongoClient.connect(mongoURI , function(err, db){
		if(err){
			console.log("GET CURRCODE: OPENING", err);
		} else {
			var collection = db.collection('codeCounter');
			collection.find().toArray(function(err, res) {
				if(err){
					console.log("GET CURRCODE: READING", err);
				} else{
					console.log(res[0]);
					codeCounter = JSON.parse(JSON.stringify(res[0].codeCounter));
					showTest();
					//
				}
			})
		}
	});

	fs.readFile('dict.json', 'utf8', function (err, data) {
		if(err) throw err;
		console.log(JSON.parse(data));
		dict = JSON.parse(data);
		showTest();
	});
}
init();

//IDK Why the latter dont work but im sure this part does
/*module.exports.codeCounter = {};
module.exports.dict = {};
module.exports.initf = false;*/
/*var codeCounter = [];
var dict = [];
var initf = false;

var init = function() {
	//get codeCounter
	console.log("initing");//
	console.log(init);
	if(this.initf) {
		return; //
	}
	initf = true;
	MongoClient.connect(mongoURI , function(err, db){
		if(err){
			console.log("GET CURRCODE: OPENING", err);
		} else {
			var collection = db.collection('codeCounter');
			collection.find().toArray(function(err, res) {
				if(err){
					console.log("GET CURRCODE: READING", err);
				} else{
					console.log(res[0]);
					codeCounter = (res[0].codeCounter);
					//
				}
			})
		}
	});

	//getDict
	fs.readFile('dict.json', 'utf8', function (err, data) {
		if(err) throw err;
		console.log(JSON.parse(data));
		dict = JSON.parse(data);
	})
}
*/

/*
function getCurrCode(){
	return new Promise(function (resolve, reject){
		MongoClient.connect(mongoURI , function(err, db){
			if(err){
				console.log("GET CURRCODE: OPENING", err);
				reject(err);
			} else {
					var collection = db.collection('codeCounter');
					collection.find().toArray(function(err, res) {
					if(err){
						console.log("GET CURRCODE: READING", err);
					} else{
						console.log(res[0]);
						resolve(res[0].codeCounter);
						//
					}
					})
				}
			});
	});
}*/

/*limitation, if codeCounter exceeds [n,n,n,n], where n
is dictSize, counter does not change*/
var makeNewCode = function(){
		//I wonder if there is going to be any async issues, if u run two of these at the same time hmm
		var isFinished = false;
		var curr = codeCounter.length - 1;
		console.log("makeNewCode");
		console.log(this);
		codeCounter[curr]++;
		while (!isFinished && curr > 0) {
			if (codeCounter[curr] > (dict.length - 1)){
				codeCounter[curr] = 0;
				curr--;
				if (curr < 0 ){
					throw "Code Counter Overflowed, I.E Game Limit Reached";
				}
				else {
					codeCounter[curr - 1]++;
				}
			}
			else {
				isFinished = true;
			}
		}

		MongoClient.connect(mongoURI , function(err, db){
			if(err){
				console.log("WRITING CURRCODE TO DB: ", err);
				reject(err);
			} else {
					var collection = db.collection('codeCounter');
					collection.updateOne({}, {"codeCounter" : codeCounter}, function(err, res) {
					if(err){
						console.log("WRITING CURRCODE TO DB: ", err);
					} else{
						console.log("WRITING CURRCODE TO DB: Success");
					}
					})
				}
		});
		return codeCounter;
}

function genCode(){
	console.log("genCode");
	console.log("fs: " + fs);
	console.log("codeCounter: " + codeCounter);

	return new Promise(function(resolve, reject){
		//var makeCode = makeNewCode.bind(codeCounter, dict.length);
		resolve(makeNewCode());
	});
}

/*needs the mongoURI and the local dictionary JSON file path
chose to take in mongoURI rather than get from process because this is module*/
/*exports.genCode = genCode;*/
/*var Game = function (){

	MongoClient.connect(mongoURI , function(err, db){
		if(err){
			console.log("GET CURRCODE: OPENING", err);
		} else {
			var collection = db.collection('codeCounter');
			collection.find().toArray(function(err, res) {
				if(err){
					console.log("GET CURRCODE: READING", err);
				} else{
					console.log(res[0]);
					codeCounter = (res[0].codeCounter);
					//
				}
			})
		}
	});

	//getDict
	fs.readFile('dict.json', 'utf8', function (err, data) {
		if(err) throw err;
		console.log(JSON.parse(data));
		dict = JSON.parse(data);
	})

	this.dict = dict;
	this.codeCounter = codeCounter;
};

Game.prototype.makeNewCode = makeNewCode;
Game.prototype.genCode = genCode;*/
module.exports.genCode = genCode;<|endoftext|>


<commit_before>/**
 * ngAuth 0.0.1
 * (c) 2014 Sahat Yalkabov <sahat@me.com>
 * License: MIT
 */

(function(window, angular, undefined) {
  'use strict';

  angular.module('ngAuth', [])
    .provider('Auth', function() {

      var config = this.config = {
        logoutRedirect: '/',
        loginRedirect: '/',
        loginUrl: '/auth/login',
        signupUrl: '/auth/signup',
        signupRedirect: '/login',
        userGlobal: 'currentUser',
        providers: {
          facebook: {
            authorizationUrl: 'https://www.facebook.com/dialog/oauth',
            scope: 'email',
            requiredUrlParams: ['display'],
            display: 'popup',
            redirectUri: 'http://localhost:3000'
          },
          google: {
            authorizationUrl: 'https://accounts.google.com/o/oauth2/auth',
            scope: ''
          },
          linkedin: {
            authorizationUrl: 'https://www.linkedin.com/uas/oauth2/authorization',
            state: 'STATE'
          }
        }
      };

      // TODO: Use requiredUrlParams instead of passing all properties
      // TODO: pass scope delimiter
      // TODO: default responseType to code if token is obtained on server

      return {
        setProvider: function(params) {
          config.providers[params.name] = config.providers[params.name] || {};
          angular.extend(config.providers[params.name], params);
        },

        $get: function($interval, $timeout, $http, $location, $rootScope, $alert, $q, $injector, $window) {

          // BEGIN OAUTH

          // Popup window.
          var Popup = function() {
            this.popup = null;
          };

          Popup.prototype.open = function(url, keys, options) {
            var deferred = $q.defer();
            // TODO: refactor
            var optionsString = stringifyOptions(prepareOptions(options || {}));
            this.popup = $window.open(url, '*', optionsString);
            this.popup.focus();

            this.createPostMessageHandler(deferred);
            this.pollPopup(deferred);

            return deferred.promise;
          };

          Popup.prototype.pollPopup = function(deferred) {
            var intervalHandler = function() {
              if (this.popup.closed) {
                $interval.cancel(this.polling);
                deferred.reject('Popup was closed by the user.');
              }
              this.requestAuthorizationCode();
            }.bind(this);
            this.polling = $interval(intervalHandler, 35);
          };

          Popup.prototype.requestAuthorizationCode = function() {
            var query = this.popup.location.search.substring(1);
            if (query.indexOf('code') > -1) {
              var code = this.parseQueryString(query).code;
              $window.postMessage(code, $window.location.origin);
              $interval.cancel(this.polling);
              this.popup.close();
            }
          };

          Popup.prototype.createPostMessageHandler = function(deferred) {
            $window.addEventListener('message', function(event) {
              deferred.resolve(event.data);
            }, false);
          };

          Popup.prototype.parseQueryString = function(keyValue) {
            var obj = {}, key, value;
            angular.forEach((keyValue || '').split('&'), function(keyValue) {
              if (keyValue) {
                value = keyValue.split('=');
                key = decodeURIComponent(value[0]);
                obj[key] = angular.isDefined(value[1]) ? decodeURIComponent(value[1]) : true;
              }
            });
            return obj;
          };

          Popup.prototype.close = function() {
            if (this.popup) {
              this.popup.close();
              this.popup = null;
            }
          };

          function prepareOptions(options) {
            var width = options.width || 500;
            var height = options.height || 500;
            return angular.extend({
              left: ((screen.width / 2) - (width / 2)),
              top: ((screen.height / 2) - (height / 2)),
              width: width,
              height: height
            }, options);
          }

          function stringifyOptions(options) {
            var optionsStrings = [];
            for (var key in options) {
              if (options.hasOwnProperty(key)) {
                var value;
                switch (options[key]) {
                  case true:
                    value = '1';
                    break;
                  case false:
                    value = '0';
                    break;
                  default:
                    value = options[key];
                }
                optionsStrings.push(
                  key + '=' + value
                );
              }
            }
            return optionsStrings.join(',');
          }

          var oauthKeys = ['code', 'access_token', 'expires_in'];
          var defaultUrlParams = ['response_type', 'client_id', 'redirect_uri'];

          var Oauth2 = function(config) {
            this.name = config.name;
            this.clientId = config.clientId;
            this.scope = config.scope;
            this.authorizationUrl = config.authorizationUrl;
            this.redirectUri = config.redirectUri;
            this.responseType = 'code';
            this.requiredUrlParams = defaultUrlParams.concat(config.requiredUrlParams);
            this.optionalUrlParams = ['scope'];
          };

          Oauth2.prototype.camelCase = function(name) {
            return name.replace(/([\:\-\_]+(.))/g, function(_, separator, letter, offset) {
              return offset ? letter.toUpperCase() : letter;
            });
          };

          Oauth2.prototype.open = function() {
            var deferred = $q.defer();
            var url = this.buildUrl();
            var popup = new Popup();

            popup.open(url, oauthKeys).then(function(code) {
              this.exchangeForToken(code).then(function(response) {
                deferred.resolve(response.data);
              });
            }.bind(this));

            return deferred.promise;
          };

          Oauth2.prototype.exchangeForToken = function(code) {
            var params = {
              clientId: config.providers[this.name].clientId,
              redirectUri: $window.location.origin + '/',
              code: code
            };

            return $http.post('/auth/facebook', params);
          };

          Oauth2.prototype.buildUrl = function() {
            var baseUrl = this.authorizationUrl;
            var qs = this.buildQueryString();
            return [baseUrl, qs].join('?');
          };

          Oauth2.prototype.buildQueryString = function() {
            var obj = this;
            var keyValuePairs = [];

            angular.forEach(this.requiredUrlParams, function(paramName) {
              var camelizedName = obj.camelCase(paramName);
              var paramValue = obj[camelizedName];
              keyValuePairs.push([paramName, paramValue]);
            });

            angular.forEach(this.optionalUrlParams, function(paramName) {
              var camelizedName = obj.camelCase(paramName);
              var paramValue = obj[camelizedName];
              keyValuePairs.push([paramName, paramValue]);
            });

            return keyValuePairs.map(function(pair) {
              return pair.join('=');
            }).join('&');
          };

          Oauth2.createProvider = function(providerName) {
            var providerOptions = config.providers[providerName];
            var provider = new Oauth2(providerOptions);
            return provider;
          };

          // END OAUTH

          var token = $window.localStorage.token;
          if (token) {
            var payload = JSON.parse($window.atob(token.split('.')[1]));
            $rootScope[config.userGlobal] = payload.user;
          }

          return {
            authenticate: function(providerName, options) {
              var deferred = $q.defer();
              if (!providerName) {
                deferred.reject('Expected a provider named \'' + providerName + '\', did you forget to add it?');
              }
              var provider = Oauth2.createProvider(providerName);

              provider.open(options).then(function(data) {
                console.log('OPENED')
                deferred.resolve(data);
              });

              return deferred.promise;
            },

            loginOauth: function(provider) {
              provider = provider.trim().toLowerCase();

              switch (provider) {
                case 'facebook':
                  var scope = config.providers.facebook.scope.join(',');
                  FB.login(function(response) {
                    FB.api('/me', function(profile) {
                      // TODO normalize return properties like passport
                      var data = {
                        accessToken: response.authResponse.accessToken,
                        signedRequest: response.authResponse.signedRequest,
                        profile: profile
                      };
                      $http.post(config.providers.facebook.url, data).success(function(token) {
                        var payload = JSON.parse($window.atob(token.split('.')[1]));
                        $window.localStorage.token = token;
                        $rootScope[config.userGlobal] = payload.user;
                        $location.path(config.loginRedirect);
                      });
                    });
                  }, {scope: scope});
                  break;
                case 'google':

                  break;
                case 'linkedin':
                  break;
                default:
                  break;
              }
            },
            login: function(user) {
              return $http.post(config.loginUrl, user).success(function(data) {
                $window.localStorage.token = data.token;
                var payload = JSON.parse($window.atob(data.token.split('.')[1]));
                $rootScope[config.userGlobal] = payload.user;
                $location.path(config.loginRedirect);
              });
            },
            signup: function(user) {
              return $http.post(config.signupUrl, user).success(function() {
                $location.path(config.signupRedirect);
              });
            },
            logout: function() {
              delete $window.localStorage.token;
              $rootScope[config.userGlobal] = null;
              $location.path(config.logoutRedirect);
            },
            isAuthenticated: function() {
              return $rootScope[config.userGlobal];
            }
          };
        }
      };
    })
    .factory('authInterceptor', function($q, $window, $location) {
      return {
        request: function(config) {
          if ($window.localStorage.token) {
            config.headers.Authorization = 'Bearer ' + $window.localStorage.token;
          }
          return config;
        },
        responseError: function(response) {
          if (response.status === 401 || response.status === 403) {
            $location.path('/login');
          }
          return $q.reject(response);
        }
      }
    })
    .config(function($httpProvider) {
      $httpProvider.interceptors.push('authInterceptor');
    })
    .run(function($rootScope, $location) {
      $rootScope.$on('$routeChangeStart', function(event, current, previous) {
        if ($rootScope.currentUser &&
          (current.originalPath === '/login' || current.originalPath === '/signup')) {
          $location.path('/');
        }
        if (current.authenticated && !$rootScope.currentUser) {
          $location.path('/login');
        }
      });
    });
})(window, window.angular);

<commit_msg>removed oauthKeys no longer needed<commit_after>/**
 * ngAuth 0.0.1
 * (c) 2014 Sahat Yalkabov <sahat@me.com>
 * License: MIT
 */

(function(window, angular, undefined) {
  'use strict';

  angular.module('ngAuth', [])
    .provider('Auth', function() {

      var config = this.config = {
        logoutRedirect: '/',
        loginRedirect: '/',
        loginUrl: '/auth/login',
        signupUrl: '/auth/signup',
        signupRedirect: '/login',
        userGlobal: 'currentUser',
        providers: {
          facebook: {
            authorizationUrl: 'https://www.facebook.com/dialog/oauth',
            scope: 'email',
            requiredUrlParams: ['display'],
            display: 'popup',
            redirectUri: 'http://localhost:3000'
          },
          google: {
            authorizationUrl: 'https://accounts.google.com/o/oauth2/auth',
            scope: ''
          },
          linkedin: {
            authorizationUrl: 'https://www.linkedin.com/uas/oauth2/authorization',
            state: 'STATE'
          }
        }
      };

      // TODO: Use requiredUrlParams instead of passing all properties
      // TODO: pass scope delimiter
      // TODO: default responseType to code if token is obtained on server

      return {
        setProvider: function(params) {
          config.providers[params.name] = config.providers[params.name] || {};
          angular.extend(config.providers[params.name], params);
        },

        $get: function($interval, $timeout, $http, $location, $rootScope, $alert, $q, $injector, $window) {

          // BEGIN OAUTH

          // Popup window.
          var Popup = function() {
            this.popup = null;
          };

          Popup.prototype.open = function(url, keys, options) {
            var deferred = $q.defer();
            // TODO: refactor
            // todo wildcard star
            var optionsString = stringifyOptions(prepareOptions(options || {}));
            this.popup = $window.open(url, '*', optionsString);
            this.popup.focus();

            this.createPostMessageHandler(deferred);
            this.pollPopup(deferred);

            return deferred.promise;
          };

          Popup.prototype.pollPopup = function(deferred) {
            var intervalHandler = function() {
              if (this.popup.closed) {
                $interval.cancel(this.polling);
                deferred.reject('Popup was closed by the user.');
              }
              this.requestAuthorizationCode();
            }.bind(this);
            this.polling = $interval(intervalHandler, 35);
          };

          Popup.prototype.requestAuthorizationCode = function() {
            var query = this.popup.location.search.substring(1);
            if (query.indexOf('code') > -1) {
              var code = this.parseQueryString(query).code;
              $window.postMessage(code, $window.location.origin);
              $interval.cancel(this.polling);
              this.popup.close();
            }
          };

          Popup.prototype.createPostMessageHandler = function(deferred) {
            $window.addEventListener('message', function(event) {
              deferred.resolve(event.data);
            }, false);
          };

          Popup.prototype.parseQueryString = function(keyValue) {
            var obj = {}, key, value;
            angular.forEach((keyValue || '').split('&'), function(keyValue) {
              if (keyValue) {
                value = keyValue.split('=');
                key = decodeURIComponent(value[0]);
                obj[key] = angular.isDefined(value[1]) ? decodeURIComponent(value[1]) : true;
              }
            });
            return obj;
          };

          Popup.prototype.close = function() {
            if (this.popup) {
              this.popup.close();
              this.popup = null;
            }
          };

          function prepareOptions(options) {
            var width = options.width || 500;
            var height = options.height || 500;
            return angular.extend({
              left: ((screen.width / 2) - (width / 2)),
              top: ((screen.height / 2) - (height / 2)),
              width: width,
              height: height
            }, options);
          }

          function stringifyOptions(options) {
            var optionsStrings = [];
            for (var key in options) {
              if (options.hasOwnProperty(key)) {
                var value;
                switch (options[key]) {
                  case true:
                    value = '1';
                    break;
                  case false:
                    value = '0';
                    break;
                  default:
                    value = options[key];
                }
                optionsStrings.push(
                  key + '=' + value
                );
              }
            }
            return optionsStrings.join(',');
          }

          var defaultUrlParams = ['response_type', 'client_id', 'redirect_uri'];

          var Oauth2 = function(config) {
            //if (this instanceof CustomObject)

            this.name = config.name;
            this.clientId = config.clientId;
            this.scope = config.scope;
            this.authorizationUrl = config.authorizationUrl;
            this.redirectUri = config.redirectUri;
            this.responseType = 'code';
            this.requiredUrlParams = defaultUrlParams.concat(config.requiredUrlParams);
            this.optionalUrlParams = ['scope'];
          };

          Oauth2.prototype.camelCase = function(name) {
            return name.replace(/([\:\-\_]+(.))/g, function(_, separator, letter, offset) {
              return offset ? letter.toUpperCase() : letter;
            });
          };

          Oauth2.prototype.open = function() {
            var deferred = $q.defer();
            var url = this.buildUrl();
            var popup = new Popup();

            popup.open(url).then(function(code) {
              this.exchangeForToken(code).then(function(response) {
                deferred.resolve(response.data);
              });
            }.bind(this));

            return deferred.promise;
          };

          Oauth2.prototype.exchangeForToken = function(code) {
            var params = {
              clientId: config.providers[this.name].clientId,
              redirectUri: $window.location.origin + '/',
              code: code
            };

            return $http.post('/auth/facebook', params);
          };

          Oauth2.prototype.buildUrl = function() {
            var baseUrl = this.authorizationUrl;
            var qs = this.buildQueryString();
            return [baseUrl, qs].join('?');
          };

          Oauth2.prototype.buildQueryString = function() {
            var obj = this;
            var keyValuePairs = [];

            angular.forEach(this.requiredUrlParams, function(paramName) {
              var camelizedName = obj.camelCase(paramName);
              var paramValue = obj[camelizedName];
              keyValuePairs.push([paramName, paramValue]);
            });

            angular.forEach(this.optionalUrlParams, function(paramName) {
              var camelizedName = obj.camelCase(paramName);
              var paramValue = obj[camelizedName];
              keyValuePairs.push([paramName, paramValue]);
            });

            return keyValuePairs.map(function(pair) {
              return pair.join('=');
            }).join('&');
          };

          Oauth2.createProvider = function(providerName) {
            var providerOptions = config.providers[providerName];
            var provider = new Oauth2(providerOptions);
            return provider;
          };

          // END OAUTH

          var token = $window.localStorage.token;
          if (token) {
            var payload = JSON.parse($window.atob(token.split('.')[1]));
            $rootScope[config.userGlobal] = payload.user;
          }

          return {
            authenticate: function(providerName, options) {
              if (!providerName) {
                return $q.reject('Expected a provider named \'' + providerName + '\', did you forget to add it?');
              }

              var provider = Oauth2.createProvider(providerName);

              var deferred = $q.defer();

              provider.open(options).then(function(data) {
                console.log('OPENED')
                deferred.resolve(data);
              });

              return deferred.promise;
            },

            loginOauth: function(provider) {
              provider = provider.trim().toLowerCase();

              switch (provider) {
                case 'facebook':
                  var scope = config.providers.facebook.scope.join(',');
                  FB.login(function(response) {
                    FB.api('/me', function(profile) {
                      // TODO normalize return properties like passport
                      var data = {
                        accessToken: response.authResponse.accessToken,
                        signedRequest: response.authResponse.signedRequest,
                        profile: profile
                      };
                      $http.post(config.providers.facebook.url, data).success(function(token) {
                        var payload = JSON.parse($window.atob(token.split('.')[1]));
                        $window.localStorage.token = token;
                        $rootScope[config.userGlobal] = payload.user;
                        $location.path(config.loginRedirect);
                      });
                    });
                  }, {scope: scope});
                  break;
                case 'google':

                  break;
                case 'linkedin':
                  break;
                default:
                  break;
              }
            },
            login: function(user) {
              return $http.post(config.loginUrl, user).success(function(data) {
                $window.localStorage.token = data.token;
                var payload = JSON.parse($window.atob(data.token.split('.')[1]));
                $rootScope[config.userGlobal] = payload.user;
                $location.path(config.loginRedirect);
              });
            },
            signup: function(user) {
              return $http.post(config.signupUrl, user).success(function() {
                $location.path(config.signupRedirect);
              });
            },
            logout: function() {
              delete $window.localStorage.token;
              $rootScope[config.userGlobal] = null;
              $location.path(config.logoutRedirect);
            },
            isAuthenticated: function() {
              return $rootScope[config.userGlobal];
            }
          };
        }
      };
    })
    .factory('authInterceptor', function($q, $window, $location) {
      return {
        request: function(config) {
          if ($window.localStorage.token) {
            config.headers.Authorization = 'Bearer ' + $window.localStorage.token;
          }
          return config;
        },
        responseError: function(response) {
          if (response.status === 401 || response.status === 403) {
            $location.path('/login');
          }
          return $q.reject(response);
        }
      }
    })
    .config(function($httpProvider) {
      $httpProvider.interceptors.push('authInterceptor');
    })
    .run(function($rootScope, $location) {
      $rootScope.$on('$routeChangeStart', function(event, current, previous) {
        if ($rootScope.currentUser &&
          (current.originalPath === '/login' || current.originalPath === '/signup')) {
          $location.path('/');
        }
        if (current.authenticated && !$rootScope.currentUser) {
          $location.path('/login');
        }
      });
    });
})(window, window.angular);

<|endoftext|>


<commit_before>const chokidar = require('chokidar');
const path = require('path');
const {build} = require('esbuild');
const fs = require('fs');
const debounce = require('lodash.debounce');

const outFilePath = path.resolve(__dirname, '../dist/echarts.js');

const umdMark = '// ------------- WRAPPED UMD --------------- //';
const umdWrapperHead = `
${umdMark}
(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['exports'], factory);
    } else if (typeof exports === 'object' && typeof exports.nodeName !== 'string') {
        // CommonJS
        factory(exports);
    } else {
        // Browser globals
        factory((root.echarts = {}));
    }
}(typeof self !== 'undefined' ? self : this, function (exports, b) {
`;

const umdWrapperTail = `
}));`;

async function wrapUMDCode() {
    const code = fs.readFileSync(outFilePath, 'utf-8');
    if (code.indexOf(umdMark) >= 0) {
        return;
    }

    fs.writeFileSync(outFilePath, umdWrapperHead + code + umdWrapperTail, 'utf-8');

    const sourceMap = JSON.parse(fs.readFileSync(outFilePath + '.map', 'utf-8'));
    // Fast trick for fixing source map
    sourceMap.mappings = umdWrapperHead.split('\n').map(() => '').join(';') + sourceMap.mappings;

    fs.writeFileSync(outFilePath + '.map', JSON.stringify(sourceMap), 'utf-8');
}

function rebuild() {
    build({
        stdio: 'inherit',
        entryPoints: [path.resolve(__dirname, '../echarts.all.ts')],
        outfile: outFilePath,
        format: 'cjs',
        sourcemap: true,
        bundle: true,
    }).catch(e => {
        console.error(e.toString());
    }).then(async () => {
        console.time('Wrap UMD');
        await wrapUMDCode();
        console.timeEnd('Wrap UMD');
    })
}

const debouncedRebuild = debounce(rebuild, 100);

chokidar.watch([
    path.resolve(__dirname, '../src/**/*.ts'),
    path.resolve(__dirname, '../node_modules/zrender/src/**/*.ts'),
], {
    persistent: true
}).on('all', debouncedRebuild);<commit_msg>chore(devfast): replace __DEV__ with '_DEV_'<commit_after>const chokidar = require('chokidar');
const path = require('path');
const {build} = require('esbuild');
const fs = require('fs');
const debounce = require('lodash.debounce');

const outFilePath = path.resolve(__dirname, '../dist/echarts.js');

const umdMark = '// ------------- WRAPPED UMD --------------- //';
const umdWrapperHead = `
${umdMark}
(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['exports'], factory);
    } else if (typeof exports === 'object' && typeof exports.nodeName !== 'string') {
        // CommonJS
        factory(exports);
    } else {
        // Browser globals
        factory((root.echarts = {}));
    }
}(typeof self !== 'undefined' ? self : this, function (exports, b) {
`;

const umdWrapperTail = `
}));`;

async function wrapUMDCode() {
    const code = fs.readFileSync(outFilePath, 'utf-8');
    if (code.indexOf(umdMark) >= 0) {
        return;
    }

    fs.writeFileSync(
        outFilePath,
        // Replaced __DEV__ with a same length string to avoid breaking source map
        umdWrapperHead + code.replace(/__DEV__/g, "\'_DEV_\'") + umdWrapperTail,
        'utf-8'
    );

    const sourceMap = JSON.parse(fs.readFileSync(outFilePath + '.map', 'utf-8'));
    // Fast trick for fixing source map
    sourceMap.mappings = umdWrapperHead.split('\n').map(() => '').join(';') + sourceMap.mappings;

    fs.writeFileSync(outFilePath + '.map', JSON.stringify(sourceMap), 'utf-8');
}

function rebuild() {
    build({
        stdio: 'inherit',
        entryPoints: [path.resolve(__dirname, '../echarts.all.ts')],
        outfile: outFilePath,
        format: 'cjs',
        sourcemap: true,
        bundle: true,
    }).catch(e => {
        console.error(e.toString());
    }).then(async () => {
        console.time('Wrap UMD');
        await wrapUMDCode();
        console.timeEnd('Wrap UMD');
    })
}

const debouncedRebuild = debounce(rebuild, 100);

chokidar.watch([
    path.resolve(__dirname, '../src/**/*.ts'),
    path.resolve(__dirname, '../node_modules/zrender/src/**/*.ts'),
], {
    persistent: true
}).on('all', debouncedRebuild);<|endoftext|>


<commit_before>angularFiles = {
  'angularSrc': [
    'src/Angular.js',
    'src/loader.js',
    'src/AngularPublic.js',
    'src/jqLite.js',
    'src/apis.js',

    'src/auto/injector.js',

    'src/ng/anchorScroll.js',
    'src/ng/browser.js',
    'src/ng/cacheFactory.js',
    'src/ng/compile.js',
    'src/ng/controller.js',
    'src/ng/document.js',
    'src/ng/exceptionHandler.js',
    'src/ng/interpolate.js',
    'src/ng/location.js',
    'src/ng/log.js',
    'src/ng/parse.js',
    'src/ng/q.js',
    'src/ng/route.js',
    'src/ng/routeParams.js',
    'src/ng/rootScope.js',
    'src/ng/sniffer.js',
    'src/ng/window.js',
    'src/ng/http.js',
    'src/ng/httpBackend.js',
    'src/ng/locale.js',
    'src/ng/timeout.js',

    'src/ng/filter.js',
    'src/ng/filter/filter.js',
    'src/ng/filter/filters.js',
    'src/ng/filter/limitTo.js',
    'src/ng/filter/orderBy.js',

    'src/ng/directive/directives.js',
    'src/ng/directive/a.js',
    'src/ng/directive/booleanAttrs.js',
    'src/ng/directive/form.js',
    'src/ng/directive/input.js',
    'src/ng/directive/ngBind.js',
    'src/ng/directive/ngClass.js',
    'src/ng/directive/ngCloak.js',
    'src/ng/directive/ngController.js',
    'src/ng/directive/ngCsp.js',
    'src/ng/directive/ngEventDirs.js',
    'src/ng/directive/ngInclude.js',
    'src/ng/directive/ngInit.js',
    'src/ng/directive/ngNonBindable.js',
    'src/ng/directive/ngPluralize.js',
    'src/ng/directive/ngRepeat.js',
    'src/ng/directive/ngShowHide.js',
    'src/ng/directive/ngStyle.js',
    'src/ng/directive/ngSwitch.js',
    'src/ng/directive/ngTransclude.js',
    'src/ng/directive/ngView.js',
    'src/ng/directive/script.js',
    'src/ng/directive/select.js',
    'src/ng/directive/style.js'
  ],

  'angularSrcModules': [
    'src/ngCookies/cookies.js',
    'src/ngResource/resource.js',
    'src/ngSanitize/sanitize.js',
    'src/ngSanitize/directive/ngBindHtml.js',
    'src/ngSanitize/filter/linky.js',
    'src/ngMock/angular-mocks.js',

    'src/bootstrap/bootstrap.js'
  ],

  'angularScenario': [
    'src/ngScenario/Scenario.js',
    'src/ngScenario/Application.js',
    'src/ngScenario/Describe.js',
    'src/ngScenario/Future.js',
    'src/ngScenario/ObjectModel.js',
    'src/ngScenario/Describe.js',
    'src/ngScenario/Runner.js',
    'src/ngScenario/SpecRunner.js',
    'src/ngScenario/dsl.js',
    'src/ngScenario/matchers.js',
    'src/ngScenario/output/Html.js',
    'src/ngScenario/output/Json.js',
    'src/ngScenario/output/Xml.js',
    'src/ngScenario/output/Object.js'
  ],

  'angularTest': [
    'test/testabilityPatch.js',
    'test/matchers.js',
    'test/ngScenario/*.js',
    'test/ngScenario/output/*.js',
    'test/ngScenario/jstd-scenario-adapter/*.js',
    'test/*.js',
    'test/auto/*.js',
    'test/bootstrap/*.js',
    'test/ng/*.js',
    'test/ng/directive/*.js',
    'test/ng/filter/*.js',
    'test/ngCookies/*.js',
    'test/ngResource/*.js',
    'test/ngSanitize/*.js',
    'test/ngSanitize/directive/*.js',
    'test/ngSanitize/filter/*.js',
    'test/ngMock/*.js'
  ],

  'jstd': [
    'lib/jasmine/jasmine.js',
    'lib/jasmine-jstd-adapter/JasmineAdapter.js',
    'lib/jquery/jquery.js',
    'test/jquery_remove.js',
    '@angularSrc',
    'src/publishExternalApis.js',
    '@angularSrcModules',
    '@angularScenario',
    'src/ngScenario/jstd-scenario-adapter/Adapter.js',
    '@angularTest',
    'example/personalLog/*.js',
    'example/personalLog/test/*.js'
  ],

  'jstdExclude': [
    'test/jquery_alias.js',
    'src/angular-bootstrap.js',
    'src/ngScenario/angular-bootstrap.js'
  ],

  'jstdScenario': [
    'build/angular-scenario.js',
    'build/jstd-scenario-adapter-config.js',
    'build/jstd-scenario-adapter.js',
    'build/docs/docs-scenario.js'
  ],

  "jstdModules": [
    'lib/jasmine/jasmine.js',
    'lib/jasmine-jstd-adapter/JasmineAdapter.js',
    'build/angular.js',
    'src/ngMock/angular-mocks.js',
    'src/ngCookies/cookies.js',
    'src/ngResource/resource.js',
    'src/ngSanitize/sanitize.js',
    'src/ngSanitize/directive/ngBindHtml.js',
    'src/ngSanitize/filter/linky.js',
    'test/matchers.js',
    'test/ngMock/*.js',
    'test/ngCookies/*.js',
    'test/ngResource/*.js',
    'test/ngSanitize/*.js',
    'test/ngSanitize/directive/*.js',
    'test/ngSanitize/filter/*.js'
  ],

  'jstdPerf': [
   'lib/jasmine/jasmine.js',
   'lib/jasmine-jstd-adapter/JasmineAdapter.js',
   '@angularSrc',
   '@angularSrcModules',
   'src/ngMock/angular-mocks.js',
   'perf/data/*.js',
   'perf/testUtils.js',
   'perf/*.js'
  ],

  'jstdPerfExclude': [
    'src/ng/angular-bootstrap.js',
    'src/ngScenario/angular-bootstrap.js'
  ],

  'jstdJquery': [
    'lib/jasmine/jasmine.js',
    'lib/jasmine-jstd-adapter/JasmineAdapter.js',
    'lib/jquery/jquery.js',
    'test/jquery_alias.js',
    '@angularSrc',
    'src/publishExternalApis.js',
    '@angularSrcModules',
    '@angularScenario',
    'src/ngScenario/jstd-scenario-adapter/Adapter.js',
    '@angularTest',
    'example/personalLog/*.js',

    'example/personalLog/test/*.js'
  ],

  'jstdJqueryExclude': [
    'src/angular-bootstrap.js',
    'src/ngScenario/angular-bootstrap.js',
    'test/jquery_remove.js'
  ]
};

if (exports) {
  exports.files = angularFiles
  exports.mergeFiles = function mergeFiles() {
    var files = [];

    [].splice.call(arguments, 0).forEach(function(file) {
      if (file.match(/testacular/)) {
        files.push(file);
      } else {
        angularFiles[file].forEach(function(f) {
          // replace @ref
          var match = f.match(/^\@(.*)/);
          if (match) {
            var deps = angularFiles[match[1]];
            files = files.concat(deps);
          } else {
            if (!/jstd|jasmine/.test(f)) { //TODO(i): remove once we don't have jstd/jasmine in repo
              files.push(f);
            }
          }
        });
      }
    });

    return files;
  }
}
<commit_msg>chore(Rakefile): remove a duplicate file in angularFiles.js<commit_after>angularFiles = {
  'angularSrc': [
    'src/Angular.js',
    'src/loader.js',
    'src/AngularPublic.js',
    'src/jqLite.js',
    'src/apis.js',

    'src/auto/injector.js',

    'src/ng/anchorScroll.js',
    'src/ng/browser.js',
    'src/ng/cacheFactory.js',
    'src/ng/compile.js',
    'src/ng/controller.js',
    'src/ng/document.js',
    'src/ng/exceptionHandler.js',
    'src/ng/interpolate.js',
    'src/ng/location.js',
    'src/ng/log.js',
    'src/ng/parse.js',
    'src/ng/q.js',
    'src/ng/route.js',
    'src/ng/routeParams.js',
    'src/ng/rootScope.js',
    'src/ng/sniffer.js',
    'src/ng/window.js',
    'src/ng/http.js',
    'src/ng/httpBackend.js',
    'src/ng/locale.js',
    'src/ng/timeout.js',

    'src/ng/filter.js',
    'src/ng/filter/filter.js',
    'src/ng/filter/filters.js',
    'src/ng/filter/limitTo.js',
    'src/ng/filter/orderBy.js',

    'src/ng/directive/directives.js',
    'src/ng/directive/a.js',
    'src/ng/directive/booleanAttrs.js',
    'src/ng/directive/form.js',
    'src/ng/directive/input.js',
    'src/ng/directive/ngBind.js',
    'src/ng/directive/ngClass.js',
    'src/ng/directive/ngCloak.js',
    'src/ng/directive/ngController.js',
    'src/ng/directive/ngCsp.js',
    'src/ng/directive/ngEventDirs.js',
    'src/ng/directive/ngInclude.js',
    'src/ng/directive/ngInit.js',
    'src/ng/directive/ngNonBindable.js',
    'src/ng/directive/ngPluralize.js',
    'src/ng/directive/ngRepeat.js',
    'src/ng/directive/ngShowHide.js',
    'src/ng/directive/ngStyle.js',
    'src/ng/directive/ngSwitch.js',
    'src/ng/directive/ngTransclude.js',
    'src/ng/directive/ngView.js',
    'src/ng/directive/script.js',
    'src/ng/directive/select.js',
    'src/ng/directive/style.js'
  ],

  'angularSrcModules': [
    'src/ngCookies/cookies.js',
    'src/ngResource/resource.js',
    'src/ngSanitize/sanitize.js',
    'src/ngSanitize/directive/ngBindHtml.js',
    'src/ngSanitize/filter/linky.js',
    'src/ngMock/angular-mocks.js',

    'src/bootstrap/bootstrap.js'
  ],

  'angularScenario': [
    'src/ngScenario/Scenario.js',
    'src/ngScenario/Application.js',
    'src/ngScenario/Describe.js',
    'src/ngScenario/Future.js',
    'src/ngScenario/ObjectModel.js',
    'src/ngScenario/Runner.js',
    'src/ngScenario/SpecRunner.js',
    'src/ngScenario/dsl.js',
    'src/ngScenario/matchers.js',
    'src/ngScenario/output/Html.js',
    'src/ngScenario/output/Json.js',
    'src/ngScenario/output/Xml.js',
    'src/ngScenario/output/Object.js'
  ],

  'angularTest': [
    'test/testabilityPatch.js',
    'test/matchers.js',
    'test/ngScenario/*.js',
    'test/ngScenario/output/*.js',
    'test/ngScenario/jstd-scenario-adapter/*.js',
    'test/*.js',
    'test/auto/*.js',
    'test/bootstrap/*.js',
    'test/ng/*.js',
    'test/ng/directive/*.js',
    'test/ng/filter/*.js',
    'test/ngCookies/*.js',
    'test/ngResource/*.js',
    'test/ngSanitize/*.js',
    'test/ngSanitize/directive/*.js',
    'test/ngSanitize/filter/*.js',
    'test/ngMock/*.js'
  ],

  'jstd': [
    'lib/jasmine/jasmine.js',
    'lib/jasmine-jstd-adapter/JasmineAdapter.js',
    'lib/jquery/jquery.js',
    'test/jquery_remove.js',
    '@angularSrc',
    'src/publishExternalApis.js',
    '@angularSrcModules',
    '@angularScenario',
    'src/ngScenario/jstd-scenario-adapter/Adapter.js',
    '@angularTest',
    'example/personalLog/*.js',
    'example/personalLog/test/*.js'
  ],

  'jstdExclude': [
    'test/jquery_alias.js',
    'src/angular-bootstrap.js',
    'src/ngScenario/angular-bootstrap.js'
  ],

  'jstdScenario': [
    'build/angular-scenario.js',
    'build/jstd-scenario-adapter-config.js',
    'build/jstd-scenario-adapter.js',
    'build/docs/docs-scenario.js'
  ],

  "jstdModules": [
    'lib/jasmine/jasmine.js',
    'lib/jasmine-jstd-adapter/JasmineAdapter.js',
    'build/angular.js',
    'src/ngMock/angular-mocks.js',
    'src/ngCookies/cookies.js',
    'src/ngResource/resource.js',
    'src/ngSanitize/sanitize.js',
    'src/ngSanitize/directive/ngBindHtml.js',
    'src/ngSanitize/filter/linky.js',
    'test/matchers.js',
    'test/ngMock/*.js',
    'test/ngCookies/*.js',
    'test/ngResource/*.js',
    'test/ngSanitize/*.js',
    'test/ngSanitize/directive/*.js',
    'test/ngSanitize/filter/*.js'
  ],

  'jstdPerf': [
   'lib/jasmine/jasmine.js',
   'lib/jasmine-jstd-adapter/JasmineAdapter.js',
   '@angularSrc',
   '@angularSrcModules',
   'src/ngMock/angular-mocks.js',
   'perf/data/*.js',
   'perf/testUtils.js',
   'perf/*.js'
  ],

  'jstdPerfExclude': [
    'src/ng/angular-bootstrap.js',
    'src/ngScenario/angular-bootstrap.js'
  ],

  'jstdJquery': [
    'lib/jasmine/jasmine.js',
    'lib/jasmine-jstd-adapter/JasmineAdapter.js',
    'lib/jquery/jquery.js',
    'test/jquery_alias.js',
    '@angularSrc',
    'src/publishExternalApis.js',
    '@angularSrcModules',
    '@angularScenario',
    'src/ngScenario/jstd-scenario-adapter/Adapter.js',
    '@angularTest',
    'example/personalLog/*.js',

    'example/personalLog/test/*.js'
  ],

  'jstdJqueryExclude': [
    'src/angular-bootstrap.js',
    'src/ngScenario/angular-bootstrap.js',
    'test/jquery_remove.js'
  ]
};

if (exports) {
  exports.files = angularFiles
  exports.mergeFiles = function mergeFiles() {
    var files = [];

    [].splice.call(arguments, 0).forEach(function(file) {
      if (file.match(/testacular/)) {
        files.push(file);
      } else {
        angularFiles[file].forEach(function(f) {
          // replace @ref
          var match = f.match(/^\@(.*)/);
          if (match) {
            var deps = angularFiles[match[1]];
            files = files.concat(deps);
          } else {
            if (!/jstd|jasmine/.test(f)) { //TODO(i): remove once we don't have jstd/jasmine in repo
              files.push(f);
            }
          }
        });
      }
    });

    return files;
  }
}
<|endoftext|>


<commit_before>import React from 'react';

import { Button, Dimmer, Divider, Grid, Header, Icon, Label, Loader, Modal, Segment } from 'semantic-ui-react'
import { Form, Input } from 'formsy-semantic-ui-react'
import slug from 'slug'
import steem from 'steem'

export default class PostForm extends React.Component {

  state = {}

  constructor(props) {
    super(props)
    this.state = {
      category: (props.forum && props.forum.tags) ? props.forum.tags[0] : null,
      recommended: (props.forum && props.forum.tags) ? props.forum.tags : [],
      submitting: false,
      waitingforblock: false,
      tags: (props.forum && props.forum.tags) ? [props.forum.tags[0]] : []
    };
  }

  handleCancel = (e) => {
    e.preventDefault()
    this.props.onCancel()
    return false
  }

  handleChange = (e, { name, value }) => {
    this.setState({ [name]: value })
  }

  addTag = (e) => {
    let additionalTag = this.state.additionalTag,
        tags = this.state.tags
    if(tags.indexOf(additionalTag) === -1 && tags.length < 5) {
      tags.push(additionalTag)
      this.setState({
        additionalTag: '',
        tags: tags
      })
    }
    e.preventDefault()
  }

  removeTag = (e, data) => {
    let tags = this.state.tags,
        idx = tags.indexOf(data.content)
    if(idx !== -1) {
      tags.splice(idx, 1)
      this.setState({ tags: tags })
    }
    e.preventDefault()
  }

  generatePermlink = (title, parent = null) => {
    var permlink = '',
        date = new Date(),
        time = date.getFullYear().toString()+(date.getMonth()+1).toString()+date.getDate().toString()+"t"+date.getHours().toString()+date.getMinutes().toString()+date.getSeconds().toString()+date.getMilliseconds().toString()+"z"
    if(title && title.trim() !== '') {
      permlink = slug(title).toString()
    }
    if(parent) {
      permlink = "re-" + parent.author + "-" + parent.permlink + "-" + time;
    }
    if(permlink.length > 255) {
      permlink = permlink.substring(permlink.length - 255, permlink.length)
    }
    permlink = permlink.toLowerCase().replace(/[^a-z0-9-]+/g, '')
    return permlink;
  }

  onValidSubmit = (formData) => {
    const data = {...formData, ...this.state}
    let t = this,
        // The parent post (if any)
        parent = this.props.parent,
        // The account posting
        account = this.props.account,
        // Use the title if given, or use the parent's title with a prefix
        title = (data.title) ? data.title : '',
        // Generate a permlink based off the choosen title
        permlink = this.generatePermlink(title, parent),
        // json_metadata to associate with the post
        json = {
          app: 'chainbb/0.1',
          format: 'markdown+html',
          tags: data.tags
        },
        ops = [
          ['comment', {
            author: account.name,
            body: data.body,
            json_metadata: JSON.stringify(json),
            parent_author: (parent) ? parent.author : '',
            parent_permlink: (parent) ? parent.permlink : data.category,
            permlink: permlink,
            title: title
          }],
          ['comment_options', {
            allow_curation_rewards: true,
            allow_votes: true,
            author: account.name,
            extensions: [[0, { "beneficiaries": [{ "account":"chainbb", "weight":100 }] }]],
            max_accepted_payout: "1000000.000 SBD",
            percent_steem_dollars: 10000,
            permlink: permlink
          }]
        ]
    this.setState({
      submitting: true
    })
    steem.broadcast.send({ operations: ops, extensions: [] }, { posting: account.key }, function(err, result) {
      if(err) {
        t.setState({
          submitting: false,
          hasError: true,
          errorMsg: err.message
        })
      } else {
        setTimeout(function() {
          t.setState({
            submitting: false,
            waitingforblock: true,
            hasError: false
          })
          setTimeout(function() {
            t.setState({
              waitingforblock: false
            })
            // If we have a parent, reload all of the children
            if(parent) {
              let parent_author = (parent.root_author) ? parent.root_author : parent.author,
                  parent_category = (parent.category) ? parent.category : 'tag',
                  parent_permlink = (parent.root_permlink) ? parent.root_permlink : parent.permlink
              if(parent.root_post) {
                [ parent_author, parent_permlink ] = parent.root_post.split('/')
              }
              t.props.actions.fetchPostResponses({
                author: parent_author,
                category: parent_category,
                permlink: parent_permlink
              })
            }
            let id = account.name + '/' + permlink
            t.props.onComplete(id)
          }, 5000)
        }, 5000)
      }
    });
  }

  dismissError = (e) => this.setState({
    hasError: false,
    errorMsg: false
  })

  render() {
    let formHeader = this.props.formHeader,
        tags = this.state.tags,
        formFieldTitle = false,
        formFieldTags = false,
        addTagButton = (
          <Button color='green' onClick={this.addTag}>
            Add Tag (Enter)
          </Button>
        ),
        display = (
          <Dimmer inverted active style={{minHeight: '100px', display: 'block'}}>
            <Loader size='large' content='Loading'/>
          </Dimmer>
        )

    const errorLabel =

    if(this.props.elements.indexOf('tags') !== -1) {
      formFieldTags = (
        <Grid stackable={true}>
          <Grid.Row>
            <Grid.Column width={8}>
              <Form.Field>
                Add additional tags
                <Input name='additionalTag' value={this.state.additionalTag} placeholder='Add up to 4 additional tags to this post.' action={addTagButton} onChange={this.handleChange} />
              </Form.Field>
            </Grid.Column>
            <Grid.Column width={8}>
              <Form.Field>
                Active Tags
                {tags.map((tag, i) => )}
              </Form.Field>
            </Grid.Column>
          </Grid.Row>
        </Grid>
      )
    }

    if(this.props.elements.indexOf('title') !== -1) {
      formFieldTitle = (
        <Form.Field>
          <Form.Input
            name="title"
            label="Post Title"
            required
            placeholder='What should this post be titled?'
            validationErrors={{
              isDefaultRequiredValue: 'A title is required'
            }}
            errorLabel={ errorLabel }
          />
        </Form.Field>
      )
    }

    display = (
      <Segment stacked>
        <Dimmer inverted active={this.state.submitting} style={{minHeight: '100px'}}>
          <Loader size='large' indeterminate content='Submitting to Blockchain'/>
        </Dimmer>
        <Dimmer inverted active={this.state.waitingforblock} style={{minHeight: '100px'}}>
          <Loader size='large' content='Waiting for next Block'/>
        </Dimmer>
        <Modal
          open={this.state.hasError}
          onClose={this.dismissError}
          basic
          size='small'
          >

          <Modal.Content>

An error has occured.

If you need assistance, please notify @jesta here on the forums, on steemit.com, or via steemit.chat. Please include the error message shown below.

              {this.state.errorMsg}

          </Modal.Content>
          <Modal.Actions>
            <Button color='green' onClick={this.dismissError} inverted>
              <Icon name='checkmark' /> Got it
            </Button>
          </Modal.Actions>
        </Modal>
        <Form
          ref={ ref => this.form = ref }
          onValidSubmit={ this.onValidSubmit }
        >
          {formHeader}
          {formFieldTitle}
          <Form.TextArea
            name="body"
            label="Post Body (Markdown Supported)"
            placeholder='Write your post here.'
            required
            errorLabel={  }
            validationErrors={{
              isDefaultRequiredValue: 'A post body is required.',
            }}
          />
          {formFieldTags}
          <Divider />
          <Button primary>Submit Post</Button>
          <Button color='orange' onClick={this.handleCancel}>Cancel</Button>
        </Form>
      </Segment>
    )
    return display
  }

}
<commit_msg>Only set an ID for the callback if it has a parent<commit_after>import React from 'react';

import { Button, Dimmer, Divider, Grid, Header, Icon, Label, Loader, Modal, Segment } from 'semantic-ui-react'
import { Form, Input } from 'formsy-semantic-ui-react'
import slug from 'slug'
import steem from 'steem'

export default class PostForm extends React.Component {

  state = {}

  constructor(props) {
    super(props)
    this.state = {
      category: (props.forum && props.forum.tags) ? props.forum.tags[0] : null,
      recommended: (props.forum && props.forum.tags) ? props.forum.tags : [],
      submitting: false,
      waitingforblock: false,
      tags: (props.forum && props.forum.tags) ? [props.forum.tags[0]] : []
    };
  }

  handleCancel = (e) => {
    e.preventDefault()
    this.props.onCancel()
    return false
  }

  handleChange = (e, { name, value }) => {
    this.setState({ [name]: value })
  }

  addTag = (e) => {
    let additionalTag = this.state.additionalTag,
        tags = this.state.tags
    if(tags.indexOf(additionalTag) === -1 && tags.length < 5) {
      tags.push(additionalTag)
      this.setState({
        additionalTag: '',
        tags: tags
      })
    }
    e.preventDefault()
  }

  removeTag = (e, data) => {
    let tags = this.state.tags,
        idx = tags.indexOf(data.content)
    if(idx !== -1) {
      tags.splice(idx, 1)
      this.setState({ tags: tags })
    }
    e.preventDefault()
  }

  generatePermlink = (title, parent = null) => {
    var permlink = '',
        date = new Date(),
        time = date.getFullYear().toString()+(date.getMonth()+1).toString()+date.getDate().toString()+"t"+date.getHours().toString()+date.getMinutes().toString()+date.getSeconds().toString()+date.getMilliseconds().toString()+"z"
    if(title && title.trim() !== '') {
      permlink = slug(title).toString()
    }
    if(parent) {
      permlink = "re-" + parent.author + "-" + parent.permlink + "-" + time;
    }
    if(permlink.length > 255) {
      permlink = permlink.substring(permlink.length - 255, permlink.length)
    }
    permlink = permlink.toLowerCase().replace(/[^a-z0-9-]+/g, '')
    return permlink;
  }

  onValidSubmit = (formData) => {
    const data = {...formData, ...this.state}
    let t = this,
        // The parent post (if any)
        parent = this.props.parent,
        // The account posting
        account = this.props.account,
        // Use the title if given, or use the parent's title with a prefix
        title = (data.title) ? data.title : '',
        // Generate a permlink based off the choosen title
        permlink = this.generatePermlink(title, parent),
        // json_metadata to associate with the post
        json = {
          app: 'chainbb/0.1',
          format: 'markdown+html',
          tags: data.tags
        },
        ops = [
          ['comment', {
            author: account.name,
            body: data.body,
            json_metadata: JSON.stringify(json),
            parent_author: (parent) ? parent.author : '',
            parent_permlink: (parent) ? parent.permlink : data.category,
            permlink: permlink,
            title: title
          }],
          ['comment_options', {
            allow_curation_rewards: true,
            allow_votes: true,
            author: account.name,
            extensions: [[0, { "beneficiaries": [{ "account":"chainbb", "weight":100 }] }]],
            max_accepted_payout: "1000000.000 SBD",
            percent_steem_dollars: 10000,
            permlink: permlink
          }]
        ]
    this.setState({
      submitting: true
    })
    steem.broadcast.send({ operations: ops, extensions: [] }, { posting: account.key }, function(err, result) {
      if(err) {
        t.setState({
          submitting: false,
          hasError: true,
          errorMsg: err.message
        })
      } else {
        setTimeout(function() {
          t.setState({
            submitting: false,
            waitingforblock: true,
            hasError: false
          })
          setTimeout(function() {
            let id = false
            t.setState({
              waitingforblock: false
            })
            // If we have a parent, reload all of the children
            if(parent) {
              // This had a parent, so set the callback to include it as the ID
              id = account.name + '/' + permlink
              let parent_author = (parent.root_author) ? parent.root_author : parent.author,
                  parent_category = (parent.category) ? parent.category : 'tag',
                  parent_permlink = (parent.root_permlink) ? parent.root_permlink : parent.permlink
              if(parent.root_post) {
                [ parent_author, parent_permlink ] = parent.root_post.split('/')
              }
              t.props.actions.fetchPostResponses({
                author: parent_author,
                category: parent_category,
                permlink: parent_permlink
              })
            }
            t.props.onComplete(id)
          }, 5000)
        }, 5000)
      }
    });
  }

  dismissError = (e) => this.setState({
    hasError: false,
    errorMsg: false
  })

  render() {
    let formHeader = this.props.formHeader,
        tags = this.state.tags,
        formFieldTitle = false,
        formFieldTags = false,
        addTagButton = (
          <Button color='green' onClick={this.addTag}>
            Add Tag (Enter)
          </Button>
        ),
        display = (
          <Dimmer inverted active style={{minHeight: '100px', display: 'block'}}>
            <Loader size='large' content='Loading'/>
          </Dimmer>
        )

    const errorLabel =

    if(this.props.elements.indexOf('tags') !== -1) {
      formFieldTags = (
        <Grid stackable={true}>
          <Grid.Row>
            <Grid.Column width={8}>
              <Form.Field>
                Add additional tags
                <Input name='additionalTag' value={this.state.additionalTag} placeholder='Add up to 4 additional tags to this post.' action={addTagButton} onChange={this.handleChange} />
              </Form.Field>
            </Grid.Column>
            <Grid.Column width={8}>
              <Form.Field>
                Active Tags
                {tags.map((tag, i) => )}
              </Form.Field>
            </Grid.Column>
          </Grid.Row>
        </Grid>
      )
    }

    if(this.props.elements.indexOf('title') !== -1) {
      formFieldTitle = (
        <Form.Field>
          <Form.Input
            name="title"
            label="Post Title"
            required
            placeholder='What should this post be titled?'
            validationErrors={{
              isDefaultRequiredValue: 'A title is required'
            }}
            errorLabel={ errorLabel }
          />
        </Form.Field>
      )
    }

    display = (
      <Segment stacked>
        <Dimmer inverted active={this.state.submitting} style={{minHeight: '100px'}}>
          <Loader size='large' indeterminate content='Submitting to Blockchain'/>
        </Dimmer>
        <Dimmer inverted active={this.state.waitingforblock} style={{minHeight: '100px'}}>
          <Loader size='large' content='Waiting for next Block'/>
        </Dimmer>
        <Modal
          open={this.state.hasError}
          onClose={this.dismissError}
          basic
          size='small'
          >

          <Modal.Content>

An error has occured.

If you need assistance, please notify @jesta here on the forums, on steemit.com, or via steemit.chat. Please include the error message shown below.

              {this.state.errorMsg}

          </Modal.Content>
          <Modal.Actions>
            <Button color='green' onClick={this.dismissError} inverted>
              <Icon name='checkmark' /> Got it
            </Button>
          </Modal.Actions>
        </Modal>
        <Form
          ref={ ref => this.form = ref }
          onValidSubmit={ this.onValidSubmit }
        >
          {formHeader}
          {formFieldTitle}
          <Form.TextArea
            name="body"
            label="Post Body (Markdown Supported)"
            placeholder='Write your post here.'
            required
            errorLabel={  }
            validationErrors={{
              isDefaultRequiredValue: 'A post body is required.',
            }}
          />
          {formFieldTags}
          <Divider />
          <Button primary>Submit Post</Button>
          <Button color='orange' onClick={this.handleCancel}>Cancel</Button>
        </Form>
      </Segment>
    )
    return display
  }

}
<|endoftext|>


<commit_before>const fs = require('fs')
const gulp = require('gulp');
const del = require('del');
const path = require('path')
const inlineNg2Template = require('gulp-inline-ng2-template');
const ngc = require('@angular/compiler-cli/src/main').main;
const less = require('less');
const exec = require('child_process').exec;
const replace = require('replace');
const jsonModify = require('gulp-json-modify');
const pkg = require('../package.json');
const gulpLess = require('gulp-less');
const gulpSequence = require('gulp-sequence');
const cmdArgs = require('./proccessCmdArgs')((process.argv));

const inlineTemplatePluginOptions = {
	base: '../src',
	useRelativePaths: true,
	styleProcessor: (path, ext, file, cb) => {
		less.render(file, {paths: ['../src/app/@ansyn/']}, (e, out) => {
			if (e) {
				throw e;
			}
			cb(null, out.css);
		});
	}
};

gulp.task('clean_dist', function () {
	return del([
		"dist/**",
	], {force: true});
});

gulp.task('clean_src-dist', function () {
	return del([
		"src-dist/**"
	], {force: true});
});

gulp.task('clean', function (done) {
	gulpSequence('clean_dist', 'clean_src-dist', function (err) {
		if (err) {
			throw err
		}
		else {
			return done()

		}
	})
});

gulp.task('copy-public-api', function () {

	return gulp.src([
		'../README.md',
		'../public_api.ts',
	])
		.pipe(gulp.dest('src-dist'));

});

gulp.task('copy-style', function () {

	return gulp.src([
		'../src/styles/**/*'
	])
		.pipe(gulpLess({
			paths: [path.join(__dirname, '../src/app/@ansyn')]
		}))
		.pipe(gulp.dest('dist/styles'))

});

gulp.task('copy-src', function () {
	// and compile less to css
	return gulp.src([
		'../src/**/*.ts',
		'!../src/**/*.spec.ts'
	])
		.pipe(inlineNg2Template(inlineTemplatePluginOptions))
		.pipe(gulp.dest('src-dist/src'))

});

gulp.task('compile', function (done) {
	return Promise.resolve()
		.then(() => ngc(['-p', 'tsconfig.ngc.json'], err => {
			throw err
		}))
});

gulp.task('getAppConfig', function (done) {
	const appConfig = fs.readFileSync('../src/app/@ansyn/assets/config/app.config.json');
	fs.writeFileSync('dist/defaultAppConfig.js', "export const appConfig = " + appConfig);
	return done()
});

gulp.task('copy-assets', function (done) {
	return gulp.src(['../src/app/@ansyn/assets/**'])
		.pipe(gulp.dest('dist/assets'))
});

gulp.task('fix-path', function (done) {
	replace({
		regex: '\'@ansyn/',
		replacement: '\'ng-ansyn/src/app/@ansyn/',
		// replacement: '\'build/dist/src/app/app/',
		paths: ['dist/'],
		recursive: true,
		silent: true
	});

	return done()

});

gulp.task('copy_packageJson', function (done) {

	const peerDependencies = {
		"@angular/animations": "5.1.2",
		"@angular/common": "5.1.2",
		"@angular/compiler": "5.1.2",
		"@angular/core": "5.1.2",
		"@angular/forms": "5.1.2",
		"@angular/http": "5.1.2",
		"@angular/platform-browser": "5.1.2",
		"@angular/platform-browser-dynamic": "5.1.2",
		"@angular/router": "5.1.2"
	};
	const dependencies = {
		...pkg.dependencies,
		"@types/openlayers": "^4.6.2",
		"@types/lodash": "4.14.88",
		"@types/ol": "^4.6.1"
	};
	Object.keys(peerDependencies).forEach(key => {
		delete dependencies[key]
	});

	return gulp.src('../package.json')
		.pipe(jsonModify({
			key: 'version',
			value: cmdArgs && cmdArgs.version ? cmdArgs.version : null
		}))
		.pipe(jsonModify({
			key: 'name',
			value: "ng-ansyn"
		}))
		.pipe(jsonModify({
			key: 'main',
			value: 'public_api'
		}))
		.pipe(jsonModify({
			key: 'private',
			value: null
		}))
		.pipe(jsonModify({
			key: 'dependencies',
			value: dependencies
		}))
		.pipe(jsonModify({
			key: 'devDependencies',
			value: {}
		}))
		.pipe(jsonModify({
			key: 'peerDependencies',
			value: peerDependencies
		}))
		.pipe(gulp.dest('dist'));
});

gulp.task('publishNpm', function (done) {
	exec('cd dist && npm publish', function (err, stdout, stderr) {
		console.log(stdout);
		console.log(stderr);
		done(err);
	});
});

gulp.task('build', function (done) {
	gulpSequence('clean', 'copy-public-api', 'copy-style', 'copy-src', 'compile', 'getAppConfig',
		'copy-assets', 'fix-path', 'copy_packageJson', (err) => {
			if (err) {
				console.log(err);
				gulpSequence('clean', () => {
					return done()
				});
			}
			else if (cmdArgs.version) {
				gulpSequence('publishNpm', 'clean', (err) => {
					console.log(err);
					gulpSequence('clean', () => {
						return done()
					})
				});

			}
			else {
				gulpSequence('clean_src-dist', () => {
					console.log("no version argument (e.g. --version 1.0.0) supplied - dist folder created");
					return done()
				})
			}
		})
});

gulp.task('testCompile', function (done) {
	gulpSequence('clean', 'copy-public-api', 'copy-src', 'compile', (err) => {
		gulpSequence('clean', () => {
			if (err) {
				console.log(err);
				throw err
			}
			else {
				return done()
			}
		})
	})
});
<commit_msg>fix comment<commit_after>const fs = require('fs')
const gulp = require('gulp');
const del = require('del');
const path = require('path')
const inlineNg2Template = require('gulp-inline-ng2-template');
const ngc = require('@angular/compiler-cli/src/main').main;
const less = require('less');
const exec = require('child_process').exec;
const replace = require('replace');
const jsonModify = require('gulp-json-modify');
const pkg = require('../package.json');
const gulpLess = require('gulp-less');
const gulpSequence = require('gulp-sequence');
const cmdArgs = require('./proccessCmdArgs')((process.argv));

const inlineTemplatePluginOptions = {
	base: '../src',
	useRelativePaths: true,
	styleProcessor: (path, ext, file, cb) => {
		less.render(file, {paths: ['../src/app/@ansyn/']}, (e, out) => {
			if (e) {
				throw e;
			}
			cb(null, out.css);
		});
	}
};

gulp.task('clean_dist', function () {
	return del([
		"dist/**",
	], {force: true});
});

gulp.task('clean_src-dist', function () {
	return del([
		"src-dist/**"
	], {force: true});
});

gulp.task('clean', function (done) {
	gulpSequence('clean_dist', 'clean_src-dist', function (err) {
		if (err) {
			throw err
		}
		else {
			return done()

		}
	})
});

gulp.task('copy-public-api', function () {

	return gulp.src([
		'../README.md',
		'../public_api.ts',
	])
		.pipe(gulp.dest('src-dist'));

});

gulp.task('copy-style', function () {

	return gulp.src([
		'../src/styles/**/*'
	])
		.pipe(gulpLess({
			paths: [path.join(__dirname, '../src/app/@ansyn')]
		}))
		.pipe(gulp.dest('dist/styles'))

});

gulp.task('copy-src', function () {
	// and compile less to css
	return gulp.src([
		'../src/**/*.ts',
		'!../src/**/*.spec.ts'
	])
		.pipe(inlineNg2Template(inlineTemplatePluginOptions))
		.pipe(gulp.dest('src-dist/src'))

});

gulp.task('compile', function (done) {
	return Promise.resolve()
		.then(() => ngc(['-p', 'tsconfig.ngc.json'], err => {
			throw err
		}))
});

gulp.task('getAppConfig', function (done) {
	const appConfig = fs.readFileSync('../src/app/@ansyn/assets/config/app.config.json');
	fs.writeFileSync('dist/defaultAppConfig.js', "export const appConfig = " + appConfig);
	return done()
});

gulp.task('copy-assets', function (done) {
	return gulp.src(['../src/app/@ansyn/assets/**'])
		.pipe(gulp.dest('dist/assets'))
});

gulp.task('fix-path', function (done) {
	replace({
		regex: '\'@ansyn/',
		replacement: '\'ng-ansyn/src/app/@ansyn/',
		// replacement: '\'build/dist/src/app/app/',
		paths: ['dist/'],
		recursive: true,
		silent: true
	});

	return done()

});

gulp.task('copy_packageJson', function (done) {

	const peerDependencies = {
		"@angular/animations": "5.1.2",
		"@angular/common": "5.1.2",
		"@angular/compiler": "5.1.2",
		"@angular/core": "5.1.2",
		"@angular/forms": "5.1.2",
		"@angular/http": "5.1.2",
		"@angular/platform-browser": "5.1.2",
		"@angular/platform-browser-dynamic": "5.1.2",
		"@angular/router": "5.1.2"
	};
	const dependencies = {
		...pkg.dependencies,
		"@types/openlayers": "^4.6.2",
		"@types/lodash": "4.14.88",
		"@types/ol": "^4.6.1"
	};
	Object.keys(peerDependencies).forEach(key => {
		delete dependencies[key]
	});

	return gulp.src('../package.json')
		.pipe(jsonModify({
			key: 'version',
			value: cmdArgs && cmdArgs.version ? cmdArgs.version : null
		}))
		.pipe(jsonModify({
			key: 'name',
			value: "ng-ansyn"
		}))
		.pipe(jsonModify({
			key: 'main',
			value: 'public_api'
		}))
		.pipe(jsonModify({
			key: 'private',
			value: null
		}))
		.pipe(jsonModify({
			key: 'dependencies',
			value: dependencies
		}))
		.pipe(jsonModify({
			key: 'devDependencies',
			value: {}
		}))
		.pipe(jsonModify({
			key: 'peerDependencies',
			value: peerDependencies
		}))
		.pipe(gulp.dest('dist'));
});

gulp.task('publishNpm', function (done) {
	exec('cd dist && npm publish', function (err, stdout, stderr) {
		console.log(stdout);
		console.log(stderr);
		done(err);
	});
});

gulp.task('build', function (done) {

	gulpSequence('clean', 'copy-public-api', 'copy-style', 'copy-src', 'compile', 'getAppConfig',
		'copy-assets', 'fix-path', 'copy_packageJson', (err) => {
			if (err) {
				console.log(err);
				gulpSequence('clean', () => {
					return done()
				});
			}
			else if (cmdArgs.version) {
				gulpSequence('publishNpm', 'clean', (err) => {
					console.log(err);
					gulpSequence('clean', () => {
						return done()
					})
				});

			}
			else {
				gulpSequence('clean_src-dist', () => {
					console.log("no version argument (e.g. gulp build --version 1.0.0) or (npm run build:gulp -- --version 1.0.0) - dist folder created");
					return done()
				})
			}
		})
});

gulp.task('testCompile', function (done) {
	gulpSequence('clean', 'copy-public-api', 'copy-src', 'compile', (err) => {
		gulpSequence('clean', () => {
			if (err) {
				console.log(err);
				throw err
			}
			else {
				return done()
			}
		})
	})
});
<|endoftext|>


<commit_before>import moment from 'moment';
import {
  isExisty,
  exclude,
} from '../lib/helpers';
import {
  find,
  has,
} from 'lodash';
import gravity from '../lib/loaders/gravity';
import total from '../lib/loaders/total';
import numeral from './fields/numeral';
import { exhibitionPeriod, exhibitionStatus } from '../lib/date';
import cached from './fields/cached';
import date from './fields/date';
import { markdown } from './fields/markdown';
import Artist from './artist';
import Partner from './partner';
import GalaxyPartner from './galaxy_partner';
import Fair from './fair';
import Artwork from './artwork';
import Location from './location';
import Image, { getDefault } from './image';
import PartnerShowEventType from './partner_show_event';
import { GravityIDFields, NodeInterface } from './object_identification';
import {
  GraphQLObjectType,
  GraphQLString,
  GraphQLNonNull,
  GraphQLList,
  GraphQLInt,
  GraphQLBoolean,
  GraphQLUnionType,
} from 'graphql';

const kind = ({ artists, fair }) => {
  if (isExisty(fair)) return 'fair';
  if (artists.length > 1) return 'group';
  if (artists.length === 1) return 'solo';
};

const PartnerShowType = new GraphQLObjectType({
  name: 'PartnerShow',
  interfaces: [NodeInterface],
  isTypeOf: (obj) => has(obj, 'partner') && has(obj, 'display_on_partner_profile'),
  fields: () => ({
    ...GravityIDFields,
    cached,
    href: {
      type: GraphQLString,
      resolve: ({ id }) => `/show/${id}`,
    },
    kind: {
      type: GraphQLString,
      resolve: (show) => {
        if (show.artists) return kind(show);
        return gravity(`partner/${show.partner.id}/show/${show.id}`).then(kind);
      },
    },
    name: {
      type: GraphQLString,
      description: 'The exhibition title',
    },
    description: {
      type: GraphQLString,
    },
    type: {
      type: GraphQLString,
      resolve: ({ fair }) =>
        isExisty(fair) ? 'Fair Booth' : 'Show',
    },
    displayable: {
      type: GraphQLBoolean,
      deprecationReason: 'Prefix Boolean returning fields with `is_`',
    },
    is_active: {
      type: GraphQLBoolean,
      description: 'Gravity doesn’t expose the `active` flag. Temporarily re-state its logic.',
      resolve: ({ start_at, end_at }) => {
        const start = moment.utc(start_at).subtract(7, 'days');
        const end = moment.utc(end_at).add(7, 'days');
        return moment.utc().isBetween(start, end);
      },
    },
    is_displayable: {
      type: GraphQLBoolean,
      resolve: ({ displayable }) => displayable,
    },
    is_fair_booth: {
      type: GraphQLBoolean,
      resolve: ({ fair }) => isExisty(fair),
    },
    press_release: markdown(),
    start_at: date,
    end_at: date,
    exhibition_period: {
      type: GraphQLString,
      description: 'A formatted description of the start to end dates',
      resolve: ({ start_at, end_at }) => exhibitionPeriod(start_at, end_at),
    },
    artists: {
      type: new GraphQLList(Artist.type),
      resolve: ({ artists }) => artists,
    },
    partner: {
      type: new GraphQLUnionType({
        name: 'PartnerTypes',
        types: [
          Partner.type,
          GalaxyPartner.type,
        ],
        resolveType: (value) => {
          if (value._links) {
            return GalaxyPartner.type;
          }
          return Partner.type;
        },
      }),
      resolve: ({ partner, galaxy_partner_id }) => {
        if (partner) {
          return partner;
        }
        return GalaxyPartner.resolve(galaxy_partner_id);
      },
    },
    fair: {
      type: Fair.type,
      resolve: ({ fair }) => fair,
    },
    location: {
      type: Location.type,
      resolve: ({ location, fair_location }) => location || fair_location,
    },
    status: {
      type: GraphQLString,
    },
    status_update: {
      type: GraphQLString,
      description: 'A formatted update on upcoming status changes',
      args: {
        max_days: {
          type: GraphQLInt,
          description: 'Before this many days no update will be generated',
        },
      },
      resolve: ({ start_at, end_at }, options) =>
        exhibitionStatus(start_at, end_at, options.max_days),
    },
    events: {
      type: new GraphQLList(PartnerShowEventType),
      resolve: ({ partner, id }) =>
        // Gravity redirects from /api/v1/show/:id => /api/v1/partner/:partner_id/show/:show_id
        // this creates issues where events will remain cached. Fetch the non-redirected
        // route to circumvent this
        gravity(`partner/${partner.id}/show/${id}`)
          .then(({ events }) => events),
    },
    counts: {
      type: new GraphQLObjectType({
        name: 'PartnerShowCounts',
        fields: {
          artworks: {
            type: GraphQLInt,
            args: {
              artist_id: {
                type: GraphQLString,
                description: 'The slug or ID of an artist in the show.',
              },
            },
            resolve: ({ id, partner }, options) => {
              return total(`partner/${partner.id}/show/${id}/artworks`, options);
            },
          },
          eligible_artworks: numeral(({ eligible_artworks_count }) =>
            eligible_artworks_count),
        },
      }),
      resolve: (partner_show) => partner_show,
    },
    artworks: {
      type: new GraphQLList(Artwork.type),
      args: {
        size: {
          type: GraphQLInt,
          description: 'Number of artworks to return',
          defaultValue: 25,
        },
        published: {
          type: GraphQLBoolean,
          defaultValue: true,
        },
        page: {
          type: GraphQLInt,
          defaultValue: 1,
        },
        all: {
          type: GraphQLBoolean,
          default: false,
        },
        for_sale: {
          type: GraphQLBoolean,
          default: false,
        },
        exclude: {
          type: new GraphQLList(GraphQLString),
          description: 'List of artwork IDs to exclude from the response (irrespective of size)',
        },
      },
      resolve: (show, options) => {
        const path = `partner/${show.partner.id}/show/${show.id}/artworks`;

        let fetch = null;

        if (options.all) {
          fetch = gravity.all(path, options);
        } else {
          fetch = gravity(path, options);
        }

        return fetch
          .then(exclude(options.exclude, 'id'));
      },
    },
    meta_image: {
      type: Image.type,
      resolve: ({ id, partner, image_versions, image_url }) => {
        if (image_versions && image_versions.length && image_url) {
          return Image.resolve({ image_versions, image_url });
        }

        return gravity(`partner/${partner.id}/show/${id}/artworks`, {
          published: true,
        })
          .then(artworks => {
            Image.resolve(getDefault(find(artworks, { can_share_image: true })));
          });
      },
    },
    cover_image: {
      type: Image.type,
      resolve: ({ id, partner, image_versions, image_url }) => {
        if (image_versions && image_versions.length && image_url) {
          return Image.resolve({ image_versions, image_url });
        }

        return gravity(`partner/${partner.id}/show/${id}/artworks`, {
          size: 1,
          published: true,
        })
          .then(artworks => {
            const artwork = artworks[0];
            return artwork && Image.resolve(getDefault(artwork.images));
          });
      },
    },
    images: {
      type: new GraphQLList(Image.type),
      args: {
        size: {
          type: GraphQLInt,
          description: 'Number of images to return',
        },
        default: {
          type: GraphQLBoolean,
          description: 'Pass true/false to include cover or not',
        },
        page: {
          type: GraphQLInt,
        },
      },
      resolve: ({ id }, options) => {
        return gravity(`partner_show/${id}/images`, options)
          .then(Image.resolve);
      },
    },
  }),
});

const PartnerShow = {
  type: PartnerShowType,
  description: 'A Partner Show',
  args: {
    id: {
      type: new GraphQLNonNull(GraphQLString),
      description: 'The slug or ID of the PartnerShow',
    },
  },
  resolve: (root, { id }) => {
    return gravity(`show/${id}`)
      .then(show => {
        if (!show.displayable && !show.is_reference) return new Error('Show Not Found');
        return show;
      });
  },
};

export default PartnerShow;
<commit_msg>Use a different node for galaxy_partner rather than overloading partner<commit_after>import moment from 'moment';
import {
  isExisty,
  exclude,
} from '../lib/helpers';
import {
  find,
  has,
} from 'lodash';
import gravity from '../lib/loaders/gravity';
import total from '../lib/loaders/total';
import numeral from './fields/numeral';
import { exhibitionPeriod, exhibitionStatus } from '../lib/date';
import cached from './fields/cached';
import date from './fields/date';
import { markdown } from './fields/markdown';
import Artist from './artist';
import Partner from './partner';
import GalaxyPartner from './galaxy_partner';
import Fair from './fair';
import Artwork from './artwork';
import Location from './location';
import Image, { getDefault } from './image';
import PartnerShowEventType from './partner_show_event';
import { GravityIDFields, NodeInterface } from './object_identification';
import {
  GraphQLObjectType,
  GraphQLString,
  GraphQLNonNull,
  GraphQLList,
  GraphQLInt,
  GraphQLBoolean,
} from 'graphql';

const kind = ({ artists, fair }) => {
  if (isExisty(fair)) return 'fair';
  if (artists.length > 1) return 'group';
  if (artists.length === 1) return 'solo';
};

const PartnerShowType = new GraphQLObjectType({
  name: 'PartnerShow',
  interfaces: [NodeInterface],
  isTypeOf: (obj) => has(obj, 'partner') && has(obj, 'display_on_partner_profile'),
  fields: () => ({
    ...GravityIDFields,
    cached,
    href: {
      type: GraphQLString,
      resolve: ({ id }) => `/show/${id}`,
    },
    kind: {
      type: GraphQLString,
      resolve: (show) => {
        if (show.artists) return kind(show);
        return gravity(`partner/${show.partner.id}/show/${show.id}`).then(kind);
      },
    },
    name: {
      type: GraphQLString,
      description: 'The exhibition title',
    },
    description: {
      type: GraphQLString,
    },
    type: {
      type: GraphQLString,
      resolve: ({ fair }) =>
        isExisty(fair) ? 'Fair Booth' : 'Show',
    },
    displayable: {
      type: GraphQLBoolean,
      deprecationReason: 'Prefix Boolean returning fields with `is_`',
    },
    is_active: {
      type: GraphQLBoolean,
      description: 'Gravity doesn’t expose the `active` flag. Temporarily re-state its logic.',
      resolve: ({ start_at, end_at }) => {
        const start = moment.utc(start_at).subtract(7, 'days');
        const end = moment.utc(end_at).add(7, 'days');
        return moment.utc().isBetween(start, end);
      },
    },
    is_displayable: {
      type: GraphQLBoolean,
      resolve: ({ displayable }) => displayable,
    },
    is_fair_booth: {
      type: GraphQLBoolean,
      resolve: ({ fair }) => isExisty(fair),
    },
    press_release: markdown(),
    start_at: date,
    end_at: date,
    exhibition_period: {
      type: GraphQLString,
      description: 'A formatted description of the start to end dates',
      resolve: ({ start_at, end_at }) => exhibitionPeriod(start_at, end_at),
    },
    artists: {
      type: new GraphQLList(Artist.type),
      resolve: ({ artists }) => artists,
    },
    galaxy_partner: {
      type: GalaxyPartner.type,
      resolve: ({ galaxy_partner_id }) => {
        if (galaxy_partner_id) {
          return GalaxyPartner.resolve(galaxy_partner_id);
        }
      },
    },
    partner: {
      type: Partner.type,
      resolve: ({ partner }) => partner,
    },
    fair: {
      type: Fair.type,
      resolve: ({ fair }) => fair,
    },
    location: {
      type: Location.type,
      resolve: ({ location, fair_location }) => location || fair_location,
    },
    status: {
      type: GraphQLString,
    },
    status_update: {
      type: GraphQLString,
      description: 'A formatted update on upcoming status changes',
      args: {
        max_days: {
          type: GraphQLInt,
          description: 'Before this many days no update will be generated',
        },
      },
      resolve: ({ start_at, end_at }, options) =>
        exhibitionStatus(start_at, end_at, options.max_days),
    },
    events: {
      type: new GraphQLList(PartnerShowEventType),
      resolve: ({ partner, id }) =>
        // Gravity redirects from /api/v1/show/:id => /api/v1/partner/:partner_id/show/:show_id
        // this creates issues where events will remain cached. Fetch the non-redirected
        // route to circumvent this
        gravity(`partner/${partner.id}/show/${id}`)
          .then(({ events }) => events),
    },
    counts: {
      type: new GraphQLObjectType({
        name: 'PartnerShowCounts',
        fields: {
          artworks: {
            type: GraphQLInt,
            args: {
              artist_id: {
                type: GraphQLString,
                description: 'The slug or ID of an artist in the show.',
              },
            },
            resolve: ({ id, partner }, options) => {
              return total(`partner/${partner.id}/show/${id}/artworks`, options);
            },
          },
          eligible_artworks: numeral(({ eligible_artworks_count }) =>
            eligible_artworks_count),
        },
      }),
      resolve: (partner_show) => partner_show,
    },
    artworks: {
      type: new GraphQLList(Artwork.type),
      args: {
        size: {
          type: GraphQLInt,
          description: 'Number of artworks to return',
          defaultValue: 25,
        },
        published: {
          type: GraphQLBoolean,
          defaultValue: true,
        },
        page: {
          type: GraphQLInt,
          defaultValue: 1,
        },
        all: {
          type: GraphQLBoolean,
          default: false,
        },
        for_sale: {
          type: GraphQLBoolean,
          default: false,
        },
        exclude: {
          type: new GraphQLList(GraphQLString),
          description: 'List of artwork IDs to exclude from the response (irrespective of size)',
        },
      },
      resolve: (show, options) => {
        const path = `partner/${show.partner.id}/show/${show.id}/artworks`;

        let fetch = null;

        if (options.all) {
          fetch = gravity.all(path, options);
        } else {
          fetch = gravity(path, options);
        }

        return fetch
          .then(exclude(options.exclude, 'id'));
      },
    },
    meta_image: {
      type: Image.type,
      resolve: ({ id, partner, image_versions, image_url }) => {
        if (image_versions && image_versions.length && image_url) {
          return Image.resolve({ image_versions, image_url });
        }

        return gravity(`partner/${partner.id}/show/${id}/artworks`, {
          published: true,
        })
          .then(artworks => {
            Image.resolve(getDefault(find(artworks, { can_share_image: true })));
          });
      },
    },
    cover_image: {
      type: Image.type,
      resolve: ({ id, partner, image_versions, image_url }) => {
        if (image_versions && image_versions.length && image_url) {
          return Image.resolve({ image_versions, image_url });
        }

        return gravity(`partner/${partner.id}/show/${id}/artworks`, {
          size: 1,
          published: true,
        })
          .then(artworks => {
            const artwork = artworks[0];
            return artwork && Image.resolve(getDefault(artwork.images));
          });
      },
    },
    images: {
      type: new GraphQLList(Image.type),
      args: {
        size: {
          type: GraphQLInt,
          description: 'Number of images to return',
        },
        default: {
          type: GraphQLBoolean,
          description: 'Pass true/false to include cover or not',
        },
        page: {
          type: GraphQLInt,
        },
      },
      resolve: ({ id }, options) => {
        return gravity(`partner_show/${id}/images`, options)
          .then(Image.resolve);
      },
    },
  }),
});

const PartnerShow = {
  type: PartnerShowType,
  description: 'A Partner Show',
  args: {
    id: {
      type: new GraphQLNonNull(GraphQLString),
      description: 'The slug or ID of the PartnerShow',
    },
  },
  resolve: (root, { id }) => {
    return gravity(`show/${id}`)
      .then(show => {
        if (!show.displayable && !show.is_reference) return new Error('Show Not Found');
        return show;
      });
  },
};

export default PartnerShow;
<|endoftext|>


<commit_before><commit_msg>Added new boolean property, lead, to company. (#191)<commit_after><|endoftext|>


<commit_before>import { notarize } from 'electron-notarize';

// todo: detect macOS target

module.exports = async function (params) {
	await notarize({
		"com.dangeredwolf.ModernDeck",
		"./dist/mac/ModernDeck.app",
		process.env.MDAppleID,
		process.env.MDAppleAppPassword
	});
};
<commit_msg>Update notarize.js<commit_after>import { notarize } from 'electron-notarize';

// todo: detect macOS target

console.log("Notarizing app... this will take a while...");

module.exports = async function (params) {
	await notarize({
		"com.dangeredwolf.ModernDeck",
		"./dist/mac/ModernDeck.app",
		process.env.MDAppleID,
		process.env.MDAppleAppPassword
	});
};
<|endoftext|>


<commit_before><commit_msg>users table update<commit_after><|endoftext|>