<commit_before>// @flow
import React, {PureComponent} from 'react';
import {
  isBooleanLiteral,
  isNullLiteral,
  isNumericLiteral,
  isStringLiteral,
  isArrayExpression,
  isObjectExpression
} from '../utils/checks';

const {Fragment} = (React: any);

class KeyInfo extends PureComponent<any> {

  render() {
    const {children, keys} = this.props;
    return (

          {keys.map((key, i) => [
            {key},
            i + 1 < keys.length ? ' | ' : ''
          ])}

        {children}

    )
  }

}

const KeySection = ({children, title}) => (

{title}

    {children}

);

class NavigateSection extends PureComponent<{}> {

  render() {
    return (
      <KeySection title="Navigate">
        <KeyInfo keys={['Left']}>Left</KeyInfo>
        <KeyInfo keys={['Right']}>Right</KeyInfo>
        <KeyInfo keys={['Up']}>Up</KeyInfo>
        <KeyInfo keys={['Down']}>Down</KeyInfo>
        <KeyInfo keys={['Tab']}>To next editable</KeyInfo>
        <KeyInfo keys={['+ Shift']}>To previous editable</KeyInfo>
      </KeySection>
    )
  }

}

class GeneralSection extends PureComponent<{}> {

  render() {
    return (
      <KeySection title="General">
        <KeyInfo keys={['Ctrl + z']}>Undo</KeyInfo>
        <KeyInfo keys={['+ Shift']}>Redo</KeyInfo>
        <KeyInfo keys={['Ctrl + c']}>Copy selected</KeyInfo>
        <KeyInfo keys={['Ctrl + v']}>Paste into selected</KeyInfo>
      </KeySection>
    )
  }

}

export default class Keymap extends PureComponent<any> {

  render() {
    const {isInArray, selected, selectedNode} = this.props;
    const itemType = isInArray ? 'element' : 'property';
    const isKeySelected = selected.last() === 'key';
    const selectedIsNullLiteral = !isKeySelected && isNullLiteral(selectedNode);
    const selectedIsNumericLiteral = selectedNode && isNumericLiteral(selectedNode);
    return (

        <NavigateSection/>

        <KeySection title="Modify">
          <KeyInfo keys={['Enter']}>
            Insert {isInArray || isArrayExpression(selectedNode) ? 'element' : 'property'}
          </KeyInfo>
          <KeyInfo keys={['Ctrl + d']}>
            Delete {itemType}
          </KeyInfo>
          <KeyInfo keys={['Alt + ⬆']}>
            Move {itemType} up
          </KeyInfo>
          <KeyInfo keys={['Alt + ⬇']}>
            Move {itemType} down
          </KeyInfo>
          {selectedNode && isBooleanLiteral(selectedNode) && (
            <KeyInfo keys={['t', 'f']}>Set to true/false</KeyInfo>
          )}
          {selectedIsNumericLiteral && (
            <Fragment>
              <KeyInfo keys={['i', 'd']}>Inc-/Decrement</KeyInfo>
              <KeyInfo keys={['Shift + i', 'd']}>Inc-/Decrement by 10</KeyInfo>
            </Fragment>
          )}
        </KeySection>

        {!isKeySelected && (
          <KeySection title="Change type">
            {[
              [isStringLiteral, ['s', '\''], 'String'],
              [isNumericLiteral, ['n'], 'Number'],
              [isBooleanLiteral, ['t'], 'true (Boolean)'],
              [isBooleanLiteral, ['f'], 'false (Boolean)'],
              [isArrayExpression, ['a', '['], 'Array'],
              [isObjectExpression, ['o', String.fromCharCode(123)], 'Object'],
              [isNullLiteral, ['.'], 'Null']
            ].map(([checkFn, keys, label]) => (
              !checkFn(selectedNode) && (
                <KeyInfo key={label} keys={selectedIsNullLiteral ? keys : ['Alt + ' + keys[0]]}>
                  {label}
                </KeyInfo>
              )
            ))}
          </KeySection>
        )}

        <GeneralSection/>

    );
  }

}<commit_msg>fix missing child keys in keymap<commit_after>// @flow
import React, {PureComponent} from 'react';
import {
  isBooleanLiteral,
  isNullLiteral,
  isNumericLiteral,
  isStringLiteral,
  isArrayExpression,
  isObjectExpression
} from '../utils/checks';

const {Fragment} = (React: any);

class KeyInfo extends PureComponent<any> {

  render() {
    const {children, keys} = this.props;
    return (

          {keys.map((key, i) => (
            <Fragment key={key}>
              {key}
              {i + 1 < keys.length ? ' | ' : ''}
            </Fragment>
          ))}

        {children}

    )
  }

}

const KeySection = ({children, title}) => (

{title}

    {children}

);

class NavigateSection extends PureComponent<{}> {

  render() {
    return (
      <KeySection title="Navigate">
        <KeyInfo keys={['Left']}>Left</KeyInfo>
        <KeyInfo keys={['Right']}>Right</KeyInfo>
        <KeyInfo keys={['Up']}>Up</KeyInfo>
        <KeyInfo keys={['Down']}>Down</KeyInfo>
        <KeyInfo keys={['Tab']}>To next editable</KeyInfo>
        <KeyInfo keys={['+ Shift']}>To previous editable</KeyInfo>
      </KeySection>
    )
  }

}

class GeneralSection extends PureComponent<{}> {

  render() {
    return (
      <KeySection title="General">
        <KeyInfo keys={['Ctrl + z']}>Undo</KeyInfo>
        <KeyInfo keys={['+ Shift']}>Redo</KeyInfo>
        <KeyInfo keys={['Ctrl + c']}>Copy selected</KeyInfo>
        <KeyInfo keys={['Ctrl + v']}>Paste into selected</KeyInfo>
      </KeySection>
    )
  }

}

export default class Keymap extends PureComponent<any> {

  render() {
    const {isInArray, selected, selectedNode} = this.props;
    const itemType = isInArray ? 'element' : 'property';
    const isKeySelected = selected.last() === 'key';
    const selectedIsNullLiteral = !isKeySelected && isNullLiteral(selectedNode);
    const selectedIsNumericLiteral = selectedNode && isNumericLiteral(selectedNode);
    return (

        <NavigateSection/>

        <KeySection title="Modify">
          <KeyInfo keys={['Enter']}>
            Insert {isInArray || isArrayExpression(selectedNode) ? 'element' : 'property'}
          </KeyInfo>
          <KeyInfo keys={['Ctrl + d']}>
            Delete {itemType}
          </KeyInfo>
          <KeyInfo keys={['Alt + ⬆']}>
            Move {itemType} up
          </KeyInfo>
          <KeyInfo keys={['Alt + ⬇']}>
            Move {itemType} down
          </KeyInfo>
          {selectedNode && isBooleanLiteral(selectedNode) && (
            <KeyInfo keys={['t', 'f']}>Set to true/false</KeyInfo>
          )}
          {selectedIsNumericLiteral && (
            <Fragment>
              <KeyInfo keys={['i', 'd']}>Inc-/Decrement</KeyInfo>
              <KeyInfo keys={['Shift + i', 'd']}>Inc-/Decrement by 10</KeyInfo>
            </Fragment>
          )}
        </KeySection>

        {!isKeySelected && (
          <KeySection title="Change type">
            {[
              [isStringLiteral, ['s', '\''], 'String'],
              [isNumericLiteral, ['n'], 'Number'],
              [isBooleanLiteral, ['t'], 'true (Boolean)'],
              [isBooleanLiteral, ['f'], 'false (Boolean)'],
              [isArrayExpression, ['a', '['], 'Array'],
              [isObjectExpression, ['o', String.fromCharCode(123)], 'Object'],
              [isNullLiteral, ['.'], 'Null']
            ].map(([checkFn, keys, label]) => (
              !checkFn(selectedNode) && (
                <KeyInfo key={label} keys={selectedIsNullLiteral ? keys : ['Alt + ' + keys[0]]}>
                  {label}
                </KeyInfo>
              )
            ))}
          </KeySection>
        )}

        <GeneralSection/>

    );
  }

}<|endoftext|>


<commit_before>import * as CryptoJS from 'crypto-js';
import Hogan from 'hogan.js';
const Promise = require('bluebird');
const fs = Promise.promisifyAll(require('fs'));
import config from '../../config';
//Setup email
import * as nodemailer from 'nodemailer';
import smtpTransport from 'nodemailer-smtp-transport';
// create reusable transporter object using the default SMTP transport
const transporter = nodemailer.createTransport({service: 'gmail', auth: config.email.auth});
// const transporter = nodemailer.createTransport(smtpTransport(config.email));

// Encrypt
export function encrypt(text) {

  return CryptoJS.AES.encrypt(text, config.secret).toString();

}

// Decrypt
export function decrypt(ciphertext) {

  let bytes = CryptoJS.AES.decrypt(ciphertext.toString(), config.secret);
  return bytes.toString(CryptoJS.enc.Utf8);

}

// Make random string
export function makeid(length) {

  let text = "";
  const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  for (let i = 0; i < length; i++)
    text += possible.charAt(Math.floor(Math.random() * possible.length));
  return text;

}

// hasRole
export function hasRole(rolesRequired, rolesUser) {
  let isAuthorized = false;
  rolesRequired.forEach(rolReq => {
    if (rolesUser.includes(rolReq))
      isAuthorized = true;
    return;
  });
  return isAuthorized;
}

// Calculate time rol
export function calculateTTL(roles) {
  try {
    if (roles.length > 0) {
      let array = [];
      let isInfinite = false;
      roles.forEach(rol => {
        config.roles.forEach(item => {
          if (rol === item.rol) {
            if (item.time === 'infinite') {
              isInfinite = true;
              return;
            } else if (item.time){
              array.push(item.time);
            }
          }
        });
      });
      if (isInfinite) {
        return null;
      } else {
        return parseInt(Math.max.apply(Math, array)) * 60;
      }
    } else {
      return null;
    }
  } catch (err) {
    return null;
  }
}

// Get Template
export function getTemplate(path) {

  if (path.indexOf('.js') > -1) {
    return Promise.resolve(require(`${config.base}/views/${path}`).default);
  } else {
    return fs.readFileAsync(`${config.base}/views/${path}`, 'utf8');
  }

}

// Replace in Template
export function setTemplate(template, values) {

  let HoganTemplate = Hogan.compile(template);
  return HoganTemplate.render(values);

}

// Send Email

export function sendEmail(message) {
  return Promise.resolve(transporter.sendMail(message), transporter.close());
}
<commit_msg>updated lib/utility<commit_after>import * as CryptoJS from 'crypto-js';
import Hogan from 'hogan.js';
const Promise = require('bluebird');
const fs = Promise.promisifyAll(require('fs'));
import config from '../../config';
// Setup email
import * as nodemailer from 'nodemailer';
import smtpTransport from 'nodemailer-smtp-transport';
// create reusable transporter object using the default SMTP transport
const transporter = nodemailer.createTransport({service: 'gmail', auth: config.email.auth});
// const transporter = nodemailer.createTransport(smtpTransport(config.email));

// Encrypt
export function encrypt(text) {
  return CryptoJS.AES.encrypt(text, config.secret).toString();
}

// Decrypt
export function decrypt(ciphertext) {
  let bytes = CryptoJS.AES.decrypt(ciphertext.toString(), config.secret);
  return bytes.toString(CryptoJS.enc.Utf8);
}

// Make random string
export function makeid(length) {
  let text = "";
  const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  for (let i = 0; i < length; i++)
    text += possible.charAt(Math.floor(Math.random() * possible.length));
  return text;
}

// hasRole
export function hasRole(rolesRequired, rolesUser) {
  let isAuthorized = false;
  rolesRequired.forEach(rolReq => {
    if (rolesUser.includes(rolReq))
      isAuthorized = true;
    return;
  });
  return isAuthorized;
}

// Calculate time session by rol
export function ttl(roles) {
  try {
    if (roles.length > 0) {
      let array = [];
      let isInfinite = false;
      roles.forEach(rol => {
        config.roles.forEach(item => {
          if (rol === item.rol) {
            if (item.time === 'infinite') {
              isInfinite = true;
              return;
            } else if (item.time) {
              array.push(item.time);
            }
          }
        });
      });
      if (isInfinite) {
        return null;
      } else {
        return parseInt(Math.max.apply(Math, array)) * 60;
      }
    } else {
      return null;
    }
  } catch (err) {
    return null;
  }
}

// Get Template
export function getTemplate(path) {
  if (path.indexOf('.js') > -1) {
    return Promise.resolve(require(`${config.base}/views/${path}`).default);
  } else {
    return fs.readFileAsync(`${config.base}/views/${path}`, 'utf8');
  }
}

// Replace in Template
export function setTemplate(template, values) {
  let HoganTemplate = Hogan.compile(template);
  return HoganTemplate.render(values);
}

// Send Email
export function sendEmail(message) {
  return Promise.resolve(transporter.sendMail(message), transporter.close());
}
<|endoftext|>


<commit_before>import React, {Component} from 'react';
import PropTypes from 'prop-types';
import ComponentCommon from './component-common';
import ErrorMessages from './error-messages';
import Help from './help';
import Row from './row';
import SelectControl from './controls/select';

class Select extends Component {
  handleChange = event => {
    const target = event.currentTarget;
    let value;
    if (this.props.multiple) {
      value = target.options
        .filter(option => option.selected)
        .map(option => option.value);
    } else {
      value = target.value;
    }
    this.props.onSetValue(value);
    this.props.onChange(this.props.name, value);
  };

  initElementRef = control => {
    this.element = control ? control.element : null;
  };

  render() {
    const inputProps = Object.assign({}, this.props);
    Object.keys(ComponentCommon.propTypes).forEach(key => {
      delete inputProps[key];
    });

    const control = (
      <SelectControl
        {...inputProps}
        onChange={this.handleChange}
        ref={this.initElementRef}
      />
    );

    if (this.props.layout === 'elementOnly') {
      return control;
    }

    return (
      <Row {...this.props} htmlFor={this.props.id}>
        {control}
        {this.props.help ? <Help help={this.props.help} /> : null}
        {this.props.showErrors ? (
          <ErrorMessages messages={this.props.errorMessages} />
        ) : null}
      </Row>
    );
  }
}

Select.propTypes = {
  ...SelectControl.propTypes,
  ...ComponentCommon.propTypes,
  multiple: PropTypes.bool,
  options: PropTypes.arrayOf(
    PropTypes.shape({
      value: PropTypes.string,
      label: PropTypes.string,
      group: PropTypes.string,
    }),
  ),
};

Select.defaultProps = {
  ...ComponentCommon.defaultTypes,
  options: [],
};

export default Select;
<commit_msg>Fix defaultProps.<commit_after>import React, {Component} from 'react';
import PropTypes from 'prop-types';
import ComponentCommon from './component-common';
import ErrorMessages from './error-messages';
import Help from './help';
import Row from './row';
import SelectControl from './controls/select';

class Select extends Component {
  handleChange = event => {
    const target = event.currentTarget;
    let value;
    if (this.props.multiple) {
      value = target.options
        .filter(option => option.selected)
        .map(option => option.value);
    } else {
      value = target.value;
    }
    this.props.onSetValue(value);
    this.props.onChange(this.props.name, value);
  };

  initElementRef = control => {
    this.element = control ? control.element : null;
  };

  render() {
    const inputProps = Object.assign({}, this.props);
    Object.keys(ComponentCommon.propTypes).forEach(key => {
      delete inputProps[key];
    });

    const control = (
      <SelectControl
        {...inputProps}
        onChange={this.handleChange}
        ref={this.initElementRef}
      />
    );

    if (this.props.layout === 'elementOnly') {
      return control;
    }

    return (
      <Row {...this.props} htmlFor={this.props.id}>
        {control}
        {this.props.help ? <Help help={this.props.help} /> : null}
        {this.props.showErrors ? (
          <ErrorMessages messages={this.props.errorMessages} />
        ) : null}
      </Row>
    );
  }
}

Select.propTypes = {
  ...SelectControl.propTypes,
  ...ComponentCommon.propTypes,
  multiple: PropTypes.bool,
  options: PropTypes.arrayOf(
    PropTypes.shape({
      value: PropTypes.string,
      label: PropTypes.string,
      group: PropTypes.string,
    }),
  ),
};

Select.defaultProps = {
  ...ComponentCommon.defaultProps,
  options: [],
};

export default Select;
<|endoftext|>


<commit_before>export default function isType(obj, type) {
    // use 'typeof' operator in an if clause yields in better performance than switch-case

    if (obj === null || obj === undefined) {
        return false;
    }
    if (typeof obj === 'number') {
        return type === Number;
    }
    else if (typeof obj === 'string') {
        return type === String;
    }
    else if (typeof obj === 'function') {
        return type === Function;
    }
    else if (typeof obj === 'boolean') {
        return type === Boolean;
    }
    else {
        return obj instanceof type;
    }
}

<commit_msg>decorate<commit_after>export default function isType(obj, type) {
    // use 'typeof' operator in an if clause yields in better performance than switch-case

    if (obj === null || obj === undefined) {
        return false;
    }

    if (typeof obj === 'number') {
        return type === Number;
    }

    else if (typeof obj === 'string') {
        return type === String;
    }

    else if (typeof obj === 'function') {
        return type === Function;
    }

    else if (typeof obj === 'boolean') {
        return type === Boolean;
    }

    else {
        return obj instanceof type;
    }
}

<|endoftext|>


<commit_before>const { promisify } = require('es6-promisify');
const { BadRequest, NotFound, GeneralError } = require('@feathersjs/errors');
const aws = require('aws-sdk');
const pathUtil = require('path');
const fs = require('fs');
const logger = require('../../../logger');
const { schoolModel } = require('../../school/model');
const UserModel = require('../../user/model');
const filePermissionHelper = require('../utils/filePermissionHelper');
const { removeLeadingSlash } = require('../utils/filePathHelper');

// const prodMode = process.env.NODE_ENV === 'production';

let awsConfig = {};
try {
	//	awsConfig = require(`../../../../config/secrets.${prodMode ? 'js' : 'json'}`).aws;
	/* eslint-disable global-require, no-unused-expressions */
	(['production'].includes(process.env.NODE_ENV))
		? awsConfig = require('../../../../config/secrets.js').aws
		: awsConfig = require('../../../../config/secrets.json').aws;
	/* eslint-enable global-require, no-unused-expressions */
} catch (e) {
	logger.warning('The AWS config couldn\'t be read');
}

const AbstractFileStorageStrategy = require('./interface.js');

const createAWSObject = (schoolId) => {
	if (!awsConfig.endpointUrl) throw new Error('AWS integration is not configured on the server');

	const config = new aws.Config(awsConfig);
	config.endpoint = new aws.Endpoint(awsConfig.endpointUrl);

	return {
		s3: new aws.S3(config),
		bucket: `bucket-${schoolId}`,
	};
};

/**
 * split files-list in files, that are in current directory, and the sub-directories
 * @param data is the files-list
 * @param path the current directory, everything else is filtered
 */
const splitFilesAndDirectories = (_path, data) => {
	const path = removeLeadingSlash(_path);
	let files = [];
	const directories = [];

	data.forEach((entry) => {
		const relativePath = removeLeadingSlash(entry.key.replace(path, ''));
		const pathComponents = relativePath.split('/');

		if (pathComponents.length === 1) {
			files.push(entry);
		} else if (entry.name === '.scfake') { // prevent duplicates showing up by only considering .scfake
			const components = entry.key.split('/');
			const directoryName = components[components.length - 2]; // the component before '.scfake'
			directories.push({
				name: directoryName,
			});
		}
	});

	// remove .scfake fake file
	files = files.filter((f) => f.name !== '.scfake');

	return {
		files,
		directories,
	};
};

const getFileMetadata = (storageContext, awsObjects, bucketName, s3) => {
	const headObject = promisify(s3.headObject.bind(s3), s3);
	const getPath = (path) => {
		if (!path) {
			return '/';
		}

		let pathComponents = path.split('/');
		if (pathComponents[0] === '') pathComponents = pathComponents.slice(1); // omit leading slash
		// remove first and second directory from storageContext because it's just meta
		return `/${pathComponents.slice(2).join('/')}`;
	};

	const getFileName = (path) => {
		if (!path) {
			return '';
		}

		// a file's name is in the last part of the path
		const values = path.split('/');
		return values[values.length - 1];
	};
	awsObjects.forEach((e) => {
		e.Key = removeLeadingSlash(e.Key);
	});

	return Promise.all(awsObjects.map((object) => headObject({ Bucket: bucketName, Key: object.Key })
		.then((res) => ({
			key: object.Key,
			name: getFileName(object.Key),
			path: getPath(res.Metadata.path),
			lastModified: res.LastModified,
			size: res.ContentLength,
			type: res.ContentType,
			thumbnail: res.Metadata.thumbnail,
		}))))
		.then((data) => splitFilesAndDirectories(storageContext, data));
};

class AWSS3Strategy extends AbstractFileStorageStrategy {
	async create(schoolId) {
		if (!schoolId) {
			throw new BadRequest('No school id parameter given.');
		}
		return schoolModel.findOne({ _id: schoolId }).lean().exec()
			.then((school) => {
				if (school === null) {
					throw new NotFound('School not found.');
				}

				const awsObject = createAWSObject(school._id);
				const createBucket = promisify(awsObject.s3.createBucket.bind(awsObject.s3), awsObject.s3);

				return createBucket({ Bucket: awsObject.bucket })
					.then((res) => {
						/* Sets the CORS configuration for a bucket. */
						awsObject.s3.putBucketCors({
							Bucket: awsObject.bucket,
							CORSConfiguration: {
								CORSRules: awsConfig.cors_rules,
							},
						}, (err) => {	// define and pass error handler
							if (err) {
								logger.warning(err);
							}
						});
						return {
							message: 'Successfully created s3-bucket!',
							data: res,
						};
					});
			});
	}

	createIfNotExists(awsObject) {
		return new Promise((resolve, reject) => {
			const params = {
				Bucket: awsObject.bucket,
			};
			awsObject.s3.headBucket(params, (err) => {
				if (err && err.statusCode === 404) {
					logger.info(`Bucket ${awsObject.bucket} does not exist - creating ... `);

					awsObject.s3.createBucket({ Bucket: awsObject.bucket }, (err) => {
						if (err) {
							reject(err);
						}

						logger.info(`Bucket ${awsObject.bucket} created ... `);
						awsObject.s3.putBucketCors({
							Bucket: awsObject.bucket,
							CORSConfiguration: {
								CORSRules: awsConfig.cors_rules,
							},
						},
						(err) => {
							if (err) {
								reject(err);
							}
							resolve(awsObject);
						});
					});

					return;
				}

				logger.info(`Bucket ${awsObject.bucket} does exist`);
				resolve(awsObject);
			});
		});
	}

	/** @DEPRECATED * */
	getFiles(userId, path) {
		logger.warning('@deprecated');
		if (!userId || !path) {
			return Promise.reject(new BadRequest('Missing parameters by getFiles.'));
		}
		return filePermissionHelper.checkPermissions(userId, path)
			.then((res) => UserModel.userModel.findById(userId).exec())
			.then((result) => {
				if (!result) {
					return new NotFound('User not found');
				}
				if (!result.schoolId) {
					return new GeneralError('school not set');
				}

				const awsObject = createAWSObject(result.schoolId);
				const params = {
					Bucket: awsObject.bucket,
					Prefix: path,
				};
				return promisify(awsObject.s3.listObjectsV2.bind(awsObject.s3), awsObject.s3)(params)
					.then((res) => Promise.resolve(getFileMetadata(path, res.Contents, awsObject.bucket, awsObject.s3)));
			});
	}

	copyFile(userId, oldPath, newPath, externalSchoolId) {
		if (!userId || !oldPath || !newPath) {
			return Promise.reject(new BadRequest('Missing parameters by copyFile.', { userId, oldPath, newPath }));
		}
		return UserModel.userModel.findById(userId).lean().exec()
			.then((result) => {
				if (!result || !result.schoolId) {
					return new NotFound('User not found');
				}

				const awsObject = createAWSObject(result.schoolId);
				// files can be copied to different schools
				const sourceBucket = `bucket-${externalSchoolId || result.schoolId}`;

				const params = {
					Bucket: awsObject.bucket, // destination bucket
					CopySource: `/${sourceBucket}/${encodeURIComponent(oldPath)}`, // full source path (with bucket)
					Key: newPath, // destination path
				};
				return promisify(awsObject.s3.copyObject.bind(awsObject.s3), awsObject.s3)(params);
			})
			.catch((err) => {
				logger.warning(err);
				throw err;
			});
	}

	deleteFile(userId, filename) {
		if (!userId || !filename) {
			return Promise.reject(new BadRequest('Missing parameters by deleteFile.', { userId, filename }));
		}
		return UserModel.userModel.findById(userId).exec()
			.then((result) => {
				if (!result || !result.schoolId) {
					return new NotFound('User not found');
				}
				const awsObject = createAWSObject(result.schoolId);
				const params = {
					Bucket: awsObject.bucket,
					Delete: {
						Objects: [
							{
								Key: filename,
							},
						],
						Quiet: true,
					},
				};
				return promisify(awsObject.s3.deleteObjects.bind(awsObject.s3), awsObject.s3)(params);
			});
	}

	generateSignedUrl({ userId, flatFileName, fileType }) {
		if (!userId || !flatFileName || !fileType) {
			return Promise.reject(
				new BadRequest('Missing parameters by generateSignedUrl.', { userId, flatFileName, fileType }),
			);
		}

		return UserModel.userModel.findById(userId).exec()
			.then((result) => {
				if (!result || !result.schoolId) {
					return new NotFound('User not found');
				}

				const awsObject = createAWSObject(result.schoolId);
				return this.createIfNotExists(awsObject);
			})
			.then((awsObject) => {
				const params = {
					Bucket: awsObject.bucket,
					Key: flatFileName,
					Expires: 60,
					ContentType: fileType,
				};

				return promisify(awsObject.s3.getSignedUrl.bind(awsObject.s3), awsObject.s3)('putObject', params);
			});
	}

	getSignedUrl({
		userId, flatFileName, localFileName, download, action = 'getObject',
	}) {
		if (!userId || !flatFileName) {
			return Promise.reject(new BadRequest('Missing parameters by getSignedUrl.', { userId, flatFileName }));
		}

		return UserModel.userModel.findById(userId).lean().exec().then((result) => {
			if (!result || !result.schoolId) {
				return new NotFound('User not found');
			}

			const awsObject = createAWSObject(result.schoolId);
			const params = {
				Bucket: awsObject.bucket,
				Key: flatFileName,
				Expires: 60,
			};

			if (download) {
				params.ResponseContentDisposition = `attachment; filename = "${localFileName.replace('"', '')}"`;
			}

			return promisify(awsObject.s3.getSignedUrl.bind(awsObject.s3), awsObject.s3)(action, params);
		});
	}

	/** ** @DEPRECATED *** */
	createDirectory(userId, path) {
		logger.warning('@deprecated');
		if (!userId || !path) {
			return Promise.reject(new BadRequest('Missing parameters by createDirectory'));
		}
		return filePermissionHelper.checkPermissions(userId, path)
			.then((res) => {
				// eslint-disable-next-line no-param-reassign
				if (path[0] === '/') path = path.substring(1);
				return UserModel.userModel.findById(userId).exec().then((result) => {
					if (!result || !result.schoolId) {
						return new NotFound('User not found');
					}

					const awsObject = createAWSObject(result.schoolId);
					const fileStream = fs.createReadStream(pathUtil.join(__dirname, '..', 'resources', '.scfake'));
					const params = {
						Bucket: awsObject.bucket,
						Key: `${path}/.scfake`,
						Body: fileStream,
						Metadata: {
							path,
							name: '.scfake',
						},
					};

					return promisify(awsObject.s3.putObject.bind(awsObject.s3), awsObject.s3)(params);
				});
			});
	}

	/** ** @DEPRECATED *** */
	deleteDirectory(userId, path) {
		logger.warning('@deprecated');
		if (!userId || !path) {
			return Promise.reject(new BadRequest('Missing parameters by deleteDirectory.'));
		}
		return filePermissionHelper.checkPermissions(userId, path)
			.then((res) => UserModel.userModel.findById(userId).exec())
			.then((result) => {
				if (!result || !result.schoolId) {
					return new NotFound('User not found');
				}
				const awsObject = createAWSObject(result.schoolId);
				const params = {
					Bucket: awsObject.bucket,
					Prefix: removeLeadingSlash(path),
				};
				return this.deleteAllInDirectory(awsObject, params);
			});
	}

	/** ** @DEPRECATED *** */
	deleteAllInDirectory(awsObject, params) {
		logger.warning('@deprecated');
		return promisify(awsObject.s3.listObjectsV2.bind(awsObject.s3), awsObject.s3)(params)
			.then((data) => {
				// there should always be at least the .scfake file
				if (data.Contents.length === 0) {
					throw new Error(`Invalid Prefix ${params.Prefix}`);
				}

				const deleteParams = { Bucket: params.Bucket, Delete: {} };
				deleteParams.Delete.Objects = data.Contents.map((c) => ({ Key: c.Key }));

				return promisify(awsObject.s3.deleteObjects.bind(awsObject.s3), awsObject.s3)(deleteParams);
			})
			.then((deletionData) => {
				// AWS S3 returns only 1000 items at once
				if (deletionData.Deleted.length === 1000) return this.deleteAllInDirectory(awsObject, params);
				return Promise.resolve(deletionData);
			});
	}
}

module.exports = AWSS3Strategy;
<commit_msg>created boolean variable to not trigger download<commit_after>const { promisify } = require('es6-promisify');
const { BadRequest, NotFound, GeneralError } = require('@feathersjs/errors');
const aws = require('aws-sdk');
const pathUtil = require('path');
const fs = require('fs');
const logger = require('../../../logger');
const { schoolModel } = require('../../school/model');
const UserModel = require('../../user/model');
const filePermissionHelper = require('../utils/filePermissionHelper');
const { removeLeadingSlash } = require('../utils/filePathHelper');

// const prodMode = process.env.NODE_ENV === 'production';

let awsConfig = {};
try {
	//	awsConfig = require(`../../../../config/secrets.${prodMode ? 'js' : 'json'}`).aws;
	/* eslint-disable global-require, no-unused-expressions */
	(['production'].includes(process.env.NODE_ENV))
		? awsConfig = require('../../../../config/secrets.js').aws
		: awsConfig = require('../../../../config/secrets.json').aws;
	/* eslint-enable global-require, no-unused-expressions */
} catch (e) {
	logger.warning('The AWS config couldn\'t be read');
}

const AbstractFileStorageStrategy = require('./interface.js');

const createAWSObject = (schoolId) => {
	if (!awsConfig.endpointUrl) throw new Error('AWS integration is not configured on the server');

	const config = new aws.Config(awsConfig);
	config.endpoint = new aws.Endpoint(awsConfig.endpointUrl);

	return {
		s3: new aws.S3(config),
		bucket: `bucket-${schoolId}`,
	};
};

/**
 * split files-list in files, that are in current directory, and the sub-directories
 * @param data is the files-list
 * @param path the current directory, everything else is filtered
 */
const splitFilesAndDirectories = (_path, data) => {
	const path = removeLeadingSlash(_path);
	let files = [];
	const directories = [];

	data.forEach((entry) => {
		const relativePath = removeLeadingSlash(entry.key.replace(path, ''));
		const pathComponents = relativePath.split('/');

		if (pathComponents.length === 1) {
			files.push(entry);
		} else if (entry.name === '.scfake') { // prevent duplicates showing up by only considering .scfake
			const components = entry.key.split('/');
			const directoryName = components[components.length - 2]; // the component before '.scfake'
			directories.push({
				name: directoryName,
			});
		}
	});

	// remove .scfake fake file
	files = files.filter((f) => f.name !== '.scfake');

	return {
		files,
		directories,
	};
};

const getFileMetadata = (storageContext, awsObjects, bucketName, s3) => {
	const headObject = promisify(s3.headObject.bind(s3), s3);
	const getPath = (path) => {
		if (!path) {
			return '/';
		}

		let pathComponents = path.split('/');
		if (pathComponents[0] === '') pathComponents = pathComponents.slice(1); // omit leading slash
		// remove first and second directory from storageContext because it's just meta
		return `/${pathComponents.slice(2).join('/')}`;
	};

	const getFileName = (path) => {
		if (!path) {
			return '';
		}

		// a file's name is in the last part of the path
		const values = path.split('/');
		return values[values.length - 1];
	};
	awsObjects.forEach((e) => {
		e.Key = removeLeadingSlash(e.Key);
	});

	return Promise.all(awsObjects.map((object) => headObject({ Bucket: bucketName, Key: object.Key })
		.then((res) => ({
			key: object.Key,
			name: getFileName(object.Key),
			path: getPath(res.Metadata.path),
			lastModified: res.LastModified,
			size: res.ContentLength,
			type: res.ContentType,
			thumbnail: res.Metadata.thumbnail,
		}))))
		.then((data) => splitFilesAndDirectories(storageContext, data));
};

class AWSS3Strategy extends AbstractFileStorageStrategy {
	async create(schoolId) {
		if (!schoolId) {
			throw new BadRequest('No school id parameter given.');
		}
		return schoolModel.findOne({ _id: schoolId }).lean().exec()
			.then((school) => {
				if (school === null) {
					throw new NotFound('School not found.');
				}

				const awsObject = createAWSObject(school._id);
				const createBucket = promisify(awsObject.s3.createBucket.bind(awsObject.s3), awsObject.s3);

				return createBucket({ Bucket: awsObject.bucket })
					.then((res) => {
						/* Sets the CORS configuration for a bucket. */
						awsObject.s3.putBucketCors({
							Bucket: awsObject.bucket,
							CORSConfiguration: {
								CORSRules: awsConfig.cors_rules,
							},
						}, (err) => {	// define and pass error handler
							if (err) {
								logger.warning(err);
							}
						});
						return {
							message: 'Successfully created s3-bucket!',
							data: res,
						};
					});
			});
	}

	createIfNotExists(awsObject) {
		return new Promise((resolve, reject) => {
			const params = {
				Bucket: awsObject.bucket,
			};
			awsObject.s3.headBucket(params, (err) => {
				if (err && err.statusCode === 404) {
					logger.info(`Bucket ${awsObject.bucket} does not exist - creating ... `);

					awsObject.s3.createBucket({ Bucket: awsObject.bucket }, (err) => {
						if (err) {
							reject(err);
						}

						logger.info(`Bucket ${awsObject.bucket} created ... `);
						awsObject.s3.putBucketCors({
							Bucket: awsObject.bucket,
							CORSConfiguration: {
								CORSRules: awsConfig.cors_rules,
							},
						},
						(err) => {
							if (err) {
								reject(err);
							}
							resolve(awsObject);
						});
					});

					return;
				}

				logger.info(`Bucket ${awsObject.bucket} does exist`);
				resolve(awsObject);
			});
		});
	}

	/** @DEPRECATED * */
	getFiles(userId, path) {
		logger.warning('@deprecated');
		if (!userId || !path) {
			return Promise.reject(new BadRequest('Missing parameters by getFiles.'));
		}
		return filePermissionHelper.checkPermissions(userId, path)
			.then((res) => UserModel.userModel.findById(userId).exec())
			.then((result) => {
				if (!result) {
					return new NotFound('User not found');
				}
				if (!result.schoolId) {
					return new GeneralError('school not set');
				}

				const awsObject = createAWSObject(result.schoolId);
				const params = {
					Bucket: awsObject.bucket,
					Prefix: path,
				};
				return promisify(awsObject.s3.listObjectsV2.bind(awsObject.s3), awsObject.s3)(params)
					.then((res) => Promise.resolve(getFileMetadata(path, res.Contents, awsObject.bucket, awsObject.s3)));
			});
	}

	copyFile(userId, oldPath, newPath, externalSchoolId) {
		if (!userId || !oldPath || !newPath) {
			return Promise.reject(new BadRequest('Missing parameters by copyFile.', { userId, oldPath, newPath }));
		}
		return UserModel.userModel.findById(userId).lean().exec()
			.then((result) => {
				if (!result || !result.schoolId) {
					return new NotFound('User not found');
				}

				const awsObject = createAWSObject(result.schoolId);
				// files can be copied to different schools
				const sourceBucket = `bucket-${externalSchoolId || result.schoolId}`;

				const params = {
					Bucket: awsObject.bucket, // destination bucket
					CopySource: `/${sourceBucket}/${encodeURIComponent(oldPath)}`, // full source path (with bucket)
					Key: newPath, // destination path
				};
				return promisify(awsObject.s3.copyObject.bind(awsObject.s3), awsObject.s3)(params);
			})
			.catch((err) => {
				logger.warning(err);
				throw err;
			});
	}

	deleteFile(userId, filename) {
		if (!userId || !filename) {
			return Promise.reject(new BadRequest('Missing parameters by deleteFile.', { userId, filename }));
		}
		return UserModel.userModel.findById(userId).exec()
			.then((result) => {
				if (!result || !result.schoolId) {
					return new NotFound('User not found');
				}
				const awsObject = createAWSObject(result.schoolId);
				const params = {
					Bucket: awsObject.bucket,
					Delete: {
						Objects: [
							{
								Key: filename,
							},
						],
						Quiet: true,
					},
				};
				return promisify(awsObject.s3.deleteObjects.bind(awsObject.s3), awsObject.s3)(params);
			});
	}

	generateSignedUrl({ userId, flatFileName, fileType }) {
		if (!userId || !flatFileName || !fileType) {
			return Promise.reject(
				new BadRequest('Missing parameters by generateSignedUrl.', { userId, flatFileName, fileType }),
			);
		}

		return UserModel.userModel.findById(userId).exec()
			.then((result) => {
				if (!result || !result.schoolId) {
					return new NotFound('User not found');
				}

				const awsObject = createAWSObject(result.schoolId);
				return this.createIfNotExists(awsObject);
			})
			.then((awsObject) => {
				const params = {
					Bucket: awsObject.bucket,
					Key: flatFileName,
					Expires: 60,
					ContentType: fileType,
				};

				return promisify(awsObject.s3.getSignedUrl.bind(awsObject.s3), awsObject.s3)('putObject', params);
			});
	}

	getSignedUrl({
		userId, flatFileName, localFileName, download, action = 'getObject',
	}) {
		if (!userId || !flatFileName) {
			return Promise.reject(new BadRequest('Missing parameters by getSignedUrl.', { userId, flatFileName }));
		}

		return UserModel.userModel.findById(userId).lean().exec().then((result) => {
			if (!result || !result.schoolId) {
				return new NotFound('User not found');
			}

			const awsObject = createAWSObject(result.schoolId);
			const params = {
				Bucket: awsObject.bucket,
				Key: flatFileName,
				Expires: 60,
			};
			const getBoolean = (value) => value === true || value === 'true';
			if (getBoolean(download)) {
				params.ResponseContentDisposition = `attachment; filename = "${localFileName.replace('"', '')}"`;
			}
			logger.info(params.ResponseContentDisposition);
			return promisify(awsObject.s3.getSignedUrl.bind(awsObject.s3), awsObject.s3)(action, params);
		});
	}

	/** ** @DEPRECATED *** */
	createDirectory(userId, path) {
		logger.warning('@deprecated');
		if (!userId || !path) {
			return Promise.reject(new BadRequest('Missing parameters by createDirectory'));
		}
		return filePermissionHelper.checkPermissions(userId, path)
			.then((res) => {
				// eslint-disable-next-line no-param-reassign
				if (path[0] === '/') path = path.substring(1);
				return UserModel.userModel.findById(userId).exec().then((result) => {
					if (!result || !result.schoolId) {
						return new NotFound('User not found');
					}

					const awsObject = createAWSObject(result.schoolId);
					const fileStream = fs.createReadStream(pathUtil.join(__dirname, '..', 'resources', '.scfake'));
					const params = {
						Bucket: awsObject.bucket,
						Key: `${path}/.scfake`,
						Body: fileStream,
						Metadata: {
							path,
							name: '.scfake',
						},
					};

					return promisify(awsObject.s3.putObject.bind(awsObject.s3), awsObject.s3)(params);
				});
			});
	}

	/** ** @DEPRECATED *** */
	deleteDirectory(userId, path) {
		logger.warning('@deprecated');
		if (!userId || !path) {
			return Promise.reject(new BadRequest('Missing parameters by deleteDirectory.'));
		}
		return filePermissionHelper.checkPermissions(userId, path)
			.then((res) => UserModel.userModel.findById(userId).exec())
			.then((result) => {
				if (!result || !result.schoolId) {
					return new NotFound('User not found');
				}
				const awsObject = createAWSObject(result.schoolId);
				const params = {
					Bucket: awsObject.bucket,
					Prefix: removeLeadingSlash(path),
				};
				return this.deleteAllInDirectory(awsObject, params);
			});
	}

	/** ** @DEPRECATED *** */
	deleteAllInDirectory(awsObject, params) {
		logger.warning('@deprecated');
		return promisify(awsObject.s3.listObjectsV2.bind(awsObject.s3), awsObject.s3)(params)
			.then((data) => {
				// there should always be at least the .scfake file
				if (data.Contents.length === 0) {
					throw new Error(`Invalid Prefix ${params.Prefix}`);
				}

				const deleteParams = { Bucket: params.Bucket, Delete: {} };
				deleteParams.Delete.Objects = data.Contents.map((c) => ({ Key: c.Key }));

				return promisify(awsObject.s3.deleteObjects.bind(awsObject.s3), awsObject.s3)(deleteParams);
			})
			.then((deletionData) => {
				// AWS S3 returns only 1000 items at once
				if (deletionData.Deleted.length === 1000) return this.deleteAllInDirectory(awsObject, params);
				return Promise.resolve(deletionData);
			});
	}
}

module.exports = AWSS3Strategy;
<|endoftext|>


<commit_before>import Light from './Light';
import LightEngine from './LightEngine';
import SceneManager from '../base/SceneManager';

import {
    SphereGeometry,
    MeshPhongMaterial,
    PointLight as THREEPointLight
} from 'three';

export default class LightPoint extends Light {

    constructor({ color, intensity, distance, position, name }) {

        super({ color, intensity, name });

        this.geometry = new SphereGeometry(
            LightEngine.holderRadius,
            LightEngine.holderSegment,
            LightEngine.holderSegment
        );
        this.material = new MeshPhongMaterial({color: this.color});
        this.mesh = new Mesh(this.geometry, this.material);
        this.light = new THREEPointLight(color, intensity, distance);

        this.mesh.mesh.add(this.light);

        SceneManager.add(this.light, this);

    }
}
<commit_msg>M-49 restored pointlight (#67)<commit_after>import Light from './Light';
import SceneManager from '../base/SceneManager';

import {
    PointLight as THREEPointLight
} from 'three';

export default class PointLight extends Light {

    constructor({ color, intensity, distance, name }) {
        super({ color, intensity, name });
        this.light = new THREEPointLight(color, intensity, distance);

        SceneManager.add(this.light, this);
    }

    addHelper() {
        this.helper = true;
        this.addHolder();
    }
}
<|endoftext|>


<commit_before>game.PlayScreen = me.ScreenObject.extend({
	init: function() {
		//TODO?
	},

	/**
	 *  action to perform on state change
	 */
	onResetEvent: function() {
		// load a level
//		me.game.world.addChild(
//		    new me.SpriteObject (
//		        0,0,
//		        me.loader.getImage('black_screen')
//		    ),
//		    1
//		);
		me.input.bindKey(me.input.KEY.LEFT, "left");
		me.input.bindKey(me.input.KEY.RIGHT, "right");
		me.input.bindKey(me.input.KEY.UP, "up");
		me.input.bindKey(me.input.KEY.DOWN, "down");

		var test = false;
		me.game.world.addChild(new me.SpriteObject(0,0, me.loader.getImage("black_Screen")));
		me.audio.stopTrack();
		me.audio.playTrack("beeline_bgm", 0.5);
		me.levelDirector.loadLevel("orthogonal");

		// reset the score
		game.data.score = 0;
		game.data.honey = 0;
		game.data.idle = 0;
		game.data.harvest = 0;
		game.data.attack = 0;

		// add our HUD to the game world
//		me.game.world.addChild(new me.SpriteObject(0,0, me.loader.getImage("hud")), 2);
		this.HUD = new game.HUD.Container();
//		me.game.world.addChild(new me.SpriteObject(0,0, me.loader.getImage("hud")), Infinity - 1);
		me.game.world.addChild(this.HUD);
		game.data.moveActive=false;

		me.input.registerPointerEvent("pointerdown", me.game.viewport, function (event) {
			var world={};
			world.x=event.gameWorldX;
			world.y=event.gameWorldY;
			game.data.move=world;
			game.data.moveActive=true;
			var layer = me.game.currentLevel.getLayerByName("fog");
			var tile = layer.getTile(world.x,world.y);
			if(tile!=null){
				//TODO:  do something with tile
				console.log("Clicked on tile "+tile.tileId);
				var tx=tile.col;
				var ty=tile.row;
				layer.clearTile(tx,ty);
			}
			return true;
		});

		me.input.registerPointerEvent("pointerup", me.game.viewport, function (event) {
			game.data.moveActive=false;
			return true;
		});

		me.input.registerPointerEvent("pointermove", me.game.viewport, function (event) {
			if(game.moveActive) {
				var world={};
				world.x=event.gameWorldX;
				world.y=event.gameWorldY;
				me.viewport.move(game.data.move.x-world.x,game.data.move.y-world.y);
				game.data.move=world;
				return true;
			}
			return false;
		});

//		me.game.HUD.Container.addChild(new me.SpriteObject(0,0, me.loader.getImage("hud")), this.z);
//		if mouse down  <--- no idea how to detect!!!
//			if mouse is moved less then threshold
//				click detected
//			else {
//				drag detected
//			}
//
//	this.handler2 = me.event.subscribe(me.input.registerPointerEvent("pointerdown", new me.Rect(new me.Vector2d(0,0), 800, 480), function () { test = true;me.audio.play("Click"); }));
//		me.input.bindKey(me.input.KEY.ENTER, "enter", true);
//		me.input.bindPointer(me.input.mouse.LEFT, me.input.KEY.ENTER);
//		this.handler = me.event.subscribe(me.event.KEYDOWN, function (action, keyCode, edge) {
//		    if (action === "enter") {
//		    	moveBox = new me.Rect(new me.Vector2d(me.input.mouse.pos.x - 20, me.input.mouse.pos.y - 20), 40, 40);
//		    	me.audio.play("Click");
//		    	while (test == true) {
//		    	me.audio.play("Bear_Harvest");
//		    		if (!moveBox.containsPoint(me.input.mouse.pos.x, me.input.mouse.pos.y)){
//		    			me.audio.play("Click");
//		    			while (me.input.isKeyPressed("enter")) {
//		    				game.PlayScreen.moveTo(me.input.mouse.pos.x, me.input.mouse.pos.y);
//		    			}
//		    			game.PlayScreen.move(me.input.mouse.pos.x, me.input.mouse.pos.y);
//		        		// play something on tap / enter
//		        		// this will unlock audio on mobile devices
//		       	 		me.audio.play("Click");
//		       		}
//		       		 //else if (creditsBox.containsPoint(me.input.mouse.pos.x, me.input.mouse.pos.y)) {
//		        	me.audio.play("Click");
//		        	me.state.change(me.state.CREDITS);
//		        } else if (instructionsBox.containsPoint(me.input.mouse.pos.x, me.input.mouse.pos.y)) {
//		        	me.audio.play("Click");
//		        	me.state.change(me.state.USER);
//
//		        }
//		    }
//		});

	},

	/**
	 *  action to perform when leaving this screen (state change)
	 */
	onDestroyEvent: function() {
		me.input.unbindKey(me.input.KEY.LEFT);
		me.input.unbindKey(me.input.KEY.RIGHT);
		me.input.unbindKey(me.input.KEY.UP);
		me.input.unbindKey(me.input.KEY.DOWN);

		me.input.releasePointerEvent("pointerdown",me.game.viewport);
		me.input.releasePointerEvent("pointermove",me.game.viewport);

	// remove the HUD from the game world
		me.game.world.removeChild(this.HUD);
		me.audio.stopTrack();
	}
});
<commit_msg>Added handler for click and drag for both fog and for background tiles. Flower tile scheduling is next.<commit_after>game.PlayScreen = me.ScreenObject.extend({
	init: function() {
		//TODO?
	},

	/**
	 *  action to perform on state change
	 */
	onResetEvent: function() {
		// load a level
//		me.game.world.addChild(
//		    new me.SpriteObject (
//		        0,0,
//		        me.loader.getImage('black_screen')
//		    ),
//		    1
//		);
		me.input.bindKey(me.input.KEY.LEFT, "left");
		me.input.bindKey(me.input.KEY.RIGHT, "right");
		me.input.bindKey(me.input.KEY.UP, "up");
		me.input.bindKey(me.input.KEY.DOWN, "down");

		var test = false;
		me.game.world.addChild(new me.SpriteObject(0,0, me.loader.getImage("black_Screen")));
		me.audio.stopTrack();
		me.audio.playTrack("beeline_bgm", 0.5);
		me.levelDirector.loadLevel("orthogonal");

		// reset the score
		game.data.score = 0;
		game.data.honey = 0;
		game.data.idle = 0;
		game.data.harvest = 0;
		game.data.attack = 0;

		// add our HUD to the game world
//		me.game.world.addChild(new me.SpriteObject(0,0, me.loader.getImage("hud")), 2);
		this.HUD = new game.HUD.Container();
//		me.game.world.addChild(new me.SpriteObject(0,0, me.loader.getImage("hud")), Infinity - 1);
		me.game.world.addChild(this.HUD);
		game.data.moveActive=false;

		me.input.registerPointerEvent("pointerdown", me.game.viewport, function (event) {
			var page={};
			page.x=event.screenX;
			page.y=event.screenY;
			game.data.move=page;
			game.data.moveActive=true;
			game.data.dragActive=false;
			return true;
		});

		me.input.registerPointerEvent("pointerup", me.game.viewport, function (event) {
			if(!game.data.dragActive) {
				var layer = me.game.currentLevel.getLayerByName("fog");
				var tile = layer.getTile(event.gameWorldX,event.gameWorldY);
				if(tile!=null){
					//TODO:  do something with tile
					console.log("Clicked on fog tile "+tile.tileId);
					var tx=tile.col;
					var ty=tile.row;
					layer.clearTile(tx,ty);
				} else {
					layer=me.game.currentLevel.getLayerByName("background");
					tile=layer.getTile(event.gameWorldX,event.gameWorldY);
					if(tile!=null) {
						var tx=tile.col;
						var ty=tile.row;
						console.log("Clicked on tileId "+tile.tileId+" @ "+tile.col+", "+tile.row);
						//if(tile.tileId>=
						//layer.setTile(tx,ty,tileId);
					}
				}
			}

			game.data.moveActive=false;
			game.data.dragActive=false;

			return true;
		});

		me.input.registerPointerEvent("pointermove", me.game.viewport, function (event) {
			if(game.data.moveActive) {
				var page={};
				page.x=event.screenX;
				page.y=event.screenY;
				me.game.viewport.move(game.data.move.x-page.x,game.data.move.y-page.y);
				game.data.move=page;
				game.data.dragActive=true;
				return true;
			}
			return false;
		});

//		me.game.HUD.Container.addChild(new me.SpriteObject(0,0, me.loader.getImage("hud")), this.z);
//		if mouse down  <--- no idea how to detect!!!
//			if mouse is moved less then threshold
//				click detected
//			else {
//				drag detected
//			}
//
//	this.handler2 = me.event.subscribe(me.input.registerPointerEvent("pointerdown", new me.Rect(new me.Vector2d(0,0), 800, 480), function () { test = true;me.audio.play("Click"); }));
//		me.input.bindKey(me.input.KEY.ENTER, "enter", true);
//		me.input.bindPointer(me.input.mouse.LEFT, me.input.KEY.ENTER);
//		this.handler = me.event.subscribe(me.event.KEYDOWN, function (action, keyCode, edge) {
//		    if (action === "enter") {
//		    	moveBox = new me.Rect(new me.Vector2d(me.input.mouse.pos.x - 20, me.input.mouse.pos.y - 20), 40, 40);
//		    	me.audio.play("Click");
//		    	while (test == true) {
//		    	me.audio.play("Bear_Harvest");
//		    		if (!moveBox.containsPoint(me.input.mouse.pos.x, me.input.mouse.pos.y)){
//		    			me.audio.play("Click");
//		    			while (me.input.isKeyPressed("enter")) {
//		    				game.PlayScreen.moveTo(me.input.mouse.pos.x, me.input.mouse.pos.y);
//		    			}
//		    			game.PlayScreen.move(me.input.mouse.pos.x, me.input.mouse.pos.y);
//		        		// play something on tap / enter
//		        		// this will unlock audio on mobile devices
//		       	 		me.audio.play("Click");
//		       		}
//		       		 //else if (creditsBox.containsPoint(me.input.mouse.pos.x, me.input.mouse.pos.y)) {
//		        	me.audio.play("Click");
//		        	me.state.change(me.state.CREDITS);
//		        } else if (instructionsBox.containsPoint(me.input.mouse.pos.x, me.input.mouse.pos.y)) {
//		        	me.audio.play("Click");
//		        	me.state.change(me.state.USER);
//
//		        }
//		    }
//		});

	},

	/**
	 *  action to perform when leaving this screen (state change)
	 */
	onDestroyEvent: function() {
		me.input.unbindKey(me.input.KEY.LEFT);
		me.input.unbindKey(me.input.KEY.RIGHT);
		me.input.unbindKey(me.input.KEY.UP);
		me.input.unbindKey(me.input.KEY.DOWN);

		me.input.releasePointerEvent("pointerdown",me.game.viewport);
		me.input.releasePointerEvent("pointermove",me.game.viewport);

	// remove the HUD from the game world
		me.game.world.removeChild(this.HUD);
		me.audio.stopTrack();
	}
});
<|endoftext|>


<commit_before>/*
==================================================================================================
  Core - JavaScript Foundation
  Copyright 2012-2013 Sebastian Werner
==================================================================================================
*/

core.Class("core.mvc.view.Dom",
{
  include : [core.mvc.view.Abstract],
  implement : [core.mvc.view.IView],

  construct: function(presenter) {
    core.mvc.view.Abstract.call(this, presenter);
  },

  properties :
  {
    /** Instance of compiled template to produce final data / text for output e.g. HTML, JSON, ... */
    template :
    {
      type: core.template.Template,
      nullable : true,
      apply : function() {
        this.render();
      }
    },

    /** The root element to render into */
    root :
    {
      type: "Node",
      nullable : true,
      apply : function(value, old) {
        this.render();
      }
    }
  },

  events :
  {
    render : core.event.Simple

  },

  members :
  {
    // Interface implementation
    render : function()
    {
      if (this.__renderScheduled != null) {
        return;
      }

      /** #require(ext.RequestAnimationFrame) */
      this.__renderScheduled = requestAnimationFrame(core.util.Function.bind(this.__renderRequest, this));
    },

    __renderRequest : function()
    {
      if (this._shouldRender())
      {
        this.__render();
        this.__renderScheduled = null;
      }
      else
      {
        this.__renderScheduled = requestAnimationFrame(core.util.Function.bind(this.__renderRequest, this));
      }
    },

    /**
     * Internal render method which is called in buffered mode
     * so that only one rendering happens per frame.
     */
    __render : function()
    {
      var presenter = this.getPresenter();
      if (!presenter) {
        return;
      }

      var elem = this.getRoot();
      if (!elem) {
        return;
      }

      var template = this.getTemplate();
      if (!template) {
        return;
      }

      this._beforeRender();
      elem.innerHTML = template.render(presenter);
      this._afterRender();

      // Let others know
      this.fireEvent("render");
    },

    _shouldRender : function() {
      return this.__isLoading == 0;
    },

    _beforeRender : function() {
      // placeholder
    },

    _afterRender : function() {
      // placeholder
    },

    // Interface implementation
    show : function()
    {
      var elem = this.getRoot();
      if (!elem) {
        return;
      }

      elem.style.display = "";
      this.fireEvent("show");
    },

    // Interface implementation
    hide : function()
    {
      var elem = this.getRoot();
      if (!elem) {
        return;
      }

      elem.style.display = "none";
      this.fireEvent("hide");
    },

    __isLoading : 0,

    /**
     * Loads the given @tmpl {Uri} via the text loader (XHR) and creates
     * a new template instance which is auto applied to the #text property afterwards.
     */
    loadTemplate : function(tmpl, nocache)
    {
      this.__isLoading++;
      core.io.Text.load(jasy.Asset.toUri(tmpl), this.__loadTemplateCallback, this, nocache);
    },

    __loadTemplateCallback : function(uri, errornous, data)
    {
      this.__isLoading--;

      if (errornous) {
        throw new Error("Could not load template: " + uri + "!");
      }

      this.setTemplate(core.template.Compiler.compile(data.text));
    },

    loadStyleSheet : function(sheet, nocache)
    {
      this.__isLoading++;
      core.io.StyleSheet.load(jasy.Asset.toUri(sheet), this.__loadStyleSheetCallback, this, nocache);
    },

    __loadStyleSheetCallback : function(uri, errornous)
    {
      this.__isLoading--;

      if (errornous) {
        throw new Error("Could not load style sheet: " + uri + "!");
      }
    }
  }
});
<commit_msg>Auto-root setup for DOM views<commit_after>/*
==================================================================================================
  Core - JavaScript Foundation
  Copyright 2012-2013 Sebastian Werner
==================================================================================================
*/

core.Class("core.mvc.view.Dom",
{
  include : [core.mvc.view.Abstract],
  implement : [core.mvc.view.IView],

  construct: function(presenter, root)
  {
    core.mvc.view.Abstract.call(this, presenter);

    if (root != null)
    {
      if (jasy.Env.isSet("debug")) {
        core.Assert.isType(root, "Node", "Invalid root node!");
      }

      this.setRoot(root);
    }
  },

  properties :
  {
    /** Instance of compiled template to produce final data / text for output e.g. HTML, JSON, ... */
    template :
    {
      type: core.template.Template,
      nullable : true,
      apply : function() {
        this.render();
      }
    },

    /** The root element to render into */
    root :
    {
      type: "Node",
      nullable : true,
      apply : function(value, old) {
        this.render();
      }
    }
  },

  events :
  {
    render : core.event.Simple

  },

  members :
  {
    // Interface implementation
    render : function()
    {
      if (this.__renderScheduled != null) {
        return;
      }

      /** #require(ext.RequestAnimationFrame) */
      this.__renderScheduled = requestAnimationFrame(core.util.Function.bind(this.__renderRequest, this));
    },

    __renderRequest : function()
    {
      if (this._shouldRender())
      {
        this.__render();
        this.__renderScheduled = null;
      }
      else
      {
        this.__renderScheduled = requestAnimationFrame(core.util.Function.bind(this.__renderRequest, this));
      }
    },

    /**
     * Internal render method which is called in buffered mode
     * so that only one rendering happens per frame.
     */
    __render : function()
    {
      var presenter = this.getPresenter();
      if (!presenter) {
        return;
      }

      var elem = this.getRoot();
      if (!elem) {
        return;
      }

      var template = this.getTemplate();
      if (!template) {
        return;
      }

      this._beforeRender();
      elem.innerHTML = template.render(presenter);
      this._afterRender();

      // Let others know
      this.fireEvent("render");
    },

    _shouldRender : function() {
      return this.__isLoading == 0;
    },

    _beforeRender : function() {
      // placeholder
    },

    _afterRender : function() {
      // placeholder
    },

    // Interface implementation
    show : function()
    {
      var elem = this.getRoot();
      if (!elem) {
        return;
      }

      elem.style.display = "";
      this.fireEvent("show");
    },

    // Interface implementation
    hide : function()
    {
      var elem = this.getRoot();
      if (!elem) {
        return;
      }

      elem.style.display = "none";
      this.fireEvent("hide");
    },

    __isLoading : 0,

    /**
     * Loads the given @tmpl {Uri} via the text loader (XHR) and creates
     * a new template instance which is auto applied to the #text property afterwards.
     */
    loadTemplate : function(tmpl, nocache)
    {
      this.__isLoading++;
      core.io.Text.load(jasy.Asset.toUri(tmpl), this.__loadTemplateCallback, this, nocache);
    },

    __loadTemplateCallback : function(uri, errornous, data)
    {
      this.__isLoading--;

      if (errornous) {
        throw new Error("Could not load template: " + uri + "!");
      }

      this.setTemplate(core.template.Compiler.compile(data.text));
    },

    loadStyleSheet : function(sheet, nocache)
    {
      this.__isLoading++;
      core.io.StyleSheet.load(jasy.Asset.toUri(sheet), this.__loadStyleSheetCallback, this, nocache);
    },

    __loadStyleSheetCallback : function(uri, errornous)
    {
      this.__isLoading--;

      if (errornous) {
        throw new Error("Could not load style sheet: " + uri + "!");
      }
    }
  }
});
<|endoftext|>


<commit_before>'use strict';

process.env.NODE_ENV = 'production'; // Drastically increase performances

const path     = require('path');
const os       = require('os');
const electron = require('electron');

const IpcManager         = require('./ipc');             // Manages IPC evens
const TrayManager        = require('./tray');            // Manages Tray
const ConfigManager      = require('./config');          // Handles config
const PowerMonitor       = require('./power-monitor');   // Handle power events
const IntegrationManager = require('./integration');     // Applies various integrations

const app           = electron.app;              // Module to control application life.
const nativeImage   = electron.nativeImage;
const BrowserWindow = electron.BrowserWindow;    // Module to create native browser window.

const appRoot = path.resolve(__dirname, '../..'); // app/ directory
const srcPath = path.join(appRoot, 'src'); // app/src/ directory

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the javascript object is GCed.
let mainWindow = null;

// Quit when all windows are closed
app.on('window-all-closed', () => {
    if (process.platform !== 'darwin')
        app.quit();
});

// This method will be called when Electron has done everything
// initialization and ready for creating browser windows.
app.on('ready', () => {

    const configManager = new ConfigManager(app);
    const { bounds, useNativeFrame } = configManager.getConfig();

    const logosPath = path.join(appRoot, 'src', 'images', 'logos');
    const museeksIcons = {
        '256': nativeImage.createFromPath(path.join(logosPath, 'museeks.png')),
        '128': nativeImage.createFromPath(path.join(logosPath, 'museeks-128.png')),
        '64': nativeImage.createFromPath(path.join(logosPath, 'museeks-64.png')),
        '48': nativeImage.createFromPath(path.join(logosPath, 'museeks-48.png')),
        '32': nativeImage.createFromPath(path.join(logosPath, 'museeks-32.png')),
        'ico': nativeImage.createFromPath(path.join(logosPath, 'museeks.ico')),
        'tray': nativeImage.createFromPath(path.join(logosPath, 'museeks-tray.png')),
        'tray-ico': nativeImage.createFromPath(path.join(logosPath, 'museeks-tray.png'))
    };

    // Browser Window options
    const mainWindowOption = {
        title     : 'Museeks',
        icon      :  os.platform() === 'win32' ? museeksIcons['ico'] : museeksIcons['256'],
        x         :  bounds.x,
        y         :  bounds.y,
        width     :  bounds.width,
        height    :  bounds.height,
        minWidth  :  900,
        minHeight :  550,
        frame     :  useNativeFrame,
        show      :  false
    };

    // Create the browser window
    mainWindow = new BrowserWindow(mainWindowOption);

    // ... and load our html page
    mainWindow.loadURL(`file://${srcPath}/app.html#/library`);

    mainWindow.on('closed', () => {
        // Dereference the window object
        mainWindow = null;
    });

    mainWindow.on('ready-to-show', () => {
        mainWindow.show();
    });

    // IPC events
    const ipcManager = new IpcManager(mainWindow);
    ipcManager.bindEvents();

    // Power monitor
    const powerMonitor = new PowerMonitor(mainWindow);
    powerMonitor.enable();

    // Tray manager
    const trayIcon = os.platform() === 'win32' ? museeksIcons['tray-ico'] : museeksIcons['tray'];
    const trayManager = new TrayManager(mainWindow, trayIcon);
    trayManager.bindEvents();

    // integrations
    const integrations = new IntegrationManager(mainWindow);
    integrations.enable();
});
<commit_msg>Fix tray dimensions on Mac and some Linux distributions<commit_after>'use strict';

process.env.NODE_ENV = 'production'; // Drastically increase performances

const path     = require('path');
const os       = require('os');
const electron = require('electron');

const IpcManager         = require('./ipc');             // Manages IPC evens
const TrayManager        = require('./tray');            // Manages Tray
const ConfigManager      = require('./config');          // Handles config
const PowerMonitor       = require('./power-monitor');   // Handle power events
const IntegrationManager = require('./integration');     // Applies various integrations

const app           = electron.app;              // Module to control application life.
const nativeImage   = electron.nativeImage;
const BrowserWindow = electron.BrowserWindow;    // Module to create native browser window.

const appRoot = path.resolve(__dirname, '../..'); // app/ directory
const srcPath = path.join(appRoot, 'src'); // app/src/ directory

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the javascript object is GCed.
let mainWindow = null;

// Quit when all windows are closed
app.on('window-all-closed', () => {
    if (process.platform !== 'darwin')
        app.quit();
});

// This method will be called when Electron has done everything
// initialization and ready for creating browser windows.
app.on('ready', () => {

    const configManager = new ConfigManager(app);
    const { bounds, useNativeFrame } = configManager.getConfig();

    const logosPath = path.join(appRoot, 'src', 'images', 'logos');
    const museeksIcons = {
        '256': nativeImage.createFromPath(path.join(logosPath, 'museeks.png')),
        '128': nativeImage.createFromPath(path.join(logosPath, 'museeks-128.png')),
        '64': nativeImage.createFromPath(path.join(logosPath, 'museeks-64.png')),
        '48': nativeImage.createFromPath(path.join(logosPath, 'museeks-48.png')),
        '32': nativeImage.createFromPath(path.join(logosPath, 'museeks-32.png')),
        'ico': nativeImage.createFromPath(path.join(logosPath, 'museeks.ico')),
        'tray': nativeImage.createFromPath(path.join(logosPath, 'museeks-tray.png')).resize({ width: 24, height: 24 }),
        'tray-ico': nativeImage.createFromPath(path.join(logosPath, 'museeks-tray.ico'))
    };

    // Browser Window options
    const mainWindowOption = {
        title     : 'Museeks',
        icon      :  os.platform() === 'win32' ? museeksIcons['ico'] : museeksIcons['256'],
        x         :  bounds.x,
        y         :  bounds.y,
        width     :  bounds.width,
        height    :  bounds.height,
        minWidth  :  900,
        minHeight :  550,
        frame     :  useNativeFrame,
        show      :  false
    };

    // Create the browser window
    mainWindow = new BrowserWindow(mainWindowOption);

    // ... and load our html page
    mainWindow.loadURL(`file://${srcPath}/app.html#/library`);

    mainWindow.on('closed', () => {
        // Dereference the window object
        mainWindow = null;
    });

    mainWindow.on('ready-to-show', () => {
        mainWindow.show();
    });

    // IPC events
    const ipcManager = new IpcManager(mainWindow);
    ipcManager.bindEvents();

    // Power monitor
    const powerMonitor = new PowerMonitor(mainWindow);
    powerMonitor.enable();

    // Tray manager
    const trayIcon = os.platform() === 'win32' ? museeksIcons['tray-ico'] : museeksIcons['tray'];
    const trayManager = new TrayManager(mainWindow, trayIcon);
    trayManager.bindEvents();

    // integrations
    const integrations = new IntegrationManager(mainWindow);
    integrations.enable();
});
<|endoftext|>


<commit_before>'use strict'

const t = require('tap')
const test = t.test
const request = require('request')
const Bluebird = require('bluebird')
const fastify = require('..')()

const opts = {
  schema: {
    response: {
      '2xx': {
        type: 'object',
        properties: {
          hello: {
            type: 'string'
          }
        }
      }
    }
  }
}

test('shorthand - promise es6 get', t => {
  t.plan(1)
  try {
    fastify.get('/', opts, function (req, reply) {
      const promise = new Promise((resolve, reject) => {
        resolve({ hello: 'world' })
      })
      reply.header('content-type', 'application/json').code(200).send(promise)
    })
    t.pass()
  } catch (e) {
    t.fail()
  }
})

test('shorthand - return promise es6 get', t => {
  t.plan(1)
  try {
    fastify.get('/return', opts, function (req, reply) {
      const promise = new Promise((resolve, reject) => {
        resolve({ hello: 'world' })
      })
      return promise
    })
    t.pass()
  } catch (e) {
    t.fail()
  }
})

test('shorthand - promise es6 get error', t => {
  t.plan(1)
  try {
    fastify.get('/error', opts, function (req, reply) {
      const promise = new Promise((resolve, reject) => {
        reject(new Error('some error'))
      })
      reply.send(promise)
    })
    t.pass()
  } catch (e) {
    t.fail()
  }
})

test('shorthand - promise bluebird get', t => {
  t.plan(1)
  try {
    fastify.get('/bluebird', opts, function (req, reply) {
      const promise = new Bluebird((resolve, reject) => {
        resolve({ hello: 'world' })
      })
      reply.header('content-type', 'application/json').code(200).send(promise)
    })
    t.pass()
  } catch (e) {
    t.fail()
  }
})

test('shorthand - promise bluebird get error', t => {
  t.plan(1)
  try {
    fastify.get('/bluebird-error', opts, function (req, reply) {
      const promise = new Bluebird((resolve, reject) => {
        reject(new Error('some error'))
      })
      reply.send(promise)
    })
    t.pass()
  } catch (e) {
    t.fail()
  }
})

fastify.listen(0, err => {
  t.error(err)
  fastify.server.unref()

  test('shorthand - request promise es6 get', t => {
    t.plan(4)
    request({
      method: 'GET',
      uri: 'http://localhost:' + fastify.server.address().port
    }, (err, response, body) => {
      t.error(err)
      t.strictEqual(response.statusCode, 200)
      t.strictEqual(response.headers['content-length'], '' + body.length)
      t.deepEqual(JSON.parse(body), { hello: 'world' })
    })
  })

  test('shorthand - request return promise es6 get', t => {
    t.plan(4)
    request({
      method: 'GET',
      uri: 'http://localhost:' + fastify.server.address().port + '/return'
    }, (err, response, body) => {
      t.error(err)
      t.strictEqual(response.statusCode, 200)
      t.strictEqual(response.headers['content-length'], '' + body.length)
      t.deepEqual(JSON.parse(body), { hello: 'world' })
    })
  })

  test('shorthand - request promise es6 get error', t => {
    t.plan(2)
    request({
      method: 'GET',
      uri: 'http://localhost:' + fastify.server.address().port + '/error'
    }, (err, response, body) => {
      t.error(err)
      t.strictEqual(response.statusCode, 500)
    })
  })

  test('shorthand - request promise bluebird get', t => {
    t.plan(4)
    request({
      method: 'GET',
      uri: 'http://localhost:' + fastify.server.address().port + '/bluebird'
    }, (err, response, body) => {
      t.error(err)
      t.strictEqual(response.statusCode, 200)
      t.strictEqual(response.headers['content-length'], '' + body.length)
      t.deepEqual(JSON.parse(body), { hello: 'world' })
    })
  })

  test('shorthand - request promise bluebird get error', t => {
    t.plan(2)
    request({
      method: 'GET',
      uri: 'http://localhost:' + fastify.server.address().port + '/bluebird-error'
    }, (err, response, body) => {
      t.error(err)
      t.strictEqual(response.statusCode, 500)
    })
  })

  test('request promise double send', t => {
    t.plan(3)
    fastify.get('/kaboom', function (req, reply) {
      setTimeout(function () {
        // this should not throw
        reply.send(Promise.resolve({ hello: 'world' }))
      }, 20)
      return Promise.resolve({ hello: '42' })
    })

    request({
      method: 'GET',
      uri: 'http://localhost:' + fastify.server.address().port + '/kaboom'
    }, (err, response, body) => {
      t.error(err)
      t.strictEqual(response.statusCode, 200)
      t.deepEqual(JSON.parse(body), { hello: '42' })
    })
  })
})
<commit_msg>Add one more test to cover when a promise rejects<commit_after>'use strict'

const t = require('tap')
const test = t.test
const request = require('request')
const Bluebird = require('bluebird')
const fastify = require('..')()

const opts = {
  schema: {
    response: {
      '2xx': {
        type: 'object',
        properties: {
          hello: {
            type: 'string'
          }
        }
      }
    }
  }
}

test('shorthand - promise es6 get', t => {
  t.plan(1)
  try {
    fastify.get('/', opts, function (req, reply) {
      const promise = new Promise((resolve, reject) => {
        resolve({ hello: 'world' })
      })
      reply.header('content-type', 'application/json').code(200).send(promise)
    })
    t.pass()
  } catch (e) {
    t.fail()
  }
})

test('shorthand - return promise es6 get', t => {
  t.plan(1)
  try {
    fastify.get('/return', opts, function (req, reply) {
      const promise = new Promise((resolve, reject) => {
        resolve({ hello: 'world' })
      })
      return promise
    })
    t.pass()
  } catch (e) {
    t.fail()
  }
})

test('shorthand - return promise es6 get error', t => {
  t.plan(1)
  try {
    fastify.get('/return-error', opts, function (req, reply) {
      const promise = new Promise((resolve, reject) => {
        reject(new Error('some error'))
      })
      return promise
    })
    t.pass()
  } catch (e) {
    t.fail()
  }
})

test('shorthand - promise es6 get error', t => {
  t.plan(1)
  try {
    fastify.get('/error', opts, function (req, reply) {
      const promise = new Promise((resolve, reject) => {
        reject(new Error('some error'))
      })
      reply.send(promise)
    })
    t.pass()
  } catch (e) {
    t.fail()
  }
})

test('shorthand - promise bluebird get', t => {
  t.plan(1)
  try {
    fastify.get('/bluebird', opts, function (req, reply) {
      const promise = new Bluebird((resolve, reject) => {
        resolve({ hello: 'world' })
      })
      reply.header('content-type', 'application/json').code(200).send(promise)
    })
    t.pass()
  } catch (e) {
    t.fail()
  }
})

test('shorthand - promise bluebird get error', t => {
  t.plan(1)
  try {
    fastify.get('/bluebird-error', opts, function (req, reply) {
      const promise = new Bluebird((resolve, reject) => {
        reject(new Error('some error'))
      })
      reply.send(promise)
    })
    t.pass()
  } catch (e) {
    t.fail()
  }
})

fastify.listen(0, err => {
  t.error(err)
  fastify.server.unref()

  test('shorthand - request promise es6 get', t => {
    t.plan(4)
    request({
      method: 'GET',
      uri: 'http://localhost:' + fastify.server.address().port
    }, (err, response, body) => {
      t.error(err)
      t.strictEqual(response.statusCode, 200)
      t.strictEqual(response.headers['content-length'], '' + body.length)
      t.deepEqual(JSON.parse(body), { hello: 'world' })
    })
  })

  test('shorthand - request return promise es6 get', t => {
    t.plan(4)
    request({
      method: 'GET',
      uri: 'http://localhost:' + fastify.server.address().port + '/return'
    }, (err, response, body) => {
      t.error(err)
      t.strictEqual(response.statusCode, 200)
      t.strictEqual(response.headers['content-length'], '' + body.length)
      t.deepEqual(JSON.parse(body), { hello: 'world' })
    })
  })

  test('shorthand - request promise es6 get error', t => {
    t.plan(2)
    request({
      method: 'GET',
      uri: 'http://localhost:' + fastify.server.address().port + '/error'
    }, (err, response, body) => {
      t.error(err)
      t.strictEqual(response.statusCode, 500)
    })
  })

  test('shorthand - request promise es6 get return error', t => {
    t.plan(2)
    request({
      method: 'GET',
      uri: 'http://localhost:' + fastify.server.address().port + '/return-error'
    }, (err, response, body) => {
      t.error(err)
      t.strictEqual(response.statusCode, 500)
    })
  })

  test('shorthand - request promise bluebird get', t => {
    t.plan(4)
    request({
      method: 'GET',
      uri: 'http://localhost:' + fastify.server.address().port + '/bluebird'
    }, (err, response, body) => {
      t.error(err)
      t.strictEqual(response.statusCode, 200)
      t.strictEqual(response.headers['content-length'], '' + body.length)
      t.deepEqual(JSON.parse(body), { hello: 'world' })
    })
  })

  test('shorthand - request promise bluebird get error', t => {
    t.plan(2)
    request({
      method: 'GET',
      uri: 'http://localhost:' + fastify.server.address().port + '/bluebird-error'
    }, (err, response, body) => {
      t.error(err)
      t.strictEqual(response.statusCode, 500)
    })
  })

  test('request promise double send', t => {
    t.plan(3)
    fastify.get('/kaboom', function (req, reply) {
      setTimeout(function () {
        // this should not throw
        reply.send(Promise.resolve({ hello: 'world' }))
      }, 20)
      return Promise.resolve({ hello: '42' })
    })

    request({
      method: 'GET',
      uri: 'http://localhost:' + fastify.server.address().port + '/kaboom'
    }, (err, response, body) => {
      t.error(err)
      t.strictEqual(response.statusCode, 200)
      t.deepEqual(JSON.parse(body), { hello: '42' })
    })
  })
})
<|endoftext|>


<commit_before>// @flow

import {Platform} from 'react-native'

export const aqua = '#7FDBFF'
export const black = '#111111'
export const blue = '#0074D9'
export const fuchsia = '#F012BE'
export const gray = '#AAAAAA'
export const green = '#2ECC40'
// export const lime = '#01FF70'
// export const maroon = '#85144b'
export const navy = '#001f3f'
// export const olive = '#3D9970'
export const orange = '#FF851B'
export const purple = '#B10DC9'
export const red = '#FF4136'
export const silver = '#DDDDDD'
// export const teal = '#39CCCC'
export const white = '#FFFFFF'
export const yellow = '#FFDC00'
export const transparent = 'transparent'

export const iosGray = silver

export const androidLightBackground = 'rgb(244, 244, 244)'
export const androidSeparator = 'rgb(224, 224, 224)'
export const androidDisabledIcon = 'rgb(224, 224, 224)'
export const androidTextColor = 'rgb(113, 113, 118)'
export const androidTabAccentColor = '#ffeb3b'

export const iosLightBackground = 'rgb(240, 239, 245)'
export const iosSeparator = '#C8C7CC'
export const iosLightBorder = iosSeparator
export const iosDisabledText = 'rgb(142, 142, 147)'
export const iosText = iosSeparator
export const iosNavbarBottomBorder = iosSeparator
export const iosListSectionHeader = 'rgb(248, 248, 248)'
export const iosPlaceholderText = iosSeparator
export const iosHeaderTopBorder = iosSeparator
export const iosHeaderBottomBorder = 'rgb(224, 224, 224)'

export const sectionBgColor =
	Platform.OS === 'ios' ? iosLightBackground : androidLightBackground

export const tableviewAccessoryColor = 'rgb(0, 122, 255)'

export const semitransparentGray = 'rgba(0,0,0,0.2)'

// MARK: Oleville colors
export const theLatest = '#00BFFF'
export const olevilleGold = '#ffc107'
export const darkGold = '#c79100'
export const olevilleBackground = '#F0F0E1'

// MARK: KSTO Colors
export const kstoPrimaryLight = '#c5c5e8'
export const kstoSecondaryLight = '#7789bb'
export const kstoPrimaryDark = '#686ea1'
export const kstoSecondaryDark = '#4c4f71'
export const kstoTextLight = '#dcdde5'
export const kstoTextDark = '#bebad4'

// MARK: System Colors
export const infoBlue = 'rgb(47, 112, 225)'
export const success = 'rgb(83, 215, 106)'
export const warning = 'rgb(221, 170, 59)'
export const danger = 'rgb(229, 0, 15)'

// MARK: Whites
export const antiqueWhite = 'rgb(250, 235, 215)'
export const oldLace = 'rgb(253, 245, 230)'
export const ivory = 'rgb(255, 255, 240)'
export const seashell = 'rgb(255, 245, 238)'
export const ghostWhite = 'rgb(248, 248, 255)'
export const snow = 'rgb(255, 250, 250)'
export const linen = 'rgb(250, 240, 230)'

// MARK: Grays
export const black25Percent = 'rgb(63.75, 63.75, 63.75)'
export const black50Percent = 'rgb(127.5, 127.5, 127.5)'
export const black75Percent = 'rgb(191.25, 191.25, 191.25)'
export const warmGray = 'rgb(133, 117, 112)'
export const coolGray = 'rgb(118, 122, 133)'
export const charcoal = 'rgb(34, 34, 34)'

// MARK: Blues
export const teal = 'rgb(28, 160, 170)'
export const steelBlue = 'rgb(103, 153, 170)'
export const robinEgg = 'rgb(141, 218, 247)'
export const pastelBlue = 'rgb(99, 161, 247)'
export const turquoise = 'rgb(112, 219, 219)'
export const skyBlue = 'rgb(0, 178, 238)'
export const indigo = 'rgb(13, 79, 139)'
export const denim = 'rgb(67, 114, 170)'
export const blueberry = 'rgb(89, 113, 173)'
export const cornflower = 'rgb(100, 149, 237)'
export const babyBlue = 'rgb(190, 220, 230)'
export const midnightBlue = 'rgb(13, 26, 35)'
export const fadedBlue = 'rgb(23, 137, 155)'
export const iceberg = 'rgb(200, 213, 219)'
export const wave = 'rgb(102, 169, 251)'

// MARK: Greens
export const emerald = 'rgb(1, 152, 117)'
export const grass = 'rgb(99, 214, 74)'
export const pastelGreen = 'rgb(126, 242, 124)'
export const seafoam = 'rgb(77, 226, 140)'
export const paleGreen = 'rgb(176, 226, 172)'
export const cactusGreen = 'rgb(99, 111, 87)'
export const chartreuse = 'rgb(69, 139, 0)'
export const hollyGreen = 'rgb(32, 87, 14)'
export const olive = 'rgb(91, 114, 34)'
export const oliveDrab = 'rgb(107, 142, 35)'
export const moneyGreen = 'rgb(134, 198, 124)'
export const honeydew = 'rgb(216, 255, 231)'
export const lime = 'rgb(56, 237, 56)'
export const cardTable = 'rgb(87, 121, 107)'

// MARK: Reds
export const salmon = 'rgb(233, 87, 95)'
export const brickRed = 'rgb(151, 27, 16)'
export const easterPink = 'rgb(241, 167, 162)'
export const grapefruit = 'rgb(228, 31, 54)'
export const pink = 'rgb(255, 95, 154)'
export const indianRed = 'rgb(205, 92, 92)'
export const strawberry = 'rgb(190, 38, 37)'
export const coral = 'rgb(240, 128, 128)'
export const maroon = 'rgb(80, 4, 28)'
export const watermelon = 'rgb(242, 71, 63)'
export const tomato = 'rgb(255, 99, 71)'
export const pinkLipstick = 'rgb(255, 105, 180)'
export const paleRose = 'rgb(255, 228, 225)'
export const crimson = 'rgb(187, 18, 36)'

// MARK: Purples
export const eggplant = 'rgb(105, 5, 98)'
export const pastelPurple = 'rgb(207, 100, 235)'
export const palePurple = 'rgb(229, 180, 235)'
export const coolPurple = 'rgb(140, 93, 228)'
export const violet = 'rgb(191, 95, 255)'
export const plum = 'rgb(139, 102, 139)'
export const lavender = 'rgb(204, 153, 204)'
export const raspberry = 'rgb(135, 38, 87)'
export const fuschia = 'rgb(255, 20, 147)'
export const grape = 'rgb(54, 11, 88)'
export const periwinkle = 'rgb(135, 159, 237)'
export const orchid = 'rgb(218, 112, 214)'

// MARK: Yellows
export const goldenrod = 'rgb(215, 170, 51)'
export const yellowGreen = 'rgb(192, 242, 39)'
export const banana = 'rgb(229, 227, 58)'
export const mustard = 'rgb(205, 171, 45)'
export const buttermilk = 'rgb(254, 241, 181)'
export const gold = 'rgb(139, 117, 18)'
export const cream = 'rgb(240, 226, 187)'
export const lightCream = 'rgb(240, 238, 215)'
export const wheat = 'rgb(240, 238, 215)'
export const beige = 'rgb(245, 245, 220)'

// MARK: Oranges
export const peach = 'rgb(242, 187, 97)'
export const burntOrange = 'rgb(184, 102, 37)'
export const pastelOrange = 'rgb(248, 197, 143)'
export const cantaloupe = 'rgb(250, 154, 79)'
export const carrot = 'rgb(237, 145, 33)'
export const mandarin = 'rgb(247, 145, 55)'

// MARK: Browns
export const chiliPowder = 'rgb(199, 63, 23)'
export const burntSienna = 'rgb(138, 54, 15)'
export const chocolate = 'rgb(94, 38, 5)'
export const coffee = 'rgb(141, 60, 15)'
export const cinnamon = 'rgb(123, 63, 9)'
export const almond = 'rgb(196, 142, 72)'
export const eggshell = 'rgb(252, 230, 201)'
export const sand = 'rgb(222, 182, 151)'
export const mud = 'rgb(70, 45, 29)'
export const sienna = 'rgb(160, 82, 45)'
export const dust = 'rgb(236, 214, 197)'

export const tint = mandarin

// MARK: gradients
export const redToPurple = ['rgb(249,64,77)', 'rgb(217,37,111)']
export const orangeToRed = ['rgb(250,120,37)', 'rgb(242,38,83)']
export const yellowToGoldDark = ['rgb(234,185,29)', 'rgb(226,123,19)']
export const yellowToGoldLight = ['rgb(238,209,0)', 'rgb(237,158,0)']
export const grassToLime = ['rgb(125,209,24)', 'rgb(88,186,34)']
export const seafoamToGrass = ['rgb(15,201,121)', 'rgb(58,181,42)']
export const tealToSeafoam = ['rgb(3,220,156)', 'rgb(19,188,156)']
export const lightBlueToBlueLight = ['rgb(1,194,199)', 'rgb(10,158,196)']
export const lightBlueToBlueDark = ['rgb(5,187,219)', 'rgb(25,145,234)']
export const darkBlueToIndigo = ['rgb(48,112,228)', 'rgb(95,72,229)']
export const purpleToIndigo = ['rgb(129,88,252)', 'rgb(92,80,236)']
export const magentaToPurple = ['rgb(213,69,196)', 'rgb(160,50,230)']
export const pinkToHotpink = ['rgb(248,102,149)', 'rgb(209,44,159)']
export const grayToDarkGray = ['rgb(118,134,157)', 'rgb(85,96,124)']
export const navyToNavy = ['rgb(32,67,107)', 'rgb(0,48,104)']

// MARK: homescreen button foregrounds
export const homescreenForegroundLight = 'rgba(255, 255, 255, 0.9)'
export const homescreenForegroundDark = 'rgba(0, 0, 0, 0.65)'

// MARK: St. Olaf colors
export const sto = {
	black: '#242121',
	darkGray: '#53585A',
	mediumGray: '#E0DAD6',
	lightGray: '#F7F5F2',
	gold: '#E3A025',
	lightGold: '#F7C55A',
	cranberry: '#B11556',
	lime: '#A3D65C',
	orange: '#FA8D29',
	red: '#E84A36',
	lightBlue: '#83DBE0',
	blue: '#00ADD9',
	teal: '#00827E',
	purple: '#6E3A5D',
	navy: '#233746',
	mint: '#CFE1D7',
}

export const stoText = {
	black: white,
	darkGray: white,
	mediumGray: black,
	lightGray: black,
	gold: black,
	lightGold: black,
	cranberry: white,
	lime: black,
	orange: black,
	red: transparent,
	lightBlue: black,
	blue: black,
	teal: white,
	purple: white,
	navy: white,
	mint: black,
}
<commit_msg>Capitalize olevilleGold :moneybag:<commit_after>// @flow

import {Platform} from 'react-native'

export const aqua = '#7FDBFF'
export const black = '#111111'
export const blue = '#0074D9'
export const fuchsia = '#F012BE'
export const gray = '#AAAAAA'
export const green = '#2ECC40'
// export const lime = '#01FF70'
// export const maroon = '#85144b'
export const navy = '#001f3f'
// export const olive = '#3D9970'
export const orange = '#FF851B'
export const purple = '#B10DC9'
export const red = '#FF4136'
export const silver = '#DDDDDD'
// export const teal = '#39CCCC'
export const white = '#FFFFFF'
export const yellow = '#FFDC00'
export const transparent = 'transparent'

export const iosGray = silver

export const androidLightBackground = 'rgb(244, 244, 244)'
export const androidSeparator = 'rgb(224, 224, 224)'
export const androidDisabledIcon = 'rgb(224, 224, 224)'
export const androidTextColor = 'rgb(113, 113, 118)'
export const androidTabAccentColor = '#ffeb3b'

export const iosLightBackground = 'rgb(240, 239, 245)'
export const iosSeparator = '#C8C7CC'
export const iosLightBorder = iosSeparator
export const iosDisabledText = 'rgb(142, 142, 147)'
export const iosText = iosSeparator
export const iosNavbarBottomBorder = iosSeparator
export const iosListSectionHeader = 'rgb(248, 248, 248)'
export const iosPlaceholderText = iosSeparator
export const iosHeaderTopBorder = iosSeparator
export const iosHeaderBottomBorder = 'rgb(224, 224, 224)'

export const sectionBgColor =
	Platform.OS === 'ios' ? iosLightBackground : androidLightBackground

export const tableviewAccessoryColor = 'rgb(0, 122, 255)'

export const semitransparentGray = 'rgba(0,0,0,0.2)'

// MARK: Oleville colors
export const theLatest = '#00BFFF'
export const olevilleGold = '#FFC107'
export const darkGold = '#c79100'
export const olevilleBackground = '#F0F0E1'

// MARK: KSTO Colors
export const kstoPrimaryLight = '#c5c5e8'
export const kstoSecondaryLight = '#7789bb'
export const kstoPrimaryDark = '#686ea1'
export const kstoSecondaryDark = '#4c4f71'
export const kstoTextLight = '#dcdde5'
export const kstoTextDark = '#bebad4'

// MARK: System Colors
export const infoBlue = 'rgb(47, 112, 225)'
export const success = 'rgb(83, 215, 106)'
export const warning = 'rgb(221, 170, 59)'
export const danger = 'rgb(229, 0, 15)'

// MARK: Whites
export const antiqueWhite = 'rgb(250, 235, 215)'
export const oldLace = 'rgb(253, 245, 230)'
export const ivory = 'rgb(255, 255, 240)'
export const seashell = 'rgb(255, 245, 238)'
export const ghostWhite = 'rgb(248, 248, 255)'
export const snow = 'rgb(255, 250, 250)'
export const linen = 'rgb(250, 240, 230)'

// MARK: Grays
export const black25Percent = 'rgb(63.75, 63.75, 63.75)'
export const black50Percent = 'rgb(127.5, 127.5, 127.5)'
export const black75Percent = 'rgb(191.25, 191.25, 191.25)'
export const warmGray = 'rgb(133, 117, 112)'
export const coolGray = 'rgb(118, 122, 133)'
export const charcoal = 'rgb(34, 34, 34)'

// MARK: Blues
export const teal = 'rgb(28, 160, 170)'
export const steelBlue = 'rgb(103, 153, 170)'
export const robinEgg = 'rgb(141, 218, 247)'
export const pastelBlue = 'rgb(99, 161, 247)'
export const turquoise = 'rgb(112, 219, 219)'
export const skyBlue = 'rgb(0, 178, 238)'
export const indigo = 'rgb(13, 79, 139)'
export const denim = 'rgb(67, 114, 170)'
export const blueberry = 'rgb(89, 113, 173)'
export const cornflower = 'rgb(100, 149, 237)'
export const babyBlue = 'rgb(190, 220, 230)'
export const midnightBlue = 'rgb(13, 26, 35)'
export const fadedBlue = 'rgb(23, 137, 155)'
export const iceberg = 'rgb(200, 213, 219)'
export const wave = 'rgb(102, 169, 251)'

// MARK: Greens
export const emerald = 'rgb(1, 152, 117)'
export const grass = 'rgb(99, 214, 74)'
export const pastelGreen = 'rgb(126, 242, 124)'
export const seafoam = 'rgb(77, 226, 140)'
export const paleGreen = 'rgb(176, 226, 172)'
export const cactusGreen = 'rgb(99, 111, 87)'
export const chartreuse = 'rgb(69, 139, 0)'
export const hollyGreen = 'rgb(32, 87, 14)'
export const olive = 'rgb(91, 114, 34)'
export const oliveDrab = 'rgb(107, 142, 35)'
export const moneyGreen = 'rgb(134, 198, 124)'
export const honeydew = 'rgb(216, 255, 231)'
export const lime = 'rgb(56, 237, 56)'
export const cardTable = 'rgb(87, 121, 107)'

// MARK: Reds
export const salmon = 'rgb(233, 87, 95)'
export const brickRed = 'rgb(151, 27, 16)'
export const easterPink = 'rgb(241, 167, 162)'
export const grapefruit = 'rgb(228, 31, 54)'
export const pink = 'rgb(255, 95, 154)'
export const indianRed = 'rgb(205, 92, 92)'
export const strawberry = 'rgb(190, 38, 37)'
export const coral = 'rgb(240, 128, 128)'
export const maroon = 'rgb(80, 4, 28)'
export const watermelon = 'rgb(242, 71, 63)'
export const tomato = 'rgb(255, 99, 71)'
export const pinkLipstick = 'rgb(255, 105, 180)'
export const paleRose = 'rgb(255, 228, 225)'
export const crimson = 'rgb(187, 18, 36)'

// MARK: Purples
export const eggplant = 'rgb(105, 5, 98)'
export const pastelPurple = 'rgb(207, 100, 235)'
export const palePurple = 'rgb(229, 180, 235)'
export const coolPurple = 'rgb(140, 93, 228)'
export const violet = 'rgb(191, 95, 255)'
export const plum = 'rgb(139, 102, 139)'
export const lavender = 'rgb(204, 153, 204)'
export const raspberry = 'rgb(135, 38, 87)'
export const fuschia = 'rgb(255, 20, 147)'
export const grape = 'rgb(54, 11, 88)'
export const periwinkle = 'rgb(135, 159, 237)'
export const orchid = 'rgb(218, 112, 214)'

// MARK: Yellows
export const goldenrod = 'rgb(215, 170, 51)'
export const yellowGreen = 'rgb(192, 242, 39)'
export const banana = 'rgb(229, 227, 58)'
export const mustard = 'rgb(205, 171, 45)'
export const buttermilk = 'rgb(254, 241, 181)'
export const gold = 'rgb(139, 117, 18)'
export const cream = 'rgb(240, 226, 187)'
export const lightCream = 'rgb(240, 238, 215)'
export const wheat = 'rgb(240, 238, 215)'
export const beige = 'rgb(245, 245, 220)'

// MARK: Oranges
export const peach = 'rgb(242, 187, 97)'
export const burntOrange = 'rgb(184, 102, 37)'
export const pastelOrange = 'rgb(248, 197, 143)'
export const cantaloupe = 'rgb(250, 154, 79)'
export const carrot = 'rgb(237, 145, 33)'
export const mandarin = 'rgb(247, 145, 55)'

// MARK: Browns
export const chiliPowder = 'rgb(199, 63, 23)'
export const burntSienna = 'rgb(138, 54, 15)'
export const chocolate = 'rgb(94, 38, 5)'
export const coffee = 'rgb(141, 60, 15)'
export const cinnamon = 'rgb(123, 63, 9)'
export const almond = 'rgb(196, 142, 72)'
export const eggshell = 'rgb(252, 230, 201)'
export const sand = 'rgb(222, 182, 151)'
export const mud = 'rgb(70, 45, 29)'
export const sienna = 'rgb(160, 82, 45)'
export const dust = 'rgb(236, 214, 197)'

export const tint = mandarin

// MARK: gradients
export const redToPurple = ['rgb(249,64,77)', 'rgb(217,37,111)']
export const orangeToRed = ['rgb(250,120,37)', 'rgb(242,38,83)']
export const yellowToGoldDark = ['rgb(234,185,29)', 'rgb(226,123,19)']
export const yellowToGoldLight = ['rgb(238,209,0)', 'rgb(237,158,0)']
export const grassToLime = ['rgb(125,209,24)', 'rgb(88,186,34)']
export const seafoamToGrass = ['rgb(15,201,121)', 'rgb(58,181,42)']
export const tealToSeafoam = ['rgb(3,220,156)', 'rgb(19,188,156)']
export const lightBlueToBlueLight = ['rgb(1,194,199)', 'rgb(10,158,196)']
export const lightBlueToBlueDark = ['rgb(5,187,219)', 'rgb(25,145,234)']
export const darkBlueToIndigo = ['rgb(48,112,228)', 'rgb(95,72,229)']
export const purpleToIndigo = ['rgb(129,88,252)', 'rgb(92,80,236)']
export const magentaToPurple = ['rgb(213,69,196)', 'rgb(160,50,230)']
export const pinkToHotpink = ['rgb(248,102,149)', 'rgb(209,44,159)']
export const grayToDarkGray = ['rgb(118,134,157)', 'rgb(85,96,124)']
export const navyToNavy = ['rgb(32,67,107)', 'rgb(0,48,104)']

// MARK: homescreen button foregrounds
export const homescreenForegroundLight = 'rgba(255, 255, 255, 0.9)'
export const homescreenForegroundDark = 'rgba(0, 0, 0, 0.65)'

// MARK: St. Olaf colors
export const sto = {
	black: '#242121',
	darkGray: '#53585A',
	mediumGray: '#E0DAD6',
	lightGray: '#F7F5F2',
	gold: '#E3A025',
	lightGold: '#F7C55A',
	cranberry: '#B11556',
	lime: '#A3D65C',
	orange: '#FA8D29',
	red: '#E84A36',
	lightBlue: '#83DBE0',
	blue: '#00ADD9',
	teal: '#00827E',
	purple: '#6E3A5D',
	navy: '#233746',
	mint: '#CFE1D7',
}

export const stoText = {
	black: white,
	darkGray: white,
	mediumGray: black,
	lightGray: black,
	gold: black,
	lightGold: black,
	cranberry: white,
	lime: black,
	orange: black,
	red: transparent,
	lightBlue: black,
	blue: black,
	teal: white,
	purple: white,
	navy: white,
	mint: black,
}
<|endoftext|>