<commit_before>/**
 * React Starter Kit (https://www.reactstarterkit.com/)
 *
 * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */

import React, { Component, PropTypes } from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import { connect } from 'react-redux';

import GroupToolbar from '../../components/GroupToolbar/GroupToolbar';
import Link from '../../components/Link/Link';
import TimeShareContainer from '../../components/Timetable/TimeShareContainer';

import s from './Group.css';
import { fetchGroups } from '../../actions/group';
import { fetchFriends } from '../../actions/friend';
import { fetchGroupTimetable } from '../../actions/timeshare';

const title = 'Groups';

class Group extends Component {
  static propTypes = {
    friend: PropTypes.object.isRequired,
    group: PropTypes.object.isRequired,
    isLoggedIn: PropTypes.bool.isRequired,
    semester: PropTypes.string.isRequired,
    year: PropTypes.string.isRequired,
    fetchGroups: PropTypes.func.isRequired,
    fetchGroupTimetable: PropTypes.func.isRequired,
  }

  static contextTypes = {
    setTitle: PropTypes.func.isRequired,
  }

  state = {
    groupShown: null,
    groupId: null,
    date: this.formatDate(new Date()),
  }

  componentWillMount() {
    // Initialize timesharing table
    this.state.groupShown = this.props.group.data[0] || {};
    this.state.groupId = this.state.groupShown.teamId;
    this.props.fetchGroupTimetable({ groupId: this.state.groupId, date: this.state.date });
  }

  componentDidMount() {
    const { year, semester, isLoggedIn, group } = this.props;
    if (!group.isInitialized && isLoggedIn) {
      this.props.fetchGroups({ year, semester });
    }
  }

  formatDate(date) {
    return date.getFullYear() + '-' +  ('00' + (date.getMonth() + 1)).slice(-2) + '-' + ('00' + date.getDate()).slice(-2);
  }

  handleGroupChange = (event, key, groupId) => {
    this.state.groupShown = this.props.group.data.find(d => d.teamId === groupId);
    this.state.groupId = groupId;
    this.props.fetchGroupTimetable({ groupId, date: this.state.date });
  }

  handleDateChange = (event, date) => {
    this.state.date = this.formatDate(date);
    console.log(this.state);
    if (this.state.groupId) {
        this.props.fetchGroupTimetable({ groupId: this.state.groupId, date: this.state.date });
    }
    return { event, date };
  }

  render() {
    if (!this.props.isLoggedIn) {
      return (

            Please
            <Link to="/login">
              login
            </Link>
             to compare your timetable!

      );
    }
    this.context.setTitle(title);

    const noGroupContainer = (

You do not have any groups. Create one!

    );

    const holidayContainer = (

It's school break!

    );

    /* eslint-disable */
    const dummydata = {
            "createdBy": {
                "userId": "3",
                "name": "Zhi An"
            },
            "teamId": "{id}",
            "teamName": "3216 final project",
            "year": "2016-2017",
            "semester": "1",
            "members": [
                {
                    "userId": "1",
                    "name": "Niko",
                    "acceptInvitation": 1,
                    "timetable": [
                        {
                            "id": 2,
                            "timetableId": 1,
                            "moduleId": 514,
                            "lessonType": "sectional",
                            "classNumber": 1,
                            "createdAt": "2016-09-12T08:26:51.449Z",
                            "updatedAt": "2016-09-12T08:26:51.449Z",
                            "module": {
                                "id": 514,
                                "year": "2016-2017",
                                "semester": 1,
                                "code": "CS1010",
                                "title": "Programming Methodology",
                                "description": "This is CS1010.",
                                "department": "Computer Science",
                                "credit": 4,
                                "workload": "2-1-1-3-3",
                                "prerequisite": null,
                                "preclusion": "CG1101, CS1010E",
                                "examDate": "2016-11-23T01:00:00.000Z",
                                "timetable": {
                                    "ClassNo": "B3",
                                    "LessonType": "Laboratory",
                                    "WeekText": "Odd Week",
                                    "DayText": "Wednesday",
                                    "StartTime": "1400",
                                    "EndTime": "1700",
                                    "Venue": "S12-0402"
                                },
                                "createdAt": "2016-09-12T08:33:46.506Z",
                                "updatedAt": "2016-09-12T08:33:46.507Z"
                            }
                        },
                        {
                            "id": 3,
                            "timetableId": 1,
                            "moduleId": 522,
                            "lessonType": "sectional",
                            "classNumber": 1,
                            "createdAt": "2016-09-12T08:26:51.450Z",
                            "updatedAt": "2016-09-12T08:26:51.450Z",
                            "module": {
                                "id": 522,
                                "year": "2016-2017",
                                "semester": 1,
                                "code": "CS1231",
                                "title": "Discrete Structures",
                                "description": "This is CS1231",
                                "department": "Computer Science",
                                "credit": 4,
                                "workload": "3-1-0-3-3",
                                "prerequisite": "A-level Mathematics or H2 Mathematics or MA1301 or MA1301FC or MA1301X",
                                "preclusion": "MA1100",
                                "examDate": "2016-11-23T09:00:00.000Z",
                                "timetable": {
                                    "ClassNo": "4",
                                    "LessonType": "Tutorial",
                                    "WeekText": "Every Week",
                                    "DayText": "Wednesday",
                                    "StartTime": "1100",
                                    "EndTime": "1200",
                                    "Venue": "COM1-0209"
                                },
                                "createdAt": "2016-09-12T08:33:46.542Z",
                                "updatedAt": "2016-09-12T08:33:46.542Z"
                            }
                        }
                    ]
                },
                {
                    "userId": "3",
                    "name": "Zhi An",
                    "acceptInvitation": 0,
                    "timetable": [
                        {
                            "id": 3,
                            "timetableId": 1,
                            "moduleId": 522,
                            "lessonType": "sectional",
                            "classNumber": 1,
                            "createdAt": "2016-09-12T08:26:51.450Z",
                            "updatedAt": "2016-09-12T08:26:51.450Z",
                            "module": {
                                "id": 522,
                                "year": "2016-2017",
                                "semester": 1,
                                "code": "CS1231",
                                "title": "Discrete Structures",
                                "description": "This is CS1231",
                                "department": "Computer Science",
                                "credit": 4,
                                "workload": "3-1-0-3-3",
                                "prerequisite": "A-level Mathematics or H2 Mathematics or MA1301 or MA1301FC or MA1301X",
                                "preclusion": "MA1100",
                                "examDate": "2016-11-23T09:00:00.000Z",
                                "timetable": {
                                    "ClassNo": "4",
                                    "LessonType": "Tutorial",
                                    "WeekText": "Every Week",
                                    "DayText": "Wednesday",
                                    "StartTime": "1100",
                                    "EndTime": "1200",
                                    "Venue": "COM1-0209"
                                },
                                "createdAt": "2016-09-12T08:33:46.542Z",
                                "updatedAt": "2016-09-12T08:33:46.542Z"
                            }
                        }
                    ]
                }
            ]
        };
    /* eslint-enable */

    var timeShareContainer = noGroupContainer;
    if (!this.props.group.isFetching && this.props.group.isInitialized) {
      if (this.props.group.data.length > 0 && !this.props.timeshare.isFetching) {
        if (this.props.timeshare.data.holiday) {
          timeShareContainer = holidayContainer;
        } else {
          const groupData = this.props.timeshare.data || {};
          timeShareContainer = <TimeShareContainer group={groupData} />;
        }
      }
    }

    return (

        <GroupToolbar
          groupShown={this.state.groupShown}
          groups={this.props.group.data}
          handleGroupChange={this.handleGroupChange}
          handleDateChange={this.handleDateChange}
        />
        {timeShareContainer}

    );
  }
}

const mapState = (state) => ({
  year: state.selection.year,
  semester: state.selection.semester,
  isLoggedIn: !!state.user.data.id,
  group: state.group,
  friend: state.friend,
  timeshare: state.timeshare,
});

const mapDispatch = {
  fetchGroups,
  fetchFriends,
  fetchGroupTimetable,
};

export default connect(mapState, mapDispatch)(withStyles(s)(Group));
<commit_msg>Remove showing of 'no group' before timesharing loads<commit_after>/**
 * React Starter Kit (https://www.reactstarterkit.com/)
 *
 * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */

import React, { Component, PropTypes } from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import { connect } from 'react-redux';

import GroupToolbar from '../../components/GroupToolbar/GroupToolbar';
import Link from '../../components/Link/Link';
import TimeShareContainer from '../../components/Timetable/TimeShareContainer';

import s from './Group.css';
import { fetchGroups } from '../../actions/group';
import { fetchFriends } from '../../actions/friend';
import { fetchGroupTimetable } from '../../actions/timeshare';

const title = 'Groups';

class Group extends Component {
  static propTypes = {
    friend: PropTypes.object.isRequired,
    group: PropTypes.object.isRequired,
    isLoggedIn: PropTypes.bool.isRequired,
    semester: PropTypes.string.isRequired,
    year: PropTypes.string.isRequired,
    fetchGroups: PropTypes.func.isRequired,
    fetchGroupTimetable: PropTypes.func.isRequired,
  }

  static contextTypes = {
    setTitle: PropTypes.func.isRequired,
  }

  state = {
    groupShown: null,
    groupId: null,
    date: this.formatDate(new Date()),
  }

  componentWillMount() {
    // Initialize timesharing table
    this.state.groupShown = this.props.group.data[0] || {};
    this.state.groupId = this.state.groupShown.teamId;
    this.props.fetchGroupTimetable({ groupId: this.state.groupId, date: this.state.date });
  }

  componentDidMount() {
    const { year, semester, isLoggedIn, group } = this.props;
    if (!group.isInitialized && isLoggedIn) {
      this.props.fetchGroups({ year, semester });
    }
  }

  formatDate(date) {
    return date.getFullYear() + '-' +  ('00' + (date.getMonth() + 1)).slice(-2) + '-' + ('00' + date.getDate()).slice(-2);
  }

  handleGroupChange = (event, key, groupId) => {
    this.state.groupShown = this.props.group.data.find(d => d.teamId === groupId);
    this.state.groupId = groupId;
    this.props.fetchGroupTimetable({ groupId, date: this.state.date });
  }

  handleDateChange = (event, date) => {
    this.state.date = this.formatDate(date);
    console.log(this.state);
    if (this.state.groupId) {
        this.props.fetchGroupTimetable({ groupId: this.state.groupId, date: this.state.date });
    }
    return { event, date };
  }

  render() {
    if (!this.props.isLoggedIn) {
      return (

            Please
            <Link to="/login">
              login
            </Link>
             to compare your timetable!

      );
    }
    this.context.setTitle(title);

    const noGroupContainer = (

You do not have any groups. Create one!

    );

    const holidayContainer = (

It's school break!

    );

    /* eslint-disable */
    const dummydata = {
            "createdBy": {
                "userId": "3",
                "name": "Zhi An"
            },
            "teamId": "{id}",
            "teamName": "3216 final project",
            "year": "2016-2017",
            "semester": "1",
            "members": [
                {
                    "userId": "1",
                    "name": "Niko",
                    "acceptInvitation": 1,
                    "timetable": [
                        {
                            "id": 2,
                            "timetableId": 1,
                            "moduleId": 514,
                            "lessonType": "sectional",
                            "classNumber": 1,
                            "createdAt": "2016-09-12T08:26:51.449Z",
                            "updatedAt": "2016-09-12T08:26:51.449Z",
                            "module": {
                                "id": 514,
                                "year": "2016-2017",
                                "semester": 1,
                                "code": "CS1010",
                                "title": "Programming Methodology",
                                "description": "This is CS1010.",
                                "department": "Computer Science",
                                "credit": 4,
                                "workload": "2-1-1-3-3",
                                "prerequisite": null,
                                "preclusion": "CG1101, CS1010E",
                                "examDate": "2016-11-23T01:00:00.000Z",
                                "timetable": {
                                    "ClassNo": "B3",
                                    "LessonType": "Laboratory",
                                    "WeekText": "Odd Week",
                                    "DayText": "Wednesday",
                                    "StartTime": "1400",
                                    "EndTime": "1700",
                                    "Venue": "S12-0402"
                                },
                                "createdAt": "2016-09-12T08:33:46.506Z",
                                "updatedAt": "2016-09-12T08:33:46.507Z"
                            }
                        },
                        {
                            "id": 3,
                            "timetableId": 1,
                            "moduleId": 522,
                            "lessonType": "sectional",
                            "classNumber": 1,
                            "createdAt": "2016-09-12T08:26:51.450Z",
                            "updatedAt": "2016-09-12T08:26:51.450Z",
                            "module": {
                                "id": 522,
                                "year": "2016-2017",
                                "semester": 1,
                                "code": "CS1231",
                                "title": "Discrete Structures",
                                "description": "This is CS1231",
                                "department": "Computer Science",
                                "credit": 4,
                                "workload": "3-1-0-3-3",
                                "prerequisite": "A-level Mathematics or H2 Mathematics or MA1301 or MA1301FC or MA1301X",
                                "preclusion": "MA1100",
                                "examDate": "2016-11-23T09:00:00.000Z",
                                "timetable": {
                                    "ClassNo": "4",
                                    "LessonType": "Tutorial",
                                    "WeekText": "Every Week",
                                    "DayText": "Wednesday",
                                    "StartTime": "1100",
                                    "EndTime": "1200",
                                    "Venue": "COM1-0209"
                                },
                                "createdAt": "2016-09-12T08:33:46.542Z",
                                "updatedAt": "2016-09-12T08:33:46.542Z"
                            }
                        }
                    ]
                },
                {
                    "userId": "3",
                    "name": "Zhi An",
                    "acceptInvitation": 0,
                    "timetable": [
                        {
                            "id": 3,
                            "timetableId": 1,
                            "moduleId": 522,
                            "lessonType": "sectional",
                            "classNumber": 1,
                            "createdAt": "2016-09-12T08:26:51.450Z",
                            "updatedAt": "2016-09-12T08:26:51.450Z",
                            "module": {
                                "id": 522,
                                "year": "2016-2017",
                                "semester": 1,
                                "code": "CS1231",
                                "title": "Discrete Structures",
                                "description": "This is CS1231",
                                "department": "Computer Science",
                                "credit": 4,
                                "workload": "3-1-0-3-3",
                                "prerequisite": "A-level Mathematics or H2 Mathematics or MA1301 or MA1301FC or MA1301X",
                                "preclusion": "MA1100",
                                "examDate": "2016-11-23T09:00:00.000Z",
                                "timetable": {
                                    "ClassNo": "4",
                                    "LessonType": "Tutorial",
                                    "WeekText": "Every Week",
                                    "DayText": "Wednesday",
                                    "StartTime": "1100",
                                    "EndTime": "1200",
                                    "Venue": "COM1-0209"
                                },
                                "createdAt": "2016-09-12T08:33:46.542Z",
                                "updatedAt": "2016-09-12T08:33:46.542Z"
                            }
                        }
                    ]
                }
            ]
        };
    /* eslint-enable */

    var timeShareContainer = null;
    if (!this.props.group.isFetching && this.props.group.isInitialized) {
      if (this.props.group.data.length > 0 && !this.props.timeshare.isFetching) {
        if (this.props.timeshare.data.holiday) {
          timeShareContainer = holidayContainer;
        } else {
          const groupData = this.props.timeshare.data || {};
          timeShareContainer = <TimeShareContainer group={groupData} />;
        }
      }
    } else {
      timeShareContainer = noGroupContainer;
    }

    return (

        <GroupToolbar
          groupShown={this.state.groupShown}
          groups={this.props.group.data}
          handleGroupChange={this.handleGroupChange}
          handleDateChange={this.handleDateChange}
        />
        {timeShareContainer}

    );
  }
}

const mapState = (state) => ({
  year: state.selection.year,
  semester: state.selection.semester,
  isLoggedIn: !!state.user.data.id,
  group: state.group,
  friend: state.friend,
  timeshare: state.timeshare,
});

const mapDispatch = {
  fetchGroups,
  fetchFriends,
  fetchGroupTimetable,
};

export default connect(mapState, mapDispatch)(withStyles(s)(Group));
<|endoftext|>


<commit_before>// For conditions of distribution and use, see copyright notice in LICENSE

/**
 * @author Toni Dahl
 */

(function ( namespace, undefined ) {

    // Util shortcuts
    var extend = namespace.util.extend,
        innerWidth = namespace.util.innerWidth,
        innerHeight = namespace.util.innerHeight;

    /**
     * Creates a scene manager object
     *
     * @constructor
     * @name SceneManager
     * @type Function
     * @param {object} container Container DOM element for WebGL renderer.
     */

    var SceneManager = namespace.SceneManager = function ( options ) {

        var defaults = {
                eulerOrder: 'ZYX',
                container: document.body,
                websocket: null,
                remoteStorage: 'http://127.0.0.1:8000/',
                meshType: 'ogre'
            },
            opts;

        // Setting options
        opts = extend( {}, defaults, options );

        // Three.js settings
        THREE.Object3D.defaultEulerOrder = this.eulerOrder = opts.eulerOrder;

        this.time = Date.now();
        this.clock = new THREE.Clock();
        this.container = opts.container;
        this.controls = null;
        this.renderer = null;
        this.scene = null;
        this.skyBoxScene = null;
        this.mainCamera = null;
        this.skyBoxCamera = null;
        this.remoteStorage = opts.remoteStorage;

        this.websocket = opts.websocket;

        this.assetManager = new namespace.AssetManager( this.remoteStorage, opts.meshType );

        this.ecManager = new namespace.ECManager( this );

        this.cameraManager = new namespace.CameraManager( this );

        this.controlManager = new namespace.Controls( this );

        this.init();
    };

    SceneManager.prototype.renderLoop = function () {
        var self = this, clock = this.clock, controls = this.controls, renderer = this.renderer;

        (function loop() {
            window.requestAnimationFrame( loop );

            /*
             self.controls.isOnObject( false );

             self.controls.rayCaster.ray.origin.copy( self.controls.getObject().position );
             self.controls.rayCaster.ray.origin.y -= 10;

             var intersections = self.controls.rayCaster.intersectObjects( self.loadedObjects ),
             distance;

             if ( intersections.length > 0 ) {

             distance = intersections[ 0 ].distance;

             if ( distance > 0 && distance < 10 ) {

             self.controls.isOnObject( true );

             }

             }
             */

            /*
             self.camera.position.y = 10;
             self.camera.position.x = Math.floor(Math.cos( self.time*0.0005) * 200);
             self.camera.position.z = Math.floor(Math.sin( self.time *0.0005) * 200);
             self.camera.lookAt( new THREE.Vector3(0,0,0) );
             */
            controls.update( clock.getDelta() );

            self.skyBoxCamera.rotation.setEulerFromRotationMatrix(
                self.mainCamera.parent.matrixWorld,
                //self.camera.matrixWorld,
                THREE.Object3D.defaultEulerOrder
            );

            renderer.render( self.skyBoxScene, self.skyBoxCamera );
            renderer.render( self.scene, self.mainCamera );

            //self.time = Date.now();
        }());

    };

    SceneManager.prototype.windowResize = function () {
        var callback = function () {
            this.renderer.setSize( innerWidth( this.container ), innerHeight( this.container ) );

            this.mainCamera.aspect = innerWidth( this.container ) / innerHeight( this.container );
            this.mainCamera.updateProjectionMatrix();
            this.skyBoxCamera.aspect = this.mainCamera.aspect;
            this.skyBoxCamera.updateProjectionMatrix();

        }.bind( this );
        window.addEventListener( 'resize', callback, false );

        return {
            stop: function () {
                window.removeEventListener( 'resize', callback );
            }
        };
    };

    SceneManager.prototype.addToScene = function ( object ) {
        this.scene.add( object );
        //console.log( object )

    };

    SceneManager.prototype.removeFromScene = function ( object ) {

        this.scene.remove( object );

    };

    SceneManager.prototype.addSkyBox = function ( skyBox ) {
        var scene = this.skyBoxScene;
        if ( scene ) {
            if ( this.getSceneObject( function ( obj ) {
                return obj.name === 'skyBox';
            }, scene ) ) {
                return;
            }
            skyBox.name = 'skyBox';
            scene.add( skyBox );
        }
    };

    SceneManager.prototype.removeSkyBox = function ( skyBox ) {
        var scene = this.skyBoxScene, sky;
        if ( this.skyBoxScene ) {
            sky = this.getSceneObject( function ( obj ) {
                return obj.name === 'skyBox';
            }, scene );

            if ( sky ) {
                scene.remove( sky );
            }
        }
    };

    SceneManager.prototype.setAmbientLight = function ( color ) {
        if ( namespace.util.toType( color ) !== 'array' ) {
            return;
        }

        var scene = this.scene, light;
        if ( scene ) {
            light = this.getSceneObject( function ( obj ) {
                return obj instanceof THREE.AmbientLight;
            } );

            if ( light ) {
                light.color.setRGB( color[0], color[1], color[2] );
            } else {
                light = new THREE.AmbientLight();
                light.color.setRGB( color[0], color[1], color[2] );
                scene.add( light );
            }
        }
    };
    SceneManager.prototype.createLight = function ( type ) {
        var light;

        if(type === 0){
            light =  this.getSceneObject( function ( obj ) {
                return obj instanceof THREE.PointLight && obj.parent instanceof THREE.Scene;
            } );

        }else if(type === 1){
            light = this.getSceneObject( function ( obj ) {
                return obj instanceof THREE.SpotLight && obj.parent instanceof THREE.Scene;
            } );
        }else if(type === 2){
            light = this.getSceneObject( function ( obj ) {
                return obj instanceof THREE.DirectionalLight && obj.parent instanceof THREE.Scene;
            } );
        }else{
            return false;
        }

        return light;

    };

    SceneManager.prototype.setMainCamera = function ( cameraEntity ) {
        var entity, camComp, camera, camControls;

        if ( cameraEntity === undefined ) {
            entity = this.cameraManager.createCameraEntity( "freelookcamera" );
        } else if ( cameraEntity instanceof namespace.Entity ) {
            entity = cameraEntity;
        }

        if ( entity ) {
            camComp = entity.getComponent( namespace.ECCamera );
            if ( camComp ) {
                camera = camComp.getCameraObject();
                camControls = entity.controls;

                if ( camControls ) {
                    camControls.setActive();
                }

                if ( camera instanceof THREE.PerspectiveCamera ) {
                    this.mainCamera = camera;
                }
            }
        }

    };

    SceneManager.prototype.getSceneObject = function ( callBack, scene ) {
        if ( typeof callBack !== "function" ) {
            return false;
        }

        if ( !scene ) {
            scene = this.scene;
        }

        var children = scene.children,
            childLength = scene.children.length,
            obj, i;

        if ( children ) {
            for ( i = childLength; i--; ) {
                obj = children[i];
                if ( callBack( obj ) ) {
                    return obj;
                }
            }
        }
        return false;
    };

    SceneManager.prototype.init = function () {

        var body = document.body, renderer, scene, skyBoxScene, camera, skyBoxCamera, controls,
            container = this.container, websocket = this.websocket,
            assetManager = this.assetManager, ecManager = this.ecManager, cameraManager = this.cameraManager,
            self = this, i;

        // *** SCENE AND SKYBOX ***
        scene = this.scene = new THREE.Scene();
        skyBoxScene = this.skyBoxScene = new THREE.Scene();

        // *** CAMERAS ***
        skyBoxCamera = this.skyBoxCamera = new THREE.PerspectiveCamera( 35, (innerWidth( container ) / innerHeight( container )), 1, 10000 );
        skyBoxCamera.lookAt( scene.position );
        this.setMainCamera();

        // *** Creating dummy lights ***
        for(i=5; i--;){
            scene.add(new THREE.PointLight(null, 0));
            scene.add(new THREE.SpotLight(null, 0));
        }

        // *** RENDERER ***
        renderer = this.renderer = new THREE.WebGLRenderer( {
            antialias: true,
            clearColor: 0x87CEEB,
            clearAlpha: 1,
            preserveDrawingBuffer: false
        } );

        renderer.autoClear = false;
        //renderer.gammaInput = true;
        //renderer.gammaOutput = true;
        renderer.shadowMapAutoUpdate = true;
        renderer.shadowMapEnabled = true;
        renderer.shadowMapSoft = false;
        renderer.shadowMapType = THREE.PCFSoftShadowMap;
        renderer.shadowMapCascade = false;
        renderer.shadowMapCullFace = THREE.CullFaceNone;

        renderer.physicallyBasedShading = true;

        renderer.setSize( innerWidth( this.container ), innerHeight( this.container ) );
        container.appendChild( this.renderer.domElement );

        // *** CONTROLS ***
        /*
         controls = this.controls = new THREE.PointerLockControls( this.mainCamera );

         scene.add( this.controls.getObject() );

         controls.rayCaster = new THREE.Raycaster();
         controls.rayCaster.ray.direction.set( 0, -1, 0 );

         controls.enabled = false;

         function pointerLockChange() {
         if ( document.mozPointerLockElement === body ||
         document.webkitPointerLockElement === body ||
         document.pointerLockElement === body ) {
         self.controls.enabled = true;
         return;
         }
         self.controls.enabled = false;
         }

         function fullScreenChange() {
         if ( document.webkitFullscreenElement === body ||
         document.mozFullscreenElement === body ||
         document.mozFullScreenElement === body ) { // Older API upper case 'S'.
         // Element is fullscreen, now we can request pointer lock
         body.requestPointerLock = body.requestPointerLock ||
         body.mozRequestPointerLock ||
         body.webkitRequestPointerLock;
         body.requestPointerLock();
         }
         }

         document.addEventListener( 'webkitpointerlockchange', pointerLockChange, false );
         document.addEventListener( 'mozpointerlockchange', pointerLockChange, false );
         document.addEventListener( 'pointerlockchange', pointerLockChange, false );
         document.addEventListener( 'fullscreenchange', fullScreenChange, false );
         document.addEventListener( 'mozfullscreenchange', fullScreenChange, false );
         document.addEventListener( 'webkitfullscreenchange', fullScreenChange, false );

         body.addEventListener( 'click', function ( event ) {
         if ( body.webkitRequestPointerLock ) {
         if ( document.mozPointerLockElement !== body &&
         document.webkitPointerLockElement !== body &&
         document.pointerLockElement !== body ) {
         body.requestPointerLock = body.requestPointerLock ||
         body.mozRequestPointerLock ||
         body.webkitRequestPointerLock;
         body.requestPointerLock();
         }
         } else {
         body.requestFullscreen = body.requestFullscreen ||
         body.mozRequestFullscreen ||
         body.mozRequestFullScreen || // Older API upper case 'S'.
         body.webkitRequestFullscreen;
         body.requestFullscreen();
         }

         }, false );

         */

        // *** SIGNAL LISTENERS ***
        //Windows resize listener
        this.windowResize();
        ecManager.entityCreated.add( cameraManager.onEntityCreated, cameraManager );

        if ( websocket ) {
            websocket.bindEvent( "RemoteStorage", function ( data ) {
                assetManager.setRemoteStorage( data );
            } );
        }

        // *** HELPERS FOR DEVELOPING ***
        var axes = new THREE.AxisHelper( 50 );
        axes.position.y = 30;
        scene.add( axes );

    };

    SceneManager.prototype.start = function () {
        try {
            if ( !this.websocket ) {
                throw new Error( ["Invalid WebSocket connection."] );
            }
            this.renderLoop();
            this.websocket.connect();
        } catch (e) {
            console.error( 'SceneManager:', e.stack );
        }
    };

}( window['webtundra'] = window['webtundra'] || {} ));

<commit_msg>Added some more dummy lights and fixed minor things.<commit_after>// For conditions of distribution and use, see copyright notice in LICENSE

/**
 * @author Toni Dahl
 */

(function ( namespace, undefined ) {

    // Util shortcuts
    var extend = namespace.util.extend,
        innerWidth = namespace.util.innerWidth,
        innerHeight = namespace.util.innerHeight;

    /**
     * Creates a scene manager object
     *
     * @constructor
     * @name SceneManager
     * @type Function
     * @param {object} container Container DOM element for WebGL renderer.
     */

    var SceneManager = namespace.SceneManager = function ( options ) {

        var defaults = {
                eulerOrder: 'ZYX',
                container: document.body,
                websocket: null,
                remoteStorage: 'http://127.0.0.1:8000/',
                meshType: 'ogre'
            },
            opts;

        // Setting options
        opts = extend( {}, defaults, options );

        // Three.js settings
        THREE.Object3D.defaultEulerOrder = this.eulerOrder = opts.eulerOrder;

        this.time = Date.now();
        this.clock = new THREE.Clock();
        this.container = opts.container;
        this.controls = null;
        this.renderer = null;
        this.scene = null;
        this.skyBoxScene = null;
        this.mainCamera = null;
        this.skyBoxCamera = null;
        this.remoteStorage = opts.remoteStorage;

        this.websocket = opts.websocket;

        this.assetManager = new namespace.AssetManager( this.remoteStorage, opts.meshType );

        this.ecManager = new namespace.ECManager( this );

        this.cameraManager = new namespace.CameraManager( this );

        this.controlManager = new namespace.Controls( this );

        this.init();
    };

    SceneManager.prototype.renderLoop = function () {
        var self = this, clock = this.clock, controls = this.controls, renderer = this.renderer;

        (function loop() {
            window.requestAnimationFrame( loop );

            /*
             self.controls.isOnObject( false );

             self.controls.rayCaster.ray.origin.copy( self.controls.getObject().position );
             self.controls.rayCaster.ray.origin.y -= 10;

             var intersections = self.controls.rayCaster.intersectObjects( self.loadedObjects ),
             distance;

             if ( intersections.length > 0 ) {

             distance = intersections[ 0 ].distance;

             if ( distance > 0 && distance < 10 ) {

             self.controls.isOnObject( true );

             }

             }
             */

            /*
             self.camera.position.y = 10;
             self.camera.position.x = Math.floor(Math.cos( self.time*0.0005) * 200);
             self.camera.position.z = Math.floor(Math.sin( self.time *0.0005) * 200);
             self.camera.lookAt( new THREE.Vector3(0,0,0) );
             */
            controls.update( clock.getDelta() );

            self.skyBoxCamera.rotation.setEulerFromRotationMatrix(
                self.mainCamera.parent.matrixWorld,
                //self.camera.matrixWorld,
                THREE.Object3D.defaultEulerOrder
            );

            renderer.render( self.skyBoxScene, self.skyBoxCamera );
            renderer.render( self.scene, self.mainCamera );

            //self.time = Date.now();
        }());

    };

    SceneManager.prototype.windowResize = function () {
        var callback = function () {
            this.renderer.setSize( innerWidth( this.container ), innerHeight( this.container ) );

            this.mainCamera.aspect = innerWidth( this.container ) / innerHeight( this.container );
            this.mainCamera.updateProjectionMatrix();
            this.skyBoxCamera.aspect = this.mainCamera.aspect;
            this.skyBoxCamera.updateProjectionMatrix();

        }.bind( this );
        window.addEventListener( 'resize', callback, false );

        return {
            stop: function () {
                window.removeEventListener( 'resize', callback );
            }
        };
    };

    SceneManager.prototype.addToScene = function ( object ) {
        this.scene.add( object );
        //console.log( object )

    };

    SceneManager.prototype.removeFromScene = function ( object ) {

        this.scene.remove( object );

    };

    SceneManager.prototype.addSkyBox = function ( skyBox ) {
        var scene = this.skyBoxScene;
        if ( scene ) {
            if ( this.getSceneObject( function ( obj ) {
                return obj.name === 'skyBox';
            }, scene ) ) {
                return false;
            }
            skyBox.name = 'skyBox';
            scene.add( skyBox );

            return true;
        }
    };

    SceneManager.prototype.removeSkyBox = function ( skyBox ) {
        var scene = this.skyBoxScene, sky;
        if ( this.skyBoxScene ) {
            sky = this.getSceneObject( function ( obj ) {
                return obj.name === 'skyBox';
            }, scene );

            if ( sky ) {
                scene.remove( sky );
            }
        }
    };

    SceneManager.prototype.setAmbientLight = function ( color ) {
        if ( namespace.util.toType( color ) !== 'array' ) {
            return;
        }

        var scene = this.scene, light;
        if ( scene ) {
            light = this.getSceneObject( function ( obj ) {
                return obj instanceof THREE.AmbientLight;
            } );

            if ( light ) {
                light.color.setRGB( color[0], color[1], color[2] );
            } else {
                light = new THREE.AmbientLight();
                light.color.setRGB( color[0], color[1], color[2] );
                scene.add( light );
            }
        }
    };
    SceneManager.prototype.createLight = function ( type ) {
        var light;

        if(type === 0){
            light =  this.getSceneObject( function ( obj ) {
                return obj instanceof THREE.PointLight && obj.parent instanceof THREE.Scene;
            } );

        }else if(type === 1){
            light = this.getSceneObject( function ( obj ) {
                return obj instanceof THREE.SpotLight && obj.parent instanceof THREE.Scene;
            } );
        }else if(type === 2){
            light = this.getSceneObject( function ( obj ) {
                return obj instanceof THREE.DirectionalLight && obj.parent instanceof THREE.Scene;
            } );
        }else if(type === 3) {
            light = this.getSceneObject( function ( obj ) {
                return obj instanceof THREE.AmbientLight && obj.parent instanceof THREE.Scene;
            } );
        }else{
            return false;
        }

        return light;

    };

    SceneManager.prototype.setMainCamera = function ( cameraEntity ) {
        var entity, camComp, camera, camControls;

        if ( cameraEntity === undefined ) {
            entity = this.cameraManager.createCameraEntity( "freelookcamera" );
        } else if ( cameraEntity instanceof namespace.Entity ) {
            entity = cameraEntity;
        }

        if ( entity ) {
            camComp = entity.getComponent( namespace.ECCamera );
            if ( camComp ) {
                camera = camComp.getCameraObject();
                camControls = entity.controls;

                if ( camControls ) {
                    camControls.setActive();
                }

                if ( camera instanceof THREE.PerspectiveCamera ) {
                    this.mainCamera = camera;
                }
            }
        }

    };

    SceneManager.prototype.getSceneObject = function ( callBack, scene ) {
        if ( typeof callBack !== "function" ) {
            return false;
        }

        if ( !scene ) {
            scene = this.scene;
        }

        var children = scene.children,
            childLength = scene.children.length,
            obj, i;

        if ( children ) {
            for ( i = childLength; i--; ) {
                obj = children[i];
                if ( callBack( obj ) ) {
                    return obj;
                }
            }
        }
        return false;
    };

    SceneManager.prototype.init = function () {

        var body = document.body, renderer, scene, skyBoxScene, camera, skyBoxCamera, controls,
            container = this.container, websocket = this.websocket,
            assetManager = this.assetManager, ecManager = this.ecManager, cameraManager = this.cameraManager,
            self = this, i;

        // *** SCENE AND SKYBOX ***
        scene = this.scene = new THREE.Scene();
        skyBoxScene = this.skyBoxScene = new THREE.Scene();

        // *** CAMERAS ***
        skyBoxCamera = this.skyBoxCamera = new THREE.PerspectiveCamera( 35, (innerWidth( container ) / innerHeight( container )), 1, 10000 );
        skyBoxCamera.lookAt( scene.position );
        this.setMainCamera();

        // *** Dummy lights ***
        for(i=5; i--;){
            scene.add(new THREE.PointLight(null, 0));
            scene.add(new THREE.SpotLight(null, 0));
        }
        scene.add(new THREE.DirectionalLight(null, 0));
        scene.add(new THREE.AmbientLight(null, 0));

        // *** RENDERER ***
        renderer = this.renderer = new THREE.WebGLRenderer( {
            antialias: true,
            clearColor: 0x87CEEB,
            clearAlpha: 1,
            preserveDrawingBuffer: false
        } );

        renderer.autoClear = false;
        //renderer.gammaInput = true;
        //renderer.gammaOutput = true;
        renderer.shadowMapAutoUpdate = true;
        renderer.shadowMapEnabled = true;
        //renderer.shadowMapSoft = false;
        //renderer.shadowMapType = THREE.PCFSoftShadowMap;
        renderer.shadowMapCascade = false;
        renderer.shadowMapCullFace = THREE.CullFaceNone;

        renderer.physicallyBasedShading = true;

        renderer.setSize( innerWidth( this.container ), innerHeight( this.container ) );
        container.appendChild( this.renderer.domElement );

        // *** CONTROLS ***
        /*
         controls = this.controls = new THREE.PointerLockControls( this.mainCamera );

         scene.add( this.controls.getObject() );

         controls.rayCaster = new THREE.Raycaster();
         controls.rayCaster.ray.direction.set( 0, -1, 0 );

         controls.enabled = false;

         function pointerLockChange() {
         if ( document.mozPointerLockElement === body ||
         document.webkitPointerLockElement === body ||
         document.pointerLockElement === body ) {
         self.controls.enabled = true;
         return;
         }
         self.controls.enabled = false;
         }

         function fullScreenChange() {
         if ( document.webkitFullscreenElement === body ||
         document.mozFullscreenElement === body ||
         document.mozFullScreenElement === body ) { // Older API upper case 'S'.
         // Element is fullscreen, now we can request pointer lock
         body.requestPointerLock = body.requestPointerLock ||
         body.mozRequestPointerLock ||
         body.webkitRequestPointerLock;
         body.requestPointerLock();
         }
         }

         document.addEventListener( 'webkitpointerlockchange', pointerLockChange, false );
         document.addEventListener( 'mozpointerlockchange', pointerLockChange, false );
         document.addEventListener( 'pointerlockchange', pointerLockChange, false );
         document.addEventListener( 'fullscreenchange', fullScreenChange, false );
         document.addEventListener( 'mozfullscreenchange', fullScreenChange, false );
         document.addEventListener( 'webkitfullscreenchange', fullScreenChange, false );

         body.addEventListener( 'click', function ( event ) {
         if ( body.webkitRequestPointerLock ) {
         if ( document.mozPointerLockElement !== body &&
         document.webkitPointerLockElement !== body &&
         document.pointerLockElement !== body ) {
         body.requestPointerLock = body.requestPointerLock ||
         body.mozRequestPointerLock ||
         body.webkitRequestPointerLock;
         body.requestPointerLock();
         }
         } else {
         body.requestFullscreen = body.requestFullscreen ||
         body.mozRequestFullscreen ||
         body.mozRequestFullScreen || // Older API upper case 'S'.
         body.webkitRequestFullscreen;
         body.requestFullscreen();
         }

         }, false );

         */

        // *** SIGNAL LISTENERS ***
        //Windows resize listener
        this.windowResize();
        ecManager.entityCreated.add( cameraManager.onEntityCreated, cameraManager );

        if ( websocket ) {
            websocket.bindEvent( "RemoteStorage", function ( data ) {
                assetManager.setRemoteStorage( data );
            } );
        }

        // *** HELPERS FOR DEVELOPING ***
        var axes = new THREE.AxisHelper( 50 );
        axes.position.y = 30;
        scene.add( axes );

    };

    SceneManager.prototype.start = function () {
        try {
            if ( !this.websocket ) {
                throw new Error( ["Invalid WebSocket connection."] );
            }
            this.renderLoop();
            this.websocket.connect();
        } catch (e) {
            console.error( 'SceneManager:', e.stack );
        }
    };

}( window['webtundra'] = window['webtundra'] || {} ));

<|endoftext|>


<commit_before>import React, { Component } from 'react';
import {
  Container,
  Header,
  Title,
  Content,
  Button,
  Icon,
  Text,
} from 'native-base';

export default class NHTabs extends Component {
  render() {
    return (
      <Container>
        <Header>
          <Title>درباره</Title>

          <Button transparent onPress={this.props.openDrawer}>
            <Icon name="ios-menu" />
          </Button>
        </Header>

        <Content style={{padding: 10}}>
          <Text>
            در این برنامه علاوه بر تبدیل اعداد به حروف می توان پسوند ریال و تومان را نیز در خواند پول بررسی کرد.
          </Text>
          <Text style={{paddingTop: 10}}>
            در هر صفحه برای آشنایی با نحوه استفاده می توانید قسمت راهنما را بزنید.
          </Text>
          <Text style={{paddingTop: 10}}>
            توسط منوی شناور می توانید بین این دو امکان جابجا شوید یا از برنامه خارج گردید.
          </Text>
          <Text style={{paddingTop: 10}}>
            ایمیل: 2rajpx@gmail.com
          </Text>
        </Content>
      </Container>
    );
  }
}
<commit_msg>del: email from app<commit_after>import React, { Component } from 'react';
import {
  Container,
  Header,
  Title,
  Content,
  Button,
  Icon,
  Text,
} from 'native-base';

export default class NHTabs extends Component {
  render() {
    return (
      <Container>
        <Header>
          <Title>درباره</Title>

          <Button transparent onPress={this.props.openDrawer}>
            <Icon name="ios-menu" />
          </Button>
        </Header>

        <Content style={{padding: 10}}>
          <Text>
            در این برنامه علاوه بر تبدیل اعداد به حروف می توان پسوند ریال و تومان را نیز در خواند پول بررسی کرد.
          </Text>
          <Text style={{paddingTop: 10}}>
            در هر صفحه برای آشنایی با نحوه استفاده می توانید قسمت راهنما را بزنید.
          </Text>
          <Text style={{paddingTop: 10}}>
            توسط منوی شناور می توانید بین این دو امکان جابجا شوید یا از برنامه خارج گردید.
          </Text>
        </Content>
      </Container>
    );
  }
}
<|endoftext|>


<commit_before>/* cloak server */
/* jshint node:true */

var _ = require('underscore');
var socketIO = require('socket.io');
var uuid = require('node-uuid');
var colors = require('colors');

var User = require('./user.js');
var Room = require('./room.js');
var Timer = require('./timer.js');

module.exports = (function() {

  var users = {};
  var usernames = {};
  var rooms = {};
  var socketIdToUserId = {};
  var io;
  var gameLoopInterval;
  var lobby;
  var roomNum = 0;

  var defaults = {
    port: 8090,
    logLevel: 1,
    gameLoopSpeed: 100,
    defaultRoomSize: null,
    autoCreateRooms: false,
    minRoomMembers: null,
    reconnectWait: 10000,
    pruneEmptyRooms: null,
    roomLife: null,
    autoJoinLobby: true,
    notifyRoomChanges: true
  };

  var config;
  var events;

  colors.setTheme({
    info: 'cyan',
    warn: 'yellow',
    error: 'red'
  });

  var cloak = {

    // shorthand to get host string for socket
    _host: function(socket) {
      return socket.handshake.address.address;
    },

    // configure the server
    configure: function(configArg) {

      config = _.extend({}, defaults);
      events = {};

      _(configArg).forEach(function(val, key) {
        if (key === 'room' ||
            key === 'lobby') {
          events[key] = val;
        }
        else {
          config[key] = val;
        }
      });
    },

    // run the server
    run: function() {

      io = socketIO.listen(config.port);

      io.set('log level', config.logLevel);

      lobby = new Room('Lobby', 0, events.lobby, true);

      Room.prototype._lobby = lobby;
      Room.prototype._autoJoinLobby = config.autoJoinLobby;
      Room.prototype._minRoomMembers = config.minRoomMembers;

      io.sockets.on('connection', function(socket) {
        console.log((cloak._host(socket) + ' connects').info);

        socket.on('disconnect', function(data) {
          var uid = socketIdToUserId[socket.id];
          var user = cloak._getUser(uid);
          if (!user) {
            return;
          }
          user.disconnectedSince = new Date().getTime();
          delete socketIdToUserId[socket.id];
          console.log((cloak._host(socket) + ' disconnects').info);
        });

        socket.on('cloak-begin', function(data) {
          var user = new User(socket);
          users[user.id] = user;
          socketIdToUserId[socket.id] = user.id;
          cloak._setupHandlers(socket);
          socket.emit('cloak-beginResponse', {uid:user.id, config:config});
          console.log((cloak._host(socket) + ' begins').info);
          if (config.autoJoinLobby) {
            lobby.addMember(user);
          }
        });

        socket.on('cloak-resume', function(data) {
          var uid = data.uid;
          var user = users[uid];
          if (user !== undefined) {
            socketIdToUserId[socket.id] = uid;
            user._socket = socket;
            delete user.disconnectedSince;
            cloak._setupHandlers(socket);
            socket.emit('cloak-resumeResponse', {
              valid: true,
              config: config
            });
            console.log((cloak._host(socket) + ' resumes').info);
          }
          else {
            socket.emit('cloak-resumeResponse', {valid: false});
            console.log((cloak._host(socket) + ' fails to resume').info);
          }
        });

        socket.on('cloak-listUsers', function(data) {
          var user = cloak._getUserForSocket(socket);
          socket.emit('cloak-listUsersResponse', {
            users: _.map(user.room.members, function(member) {
              return {
                id: member.id,
                username: member.username,
                room: {
                  id: member.room.id,
                  name: member.room.name,
                  size: member.room.size,
                  userCount: member.room.members.length,
                  lobby: (member.room.id === lobby.id)
                }
              };
            })
          });
        });

        socket.on('cloak-joinLobby', function() {
          var user = cloak._getUserForSocket(socket);
          lobby.addMember(user);
          socket.emit('cloak-joinLobbyResponse', {
            success: true
          });
        });

        socket.on('cloak-leaveRoom', function() {
          var user = cloak._getUserForSocket(socket);
          user.leaveRoom();
          socket.emit('cloak-leaveRoomResponse', {
            success: true
          });
        });

        socket.on('cloak-registerUsername', function(data) {
          var uid = cloak._getUidForSocket(socket);
          var username = data.username;
          var usernames = _.pluck(users, 'username');
          var success = false;
          if (_.indexOf(usernames, username) === -1) {
            success = true;
            users[uid].username = username;
          }
          socket.emit('cloak-registerUsernameResponse', {
            success: success
          });
        });
      });

      gameLoopInterval = setInterval(function() {
        var room;

        // Pulse all rooms
        _(rooms).forEach(function(room) {
          if (config.roomLife !== null &&
              new Date().getTime() - room.created >= config.roomLife) {
            cloak.deleteRoom(room);
          }
          else if (config.pruneEmptyRooms &&
                   room.members.length < 1 &&
                   new Date().getTime() - room._lastEmpty >= config.pruneEmptyRooms) {
            cloak.deleteRoom(room);
          }
          else {
            room.pulse();
          }
        });

        // autoCreateRooms
        if (config.autoCreateRooms &&
            config.minRoomMembers !== null &&
            lobby.members.length >= config.minRoomMembers) {
          roomNum++;
          room = cloak.createRoom('Room ' + roomNum);
          _.range(config.minRoomMembers).forEach(function(i) {
            room.addMember(lobby.members[0]);
          });
        }

        // Prune rooms with member counts below minRoomMembers
        if (config.minRoomMembers !== null) {
          _(rooms).forEach(function(room) {
            if (room._hasReachedMin &&
                room.members.length < config.minRoomMembers) {
              cloak.deleteRoom(room);
            }
          });
        }

        // reconnectWait and reconnectWaitRoomless
        // aka prune users that have been disconnected too long
        if (config.reconnectWait !== null ||
            config.reconnectWaitRoomless !== null) {
          _(users).forEach(function(user) {

            if (user.connected()) {
              return;
            }

            var wait = null;
            if (user.room === undefined && config.reconnectWaitRoomless) {
                wait = config.reconnectWaitRoomless;
            }
            else {
              wait = config.reconnectWait;
            }

            if (wait !== null &&
                new Date().getTime() - user.disconnectedSince >= wait) {
              cloak.deleteUser(user);
            }
          });
        }

      }, config.gameLoopSpeed);

      console.log(('cloak running on port ' + config.port).info);

    },

    _setupHandlers: function(socket) {

      socket.on('cloak-listRooms', function(data) {
        socket.emit('cloak-listRoomsResponse', {
          rooms: cloak._listRoomsForClient()
        });
      });

      socket.on('cloak-joinRoom', function(data) {
        var uid = cloak._getUidForSocket(socket);
        var user = users[uid];
        var room = rooms[data.id];
        var success = false;
        if (room &&
            !room._closing &&
            (room.size === null || room.members.length < room.size)) {
          success = room.addMember(user);
        }
        socket.emit('cloak-joinRoomResponse', {
          success: success
        });
      });

      socket.on('cloak-getRoomMembers', function(data) {
        var room = rooms[data.id];
        var response = room ? room.getMembers() : null;
        socket.emit('cloak-getRoomMembersResponse', {
          members: response
        });
      });

      _(config.messages).each(function(handler, name) {
        socket.on('message-' + name, function(arg) {
          var user = cloak._getUserForSocket(socket);
          try {
            handler(arg, user);
          }
          catch (err) {
            console.error(err);
          }
        });
      });

    },

    _listRoomsForClient: function() {
      return _(rooms).map(function(room, id) {
        return {
          id: id,
          name: room.name,
          userCount: room.members.length,
          users: _.map(room.members, function(member) {
            return {
              id: member.id,
              username: member.username
            };
          }),
          size: room.size
        };
      });
    },

    createRoom: function(name, size) {
      var roomName = name || 'Nameless Room';
      var roomSize = size || config.defaultRoomSize;
      var room = new Room(roomName, roomSize, events.room, false, config.minRoomMembers);
      rooms[room.id] = room;
      if (config.notifyRoomChanges) {
        // Message everyone in lobby
        lobby._serverMessageMembers('roomCreated', cloak._listRoomsForClient());
      }
      return room;
    },

    deleteRoom: function(room) {
      var id = room.id;
      rooms[id]._close();
      delete rooms[id];
      if (config.notifyRoomChanges) {
        // Message everyone in lobby
        lobby._serverMessageMembers('roomDeleted', cloak._listRoomsForClient());
      }
    },

    getRoom: function(id) {
      return rooms[id] || false;
    },

    deleteUser: function(user) {
      user.leaveRoom();
      user._socket.disconnect();
      delete users[user.id];
    },

    _getUidForSocket: function(socket) {
      return socketIdToUserId[socket.id];
    },

    _getUserForSocket: function(socket) {
      return this._getUser(this._getUidForSocket(socket));
    },

    _getUser: function(uid) {
      return users[uid];
    },

    userCount: function() {
      return _(users).size();
    },

    getUsers: function() {
      return _.values(users);
    },

    messageAll: function(name, arg) {
      _(users).forEach(function(user) {
        user.message(name, arg);
      });
    },

    stop: function(callback) {

      // Stop the game loop
      clearInterval(gameLoopInterval);

      // Delete all users
      _(users).forEach(function(user) {
        cloak.deleteUser(user);
      });

      // Delete all rooms
      _(rooms).forEach(function(room) {
        cloak.deleteRoom(room);
      });

      // Shut down socket server
      if (io) {
        try {
          io.server.close();
          io.server.on('close', function() {
            callback();
          });
        }
        catch(e) {
          callback();
        }
      }
      else {
        callback();
      }
    },

    createTimer: function(name, millis, descending) {
      return new Timer(name, millis || 0, descending || false);
    }

  };

  return cloak;

})();
<commit_msg>Improves readability.<commit_after>/* cloak server */
/* jshint node:true */

var _ = require('underscore');
var socketIO = require('socket.io');
var uuid = require('node-uuid');
var colors = require('colors');

var User = require('./user.js');
var Room = require('./room.js');
var Timer = require('./timer.js');

module.exports = (function() {

  var users = {};
  var usernames = {};
  var rooms = {};
  var socketIdToUserId = {};
  var io;
  var gameLoopInterval;
  var lobby;
  var roomNum = 0;

  var defaults = {
    port: 8090,
    logLevel: 1,
    gameLoopSpeed: 100,
    defaultRoomSize: null,
    autoCreateRooms: false,
    minRoomMembers: null,
    reconnectWait: 10000,
    pruneEmptyRooms: null,
    roomLife: null,
    autoJoinLobby: true,
    notifyRoomChanges: true
  };

  var config;
  var events;

  colors.setTheme({
    info: 'cyan',
    warn: 'yellow',
    error: 'red'
  });

  var cloak = {

    // shorthand to get host string for socket
    _host: function(socket) {
      return socket.handshake.address.address;
    },

    // configure the server
    configure: function(configArg) {

      config = _.extend({}, defaults);
      events = {};

      _(configArg).forEach(function(val, key) {
        if (key === 'room' ||
            key === 'lobby') {
          events[key] = val;
        }
        else {
          config[key] = val;
        }
      });
    },

    // run the server
    run: function() {

      io = socketIO.listen(config.port);

      io.set('log level', config.logLevel);

      lobby = new Room('Lobby', 0, events.lobby, true);

      Room.prototype._lobby = lobby;
      Room.prototype._autoJoinLobby = config.autoJoinLobby;
      Room.prototype._minRoomMembers = config.minRoomMembers;

      io.sockets.on('connection', function(socket) {
        console.log((cloak._host(socket) + ' connects').info);

        socket.on('disconnect', function(data) {
          var uid = socketIdToUserId[socket.id];
          var user = cloak._getUser(uid);
          if (!user) {
            return;
          }
          user.disconnectedSince = new Date().getTime();
          delete socketIdToUserId[socket.id];
          console.log((cloak._host(socket) + ' disconnects').info);
        });

        socket.on('cloak-begin', function(data) {
          var user = new User(socket);
          users[user.id] = user;
          socketIdToUserId[socket.id] = user.id;
          cloak._setupHandlers(socket);
          socket.emit('cloak-beginResponse', {uid:user.id, config:config});
          console.log((cloak._host(socket) + ' begins').info);
          if (config.autoJoinLobby) {
            lobby.addMember(user);
          }
        });

        socket.on('cloak-resume', function(data) {
          var uid = data.uid;
          var user = users[uid];
          if (user !== undefined) {
            socketIdToUserId[socket.id] = uid;
            user._socket = socket;
            delete user.disconnectedSince;
            cloak._setupHandlers(socket);
            socket.emit('cloak-resumeResponse', {
              valid: true,
              config: config
            });
            console.log((cloak._host(socket) + ' resumes').info);
          }
          else {
            socket.emit('cloak-resumeResponse', {valid: false});
            console.log((cloak._host(socket) + ' fails to resume').info);
          }
        });

        socket.on('cloak-listUsers', function(data) {
          var user = cloak._getUserForSocket(socket);
          socket.emit('cloak-listUsersResponse', {
            users: _.map(user.room.members, function(member) {
              return {
                id: member.id,
                username: member.username,
                room: {
                  id: member.room.id,
                  name: member.room.name,
                  size: member.room.size,
                  userCount: member.room.members.length,
                  lobby: (member.room.id === lobby.id)
                }
              };
            })
          });
        });

        socket.on('cloak-joinLobby', function() {
          var user = cloak._getUserForSocket(socket);
          lobby.addMember(user);
          socket.emit('cloak-joinLobbyResponse', {
            success: true
          });
        });

        socket.on('cloak-leaveRoom', function() {
          var user = cloak._getUserForSocket(socket);
          user.leaveRoom();
          socket.emit('cloak-leaveRoomResponse', {
            success: true
          });
        });

        socket.on('cloak-registerUsername', function(data) {
          var uid = cloak._getUidForSocket(socket);
          var username = data.username;
          var usernames = _.pluck(users, 'username');
          var success = false;
          if (_.indexOf(usernames, username) === -1) {
            success = true;
            users[uid].username = username;
          }
          socket.emit('cloak-registerUsernameResponse', {
            success: success
          });
        });
      });

      gameLoopInterval = setInterval(function() {
        var room;

        // Pulse all rooms
        _(rooms).forEach(function(room) {
          var oldEnoughToPrune = room.members.length < 1 && new Date().getTime() - room._lastEmpty >= config.pruneEmptyRooms;
          var roomExpired = config.roomLife !== null && new Date().getTime() - room.created >= config.roomLife;

          if (roomExpired) {
            cloak.deleteRoom(room);
          }
          else if (config.pruneEmptyRooms && oldEnoughToPrune) {
            cloak.deleteRoom(room);
          }
          else {
            room.pulse();
          }
        });

        var membersAvailable = config.minRoomMembers !== null && lobby.members.length >= config.minRoomMembers;

        // autoCreateRooms
        if (config.autoCreateRooms && membersAvailable) {
          roomNum++;
          room = cloak.createRoom('Room ' + roomNum);
          _.range(config.minRoomMembers).forEach(function(i) {
            room.addMember(lobby.members[0]);
          });
        }

        // Prune rooms with member counts below minRoomMembers
        if (config.minRoomMembers !== null) {
          _(rooms).forEach(function(room) {
            if (room._hasReachedMin && room.members.length < config.minRoomMembers) {
              cloak.deleteRoom(room);
            }
          });
        }

        // reconnectWait and reconnectWaitRoomless
        // aka prune users that have been disconnected too long
        if (config.reconnectWait !== null || config.reconnectWaitRoomless !== null) {
          _(users).forEach(function(user) {

            if (user.connected()) {
              return;
            }

            var wait = null;
            if (user.room === undefined && config.reconnectWaitRoomless) {
                wait = config.reconnectWaitRoomless;
            }
            else {
              wait = config.reconnectWait;
            }

            var userExpired = new Date().getTime() - user.disconnectedSince >= wait;

            if (wait !== null && userExpired) {
              cloak.deleteUser(user);
            }
          });
        }

      }, config.gameLoopSpeed);

      console.log(('cloak running on port ' + config.port).info);

    },

    _setupHandlers: function(socket) {

      socket.on('cloak-listRooms', function(data) {
        socket.emit('cloak-listRoomsResponse', {
          rooms: cloak._listRoomsForClient()
        });
      });

      socket.on('cloak-joinRoom', function(data) {
        var uid = cloak._getUidForSocket(socket);
        var user = users[uid];
        var room = rooms[data.id];
        var success = false;
        if (room &&
            !room._closing &&
            (room.size === null || room.members.length < room.size)) {
          success = room.addMember(user);
        }
        socket.emit('cloak-joinRoomResponse', {
          success: success
        });
      });

      socket.on('cloak-getRoomMembers', function(data) {
        var room = rooms[data.id];
        var response = room ? room.getMembers() : null;
        socket.emit('cloak-getRoomMembersResponse', {
          members: response
        });
      });

      _(config.messages).each(function(handler, name) {
        socket.on('message-' + name, function(arg) {
          var user = cloak._getUserForSocket(socket);
          try {
            handler(arg, user);
          }
          catch (err) {
            console.error(err);
          }
        });
      });

    },

    _listRoomsForClient: function() {
      return _(rooms).map(function(room, id) {
        return {
          id: id,
          name: room.name,
          userCount: room.members.length,
          users: _.map(room.members, function(member) {
            return {
              id: member.id,
              username: member.username
            };
          }),
          size: room.size
        };
      });
    },

    createRoom: function(name, size) {
      var roomName = name || 'Nameless Room';
      var roomSize = size || config.defaultRoomSize;
      var room = new Room(roomName, roomSize, events.room, false, config.minRoomMembers);
      rooms[room.id] = room;
      if (config.notifyRoomChanges) {
        // Message everyone in lobby
        lobby._serverMessageMembers('roomCreated', cloak._listRoomsForClient());
      }
      return room;
    },

    deleteRoom: function(room) {
      var id = room.id;
      rooms[id]._close();
      delete rooms[id];
      if (config.notifyRoomChanges) {
        // Message everyone in lobby
        lobby._serverMessageMembers('roomDeleted', cloak._listRoomsForClient());
      }
    },

    getRoom: function(id) {
      return rooms[id] || false;
    },

    deleteUser: function(user) {
      user.leaveRoom();
      user._socket.disconnect();
      delete users[user.id];
    },

    _getUidForSocket: function(socket) {
      return socketIdToUserId[socket.id];
    },

    _getUserForSocket: function(socket) {
      return this._getUser(this._getUidForSocket(socket));
    },

    _getUser: function(uid) {
      return users[uid];
    },

    userCount: function() {
      return _(users).size();
    },

    getUsers: function() {
      return _.values(users);
    },

    messageAll: function(name, arg) {
      _(users).forEach(function(user) {
        user.message(name, arg);
      });
    },

    stop: function(callback) {

      // Stop the game loop
      clearInterval(gameLoopInterval);

      // Delete all users
      _(users).forEach(function(user) {
        cloak.deleteUser(user);
      });

      // Delete all rooms
      _(rooms).forEach(function(room) {
        cloak.deleteRoom(room);
      });

      // Shut down socket server
      if (io) {
        try {
          io.server.close();
          io.server.on('close', function() {
            callback();
          });
        }
        catch(e) {
          callback();
        }
      }
      else {
        callback();
      }
    },

    createTimer: function(name, millis, descending) {
      return new Timer(name, millis || 0, descending || false);
    }

  };

  return cloak;

})();
<|endoftext|>


<commit_before>//Import Depedencies
const express = require('express');
const router = express.Router();

const controller = require('./controller');
const config = require('../../config');

const geneQueryService = require('../gene-query');

const isAuthenticated = token => {
  return config.MASTER_PASSWORD != '' && config.MASTER_PASSWORD === token;
};
const errorMsg = {
  error: 'Invalid access token'
};

// Expose a rest endpoint for controller.submitLayout
router.post('/submit-layout', function (req, res) {
  if (isAuthenticated(req.body.token)) {
    controller.submitLayout(req.body.uri, req.body.version, req.body.layout, req.body.user)
      .then((package) => {
        res.json(package);
      });
  } else {
    res.json(errorMsg);
  }
});

// Expose a rest endpoint for controller.submitGraph
router.post('/submit-graph', function (req, res) {
  if (isAuthenticated(req.body.token)) {
    controller.submitGraph(req.body.uri, req.body.version, req.body.graph)
    .then((package) => {
      res.json(package);
    });
  } else {
    res.json(errorMsg);
  }
});

// Expose a rest endpoint for controller.submitDiff
router.post('/submit-diff', function (req, res) {
  if (isAuthenticated(req.body.token)) {
    controller.submitDiff(req.body.uri, req.body.version, req.body.diff, req.body.user)
      .then((package) => {
        res.json(package);
      });
  } else {
    res.json(errorMsg);
  }
});

// Expose a rest endpoint for controller.getGraphAndLayout
router.get('/get-graph-and-layout', function (req, res) {
  controller.getGraphAndLayout(req.query.uri, req.query.version).then((package) => {
    res.json(package);
  });
});

<<<<<<< HEAD
router.get('/gene-query/', (req, res) => {
  const genes = req.query.genes;

  res.json({});
=======
router.get('/test/', (req, res) => {
  const genes = req.query.genes;

  res.json(geneQueryService(genes));

>>>>>>> a8ce9c8... initial commit
});
// Expose a rest endpoint for controller.endSession
router.get('/disconnect', function (req, res) {
  controller.endSession(req.query.uri, req.query.version, req.query.user)
    .then((package) => {
      res.json(package);
    });
});

module.exports = router;<commit_msg>forgot to remove merge conflicts<commit_after>//Import Depedencies
const express = require('express');
const router = express.Router();

const controller = require('./controller');
const config = require('../../config');

const geneQueryService = require('../gene-query');

const isAuthenticated = token => {
  return config.MASTER_PASSWORD != '' && config.MASTER_PASSWORD === token;
};
const errorMsg = {
  error: 'Invalid access token'
};

// Expose a rest endpoint for controller.submitLayout
router.post('/submit-layout', function (req, res) {
  if (isAuthenticated(req.body.token)) {
    controller.submitLayout(req.body.uri, req.body.version, req.body.layout, req.body.user)
      .then((package) => {
        res.json(package);
      });
  } else {
    res.json(errorMsg);
  }
});

// Expose a rest endpoint for controller.submitGraph
router.post('/submit-graph', function (req, res) {
  if (isAuthenticated(req.body.token)) {
    controller.submitGraph(req.body.uri, req.body.version, req.body.graph)
    .then((package) => {
      res.json(package);
    });
  } else {
    res.json(errorMsg);
  }
});

// Expose a rest endpoint for controller.submitDiff
router.post('/submit-diff', function (req, res) {
  if (isAuthenticated(req.body.token)) {
    controller.submitDiff(req.body.uri, req.body.version, req.body.diff, req.body.user)
      .then((package) => {
        res.json(package);
      });
  } else {
    res.json(errorMsg);
  }
});

// Expose a rest endpoint for controller.getGraphAndLayout
router.get('/get-graph-and-layout', function (req, res) {
  controller.getGraphAndLayout(req.query.uri, req.query.version).then((package) => {
    res.json(package);
  });
});

router.get('/gene-query/', (req, res) => {
  const genes = req.query.genes;

  res.json({});
});
// Expose a rest endpoint for controller.endSession
router.get('/disconnect', function (req, res) {
  controller.endSession(req.query.uri, req.query.version, req.query.user)
    .then((package) => {
      res.json(package);
    });
});

module.exports = router;<|endoftext|>


<commit_before>import zlib from 'zlib';
import fs from 'fs';
import tar from 'tar-stream';
import docker from './docker';

export function matchLibraries(code){

	const REQUIRE_RE = /require\(['"]([^'"]+)['"](?:, ['"]([^'"]+)['"])?\);?/g;
	const IMPORT_RE  = /\bimport\s+(?:.+\s+from\s+)?[\'"]([^"\']+)["\']/g;

	const requires = code.match(REQUIRE_RE);
	const imports = code.match(IMPORT_RE);
	let r1 = [], r2 = [];

	if (requires && requires.length > 0){
		r1 = requires.map((pkg)=>{
			return pkg.replace(/require\w*\(\w*['"]/g, "").replace(/['"]\);*/g,"")
		});
	}

	if (imports && imports.length > 0){
	 	r2 = imports.map((module)=>{
			return module.replace(/import\s*/g,"").replace(/\s*(\w|\W|\s)*from\s*/g,"").replace(/['"]/g, "");
		});
	}

	return [...r1, ...r2];
}

export function flatten(arr){
	return arr.reduce((acc, row)=>{
			return row.reduce((acc, src)=>{
					acc.push(src);
					return acc;
			}, acc);
	}, [])
}

export function dedup(arr){
	let seen = {};
	return arr.filter((item)=>{
		if (seen[item])
			return false;
		seen[item] = true;
		return true;
	});
}

const _addEntry = function(pack, name, file){
	return new Promise((resolve, reject)=>{
		pack.entry({name: name}, file, function(err){
			if (err){
				console.log("error adding entry!", err);
				reject(err);
			}
			else{
				resolve(true);
			}
		});
	});
}

export function createTarFile(dockerfile, flowfile, path){

	const tarball = fs.createWriteStream(path);
	const gzip   = zlib.createGzip();
	const pack   = tar.pack();

	return _addEntry(pack, "Dockerfile", dockerfile).then(()=>{
		return _addEntry(pack, "flows.json", flowfile)
	})
	.then(()=>{

		pack.finalize();

		const stream = pack.pipe(gzip).pipe(tarball);

		return new Promise((resolve,reject)=>{

			stream.on('finish', function (err) {
				if(err){
					console.log("error creating tar file", err);
					reject(err);
				}else{
					console.log("successfully created tar file",path);
					resolve(path);
				}
			});
		});
	});
}
	/*return new Promise((resolve, reject)=>{
		var tarball = fs.createWriteStream(path);
		const gzip   = zlib.createGzip();
		const pack   = tar.pack();
		pack.entry({name: 'Dockerfile'}, dockerfile, function(err){
			if (err){
				reject(err);
			}

			console.log("am herwe");

			pack.entry({name: "flows.json"}, flowfile, function(err){
				if (err){

        	   		reject(err);
        		}
        		console.log("finalising");
        		pack.finalize();

        		const stream = pack.pipe(gzip).pipe(tarball);

				stream.on('finish', function (err) {
					resolve(path);
				});
			});
		});
	})
}*/

/*export function createTarFile(dockerfile, path){

	return new Promise((resolve, reject)=>{

		var tarball = fs.createWriteStream(path);
		const gzip   = zlib.createGzip();
		const pack   = tar.pack();

		pack.entry({name: 'Dockerfile'}, dockerfile, function(err){
        	if (err){
        	   reject(err);
        	}
        	pack.finalize();

        	const stream = pack.pipe(gzip).pipe(tarball);

			stream.on('finish', function (err) {
				resolve(path);
			});
		});
	});
}*/

export function createDockerImage(tarfile, tag){

	console.log(`creating image for tarfile ${tarfile} with tag ${tag}`);

	return new Promise((resolve, reject)=>{
		docker.buildImage(tarfile, {t: tag, nocache:true}, function (err, output){
			if (err){
				console.warn(err);
				reject(err);
			}
			output.pipe(process.stdout);

			output.on('end', function() {
				resolve(tag);
			});
		});
	});
}

export function uploadImageToRegistry(tag, registry){

	return new Promise((resolve, reject)=>{
		if (registry && registry.trim() !== ""){
			console.log("uploading to registry", registry);

			var image = docker.getImage(tag);
			image.push({
				registry : registry
			}, function(err, data) {
				data.pipe(process.stdout);
				if (err){
					reject(err)
				}
				resolve();
			});

		}
		else{
			resolve();
		}
	});
}

export function stopAndRemoveContainer(name){

	return new Promise((resolve, reject)=>{

		const container = docker.listContainers(function (err, containers) {

			if (err){
				reject(err);
			}

			const container = containers.reduce((acc, container)=>{
				if (container.Names.indexOf(`/${name}`) != -1){
					return container;
				}
				return acc;
			},null);

			if (!container){
				console.log("did not find running container");
				resolve(true);
				return;
			}

			var containerToStop = docker.getContainer(container.Id);

			containerToStop.stop((err,data)=>{
				console.log("container stopped!");
				if (err){
					reject(err);
				}
				containerToStop.remove((err, data)=>{
					if (err){
						reject(err);
					}
					resolve(true);
				});
			});
		});

	});
}

/*
 note we open port 9123  to open a websocket to receive video from the client when
 a webcam is used and 8096 is the (docker mapped) port that serves up the webcam page
*/
export function createTestContainer(image, name, network){
	console.log(`creating test container ${image}, name: ${name}`);
	return new Promise((resolve, reject)=>{
		docker.createContainer(
								{	Image: image,
									PublishAllPorts:true,
									Links: ["mock-datasource:mock-datasource","databox-test-server:databox-test-server", "openface:openface"],
									Env: ["TESTING=true", "MOCK_DATA_SOURCE=http://mock-datasource:8080"],
									//HostConfig: {NetworkMode: network},
									Labels: {'user':`${name}`},
									ExposedPorts: {"1880/tcp": {}, "9123/tcp":{}, "8096/tcp":{}},
									PortBindings: { "9123/tcp": [{ "HostPort": "9123" }] },
									Cmd: ["npm", "start", "--", "--userDir", "/data"],
									name: `${name}-red`
								},
			function (err, container) {
				if (err){
					console.log(err);
					reject(err);
				}else{

				container.start({}, function (err, data) {
					if (err){
						console.log("error starting container",err);
						reject(err);
					}else{
						resolve(container);
					}
				});
			}
		});
	});
}

export function writeTempFile(filestr, fileName){

	return new Promise((resolve, reject)=>{
		fs.writeFile(fileName, filestr, function(err) {
			if(err) {
				reject(err);
			}

			resolve(true);
		});
	});
}

export function removeTempFile(fileName){
	return new Promise((resolve,reject)=>{
		fs.unlink(fileName, function(err){
			if(err) {
				console.log(err);
				reject(err);
			}
			resolve(true);
		});
	});
}<commit_msg>removed link to openface when build image<commit_after>import zlib from 'zlib';
import fs from 'fs';
import tar from 'tar-stream';
import docker from './docker';

export function matchLibraries(code){

	const REQUIRE_RE = /require\(['"]([^'"]+)['"](?:, ['"]([^'"]+)['"])?\);?/g;
	const IMPORT_RE  = /\bimport\s+(?:.+\s+from\s+)?[\'"]([^"\']+)["\']/g;

	const requires = code.match(REQUIRE_RE);
	const imports = code.match(IMPORT_RE);
	let r1 = [], r2 = [];

	if (requires && requires.length > 0){
		r1 = requires.map((pkg)=>{
			return pkg.replace(/require\w*\(\w*['"]/g, "").replace(/['"]\);*/g,"")
		});
	}

	if (imports && imports.length > 0){
	 	r2 = imports.map((module)=>{
			return module.replace(/import\s*/g,"").replace(/\s*(\w|\W|\s)*from\s*/g,"").replace(/['"]/g, "");
		});
	}

	return [...r1, ...r2];
}

export function flatten(arr){
	return arr.reduce((acc, row)=>{
			return row.reduce((acc, src)=>{
					acc.push(src);
					return acc;
			}, acc);
	}, [])
}

export function dedup(arr){
	let seen = {};
	return arr.filter((item)=>{
		if (seen[item])
			return false;
		seen[item] = true;
		return true;
	});
}

const _addEntry = function(pack, name, file){
	return new Promise((resolve, reject)=>{
		pack.entry({name: name}, file, function(err){
			if (err){
				console.log("error adding entry!", err);
				reject(err);
			}
			else{
				resolve(true);
			}
		});
	});
}

export function createTarFile(dockerfile, flowfile, path){

	const tarball = fs.createWriteStream(path);
	const gzip   = zlib.createGzip();
	const pack   = tar.pack();

	return _addEntry(pack, "Dockerfile", dockerfile).then(()=>{
		return _addEntry(pack, "flows.json", flowfile)
	})
	.then(()=>{

		pack.finalize();

		const stream = pack.pipe(gzip).pipe(tarball);

		return new Promise((resolve,reject)=>{

			stream.on('finish', function (err) {
				if(err){
					console.log("error creating tar file", err);
					reject(err);
				}else{
					console.log("successfully created tar file",path);
					resolve(path);
				}
			});
		});
	});
}
	/*return new Promise((resolve, reject)=>{
		var tarball = fs.createWriteStream(path);
		const gzip   = zlib.createGzip();
		const pack   = tar.pack();
		pack.entry({name: 'Dockerfile'}, dockerfile, function(err){
			if (err){
				reject(err);
			}

			console.log("am herwe");

			pack.entry({name: "flows.json"}, flowfile, function(err){
				if (err){

        	   		reject(err);
        		}
        		console.log("finalising");
        		pack.finalize();

        		const stream = pack.pipe(gzip).pipe(tarball);

				stream.on('finish', function (err) {
					resolve(path);
				});
			});
		});
	})
}*/

/*export function createTarFile(dockerfile, path){

	return new Promise((resolve, reject)=>{

		var tarball = fs.createWriteStream(path);
		const gzip   = zlib.createGzip();
		const pack   = tar.pack();

		pack.entry({name: 'Dockerfile'}, dockerfile, function(err){
        	if (err){
        	   reject(err);
        	}
        	pack.finalize();

        	const stream = pack.pipe(gzip).pipe(tarball);

			stream.on('finish', function (err) {
				resolve(path);
			});
		});
	});
}*/

export function createDockerImage(tarfile, tag){

	console.log(`creating image for tarfile ${tarfile} with tag ${tag}`);

	return new Promise((resolve, reject)=>{
		docker.buildImage(tarfile, {t: tag, nocache:true}, function (err, output){
			if (err){
				console.warn(err);
				reject(err);
			}
			output.pipe(process.stdout);

			output.on('end', function() {
				resolve(tag);
			});
		});
	});
}

export function uploadImageToRegistry(tag, registry){

	return new Promise((resolve, reject)=>{
		if (registry && registry.trim() !== ""){
			console.log("uploading to registry", registry);

			var image = docker.getImage(tag);
			image.push({
				registry : registry
			}, function(err, data) {
				data.pipe(process.stdout);
				if (err){
					reject(err)
				}
				resolve();
			});

		}
		else{
			resolve();
		}
	});
}

export function stopAndRemoveContainer(name){

	return new Promise((resolve, reject)=>{

		const container = docker.listContainers(function (err, containers) {

			if (err){
				reject(err);
			}

			const container = containers.reduce((acc, container)=>{
				if (container.Names.indexOf(`/${name}`) != -1){
					return container;
				}
				return acc;
			},null);

			if (!container){
				console.log("did not find running container");
				resolve(true);
				return;
			}

			var containerToStop = docker.getContainer(container.Id);

			containerToStop.stop((err,data)=>{
				console.log("container stopped!");
				if (err){
					reject(err);
				}
				containerToStop.remove((err, data)=>{
					if (err){
						reject(err);
					}
					resolve(true);
				});
			});
		});

	});
}

/*
 note we open port 9123  to open a websocket to receive video from the client when
 a webcam is used and 8096 is the (docker mapped) port that serves up the webcam page
*/
export function createTestContainer(image, name, network){
	console.log(`creating test container ${image}, name: ${name}`);
	return new Promise((resolve, reject)=>{
		docker.createContainer(
								{	Image: image,
									PublishAllPorts:true,
									Links: ["mock-datasource:mock-datasource","databox-test-server:databox-test-server" /*, "openface:openface"*/],
									Env: ["TESTING=true", "MOCK_DATA_SOURCE=http://mock-datasource:8080"],
									//HostConfig: {NetworkMode: network},
									Labels: {'user':`${name}`},
									ExposedPorts: {"1880/tcp": {}, "9123/tcp":{}, "8096/tcp":{}},
									PortBindings: { "9123/tcp": [{ "HostPort": "9123" }] },
									Cmd: ["npm", "start", "--", "--userDir", "/data"],
									name: `${name}-red`
								},
			function (err, container) {
				if (err){
					console.log(err);
					reject(err);
				}else{

				container.start({}, function (err, data) {
					if (err){
						console.log("error starting container",err);
						reject(err);
					}else{
						resolve(container);
					}
				});
			}
		});
	});
}

export function writeTempFile(filestr, fileName){

	return new Promise((resolve, reject)=>{
		fs.writeFile(fileName, filestr, function(err) {
			if(err) {
				reject(err);
			}

			resolve(true);
		});
	});
}

export function removeTempFile(fileName){
	return new Promise((resolve,reject)=>{
		fs.unlink(fileName, function(err){
			if(err) {
				console.log(err);
				reject(err);
			}
			resolve(true);
		});
	});
}<|endoftext|>