<commit_before>/**
 * Created by King Lee on 14-10-21.
 */
var redis_fly_flow_wrapper = require('./nosql/redis_fly_flow_wrapper');

exports.on_pay_result_verify = function(req,res){
    var orderid = req.body['orderid'];
    redis_fly_flow_wrapper.get(orderid,function(reply){
        var order_info = JSON.parse(reply);
        res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
        var code = "200";
        res.end(JSON.stringify({"code":code,"ret":order_info.ret,"amount":order_info.amount}));
    });
};
<commit_msg>add a field for on_pay_result_verify<commit_after>/**
 * Created by King Lee on 14-10-21.
 */
var redis_fly_flow_wrapper = require('./nosql/redis_fly_flow_wrapper');

exports.on_pay_result_verify = function(req,res){
    var orderid = req.body['orderid'];
    redis_fly_flow_wrapper.get(orderid,function(reply){
        var order_info = JSON.parse(reply);
        res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
        var code = "200";
        res.end(JSON.stringify({"code":code,"ret":order_info?order_info.ret:0,"amount":order_info?order_info.amount:0}));
    });
};
<|endoftext|>


<commit_before>/*jshint -W030 */ // .exist causes "Expected an assignment or function call and instead saw an expression". Disable.
'use strict';

var fs = require('fs');
var https = require('https');
var path = require('path');
var frisby = require('./../lib/icedfrisby');
var express = require('express');

var chai = require('chai');
var expect = chai.expect;

// The following tests were adapted from:
// https://github.com/visionmedia/supertest/blob/master/test/supertest.js

describe('IcedFrisby useApp(app)', function() {
    it('should start the http server on an ephemeral port', function() {
        var app = express();

        app.get('/', function(req, res) {
            res.send('^.^');
        });

        frisby.create('should start the http server on an ephemeral port')
            .useApp(app)
            .get('/')
            .expectStatus(200)
            .expectBodyContains('^.^')
            .after(function(err, res, body) {
                expect(err).to.not.exist;
            })
            .toss();
    });

    it('should work with an active http server', function() {
        var app = express();

        app.get('/', function(req, res) {
            res.send('^.^');
        });

        var server = app.listen(4000, function() {
            frisby.create('should work with an active http server')
                .useApp(app)
                .get('/')
                .expectStatus(200)
                .expectBodyContains('^.^')
                .toss();
        });
    });

    it('should start the https server on an ephemeral port', function() {
        // disable rejecting self signed certs for testing purposes
        // Attn Everyone: DO NOT USE THIS IN PRODUCTION
        process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

        var app = express();

        app.get('/', function(req, res) {
            res.send('^.^');
        });

        var fixtures = path.join(__dirname, '../', 'spec', 'fixtures');
        var server = https.createServer({
            key: fs.readFileSync(path.join(fixtures, 'test_key.pem')),
            cert: fs.readFileSync(path.join(fixtures, 'test_cert.pem'))
        }, app);

        frisby.create('should work with an active https server')
            .useApp(server)
            .get('/')
            .expectStatus(200)
            .expectBodyContains('^.^')
            .toss();
    });

    it('should work with an active https server', function() {
        // disable rejecting self signed certs for testing purposes
        // Attn Everyone: DO NOT USE THIS IN PRODUCTION
        process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

        var app = express();

        app.get('/', function(req, res) {
            res.send('^.^');
        });

        var fixtures = path.join(__dirname, '../', 'spec', 'fixtures');
        var server = https.createServer({
            key: fs.readFileSync(path.join(fixtures, 'test_key.pem')),
            cert: fs.readFileSync(path.join(fixtures, 'test_cert.pem'))
        }, app).listen();

        frisby.create('should work with an active https server')
            .useApp(server)
            .get('/')
            .expectStatus(200)
            .expectBodyContains('^.^')
            .toss();
    });
});
<commit_msg>Adding useApp() test case for when the app parameter is not defined.<commit_after>/*jshint -W030 */ // .exist causes "Expected an assignment or function call and instead saw an expression". Disable.
'use strict';

var fs = require('fs');
var https = require('https');
var path = require('path');
var frisby = require('./../lib/icedfrisby');
var express = require('express');

var chai = require('chai');
var expect = chai.expect;

// The following tests were adapted from:
// https://github.com/visionmedia/supertest/blob/master/test/supertest.js

describe('IcedFrisby useApp(app)', function() {
    it('should start the http server on an ephemeral port', function() {
        var app = express();

        app.get('/', function(req, res) {
            res.send('^.^');
        });

        frisby.create(this.test.title)
            .useApp(app)
            .get('/')
            .expectStatus(200)
            .expectBodyContains('^.^')
            .after(function(err, res, body) {
                expect(err).to.not.exist;
            })
            .toss();
    });

    it('should work with an active http server', function() {
        var app = express();

        app.get('/', function(req, res) {
            res.send('^.^');
        });

        var server = app.listen(4000, function() {
            frisby.create(this.test.title)
                .useApp(app)
                .get('/')
                .expectStatus(200)
                .expectBodyContains('^.^')
                .toss();
        });
    });

    it('should start the https server on an ephemeral port', function() {
        // disable rejecting self signed certs for testing purposes
        // Attn Everyone: DO NOT USE THIS IN PRODUCTION
        process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

        var app = express();

        app.get('/', function(req, res) {
            res.send('^.^');
        });

        var fixtures = path.join(__dirname, '../', 'spec', 'fixtures');
        var server = https.createServer({
            key: fs.readFileSync(path.join(fixtures, 'test_key.pem')),
            cert: fs.readFileSync(path.join(fixtures, 'test_cert.pem'))
        }, app);

        frisby.create(this.test.title)
            .useApp(server)
            .get('/')
            .expectStatus(200)
            .expectBodyContains('^.^')
            .toss();
    });

    it('should work with an active https server', function() {
        // disable rejecting self signed certs for testing purposes
        // Attn Everyone: DO NOT USE THIS IN PRODUCTION
        process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

        var app = express();

        app.get('/', function(req, res) {
            res.send('^.^');
        });

        var fixtures = path.join(__dirname, '../', 'spec', 'fixtures');
        var server = https.createServer({
            key: fs.readFileSync(path.join(fixtures, 'test_key.pem')),
            cert: fs.readFileSync(path.join(fixtures, 'test_cert.pem'))
        }, app).listen();

        frisby.create(this.test.title)
            .useApp(server)
            .get('/')
            .expectStatus(200)
            .expectBodyContains('^.^')
            .toss();
    });

    it('should throw an exception if app is not defined', function() {
        var self = this;

        var fn = function() {
            frisby.create(self.test.title)
                .useApp(undefined)
                .toss();
        };

        expect(fn).to.throw('No app provided');
    });
});
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	errorHandler = require('./errors'),
	Plate = mongoose.model('Plate'),
	Customer = mongoose.model('Customer'),
	Organism = mongoose.model('Organism'),
	User = mongoose.model('User'),
	_ = require('lodash');

/**
 * Create a Plate
 */
exports.create = function(req, res) {
	var plate = new Plate(req.body);
	plate.user = req.user;

	plate.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(plate);
		}
	});
};

/**
 * Show the current Plate
 */
exports.read = function(req, res) {
	res.jsonp(req.plate);
};

/**
 * Update a Plate
 */
exports.update = function(req, res) {
	var plate = req.plate;

	plate = _.extend(plate, req.body);

	plate.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(plate);
		}
	});
};

/**
 * Delete an Plate
 */
exports.delete = function(req, res) {
	var plate = req.plate;

	plate.remove(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(plate);
		}
	});
};

/**
 * List of all plates
 */
exports.list = function(req, res) {
	Plate.find().lean().sort({stage: 1}).populate('user', 'displayName').populate('assignee', 'displayName').populate('project').exec(function(err, plates) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
				Customer.populate(plates, {path: 'project.customer'}, function(err, doc) {
				if (err) {
					return res.status(400).send({
						message: errorHandler.getErrorMessage(err)
					});
				} else {
					Organism.populate(doc, {path: 'project.organism'}, function(err, doc) {
						if (err) {
							return res.status(400).send({
								message: errorHandler.getErrorMessage(err)
							});
						} else {
							res.jsonp(doc);
						}
					});
				}
			});
		}
	});
};

/**
 * Assigns a specific plate to a user. If req.body.assignee is defined, the plate can be assigned
 * on behalf of a user given the request is done by an admin user.
 */
exports.assignPlate = function(req, res) {
	Plate.findOne({_id: req.body._id}).exec(function(err, plate) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		}
		if(req.body.isAssigned) {
			return res.status(409).send({
				message: 'Plate is already assigned'
			});
		}
		var assignee;
		// Allows an admin to assign a plate to a user
		if(req.body.assignee === null) {
			assignee = req.user._id;
		} else {
			assignee = req.body.assignee._id;
		}
		plate.assignee = assignee;
		plate.isAssigned = true;
		plate.save(function(err) {
			if (err) {
				return res.status(400).send({
					message: errorHandler.getErrorMessage(err)
				});
			} else {
				res.jsonp(plate);
			}
		});
	});
};

exports.unassignPlate = function(req, res) {
	Plate.findOne({_id: req.body._id}).exec(function(err, plate) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		}
		if(!req.body.isAssigned) {
			return res.status(409).send({
				message: 'Plate is already unassigned'
			});
		}
		plate.assignee = null;
		plate.isAssigned = false;
		plate.remove(function(err) {
			if (err) {
				return res.status(400).send({
					message: errorHandler.getErrorMessage(err)
				});
			} else {
				res.jsonp(plate);
			}
		});
	});
};

/**
 * List of a user's assigned plates
 */
exports.platesByUser = function(req, res) {
	var userId = req.user._id;

	Plate.find({assignee: userId}).populate('samples').populate('project').exec(function(err, doc) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			Customer.populate(doc, {path: 'project.customer'}, function(err, doc) {
				if (err) {
					return res.status(400).send({
						message: errorHandler.getErrorMessage(err)
					});
				} else {
					Organism.populate(doc, {path: 'project.organism'}, function(err, doc) {
						if (err) {
							return res.status(400).send({
								message: errorHandler.getErrorMessage(err)
							});
						} else {
							res.jsonp(doc);
						}
					});
				}
			});
		}
	});
};

/**
 * Plate middleware
 */
exports.plateByID = function(req, res, next, id) {
	Plate.findById(id).populate('user', 'displayName').exec(function(err, plate) {
		if (err) return next(err);
		if (!plate) return next(new Error('Failed to load Plate ' + id));
		req.plate = plate;
		next();
	});
};

/**
 * Plate authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
	User.findOne({_id: req.user.id}).exec(function(err, user) {
		if (err) {
			return next(err);
		} else if (req.body.isAssigned && req.body.assignee !== null && req.body.assignee._id !== req.user.id && user.roles !== 'admin') {
			return res.status(403).send('User is not authorized');
		}
		next();
	});
};
<commit_msg>Fixes bug where plate.assignee = assignee failes because plate is null because it was not found in the database<commit_after>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	errorHandler = require('./errors'),
	Plate = mongoose.model('Plate'),
	Customer = mongoose.model('Customer'),
	Organism = mongoose.model('Organism'),
	User = mongoose.model('User'),
	_ = require('lodash');

/**
 * Create a Plate
 */
exports.create = function(req, res) {
	var plate = new Plate(req.body);
	plate.user = req.user;

	plate.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(plate);
		}
	});
};

/**
 * Show the current Plate
 */
exports.read = function(req, res) {
	res.jsonp(req.plate);
};

/**
 * Update a Plate
 */
exports.update = function(req, res) {
	var plate = req.plate;

	plate = _.extend(plate, req.body);

	plate.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(plate);
		}
	});
};

/**
 * Delete an Plate
 */
exports.delete = function(req, res) {
	var plate = req.plate;

	plate.remove(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(plate);
		}
	});
};

/**
 * List of all plates
 */
exports.list = function(req, res) {
	Plate.find().lean().sort({stage: 1}).populate('user', 'displayName').populate('assignee', 'displayName').populate('project').exec(function(err, plates) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
				Customer.populate(plates, {path: 'project.customer'}, function(err, doc) {
				if (err) {
					return res.status(400).send({
						message: errorHandler.getErrorMessage(err)
					});
				} else {
					Organism.populate(doc, {path: 'project.organism'}, function(err, doc) {
						if (err) {
							return res.status(400).send({
								message: errorHandler.getErrorMessage(err)
							});
						} else {
							res.jsonp(doc);
						}
					});
				}
			});
		}
	});
};

/**
 * Assigns a specific plate to a user. If req.body.assignee is defined, the plate can be assigned
 * on behalf of a user given the request is done by an admin user.
 */
exports.assignPlate = function(req, res) {
	Plate.findOne({_id: req.body._id}).exec(function(err, plate) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else if (plate === null) {
			return res.status(404).send({
				message: 'Plate not found'
			});
		} else if(req.body.isAssigned) {
			return res.status(409).send({
				message: 'Plate is already assigned'
			});
		}
		var assignee;
		// Allows an admin to assign a plate to a user
		if(req.body.assignee === null) {
			assignee = req.user._id;
		} else {
			assignee = req.body.assignee._id;
		}
		plate.assignee = assignee;
		plate.isAssigned = true;
		plate.save(function(err) {
			if (err) {
				return res.status(400).send({
					message: errorHandler.getErrorMessage(err)
				});
			} else {
				res.jsonp(plate);
			}
		});
	});
};

exports.unassignPlate = function(req, res) {
	Plate.findOne({_id: req.body._id}).exec(function(err, plate) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		}
		if(!req.body.isAssigned) {
			return res.status(409).send({
				message: 'Plate is already unassigned'
			});
		}
		plate.assignee = null;
		plate.isAssigned = false;
		plate.remove(function(err) {
			if (err) {
				return res.status(400).send({
					message: errorHandler.getErrorMessage(err)
				});
			} else {
				res.jsonp(plate);
			}
		});
	});
};

/**
 * List of a user's assigned plates
 */
exports.platesByUser = function(req, res) {
	var userId = req.user._id;

	Plate.find({assignee: userId}).populate('samples').populate('project').exec(function(err, doc) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			Customer.populate(doc, {path: 'project.customer'}, function(err, doc) {
				if (err) {
					return res.status(400).send({
						message: errorHandler.getErrorMessage(err)
					});
				} else {
					Organism.populate(doc, {path: 'project.organism'}, function(err, doc) {
						if (err) {
							return res.status(400).send({
								message: errorHandler.getErrorMessage(err)
							});
						} else {
							res.jsonp(doc);
						}
					});
				}
			});
		}
	});
};

/**
 * Plate middleware
 */
exports.plateByID = function(req, res, next, id) {
	Plate.findById(id).populate('user', 'displayName').exec(function(err, plate) {
		if (err) return next(err);
		if (!plate) return next(new Error('Failed to load Plate ' + id));
		req.plate = plate;
		next();
	});
};

/**
 * Plate authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
	User.findOne({_id: req.user.id}).exec(function(err, user) {
		if (err) {
			return next(err);
		} else if (req.body.isAssigned && req.body.assignee !== null && req.body.assignee._id !== req.user.id && user.roles !== 'admin') {
			return res.status(403).send('User is not authorized');
		}
		next();
	});
};
<|endoftext|>


<commit_before>exports.run = (client, message) => {
  const config = require("../../settings.json");

  const embed = new client.methods.Embed()
     .setColor("#37FDFC")
     .setTimestamp()
     .setTitle("About Margarine")
     .setDescription(`I am a lovely and helpful bot (*Sometimes.*). Doing ${config.prefix}help is great for finding ways I can assist you. I was written in Komada, a Discord.js framework.\n
     \n**Name Origin:** Butterstroke#7150's typical nickname is Butter. As in the stuff that you put on toast. My name comes from the artificial butter *(Butterstroke#7150 tends to call it 'Fake Butter')* you can buy in stores called, Margarine.\n
     \n**Creation:** I was created on ${client.user.createdAt.toLocaleString()} by Butterstroke#7150. My current version is ${config.version} as of ${config.updateDate}.\n
     \n**More Info:** To find out more about what improvements ${config.version} is going to contain, please visit this link: https://github.com/Butterstroke/MargarineBot/projects/1. Any issues, complaints, improvements, or bugs should be reported using the report command!`)
     .setThumbnail(client.user.avatarURL);
  return message.channel.send({embed});
};

exports.conf = {
    enabled: true,
    runIn: ["text", "dm"],
    aliases: [],
    permLevel: 0,
    botPerms: [],
    requiredFuncs: [],
};

exports.help = {
    name: "about",
    description: "General information about Margarine.",
    usage: "",
};
<commit_msg>Update about.js<commit_after>exports.run = async (client, message) => {
  const config = require("../../settings.json");

  const embed = new client.methods.Embed()
     .setColor("#37FDFC")
     .setTimestamp()
     .setTitle("About Margarine")
     .setDescription(`I am a lovely and helpful bot (*Sometimes.*). Doing ${config.prefix}help is great for finding ways I can assist you. I was written in Komada, a Discord.js framework.\n
     \n**Name Origin:** Butterstroke#7150's typical nickname is Butter. As in the stuff that you put on toast. My name comes from the artificial butter *(Butterstroke#7150 tends to call it 'Fake Butter')* you can buy in stores called, Margarine.\n
     \n**Creation:** I was created on ${client.user.createdAt.toLocaleString()} by ${client.users.find("id", `${config.ownerID}`).tag}. My current version is ${config.version} as of ${config.updateDate}.\n
     \n**More Information:** I have a Github repo which contains my current update tracker and the source code if you are curious. https://github.com/Butterstroke/MargarineBot`)
     .setThumbnail(client.user.avatarURL());
  return message.channel.send({embed});
};

exports.conf = {
    enabled: true,
    runIn: ["text", "dm"],
    aliases: [],
    permLevel: 0,
    botPerms: [],
    requiredFuncs: [],
};

exports.help = {
    name: "about",
    description: "General information about Margarine.",
    usage: "",
};
<|endoftext|>


<commit_before>/**
 * Service for launching Contextual Help.
 */
angular.module('dataCollectorApp.common')
  .service('contextHelpService', function($rootScope, $q, configuration, api, pipelineConstant) {

    var helpIds = {};

    this.configInitPromise = $q.all([api.admin.getHelpRef(), configuration.init()]).then(function(results) {
      helpIds = results[0].data;
    });

    this.launchHelp = function(helpId) {
      this.configInitPromise.then(function() {
        var uiHelpBaseURL, helpURL,
          relativeURL = helpIds[helpId];

        if ($rootScope.$storage.helpLocation === pipelineConstant.ONLINE_HELP) {
          uiHelpBaseURL = configuration.getUIOnlineHelpBaseURL();
        } else {
          uiHelpBaseURL = configuration.getUILocalHelpBaseURL();
        }

        helpURL = uiHelpBaseURL + '/' + (relativeURL || 'index.html');
        window.open(helpURL);
      });
    };

    this.launchHelpContents = function() {
      this.configInitPromise.then(function() {
        var uiHelpBaseURL, helpURL;
        if ($rootScope.$storage.helpLocation === pipelineConstant.ONLINE_HELP) {
          uiHelpBaseURL = configuration.getUIOnlineHelpBaseURL();
        } else {
          uiHelpBaseURL = configuration.getUILocalHelpBaseURL();
        }

        helpURL = uiHelpBaseURL + '/index.html';
        window.open(helpURL);
      });
    };

  });<commit_msg>SDC-146 See if we can open help in the same tab instead of launching a new tab every time<commit_after>/**
 * Service for launching Contextual Help.
 */
angular.module('dataCollectorApp.common')
  .service('contextHelpService', function($rootScope, $q, configuration, api, pipelineConstant) {

    var helpIds = {},
      helpWindow;

    this.configInitPromise = $q.all([api.admin.getHelpRef(), configuration.init()]).then(function(results) {
      helpIds = results[0].data;
    });

    this.launchHelp = function(helpId) {
      this.configInitPromise.then(function() {
        var uiHelpBaseURL, helpURL,
          relativeURL = helpIds[helpId];

        if ($rootScope.$storage.helpLocation === pipelineConstant.ONLINE_HELP) {
          uiHelpBaseURL = configuration.getUIOnlineHelpBaseURL();
        } else {
          uiHelpBaseURL = configuration.getUILocalHelpBaseURL();
        }

        helpURL = uiHelpBaseURL + '/' + (relativeURL || 'index.html');

        if(typeof(helpWindow) == 'undefined' || helpWindow.closed) {
          helpWindow = window.open(helpURL);
        } else {
          helpWindow.location.href = helpURL;
          helpWindow.focus();
        }

      });
    };

    this.launchHelpContents = function() {
      this.configInitPromise.then(function() {
        var uiHelpBaseURL, helpURL;
        if ($rootScope.$storage.helpLocation === pipelineConstant.ONLINE_HELP) {
          uiHelpBaseURL = configuration.getUIOnlineHelpBaseURL();
        } else {
          uiHelpBaseURL = configuration.getUILocalHelpBaseURL();
        }

        helpURL = uiHelpBaseURL + '/index.html';

        if(typeof(helpWindow) == 'undefined' || helpWindow.closed) {
          helpWindow = window.open(helpURL);
        } else {
          helpWindow.location.href = helpURL;
          helpWindow.focus();
        }

      });
    };

  });<|endoftext|>


<commit_before>'use strict';

var InvoiceChecker = {
  isValid: function ic_isValid(invoiceNumber) {
    if (typeof invoiceNumber !== 'string')
      invoiceNumber = invoiceNumber.toString(10);

    if (invoiceNumber.length !== 8)
      return false;

    if (/^\d/.test(invoiceNumber))
      return false;

    var cX = [1, 2, 1, 2, 1, 2, 4, 1];
    var cN = invoiceNumber.split('').map(function(n) {
      return parseInt(n, 10);
    });

    var sum = 0;
    cN.forEach(function(n, i) {
      var s = n * cX[i];
      if (s > 9) {
        s = Math.floor(s / 10) + (s % 10);
      }
      sum += s;
    });

    if ((sum % 10) === 0) {
      return true;
    }

    if (cN[6] === 7 && (sum % 10) === 1) {
      return true;
    }

    return false;
  }
};
<commit_msg>Remove extra file<commit_after><|endoftext|>


<commit_before>/**
 * Shopware 4
 * Copyright © shopware AG
 *
 * According to our dual licensing model, this program can be used either
 * under the terms of the GNU Affero General Public License, version 3,
 * or under a proprietary license.
 *
 * The texts of the GNU Affero General Public License with an additional
 * permission and of our proprietary license can be found at and
 * in the LICENSE file you have received along with this program.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * "Shopware" is a registered trademark of shopware AG.
 * The licensing of the program under the AGPLv3 does not imply a
 * trademark license. Therefore any rights, title and interest in
 * our trademarks remain entirely with us.
 */
/**
 * Shopware SwagBepado Plugin
 *
 * @category Shopware
 * @package Shopware\Plugins\SwagBepado
 * @copyright Copyright (c) shopware AG (http://www.shopware.de)
 */
//{namespace name=backend/bepado/view/main}
//{block name="backend/bepado/view/config/general/form"}
Ext.define('Shopware.apps.Bepado.view.config.general.Form', {
    extend: 'Ext.form.Panel',
    alias: 'widget.bepado-config-form',

    border: false,
    layout: 'anchor',
    autoScroll: true,

    /**
     * Contains the field set defaults.
     */
    defaults: {
        labelWidth: 170,
        anchor: '100%'
    },

    snippets: {
        apiKeyHeader: '{s name=config/api_key}API-Key{/s}',
        apiKeyDescription: '{s name=config/api_key_description}{/s}',
        apiKeyCheck: '{s name=config/api_key_check}Überprüfen{/s}',
        save: '{s name=config/save}Speichern{/s}',
        cancel: '{s name=config/cancel}Zurücksetzen{/s}',
        cloudSearchLabel: '{s name=config/cloud_search_label}Cloud-Search aktivieren{/s}',
        detailPageHintLabel: '{s name=config/details_page_hint}Auf der Detailseite auf Marktplatz-Artikel hinweisen{/s}',
        noIndexLabel: '{s name=config/noindex_label}Ein "noindex"-Meta-Tag bei Bepado-Produkten setzen{/s}',
        basketHintLabel: '{s name=config/basket_hint_label}Im Warenkorb auf Marktplatz Artikel hinweisen{/s}',
        bepadoAttributeLabel: '{s name=config/bepado_attribute_label}bepado Attribut{/s}',
        alternativeHostLabel: '{s name=config/bepado_alternative_host}Alternativer bepado Host (nur für Testzwecke){/s}',
        logLabel: '{s name=config/log_label}Anfragen des bepado-Servers mitschreiben{/s}'
    },

    initComponent: function() {
        var me = this;

        me.items = me.createElements(me.defaultShop);
        me.dockedItems = [{
                xtype: 'toolbar',
                dock: 'bottom',
                ui: 'shopware-ui',
                cls: 'shopware-toolbar',
                items: me.getFormButtons()
            }];

        me.generalConfigStore = Ext.create('Shopware.apps.Bepado.store.config.General');
        me.generalConfigStore.load();
        me.generalConfigStore.on('load', function() {
            me.populateForm();
        });

        me.callParent(arguments);
    },

    /**
     * Creates form elements
     * @param isDefaultShop
     * @return Array
     */
    createElements: function(isDefaultShop) {
        var me = this,
            apiFieldset = me.getApiKeyFieldset(),
            configFieldset = me.getConfigFieldset(),
            elements = [];

        if (isDefaultShop) {
            elements.push(apiFieldset);
        }
        elements.push(configFieldset);

        return elements;
    },

    /**
     * Returns form buttons, save and cancel
     * @returns Array
     */
    getFormButtons: function() {
        var me = this,
            buttons = ['->'];

        var saveButton = Ext.create('Ext.button.Button', {
            text: me.snippets.save,
            action:'save-config',
            cls:'primary'
        });

        var cancelButton = Ext.create('Ext.button.Button', {
            text: me.snippets.cancel,
            handler: function(btn) {
                btn.up('window').close();
            }
        });

        buttons.push(cancelButton);
        buttons.push(saveButton);

        return buttons;
    },

    /**
     * Returns API key field set
     *
     * @return Ext.form.FieldSet
     */
    getApiKeyFieldset: function() {
        var me = this;

        var apiFieldset = Ext.create('Ext.form.FieldSet', {
            columnWidth: 1,
            title: me.snippets.apiKeyHeader,
            defaultType: 'textfield',
            layout: 'anchor',
            items :[
                {
                    xtype: 'container',
                    html: me.snippets.apiKeyDescription
                }, {
                    fieldLabel: me.snippets.apiKeyHeader,
                    labelWidth: 200,
                    name: 'apiKey'
                }, {
                    xtype: 'button',
                    text: me.snippets.apiKeyCheck,
                    handler: function(btn) {
                        var apiField = btn.up('form').down('textfield[name=apiKey]'),
                            apiKey = apiField.getValue();
                        Ext.Ajax.request({
                            scope: this,
                            url: window.location.pathname + 'bepado/verifyApiKey',
                            success: function(result, request) {
                                var response = Ext.JSON.decode(result.responseText);
                                Ext.get(apiField.inputEl).setStyle('background-color', response.success ? '#C7F5AA' : '#FFB0AD');
                                if(response.message) {
                                    Shopware.Notification.createGrowlMessage(
                                        btn.title,
                                        response.message
                                    );
                                }
                            },
                            failure: function() { },
                            params: { apiKey: apiKey }
                        });
                    }
                }
            ]
        });

        return apiFieldset;
    },

    /**
     * Creates the field set which displayed
     * @return Ext.form.FieldSet
     */
    getConfigFieldset: function() {
        var me = this;

        var fieldset = Ext.create('Ext.form.FieldSet', {
            layout: 'column',
            border: false,
            defaults: {
                labelWidth: 170,
                anchor: '100%'
            },
            items: [
                me.createLeftElements(),
                me.createRightElements(),
                me.createBottomElements()
            ]
        });

        return fieldset;
    },

    /**
     * Creates the field set items which are displayed in the left column
     * @return Ext.container.Container
     */
    createLeftElements: function () {
        var me = this;

        var leftContainer = Ext.create('Ext.container.Container', {
            columnWidth: 0.5,
            padding: '0 20 0 0',
            layout: 'anchor',
            border: false,
            items: [
                {
                    xtype: 'checkbox',
                    name: 'cloudSearch',
                    fieldLabel: me.snippets.cloudSearchLabel,
                    inputValue: 1,
                    uncheckedValue: 0,
                    labelWidth: me.defaults.labelWidth
                }, {
                    xtype: 'checkbox',
                    name: 'detailShopInfo',
                    fieldLabel: me.snippets.detailPageHintLabel,
                    inputValue: 1,
                    uncheckedValue: 0,
                    labelWidth: me.defaults.labelWidth
                }
            ]
        });

        return leftContainer;
    },

    /**
     * Creates the field set items which are displayed in the right column
     * @return Ext.container.Container
     */
    createRightElements: function () {
        var me = this;

        var rightContainer = Ext.create('Ext.container.Container', {
            columnWidth: 0.5,
            layout: 'anchor',
            border: false,
            items: [
                {
                    xtype: 'checkbox',
                    name: 'detailProductNoIndex',
                    fieldLabel: me.snippets.noIndexLabel,
                    inputValue: 1,
                    uncheckedValue: 0,
                    labelWidth: me.defaults.labelWidth
                }, {
                    xtype: 'checkbox',
                    name: 'checkoutShopInfo',
                    fieldLabel: me.snippets.basketHintLabel,
                    inputValue: 1,
                    uncheckedValue: 0,
                    labelWidth: me.defaults.labelWidth
                }
            ]
        });

        return rightContainer;
    },

    /**
     * Creates the field set items which are displayed in the bottom
     * @return Ext.container.Container
     */
    createBottomElements: function() {
        var me = this;

        var attributeStore = new Ext.data.ArrayStore({
            fields: ['id', 'name'],
            data : [
                [1, 'attr1'],
                [2, 'attr2'],
                [3, 'attr3'],
                [4, 'attr4'],
                [5, 'attr5'],
                [6, 'attr6'],
                [7, 'attr7'],
                [8, 'attr8'],
                [9, 'attr9'],
                [10, 'attr10'],
                [11, 'attr11'],
                [12, 'attr12'],
                [13, 'attr13'],
                [14, 'attr14'],
                [15, 'attr15'],
                [16, 'attr16'],
                [17, 'attr17'],
                [18, 'attr18'],
                [19, 'attr19'],
                [20, 'attr20']
            ]
        });

        var bottomContainer = Ext.create('Ext.container.Container', {
            columnWidth: 1,
            layout: 'anchor',
            border: false,
            items: [
                {
                    xtype: 'combo',
                    name: 'bepadoAttribute',
                    required: true,
                    editable: false,
                    valueField: 'id',
                    displayField: 'name',
                    value: 19,
                    fieldLabel: me.snippets.bepadoAttributeLabel,
                    store: attributeStore,
                    labelWidth: me.defaults.labelWidth
                }, {
                    xtype: 'textfield',
                    name: 'bepadoDebugHost',
                    fieldLabel: me.snippets.alternativeHostLabel
                }, {
                    xtype: 'checkbox',
                    name: 'logRequest',
                    fieldLabel: me.snippets.logLabel,
                    inputValue: 1,
                    uncheckedValue: 0,
                    labelWidth: me.defaults.labelWidth
                }
            ]
        });

        return bottomContainer;
    },

    /**
     * Find general config record by id
     * and load into form
     */
    populateForm: function() {
        var me = this,
            record = me.generalConfigStore.getById(me.shopId);

        me.loadRecord(record);
    }
});
//{/block}
<commit_msg>BEP-569 Change general form for subshops<commit_after>/**
 * Shopware 4
 * Copyright © shopware AG
 *
 * According to our dual licensing model, this program can be used either
 * under the terms of the GNU Affero General Public License, version 3,
 * or under a proprietary license.
 *
 * The texts of the GNU Affero General Public License with an additional
 * permission and of our proprietary license can be found at and
 * in the LICENSE file you have received along with this program.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * "Shopware" is a registered trademark of shopware AG.
 * The licensing of the program under the AGPLv3 does not imply a
 * trademark license. Therefore any rights, title and interest in
 * our trademarks remain entirely with us.
 */
/**
 * Shopware SwagBepado Plugin
 *
 * @category Shopware
 * @package Shopware\Plugins\SwagBepado
 * @copyright Copyright (c) shopware AG (http://www.shopware.de)
 */
//{namespace name=backend/bepado/view/main}
//{block name="backend/bepado/view/config/general/form"}
Ext.define('Shopware.apps.Bepado.view.config.general.Form', {
    extend: 'Ext.form.Panel',
    alias: 'widget.bepado-config-form',

    border: false,
    layout: 'anchor',
    autoScroll: true,

    /**
     * Contains the field set defaults.
     */
    defaults: {
        labelWidth: 170,
        anchor: '100%'
    },

    snippets: {
        apiKeyHeader: '{s name=config/api_key}API-Key{/s}',
        apiKeyDescription: '{s name=config/api_key_description}{/s}',
        apiKeyCheck: '{s name=config/api_key_check}Überprüfen{/s}',
        save: '{s name=config/save}Speichern{/s}',
        cancel: '{s name=config/cancel}Zurücksetzen{/s}',
        cloudSearchLabel: '{s name=config/cloud_search_label}Cloud-Search aktivieren{/s}',
        detailPageHintLabel: '{s name=config/details_page_hint}Auf der Detailseite auf Marktplatz-Artikel hinweisen{/s}',
        noIndexLabel: '{s name=config/noindex_label}Ein "noindex"-Meta-Tag bei Bepado-Produkten setzen{/s}',
        basketHintLabel: '{s name=config/basket_hint_label}Im Warenkorb auf Marktplatz Artikel hinweisen{/s}',
        bepadoAttributeLabel: '{s name=config/bepado_attribute_label}bepado Attribut{/s}',
        alternativeHostLabel: '{s name=config/bepado_alternative_host}Alternativer bepado Host (nur für Testzwecke){/s}',
        logLabel: '{s name=config/log_label}Anfragen des bepado-Servers mitschreiben{/s}'
    },

    initComponent: function() {
        var me = this;

        me.items = me.createElements();
        me.dockedItems = [{
                xtype: 'toolbar',
                dock: 'bottom',
                ui: 'shopware-ui',
                cls: 'shopware-toolbar',
                items: me.getFormButtons()
            }];

        me.generalConfigStore = Ext.create('Shopware.apps.Bepado.store.config.General');
        me.generalConfigStore.load();
        me.generalConfigStore.on('load', function() {
            me.populateForm();
        });

        me.callParent(arguments);
    },

    /**
     * Creates form elements
     * @param isDefaultShop
     * @return Array
     */
    createElements: function() {
        var me = this,
            apiFieldset = me.getApiKeyFieldset(),
            configFieldset = me.getConfigFieldset(),
            elements = [];

        if (me.defaultShop) {
            elements.push(apiFieldset);
        }
        elements.push(configFieldset);

        return elements;
    },

    /**
     * Returns form buttons, save and cancel
     * @returns Array
     */
    getFormButtons: function() {
        var me = this,
            buttons = ['->'];

        var saveButton = Ext.create('Ext.button.Button', {
            text: me.snippets.save,
            action:'save-config',
            cls:'primary'
        });

        var cancelButton = Ext.create('Ext.button.Button', {
            text: me.snippets.cancel,
            handler: function(btn) {
                btn.up('window').close();
            }
        });

        buttons.push(cancelButton);
        buttons.push(saveButton);

        return buttons;
    },

    /**
     * Returns API key field set
     *
     * @return Ext.form.FieldSet
     */
    getApiKeyFieldset: function() {
        var me = this;

        var apiFieldset = Ext.create('Ext.form.FieldSet', {
            columnWidth: 1,
            title: me.snippets.apiKeyHeader,
            defaultType: 'textfield',
            layout: 'anchor',
            items :[
                {
                    xtype: 'container',
                    html: me.snippets.apiKeyDescription
                }, {
                    fieldLabel: me.snippets.apiKeyHeader,
                    labelWidth: 200,
                    name: 'apiKey'
                }, {
                    xtype: 'button',
                    text: me.snippets.apiKeyCheck,
                    handler: function(btn) {
                        var apiField = btn.up('form').down('textfield[name=apiKey]'),
                            apiKey = apiField.getValue();
                        Ext.Ajax.request({
                            scope: this,
                            url: window.location.pathname + 'bepado/verifyApiKey',
                            success: function(result, request) {
                                var response = Ext.JSON.decode(result.responseText);
                                Ext.get(apiField.inputEl).setStyle('background-color', response.success ? '#C7F5AA' : '#FFB0AD');
                                if(response.message) {
                                    Shopware.Notification.createGrowlMessage(
                                        btn.title,
                                        response.message
                                    );
                                }
                            },
                            failure: function() { },
                            params: { apiKey: apiKey }
                        });
                    }
                }
            ]
        });

        return apiFieldset;
    },

    /**
     * Creates the field set which displayed
     * @return Ext.form.FieldSet
     */
    getConfigFieldset: function() {
        var me = this,
            items = [],
            leftElements = me.createLeftElements(),
            rightElements = me.createRightElements();

        items.push(leftElements);
        items.push(rightElements);

        if (me.defaultShop) {
            var bottomElements = me.createBottomElements();
            items.push(bottomElements);
        }

        var fieldset = Ext.create('Ext.form.FieldSet', {
            layout: 'column',
            border: false,
            defaults: {
                labelWidth: 170,
                anchor: '100%'
            },
            items: items
        });

        return fieldset;
    },

    /**
     * Creates the field set items which are displayed in the left column
     * @return Ext.container.Container
     */
    createLeftElements: function () {
        var me = this;

        var leftContainer = Ext.create('Ext.container.Container', {
            columnWidth: 0.5,
            padding: '0 20 0 0',
            layout: 'anchor',
            border: false,
            items: [
                {
                    xtype: 'checkbox',
                    name: 'cloudSearch',
                    fieldLabel: me.snippets.cloudSearchLabel,
                    inputValue: 1,
                    uncheckedValue: 0,
                    labelWidth: me.defaults.labelWidth
                }, {
                    xtype: 'checkbox',
                    name: 'detailShopInfo',
                    fieldLabel: me.snippets.detailPageHintLabel,
                    inputValue: 1,
                    uncheckedValue: 0,
                    labelWidth: me.defaults.labelWidth
                }
            ]
        });

        return leftContainer;
    },

    /**
     * Creates the field set items which are displayed in the right column
     * @return Ext.container.Container
     */
    createRightElements: function () {
        var me = this;

        var rightContainer = Ext.create('Ext.container.Container', {
            columnWidth: 0.5,
            layout: 'anchor',
            border: false,
            items: [
                {
                    xtype: 'checkbox',
                    name: 'detailProductNoIndex',
                    fieldLabel: me.snippets.noIndexLabel,
                    inputValue: 1,
                    uncheckedValue: 0,
                    labelWidth: me.defaults.labelWidth
                }, {
                    xtype: 'checkbox',
                    name: 'checkoutShopInfo',
                    fieldLabel: me.snippets.basketHintLabel,
                    inputValue: 1,
                    uncheckedValue: 0,
                    labelWidth: me.defaults.labelWidth
                }
            ]
        });

        return rightContainer;
    },

    /**
     * Creates the field set items which are displayed in the bottom
     * @return Ext.container.Container
     */
    createBottomElements: function() {
        var me = this;

        var attributeStore = new Ext.data.ArrayStore({
            fields: ['id', 'name'],
            data : [
                [1, 'attr1'],
                [2, 'attr2'],
                [3, 'attr3'],
                [4, 'attr4'],
                [5, 'attr5'],
                [6, 'attr6'],
                [7, 'attr7'],
                [8, 'attr8'],
                [9, 'attr9'],
                [10, 'attr10'],
                [11, 'attr11'],
                [12, 'attr12'],
                [13, 'attr13'],
                [14, 'attr14'],
                [15, 'attr15'],
                [16, 'attr16'],
                [17, 'attr17'],
                [18, 'attr18'],
                [19, 'attr19'],
                [20, 'attr20']
            ]
        });

        var bottomContainer = Ext.create('Ext.container.Container', {
            columnWidth: 1,
            layout: 'anchor',
            border: false,
            items: [
                {
                    xtype: 'combo',
                    name: 'bepadoAttribute',
                    required: true,
                    editable: false,
                    valueField: 'id',
                    displayField: 'name',
                    value: 19,
                    fieldLabel: me.snippets.bepadoAttributeLabel,
                    store: attributeStore,
                    labelWidth: me.defaults.labelWidth
                }, {
                    xtype: 'textfield',
                    name: 'bepadoDebugHost',
                    fieldLabel: me.snippets.alternativeHostLabel
                }, {
                    xtype: 'checkbox',
                    name: 'logRequest',
                    fieldLabel: me.snippets.logLabel,
                    inputValue: 1,
                    uncheckedValue: 0,
                    labelWidth: me.defaults.labelWidth
                }
            ]
        });

        return bottomContainer;
    },

    /**
     * Find general config record by id
     * and load into form
     */
    populateForm: function() {
        var me = this,
            record = me.generalConfigStore.getById(me.shopId);

        me.loadRecord(record);
    }
});
//{/block}
<|endoftext|>


<commit_before>import * as _commands from './commands';
import { addProxyEnv, normalizeUrl } from './utils';
import { updateProxyForLoadBalancing } from './command-handlers';
import validator from './validate';

export const description = 'Setup and manage reverse proxy and ssl';

export const commands = _commands;

export const validate = {
  proxy: validator
};

// eslint-disable-next-line complexity
export function prepareConfig(config) {
  if (!config.app || !config.proxy) {
    return config;
  }

  const swarmEnabled = config.swarm && config.swarm.enabled;

  config.app.env = config.app.env || {};
  config.app.docker = config.app.docker || {};
  config.app.env = addProxyEnv(config, config.app.env);

  if (config.app.servers && config.proxy.loadBalancing) {
    Object.keys(config.app.servers).forEach(key => {
      const privateIp = config.servers[key].privateIp;
      if (privateIp) {
        config.app.servers[key].bind = privateIp;
      }
    });
  }

  if (!swarmEnabled) {
    config.app.env.VIRTUAL_PORT = config.app.docker.imagePort || 3000;
  }

  config.app.env.HTTP_FORWARDED_COUNT =
  config.app.env.HTTP_FORWARDED_COUNT || 1;

  if (swarmEnabled) {
    config.app.docker.networks = config.app.docker.networks || [];
    config.app.docker.networks.push('mup-proxy');
  }

  config.app.env.ROOT_URL = normalizeUrl(config, config.app.env);

  return config;
}

// eslint-disable-next-line complexity
export function scrubConfig(config) {
  if (config.app && config.app.env && config.app.env.LETSENCRYPT_EMAIL) {
    config.app.env.LETSENCRYPT_EMAIL = 'email@domain.com';
  }

  if (config.proxy && config.proxy.ssl && config.proxy.ssl.letsEncryptEmail) {
    config.proxy.ssl.letsEncryptEmail = 'email@domain.com';
  }

  return config;
}

// This hook runs when setting up the proxy or running mup reconfig
// This creates a small container for the proxy to know about the service
function configureServiceHook(api) {
  const config = api.getConfig();

  if (config.proxy && (api.swarmEnabled() || config.proxy.loadBalancing)) {
    return updateProxyForLoadBalancing(api);
  }
}

export const hooks = {
  'post.default.status'(api) {
    if (api.getConfig().proxy) {
      api.runCommand('proxy.status');
    }
  },
  'post.setup'(api) {
    if (api.getConfig().proxy) {
      return api.runCommand('proxy.setup');
    }
  },
  'post.reconfig': configureServiceHook,
  'post.proxy.setup': configureServiceHook
};

export function swarmOptions(config) {
  if (config && config.proxy) {
    return {
      managers: Object.keys(config.proxy.servers)
    };
  }
}
<commit_msg>Scrub proxy domains<commit_after>import * as _commands from './commands';
import { addProxyEnv, normalizeUrl } from './utils';
import { updateProxyForLoadBalancing } from './command-handlers';
import validator from './validate';

export const description = 'Setup and manage reverse proxy and ssl';

export const commands = _commands;

export const validate = {
  proxy: validator
};

// eslint-disable-next-line complexity
export function prepareConfig(config) {
  if (!config.app || !config.proxy) {
    return config;
  }

  const swarmEnabled = config.swarm && config.swarm.enabled;

  config.app.env = config.app.env || {};
  config.app.docker = config.app.docker || {};
  config.app.env = addProxyEnv(config, config.app.env);

  if (config.app.servers && config.proxy.loadBalancing) {
    Object.keys(config.app.servers).forEach(key => {
      const privateIp = config.servers[key].privateIp;
      if (privateIp) {
        config.app.servers[key].bind = privateIp;
      }
    });
  }

  if (!swarmEnabled) {
    config.app.env.VIRTUAL_PORT = config.app.docker.imagePort || 3000;
  }

  config.app.env.HTTP_FORWARDED_COUNT =
  config.app.env.HTTP_FORWARDED_COUNT || 1;

  if (swarmEnabled) {
    config.app.docker.networks = config.app.docker.networks || [];
    config.app.docker.networks.push('mup-proxy');
  }

  config.app.env.ROOT_URL = normalizeUrl(config, config.app.env);

  return config;
}

// eslint-disable-next-line complexity
export function scrubConfig(config, { scrubUrl }) {
  if (!config.proxy) {
    return config;
  }

  function scrubDomains(domains) {
    return domains.split(',').map(domain =>
      // We temporarily add a protocol so it can be parsed as a url
      scrubUrl(`http://${domain.trim()}`).slice(7)
    ).join(',');
  }

  if (config.app && config.app.env) {
    const {
      LETSENCRYPT_EMAIL,
      VIRTUAL_HOST,
      LETSENCRYPT_HOST
    } = config.app.env;

    if (LETSENCRYPT_EMAIL) {
      config.app.env.LETSENCRYPT_EMAIL = 'email@domain.com';
    }
    if (LETSENCRYPT_HOST) {
      config.app.env.LETSENCRYPT_HOST = scrubDomains(LETSENCRYPT_HOST);
    }
    if (VIRTUAL_HOST) {
      config.app.env.VIRTUAL_HOST = scrubDomains(VIRTUAL_HOST);
    }
  }

  if (config.proxy) {
    const {
      shared,
      ssl,
      domains
    } = config.proxy;

    if (ssl && ssl.letsEncryptEmail) {
      config.proxy.ssl.letsEncryptEmail = 'email@domain.com';
    }
    if (domains) {
      config.proxy.domains = scrubDomains(domains);
    }

    if (shared && shared.env && shared.env.DEFAULT_HOST) {
      shared.env.DEFAULT_HOST = scrubDomains(shared.env.DEFAULT_HOST);
    }
  }

  return config;
}

// This hook runs when setting up the proxy or running mup reconfig
// This creates a small container for the proxy to know about the service
function configureServiceHook(api) {
  const config = api.getConfig();

  if (config.proxy && (api.swarmEnabled() || config.proxy.loadBalancing)) {
    return updateProxyForLoadBalancing(api);
  }
}

export const hooks = {
  'post.default.status'(api) {
    if (api.getConfig().proxy) {
      api.runCommand('proxy.status');
    }
  },
  'post.setup'(api) {
    if (api.getConfig().proxy) {
      return api.runCommand('proxy.setup');
    }
  },
  'post.reconfig': configureServiceHook,
  'post.proxy.setup': configureServiceHook
};

export function swarmOptions(config) {
  if (config && config.proxy) {
    return {
      managers: Object.keys(config.proxy.servers)
    };
  }
}
<|endoftext|>


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

var fs = require('fs');
var path = require('path');
var http2 = require('..');
var http = require("http");

// Passing bunyan logger to http2
http2.globalAgent = new http2.Agent({
  log: require('../test/util').createLogger('client')
});

process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

// Creating an HTTP1.1 server to listen for incoming requests from Awazza
var server = http.createServer(function(request, response) {
  console.log("Received request: "+request.url+" "+JSON.stringify(request.headers));

  // Determine upstream server from requested URL
  var poptions = require('url').parse(request.url);

  // Always send request via HTTP2 over TLS
  poptions.protocol = "https:"
  poptions.port = 443
  poptions.headers = http2.convertHeadersToH2(request.headers)
  poptions.host = poptions.hostname = request.headers['host']

//  console.log("Sending request: "+JSON.stringify(poptions));
  var prequest = http2.request(poptions);
  function onErr(err) {
        console.log('PRequest error: '+err);
        response.writeHead('404');
        response.end();
  };
  prequest.on('error', onErr);

  // Receiving the response from upstream server
  prequest.on('response', function(presponse) {
        presponse.on('error', function(err) {
          console.log('PResponse Error: '+err);
          response.writeHead('404');
          response.end();
        });
	console.log("Received response: "+presponse.statusCode+" "+JSON.stringify(presponse.headers))
        response.writeHead(presponse.statusCode, '', http2.convertHeadersFromH2(presponse.headers))
	if (presponse.statusCode >= 400) {
		response.end();
	} else {
		// Pipe response to Awazza
        	presponse.pipe(response);
	}
  });

  prequest.end();
});

/*server.on('error', function(err) {
  console.log('Server error: '+err);
});*/

server.listen(process.env.HTTP2_PORT || 2345);

<commit_msg>added timeout to post-awa<commit_after>#!/usr/bin/env node

var fs = require('fs');
var path = require('path');
var http2 = require('..');
var http = require("http");

// Passing bunyan logger to http2
http2.globalAgent = new http2.Agent({
  log: require('../test/util').createLogger('client')
});

process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

// Creating an HTTP1.1 server to listen for incoming requests from Awazza
var server = http.createServer(function(request, response) {
  console.log("Received request: "+request.url+" "+JSON.stringify(request.headers));

  // Determine upstream server from requested URL
  var poptions = require('url').parse(request.url);

  // Always send request via HTTP2 over TLS
  poptions.protocol = "https:"
  poptions.port = 443
  poptions.headers = http2.convertHeadersToH2(request.headers)
  poptions.host = poptions.hostname = request.headers['host']

//  console.log("Sending request: "+JSON.stringify(poptions));
  var prequest = http2.request(poptions);
  function onErr(err) {
        console.log('PRequest error: '+err);
        response.writeHead('404');
        response.end();
  };
  prequest.on('error', onErr);

  prequest.setTimeout(5, function () {
    console.log('PRequest timed out');
    prequest.abort()
    response.writeHead(504)
    response.end()
  })

  // Receiving the response from upstream server
  prequest.on('response', function(presponse) {
        presponse.on('error', function(err) {
          console.log('PResponse Error: '+err);
          response.writeHead('404');
          response.end();
        });
	console.log("Received response: "+presponse.statusCode+" "+JSON.stringify(presponse.headers))
        response.writeHead(presponse.statusCode, '', http2.convertHeadersFromH2(presponse.headers))
	if (presponse.statusCode >= 400) {
		response.end();
	} else {
		// Pipe response to Awazza
        	presponse.pipe(response);
	}
  });

  prequest.end();
});

/*server.on('error', function(err) {
  console.log('Server error: '+err);
});*/

server.listen(process.env.HTTP2_PORT || 2345);

<|endoftext|>


<commit_before>'use strict';

var ngConstant = require('../index');
var _ = require('lodash');
var gutil = require('gulp-util');
var through = require('through2');

// TODO: add custom matcher to test the modules name expect(output).toHaveModule('ngConstants') that uses regexp
// TODO: consider adding a toString() property to the vinyl file (e.g. file.text)

describe('ngConstant', function () {

    describe('name', function () {
        it ('uses the streamed file name by default', function (done) {
            getStream({path: 'myConstantsFile.json'})
            .pipe(ngConstant())
            .on('data', function (file) {
                expect(file.contents.toString()).toContain('module("myConstantsFile"');
                done();
            });
        });

        it ('creates a modules with "ngConstants" name by default for new streams', function (done) {
            evalNgConstant({name: undefined, stream: true}, function (_, output) {
                expect(output).toContain('module("ngConstants"');
                done();
            });
        });

        it ('creates a module with the given name', function (done) {
            evalNgConstant({name: 'myConstantsModule'}, function (_, output) {
                expect(output).toContain('module("myConstantsModule"');
                done();
            });
        });
    });

    describe('deps', function () {
        it ('creates a new modules by default', function (done) {
            evalNgConstant({name: 'defaultDeps', deps: undefined}, function (_, output) {
                expect(output).toContain('module("defaultDeps", [])');
                done();
            });
        });

        it ('adds the given dependencies', function (done) {
            evalNgConstant({name: 'withDeps', deps: ['ngAnimate']}, function (_, output) {
                expect(output).toContain('module("withDeps", ["ngAnimate"])');
                done();
            });
        });

        it ('adds constants to an existing module when set to `false`', function (done) {
            evalNgConstant({name: 'noDeps', deps: false}, function (_, output) {
               expect(output).toContain('module("noDeps")');
                done();
            });
        });
    });

    describe('stream', function () {
        it ('returns an empty open stream when set to `false`', function () {
            var plugin = ngConstant({stream: false});
            expect(plugin._readableState.ended).toBe(false);
            expect(plugin._readableState.length).toBe(0);
        });

        it ('returns a closed stream with a file when set to `true`', function () {
            var stream = ngConstant({stream: true});
            expect(stream._readableState.ended).toBe(true);
            expect(stream._readableState.length).toBe(1);
        });
    });
});

describe('ngConstant.getConstants', function () {
    it('returns an array with the constants key and json string value', function () {
        var data = { constants: { hello: { foo: 'bar' } } };
        var result = ngConstant.getConstants(data);
        expect(result[0]).toEqual({name: 'hello', value: '{"foo":"bar"}'});
    });

    it('extends the data.constants with the options.constants', function () {
        var data = { constants: { hello: 'andrew' } };
        var opts = { constants: { hello: 'world' } };
        var result = ngConstant.getConstants(data, opts);
        expect(result[0]).toEqual({ name: 'hello', value: '"world"' });
    });

    it('uses the data object if data.constants is not available', function () {
        var data = { hello: 'andrew' };
        var result = ngConstant.getConstants(data);
        expect(result[0]).toEqual({ name: 'hello', value: '"andrew"' });
    });

    it('accepts a JSON string as constants from the options', function () {
        var opts = { constants: JSON.stringify({ hello: 'world' }) };
        var result = ngConstant.getConstants({}, opts);
        expect(result[0]).toEqual({ name: 'hello', value: '"world"' });
    });

    it('stringifies the value with the given option.space', function () {
        var data = { constants: { hello: { foo: 'bar' } } };
        var result = ngConstant.getConstants(data, { space: '' });
        expect(result[0].value).toEqual('{"foo":"bar"}');
        result = ngConstant.getConstants(data, { space: ' ' });
        expect(result[0].value).toEqual('{\n "foo": "bar"\n}');
    });
});

describe('ngConstant.getFilePath', function() {
    it('returns the file path from the src plugin when option dest is undefined', function() {
        expect(ngConstant.getFilePath('/foo/bar/config.json', {})).toBe('/foo/bar/config.js');
    });

    it('returns the file path defined by the dest option', function() {
        expect(ngConstant.getFilePath('/foo/bar/foo.js', { dest: 'foo.js' })).toBe('/foo/bar/foo.js');
    });
});

function getStream(fileOptions) {
    var defaults = {path: 'constants.json'};
    var file = new gutil.File(_.merge(defaults, fileOptions));
    var stream = through.obj(gutil.noop());
    stream.end(file);
    return stream;
}

function evalNgConstant(options, callback) {
    var defaults = {stream: true, constants: {greeting: 'hello' }};
    ngConstant(_.merge(defaults, options)).on('data', function (file) {
        callback(file, file.contents.toString());
    });
}
<commit_msg>chore(tests): add tests for loading YAML and JSON<commit_after>'use strict';

var ngConstant = require('../index');
var _ = require('lodash');
var gutil = require('gulp-util');
var through = require('through2');

// TODO: add custom matcher to test the modules name expect(output).toHaveModule('ngConstants') that uses regexp
// TODO: consider adding a toString() property to the vinyl file (e.g. file.text)

describe('ngConstant', function () {

    describe('file stream', function () {
        it('load the constants from a YAML file', function (done) {
            var contents = 'message: happy yaml';
            getStream({path: 'constants.yml', contents: new Buffer(contents)})
            .pipe(ngConstant())
            .on('data', function (file) {
                expect(file.contents.toString()).toContain('constant("message", "happy yaml")');
                done();
            });
        });

        it ('loads the constants from a JSON file', function (done) {
            var contents = '{ "message": "valid JSON" }';
            getStream({path: 'constants.json', contents: new Buffer(contents)})
            .pipe(ngConstant())
            .on('data', function (file) {
                expect(file.contents.toString()).toContain('constant("message", "valid JSON")');
                done();
            });
        });
    });

    describe('name', function () {
        it ('uses the streamed file name by default', function (done) {
            getStream({path: 'myConstantsFile.json'})
            .pipe(ngConstant())
            .on('data', function (file) {
                expect(file.contents.toString()).toContain('module("myConstantsFile"');
                done();
            });
        });

        it ('creates a modules with "ngConstants" name by default for new streams', function (done) {
            evalNgConstant({name: undefined, stream: true}, function (_, output) {
                expect(output).toContain('module("ngConstants"');
                done();
            });
        });

        it ('creates a module with the given name', function (done) {
            evalNgConstant({name: 'myConstantsModule'}, function (_, output) {
                expect(output).toContain('module("myConstantsModule"');
                done();
            });
        });
    });

    describe('deps', function () {
        it ('creates a new modules by default', function (done) {
            evalNgConstant({name: 'defaultDeps', deps: undefined}, function (_, output) {
                expect(output).toContain('module("defaultDeps", [])');
                done();
            });
        });

        it ('adds the given dependencies', function (done) {
            evalNgConstant({name: 'withDeps', deps: ['ngAnimate']}, function (_, output) {
                expect(output).toContain('module("withDeps", ["ngAnimate"])');
                done();
            });
        });

        it ('adds constants to an existing module when set to `false`', function (done) {
            evalNgConstant({name: 'noDeps', deps: false}, function (_, output) {
               expect(output).toContain('module("noDeps")');
                done();
            });
        });
    });

    describe('stream', function () {
        it ('returns an empty open stream when set to `false`', function () {
            var plugin = ngConstant({stream: false});
            expect(plugin._readableState.ended).toBe(false);
            expect(plugin._readableState.length).toBe(0);
        });

        it ('returns a closed stream with a file when set to `true`', function () {
            var stream = ngConstant({stream: true});
            expect(stream._readableState.ended).toBe(true);
            expect(stream._readableState.length).toBe(1);
        });
    });
});

describe('ngConstant.getConstants', function () {
    it('returns an array with the constants key and json string value', function () {
        var data = { constants: { hello: { foo: 'bar' } } };
        var result = ngConstant.getConstants(data);
        expect(result[0]).toEqual({name: 'hello', value: '{"foo":"bar"}'});
    });

    it('extends the data.constants with the options.constants', function () {
        var data = { constants: { hello: 'andrew' } };
        var opts = { constants: { hello: 'world' } };
        var result = ngConstant.getConstants(data, opts);
        expect(result[0]).toEqual({ name: 'hello', value: '"world"' });
    });

    it('uses the data object if data.constants is not available', function () {
        var data = { hello: 'andrew' };
        var result = ngConstant.getConstants(data);
        expect(result[0]).toEqual({ name: 'hello', value: '"andrew"' });
    });

    it('accepts a JSON string as constants from the options', function () {
        var opts = { constants: JSON.stringify({ hello: 'world' }) };
        var result = ngConstant.getConstants({}, opts);
        expect(result[0]).toEqual({ name: 'hello', value: '"world"' });
    });

    it('stringifies the value with the given option.space', function () {
        var data = { constants: { hello: { foo: 'bar' } } };
        var result = ngConstant.getConstants(data, { space: '' });
        expect(result[0].value).toEqual('{"foo":"bar"}');
        result = ngConstant.getConstants(data, { space: ' ' });
        expect(result[0].value).toEqual('{\n "foo": "bar"\n}');
    });
});

describe('ngConstant.getFilePath', function() {
    it('returns the file path from the src plugin when option dest is undefined', function() {
        expect(ngConstant.getFilePath('/foo/bar/config.json', {})).toBe('/foo/bar/config.js');
    });

    it('returns the file path defined by the dest option', function() {
        expect(ngConstant.getFilePath('/foo/bar/foo.js', { dest: 'foo.js' })).toBe('/foo/bar/foo.js');
    });
});

function getStream(fileOptions) {
    var defaults = {path: 'constants.json'};
    var file = new gutil.File(_.merge(defaults, fileOptions));
    var stream = through.obj(gutil.noop());
    stream.end(file);
    return stream;
}

function evalNgConstant(options, callback) {
    var defaults = {stream: true, constants: {greeting: 'hello' }};
    ngConstant(_.merge(defaults, options)).on('data', function (file) {
        callback(file, file.contents.toString());
    });
}
<|endoftext|>


<commit_before>const Command = require("../base/Command");
const moment = require("moment");
require("moment-duration-format");

class CheckAct extends Command {
    constructor(Bot) {
        super(Bot, {
            name: "checkactivity",
            aliases: ["activity", "check", "ca"],
            guildOnly: true,
            permLevel: 3,
            category: "Admin",
            flags: {
                ingame: {       // Show the last active times based on their in-game lastActivity
                    aliases: ["ig"]
                }
            },
            subArgs: {
                sort: {         // Sort by name or time
                    aliases: []
                },
                time: {         // Filter based on them being inactive past x hours
                    aliases: ["t", "hour", "hours"]
                },
                role: {         // Filter the list to a single role
                    aliases: []
                },
            }
        });
    }

    async run(Bot, message, args, options) {
        if (!message.guildSettings.useActivityLog) {
            return super.error(message, message.language.get("COMMAND_CHECKACTIVITY_NOT_ACTIVE"));
        }

        let userID = args[0];
        let activityLog = await Bot.cache.get(Bot.config.mongodb.swgohbotdb, "activityLog", {guildID: message.guild.id});
        if (Array.isArray(activityLog)) activityLog = activityLog[0];
        if (!userID) {
            // List everything for that server (With limitations)
            let objArr = Object.keys(activityLog.log).map(u => {
                return {
                    user: u,
                    time: activityLog.log[u]
                };
            });
            for (const u of objArr) {
                if (options.flags.ingame) {
                    u.ally = await Bot.getAllyCode(null, u.user, false);
                    if (Array.isArray(u.ally)) u.ally = u.ally[0];
                }
                const user = await message.guild.members.get(u.user);
                if (!user || user.user.bot) {
                    u.user = null;
                } else {
                    u.user = Bot.truncate(user.nickname ? user.nickname : user.user.username, options.flags.ingame ? 15 : 20, "..");
                    u.roles = user.roles;
                }
            }

            // Remove any bots
            objArr = objArr.filter(u => u.user !== null);
            if (options.subArgs.time && !isNaN(options.subArgs.time)) {
                // Convert the time from hours to milliseconds
                //                                   ms    sec  min
                const time = options.subArgs.time * 1000 * 60 * 60;
                // Filter out anyone that has been inactive for longer than x hours
                objArr = objArr.filter(u => {
                    const diff = moment().diff(moment(u.time));
                    return diff >= time;
                });
            }
            if (options.subArgs.role && options.subArgs.role.length > 0) {
                // Filter out anyone that does not have the specified role (Name or mention/ id)
                const roleNId = options.subArgs.role;
                // Try finding by ID first
                let role = message.guild.roles.get(roleNId.replace(/[^0-9]/gi, ""));
                if (!role) {
                    // If it can't find the role by ID, try by name
                    role = message.guild.roles.find(r => r.name === roleNId);
                }
                if (!role) {
                    // If it can't find it by role or name, error
                    return super.error(message, message.language.get("COMMAND_CHECKACTIVITY_NO_ROLE", roleNId));
                }
                // Now that we have a role, filter out anyone that doens't have it
                objArr = objArr.filter(u => {
                    const outRole = u.roles.find(r => r.id === role.id);
                    return !outRole ? false : true;
                });
            }
            if (options.subArgs.sort && options.subArgs.sort.toLowerCase() === "name") {
                // If they want to sort by name, do so
                objArr = objArr.sort((a, b) => a.user.toLowerCase() > b.user.toLowerCase() ? 1 : -1);
            } else {
                // Otherwise, sort by how recently they've been on
                objArr = objArr.sort((a, b) => b.time - a.time);
            }
            // If there's no one left after filtering everyone out, let em know
            if (!objArr.length) return super.error(message, message.language.get("COMMAND_CHECKACTIVITY_NO_MATCH"), {title: message.language.get("COMMAND_CHECKACTIVITY_NO_MATCH_TITLE")});
            // Convert the time from a unix-format time string into something human readable
            objArr = objArr.map(u => {
                u.time = getTime(moment().diff(moment(u.time)), true);
                return u;
            });

            // Limit it to 50 people if there are more
            if (objArr.length > 50) {
                objArr = objArr.slice(0, 100);
            }

            let outArr;
            if (!options.flags.ingame) {
            // Format the output into a table so it looks nice
                const headerValues = message.language.get("COMMAND_CHECKACTIVITY_TABLE_HEADERS");
                outArr = Bot.makeTable({
                    user: {value: headerValues.user, startWith: "`", endWith: "|", align: "left"},
                    time: {value: headerValues.time, endWith: "`"}
                }, objArr);
            } else {
                // Get the cooldown from the user runnign the command
                const cooldown = await Bot.getPlayerCooldown(message.author.id);

                // Check everyone's in-game activity if available
                for (let jx = 0; jx < objArr.length; jx++) {
                    if (objArr[jx].ally) {
                        // If the user has an ally code, get their player object, and from there, get the time
                        const player = await Bot.swgohAPI.player(objArr[jx].ally, message.guildSettings.language, cooldown);
                        objArr[jx].igTime = player.lastActivity;
                        objArr[jx].igTime = getTime(moment().diff(moment(objArr[jx].igTime)), true);
                    } else {
                        // If no ally code, just output N/A
                        objArr[jx].igTime = "N/A";
                    }
                }
                const headerValues = message.language.get("COMMAND_CHECKACTIVITY_TABLE_HEADERS");
                outArr = Bot.makeTable({
                    user: {value: headerValues.user, startWith: "`", endWith: "|", align: "left"},
                    time: {value: headerValues.discordTime, endWith: "|"},
                    igTime: {value: headerValues.igTime, endWith: "`"}
                }, objArr);
            }
            const fields = Bot.msgArray(outArr, "\n", 700).map(m => {
                return {name: "-", value: m};
            });

            const desc = fields.shift();
            return message.channel.send({embed: {
                author: {name: message.language.get("COMMAND_CHECKACTIVITY_LOG_HEADER", message.guild.name, objArr.length)},
                description: desc.value,
                fields: fields,
                color: 0x00FF00
            }});
        } else {
            // Make sure it's a valid userID
            if (!Bot.isUserID(userID)) {
                return super.error(message, message.language.get("COMMAND_CHECKACTIVITY_INVALID_USER"));
            }
            userID = Bot.getUserID(userID);
            const user = message.guild.members.get(userID);
            const name = user.nickname ? user.nickname : user.user.username;
            // Try and check the activity for just one user
            if (activityLog.log[userID]) {
                // Spit out user's last activity
                const lastActive = activityLog.log[userID];
                const diff = moment().diff(moment(lastActive));

                return super.error(message, message.language.get("COMMAND_CHECKACTIVITY_USER_CHECK", name, getTime(diff)), {title: message.language.get("COMMAND_CHECKACTIVITY_USER_CHECK_HEADER"), color: 0x00FF00});
            } else {
                return super.error(message, message.language.get("COMMAND_CHECKACTIVITY_NO_USER"));
            }
        }
        function getTime(diff, numOnly) {
            const days = 1000 * 60 * 60 * 24;
            const hours= 1000 * 60 * 60;
            const mins = 1000 * 60;

            let out = diff / days;
            if (out > 1) {
                return (out < 10 ? " " : "") + out.toFixed(1) + (numOnly ? "d" : " days");
            }
            out = diff / hours;
            if (out > 1) {
                return (out < 10 ? " " : "") + out.toFixed(1) + (numOnly ? "h" : " hours");
            }
            out = diff / mins;
            return (out < 10 ? "   " : "  ") + parseInt(out) + (numOnly ? "m" : " minutes");
        }
    }
}

module.exports = CheckAct;

<commit_msg>Changed stuff around to speed up ;ca -ig<commit_after>const Command = require("../base/Command");
const moment = require("moment");
require("moment-duration-format");

class CheckAct extends Command {
    constructor(Bot) {
        super(Bot, {
            name: "checkactivity",
            aliases: ["activity", "check", "ca"],
            guildOnly: true,
            permLevel: 3,
            category: "Admin",
            flags: {
                ingame: {       // Show the last active times based on their in-game lastActivity
                    aliases: ["ig"]
                }
            },
            subArgs: {
                sort: {         // Sort by name or time
                    aliases: []
                },
                time: {         // Filter based on them being inactive past x hours
                    aliases: ["t", "hour", "hours"]
                },
                role: {         // Filter the list to a single role
                    aliases: []
                },
            }
        });
    }

    async run(Bot, message, args, options) {
        if (!message.guildSettings.useActivityLog) {
            return super.error(message, message.language.get("COMMAND_CHECKACTIVITY_NOT_ACTIVE"));
        }

        let userID = args[0];
        let activityLog = await Bot.cache.get(Bot.config.mongodb.swgohbotdb, "activityLog", {guildID: message.guild.id});
        if (Array.isArray(activityLog)) activityLog = activityLog[0];
        if (!userID) {
            // List everything for that server (With limitations)
            let objArr = Object.keys(activityLog.log).map(u => {
                return {
                    user: u,
                    time: activityLog.log[u]
                };
            });
            for (const u of objArr) {
                if (options.flags.ingame) {
                    const user = await Bot.userReg.getUser(u.user);
                    if (user && user.accounts.length) {
                        const acct = user.accounts.find(a => a.primary);
                        u.ally = acct.allyCode;
                    }
                }
                const user = await message.guild.members.get(u.user);
                if (!user || user.user.bot) {
                    u.user = null;
                } else {
                    u.user = Bot.truncate(user.nickname ? user.nickname : user.user.username, options.flags.ingame ? 15 : 20, "..");
                    u.roles = user.roles;
                }
            }

            objArr = objArr.filter(u => u.ally);

            // Remove any bots
            objArr = objArr.filter(u => u.user !== null);
            if (options.subArgs.time && !isNaN(options.subArgs.time)) {
                // Convert the time from hours to milliseconds
                //                                   ms    sec  min
                const time = options.subArgs.time * 1000 * 60 * 60;
                // Filter out anyone that has been inactive for longer than x hours
                objArr = objArr.filter(u => {
                    const diff = moment().diff(moment(u.time));
                    return diff >= time;
                });
            }
            if (options.subArgs.role && options.subArgs.role.length > 0) {
                // Filter out anyone that does not have the specified role (Name or mention/ id)
                const roleNId = options.subArgs.role;
                // Try finding by ID first
                let role = message.guild.roles.get(roleNId.replace(/[^0-9]/gi, ""));
                if (!role) {
                    // If it can't find the role by ID, try by name
                    role = message.guild.roles.find(r => r.name === roleNId);
                }
                if (!role) {
                    // If it can't find it by role or name, error
                    return super.error(message, message.language.get("COMMAND_CHECKACTIVITY_NO_ROLE", roleNId));
                }
                // Now that we have a role, filter out anyone that doens't have it
                objArr = objArr.filter(u => {
                    const outRole = u.roles.find(r => r.id === role.id);
                    return !outRole ? false : true;
                });
            }
            if (options.subArgs.sort && options.subArgs.sort.toLowerCase() === "name") {
                // If they want to sort by name, do so
                objArr = objArr.sort((a, b) => a.user.toLowerCase() > b.user.toLowerCase() ? 1 : -1);
            } else {
                // Otherwise, sort by how recently they've been on
                objArr = objArr.sort((a, b) => b.time - a.time);
            }
            // If there's no one left after filtering everyone out, let em know
            if (!objArr.length) return super.error(message, message.language.get("COMMAND_CHECKACTIVITY_NO_MATCH"), {title: message.language.get("COMMAND_CHECKACTIVITY_NO_MATCH_TITLE")});
            // Convert the time from a unix-format time string into something human readable
            objArr = objArr.map(u => {
                u.time = getTime(moment().diff(moment(u.time)), true);
                return u;
            });

            // Limit it to 50 people if there are more
            if (objArr.length > 50) {
                objArr = objArr.slice(0, 50);
            }

            let outArr;
            if (!options.flags.ingame) {
                // Format the output into a table so it looks nice
                const headerValues = message.language.get("COMMAND_CHECKACTIVITY_TABLE_HEADERS");
                outArr = Bot.makeTable({
                    user: {value: headerValues.user, startWith: "`", endWith: "|", align: "left"},
                    time: {value: headerValues.time, endWith: "`"}
                }, objArr);
            } else {
                // Get all the player infos
                const ac = objArr.map(u => u.ally).filter(u => !!u);
                const players = await Bot.swgoh.fetchPlayer({
                    "allycodes": ac,
                    "project": {
                        "allyCode": 1,
                        "lastActivity": 1
                    }
                });
                if (players.error) {
                    return super.error(message, players.error);
                }
                for (const user of objArr) {
                    const player = players.result.find(u => u.allyCode === parseInt(user.ally));
                    user.igTime = player ? moment().diff(moment(player.lastActivity)) : null;
                }

                objArr = objArr.sort(( b, a) => {
                    a = a.igTime;
                    b = b.igTime;
                    if (!a && !b) return 0;
                    else if (!a) return -1;
                    else if (!b) return 1;
                    else return b - a;
                });
                objArr = objArr.map(u => {
                    u.igTime = getTime(u.igTime, true);
                    return u;
                });

                const headerValues = message.language.get("COMMAND_CHECKACTIVITY_TABLE_HEADERS");
                outArr = Bot.makeTable({
                    user: {value: headerValues.user, startWith: "`", endWith: "|", align: "left"},
                    time: {value: headerValues.discordTime, endWith: "|"},
                    igTime: {value: headerValues.igTime, endWith: "`"}
                }, objArr);
            }
            const fields = Bot.msgArray(outArr, "\n", 700).map(m => {
                return {name: "-", value: m};
            });

            const desc = fields.shift();
            return message.channel.send({embed: {
                author: {name: message.language.get("COMMAND_CHECKACTIVITY_LOG_HEADER", message.guild.name, objArr.length)},
                description: desc.value,
                fields: fields,
                color: 0x00FF00
            }});
        } else {
            // Make sure it's a valid userID
            if (!Bot.isUserID(userID)) {
                return super.error(message, message.language.get("COMMAND_CHECKACTIVITY_INVALID_USER"));
            }
            userID = Bot.getUserID(userID);
            const user = message.guild.members.get(userID);
            const name = user.nickname ? user.nickname : user.user.username;
            // Try and check the activity for just one user
            if (activityLog.log[userID]) {
                // Spit out user's last activity
                const lastActive = activityLog.log[userID];
                const diff = moment().diff(moment(lastActive));

                return super.error(message, message.language.get("COMMAND_CHECKACTIVITY_USER_CHECK", name, getTime(diff)), {title: message.language.get("COMMAND_CHECKACTIVITY_USER_CHECK_HEADER"), color: 0x00FF00});
            } else {
                return super.error(message, message.language.get("COMMAND_CHECKACTIVITY_NO_USER"));
            }
        }
        function getTime(diff, numOnly) {
            const days = 1000 * 60 * 60 * 24;
            const hours= 1000 * 60 * 60;
            const mins = 1000 * 60;

            if (!diff) return "  N/A";

            let out = diff / days;
            if (out > 1) {
                return (out < 10 ? " " : "") + out.toFixed(1) + (numOnly ? "d" : " days");
            }
            out = diff / hours;
            if (out > 1) {
                return (out < 10 ? " " : "") + out.toFixed(1) + (numOnly ? "h" : " hours");
            }
            out = diff / mins;
            return (out < 10 ? "   " : "  ") + parseInt(out) + (numOnly ? "m" : " minutes");
        }
    }
}

module.exports = CheckAct;

<|endoftext|>


<commit_before>// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

const {hasComment} = require('./util');
const {OpenCensusProvider, OpenTelemetryProvider} = require('./provider')

const defaultFields = {
    'route': true,
    'tracestate': false,
    'traceparent': false,
};

const providerMap = {
    'OpenCensus': new OpenCensusProvider(),
    'OpenTelemetry': new OpenTelemetryProvider(),
}

/**
 * All available variables for the commenter are on the `util.fields` object
 * passing the excludes parameter will result in each item being excluded from
 * the commenter output
 *
 * @param {Object} sequelize
 * @param {Object} include -  a map of values to be optionally included.
 * @param {Object} options - A configuration object specifying where to collect trace data from. Accepted fields are:
 *  TraceProvider: Should be either 'OpenCensus' or 'OpenTelemetry', indicating which library to collect trace data from.
 * @return {void}
 */
exports.wrapSequelize = (sequelize, include={}, options={TraceProvider: 'OpenCensus'}) => {

    /* c8 ignore next 2 */
    if (sequelize.___alreadySQLCommenterWrapped___)
        return;
    // Resolve trace provider
    if (!options.TraceProvider) {
        options.TraceProvider = 'OpenCensus'; // Default to OpenCensus
    }
    let traceProvider = providerMap[options.TraceProvider];
    if (!traceProvider) {
        traceProvider = OpenCensusProvider;
    }

    const run = sequelize.dialect.Query.prototype.run;

    // Please don't change this prototype from an explicit function
    // to use arrow functions lest we'll get bugs with not resolving "this".
    sequelize.dialect.Query.prototype.run = function(sql, options) {

        // If a comment already exists, do not insert a new one.
        // See internal issue #20.
        if (hasComment(sql)) // Just proceed with the next function ASAP
            return run.apply(this, [sql, options]);

        const comments = {
            client_timezone: this.sequelize.options.timezone,
            db_driver: `sequelize:${sequelizeVersion}`
        };

        if (sequelize.__middleware__) {
            const req = sequelize.__req__;

            comments.route = req.route.path;
        }

        // Add trace context to comments, depending on the current provider.
        const traceContext = traceProvider.getW3CTraceContext();
        Object.assign(comments, traceContext);

        // Filter out keys whose values are undefined or aren't to be included by default.
        const filtering = typeof include === 'object' && include && Object.keys(include).length > 0;
        const keys = Object.keys(comments).filter((key) => {
            /* c8 ignore next 6 */
            if (!filtering)
                return defaultFields[key] && comments[key];

            // Otherwise since we are filtering, we have to
            // see if the field is included and if it set.
            return include[key] && comments[key];
        });

        // Finally sort the keys alphabetically.
        keys.sort();

        const commentStr = keys.map((key) => {
            const uri_encoded_key = encodeURIComponent(key);
            const uri_encoded_value = encodeURIComponent(comments[key]);
            return `${uri_encoded_key}='${uri_encoded_value}'`;
        }).join(',');

        if (commentStr && commentStr.length > 0)
            sql = `${sql} /*${commentStr}*/`;

        return run.apply(this, [sql, options]);
    }

    // Finally mark the object as having already been wrapped.
    sequelize.___alreadySQLCommenterWrapped___ = true;
}

const resolveSequelizeVersion = () => {
    const sv = require('sequelize').version;
    if (sv)
        return sv;

    return require('sequelize/package').version;
};

// Since resolveSequelizeVersion performs expensive lookups by imports,
// we should ensure that this is resolved only once at start time.
const sequelizeVersion = resolveSequelizeVersion();

/**
 * All available variables for the commenter are on the `util.fields` object
 * passing the include parameter will result items not available in that map
 * only being included in the comment.
 *
 * @param {Object} sequelize
 * @param {Object} include A map of variables to include. If unset, we'll use default attributes.
 * @param {Object} options - A configuration object specifying where to collect trace data from. Accepted fields are:
 *  TraceProvider: Should be either 'OpenCensus' or 'OpenTelemetry', indicating which library to collect trace data from.
 * @return {Function} A middleware that is compatible with the express framework.
 */
exports.wrapSequelizeAsMiddleware = (sequelize, include=null, options) => {

    exports.wrapSequelize(sequelize, include, options);

    return (req, res, next) => {

        sequelize.__middleware__ = true;
        sequelize.__req__ = req;

        next();
    }
}
<commit_msg>nit: documentation typo<commit_after>// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

const {hasComment} = require('./util');
const {OpenCensusProvider, OpenTelemetryProvider} = require('./provider')

const defaultFields = {
    'route': true,
    'tracestate': false,
    'traceparent': false,
};

const providerMap = {
    'OpenCensus': new OpenCensusProvider(),
    'OpenTelemetry': new OpenTelemetryProvider(),
}

/**
 * All available variables for the commenter are on the `util.fields` object
 * passing the excludes parameter will result in each item being excluded from
 * the commenter output
 *
 * @param {Object} sequelize
 * @param {Object} include - a map of values to be optionally included.
 * @param {Object} options - a configuration object specifying where to collect trace data from. Accepted fields are:
 *  TraceProvider: Should be either 'OpenCensus' or 'OpenTelemetry', indicating which library to collect trace data from.
 * @return {void}
 */
exports.wrapSequelize = (sequelize, include={}, options={TraceProvider: 'OpenCensus'}) => {

    /* c8 ignore next 2 */
    if (sequelize.___alreadySQLCommenterWrapped___)
        return;
    // Resolve trace provider
    if (!options.TraceProvider) {
        options.TraceProvider = 'OpenCensus'; // Default to OpenCensus
    }
    let traceProvider = providerMap[options.TraceProvider];
    if (!traceProvider) {
        traceProvider = OpenCensusProvider;
    }

    const run = sequelize.dialect.Query.prototype.run;

    // Please don't change this prototype from an explicit function
    // to use arrow functions lest we'll get bugs with not resolving "this".
    sequelize.dialect.Query.prototype.run = function(sql, options) {

        // If a comment already exists, do not insert a new one.
        // See internal issue #20.
        if (hasComment(sql)) // Just proceed with the next function ASAP
            return run.apply(this, [sql, options]);

        const comments = {
            client_timezone: this.sequelize.options.timezone,
            db_driver: `sequelize:${sequelizeVersion}`
        };

        if (sequelize.__middleware__) {
            const req = sequelize.__req__;

            comments.route = req.route.path;
        }

        // Add trace context to comments, depending on the current provider.
        const traceContext = traceProvider.getW3CTraceContext();
        Object.assign(comments, traceContext);

        // Filter out keys whose values are undefined or aren't to be included by default.
        const filtering = typeof include === 'object' && include && Object.keys(include).length > 0;
        const keys = Object.keys(comments).filter((key) => {
            /* c8 ignore next 6 */
            if (!filtering)
                return defaultFields[key] && comments[key];

            // Otherwise since we are filtering, we have to
            // see if the field is included and if it set.
            return include[key] && comments[key];
        });

        // Finally sort the keys alphabetically.
        keys.sort();

        const commentStr = keys.map((key) => {
            const uri_encoded_key = encodeURIComponent(key);
            const uri_encoded_value = encodeURIComponent(comments[key]);
            return `${uri_encoded_key}='${uri_encoded_value}'`;
        }).join(',');

        if (commentStr && commentStr.length > 0)
            sql = `${sql} /*${commentStr}*/`;

        return run.apply(this, [sql, options]);
    }

    // Finally mark the object as having already been wrapped.
    sequelize.___alreadySQLCommenterWrapped___ = true;
}

const resolveSequelizeVersion = () => {
    const sv = require('sequelize').version;
    if (sv)
        return sv;

    return require('sequelize/package').version;
};

// Since resolveSequelizeVersion performs expensive lookups by imports,
// we should ensure that this is resolved only once at start time.
const sequelizeVersion = resolveSequelizeVersion();

/**
 * All available variables for the commenter are on the `util.fields` object
 * passing the include parameter will result items not available in that map
 * only being included in the comment.
 *
 * @param {Object} sequelize
 * @param {Object} include A map of variables to include. If unset, we'll use default attributes.
 * @param {Object} options - A configuration object specifying where to collect trace data from. Accepted fields are:
 *  TraceProvider: Should be either 'OpenCensus' or 'OpenTelemetry', indicating which library to collect trace data from.
 * @return {Function} A middleware that is compatible with the express framework.
 */
exports.wrapSequelizeAsMiddleware = (sequelize, include=null, options) => {

    exports.wrapSequelize(sequelize, include, options);

    return (req, res, next) => {

        sequelize.__middleware__ = true;
        sequelize.__req__ = req;

        next();
    }
}
<|endoftext|>