<commit_before>/*-
 * Copyright (c) 2014 Peter Tworek
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the author nor the names of any co-contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

.import "Settings.js" as Settings

var _youtube_data_v3_url = "https://www.googleapis.com/youtube/v3/";

function getYoutubeV3Url(reference, queryParams)
{
    var locale = Qt.locale().name;
    if (locale === "C") {
        locale = "en_US";
    }

    var url =  _youtube_data_v3_url + reference +
            "?regionCode=" + regionCode +
            "&key=" + NativeUtil.YouTubeDataKey +
            "&hl=" + locale;

    for (var key in queryParams) {
        if (queryParams.hasOwnProperty(key)) {
            url += "&" + key + "=" + queryParams[key];
        }
    }
    return url;
}

function getVideoCategories(result, onSuccess, onFailure)
{
    var url = getYoutubeV3Url("videoCategories", {"part" : "snippet"});

    console.debug("XHR: " + url);

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status == 200) {
                var items = JSON.parse(xhr.responseText)["items"];
                for (var i = 0; i < items.length; i++) {
                    var category = items[i];
                    if (category.snippet.assignable) {
                        result.append(category);
                    }
                }
                onSuccess();
            } else {
                onFailure({"code" : xhr.status, "details" : JSON.parse(xhr.responseText)});
            }
        }
    }
    xhr.open("GET", url);
    xhr.send();
}

function getVideosInCategory(categoryId, onSuccess, onFailure, pageToken)
{
    var resultsPerPage = Settings.get(Settings.RESULTS_PER_PAGE);
    var qParams = {};

    qParams["part"] = "snippet";
    qParams["maxResults"] = resultsPerPage;
    qParams["chart"] = "mostPopular";
    qParams["videoCategoryId"] = categoryId;

    var url = getYoutubeV3Url("videos", qParams);

    if (pageToken !== undefined) {
        url += "&pageToken=" + pageToken;
    }

    console.debug("XHR: " + url);

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status == 200) {
                onSuccess(JSON.parse(xhr.responseText));
            } else {
                onFailure({"code" : xhr.status, "details" : JSON.parse(xhr.responseText)});
            }
        }
    }
    xhr.open("GET", url);
    xhr.send();
}

function getVideoDetails(videoId, onSuccess, onFailure)
{
    var url = getYoutubeV3Url("videos", {"part" : "contentDetails, snippet",
                              "id" : videoId});

    console.debug("XHR: " + url);

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status !== 200) {
                onFailure({"code" : xhr.status, "details" : JSON.parse(xhr.responseText)});
                return;
            }
            var details = JSON.parse(xhr.responseText);
            onSuccess(details.items[0]);
        }
    }
    xhr.open("GET", url);
    xhr.send();
}

function getSearchResults(query, onSuccess, onFailure, pageToken)
{
    var qParams = {};
    qParams["q"] = query;
    qParams["part"] = "snippet";
    qParams["maxResults"] = Settings.get(Settings.RESULTS_PER_PAGE);
    if (pageToken) {
        qParams["pageToken"] = pageToken;
    }

    var url = getYoutubeV3Url("search", qParams);

    console.debug("XHR: " + url);

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == XMLHttpRequest.DONE) {
            if (xhr.status !== 200) {
                onFailure({"code" : xhr.status, "details" : JSON.parse(xhr.responseText)});
                return;
            }
            var response = JSON.parse(xhr.responseText);
            onSuccess(response);
        }
    }
    xhr.open("GET", url);
    xhr.send();
}

function getVideoUrl(videoId, onSuccess, onFailure)
{
    var req = "http://www.youtube.com/get_video_info?video_id=" + videoId +
            "&el=player_embedded&gl=US&hl=en&eurl=https://youtube.googleapis.com/v/&asf=3&sts=1588";

    console.debug("XHR: " + req);

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status !== 200) {
                onFailure({"code" : xhr.status, "details" : JSON.parse(xhr.responseText)});
                return;
            }
            var stream_map_str = undefined;
            var tokens = xhr.responseText.split("&");
            for (var i = 0; i < tokens.length; i++) {
                var pair = tokens[i].split("=");
                if (pair[0] === "url_encoded_fmt_stream_map") {
                    stream_map_str = decodeURIComponent(pair[1]);
                    break;
                }
            }

            if (stream_map_str === undefined) {
                onFailure({"code" : 0, "details" : "No video streams found!"});
                return;
            }

            //console.debug("Stream map string: " + stream_map_str );

            var stream_map_array = [];
            tokens = stream_map_str.split(',');
            for (var i = 0; i < tokens.length; i++) {
                //console.debug("Stream map array element " + i);
                var map_elements = tokens[i].split('&');
                var map = {};
                for (var k = 0; k < map_elements.length; k++) {
                    var map_entry = map_elements[k].split('=');
                    if (map_entry[0] === 'url') {
                        map[map_entry[0]] = decodeURIComponent(map_entry[1]);
                    } else {
                        map[map_entry[0]] = map_entry[1];
                    }
                    //console.debug("  " + map_entry[0] + " = " + map[map_entry[0]]);
                }
                stream_map_array[i] = map;
            }

            //console.debug(JSON.stringify(stream_map_array, undefined, 2));

            var selected_url = undefined;
            for (var i = 0; i < stream_map_array.length; i++) {
                if (stream_map_array[i].itag === "18") {
                    if ("sig" in stream_map_array[i]) {
                        selected_url = stream_map_array[i].url +
                                "&signature=" + stream_map_array[i].sig;
                    } else {
                        // Encrypted content not supported directly
                        console.log("No support for playing videos with encrypted signatures from youtube directly\n" +
                                    "Falling back yo ytapi.com");
                        selected_url = getVideoUrlYtAPI(videoId, 18);
                    }

                    break;
                }
            }

            if (selected_url === undefined) {
                onFailure({"code" : 0, "details" : "No 360p video stream found!"});
                return;
            }

            onSuccess(selected_url);
        }
    }
    xhr.open("GET", req);
    xhr.send();
}

function getVideoUrlYtAPI(videoId, itag)
{
    return "http://ytapi.com/?vid=" + videoId + "&format=direct&itag=" + itag;
}
<commit_msg>Until browsig playlist and channels is supported only show vides in search results<commit_after>/*-
 * Copyright (c) 2014 Peter Tworek
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the author nor the names of any co-contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

.import "Settings.js" as Settings

var _youtube_data_v3_url = "https://www.googleapis.com/youtube/v3/";

function getYoutubeV3Url(reference, queryParams)
{
    var locale = Qt.locale().name;
    if (locale === "C") {
        locale = "en_US";
    }

    var url =  _youtube_data_v3_url + reference +
            "?regionCode=" + regionCode +
            "&key=" + NativeUtil.YouTubeDataKey +
            "&hl=" + locale;

    for (var key in queryParams) {
        if (queryParams.hasOwnProperty(key)) {
            url += "&" + key + "=" + queryParams[key];
        }
    }
    return url;
}

function getVideoCategories(result, onSuccess, onFailure)
{
    var url = getYoutubeV3Url("videoCategories", {"part" : "snippet"});

    console.debug("XHR: " + url);

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status == 200) {
                var items = JSON.parse(xhr.responseText)["items"];
                for (var i = 0; i < items.length; i++) {
                    var category = items[i];
                    if (category.snippet.assignable) {
                        result.append(category);
                    }
                }
                onSuccess();
            } else {
                onFailure({"code" : xhr.status, "details" : JSON.parse(xhr.responseText)});
            }
        }
    }
    xhr.open("GET", url);
    xhr.send();
}

function getVideosInCategory(categoryId, onSuccess, onFailure, pageToken)
{
    var resultsPerPage = Settings.get(Settings.RESULTS_PER_PAGE);
    var qParams = {};

    qParams["part"] = "snippet";
    qParams["maxResults"] = resultsPerPage;
    qParams["chart"] = "mostPopular";
    qParams["videoCategoryId"] = categoryId;

    var url = getYoutubeV3Url("videos", qParams);

    if (pageToken !== undefined) {
        url += "&pageToken=" + pageToken;
    }

    console.debug("XHR: " + url);

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status == 200) {
                onSuccess(JSON.parse(xhr.responseText));
            } else {
                onFailure({"code" : xhr.status, "details" : JSON.parse(xhr.responseText)});
            }
        }
    }
    xhr.open("GET", url);
    xhr.send();
}

function getVideoDetails(videoId, onSuccess, onFailure)
{
    var url = getYoutubeV3Url("videos", {"part" : "contentDetails, snippet",
                              "id" : videoId});

    console.debug("XHR: " + url);

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status !== 200) {
                onFailure({"code" : xhr.status, "details" : JSON.parse(xhr.responseText)});
                return;
            }
            var details = JSON.parse(xhr.responseText);
            onSuccess(details.items[0]);
        }
    }
    xhr.open("GET", url);
    xhr.send();
}

function getSearchResults(query, onSuccess, onFailure, pageToken)
{
    var qParams = {};
    qParams["q"] = query;
    qParams["part"] = "snippet";
    qParams["maxResults"] = Settings.get(Settings.RESULTS_PER_PAGE);
    //TODO: Only search for videos until browsing channels and playlist is implemented
    qParams["type"] = "video";
    if (pageToken) {
        qParams["pageToken"] = pageToken;
    }

    var url = getYoutubeV3Url("search", qParams);

    console.debug("XHR: " + url);

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == XMLHttpRequest.DONE) {
            if (xhr.status !== 200) {
                onFailure({"code" : xhr.status, "details" : JSON.parse(xhr.responseText)});
                return;
            }
            var response = JSON.parse(xhr.responseText);
            onSuccess(response);
        }
    }
    xhr.open("GET", url);
    xhr.send();
}

function getVideoUrl(videoId, onSuccess, onFailure)
{
    var req = "http://www.youtube.com/get_video_info?video_id=" + videoId +
            "&el=player_embedded&gl=US&hl=en&eurl=https://youtube.googleapis.com/v/&asf=3&sts=1588";

    console.debug("XHR: " + req);

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status !== 200) {
                onFailure({"code" : xhr.status, "details" : JSON.parse(xhr.responseText)});
                return;
            }
            var stream_map_str = undefined;
            var tokens = xhr.responseText.split("&");
            for (var i = 0; i < tokens.length; i++) {
                var pair = tokens[i].split("=");
                if (pair[0] === "url_encoded_fmt_stream_map") {
                    stream_map_str = decodeURIComponent(pair[1]);
                    break;
                }
            }

            if (stream_map_str === undefined) {
                onFailure({"code" : 0, "details" : "No video streams found!"});
                return;
            }

            //console.debug("Stream map string: " + stream_map_str );

            var stream_map_array = [];
            tokens = stream_map_str.split(',');
            for (var i = 0; i < tokens.length; i++) {
                //console.debug("Stream map array element " + i);
                var map_elements = tokens[i].split('&');
                var map = {};
                for (var k = 0; k < map_elements.length; k++) {
                    var map_entry = map_elements[k].split('=');
                    if (map_entry[0] === 'url') {
                        map[map_entry[0]] = decodeURIComponent(map_entry[1]);
                    } else {
                        map[map_entry[0]] = map_entry[1];
                    }
                    //console.debug("  " + map_entry[0] + " = " + map[map_entry[0]]);
                }
                stream_map_array[i] = map;
            }

            //console.debug(JSON.stringify(stream_map_array, undefined, 2));

            var selected_url = undefined;
            for (var i = 0; i < stream_map_array.length; i++) {
                if (stream_map_array[i].itag === "18") {
                    if ("sig" in stream_map_array[i]) {
                        selected_url = stream_map_array[i].url +
                                "&signature=" + stream_map_array[i].sig;
                    } else {
                        // Encrypted content not supported directly
                        console.log("No support for playing videos with encrypted signatures from youtube directly\n" +
                                    "Falling back yo ytapi.com");
                        selected_url = getVideoUrlYtAPI(videoId, 18);
                    }

                    break;
                }
            }

            if (selected_url === undefined) {
                onFailure({"code" : 0, "details" : "No 360p video stream found!"});
                return;
            }

            onSuccess(selected_url);
        }
    }
    xhr.open("GET", req);
    xhr.send();
}

function getVideoUrlYtAPI(videoId, itag)
{
    return "http://ytapi.com/?vid=" + videoId + "&format=direct&itag=" + itag;
}
<|endoftext|>


<commit_before>'use strict';

// Evenements controller
angular.module('evenements').controller('EvenementsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Evenements', 'Users', 'fileReader',
	function($scope, $stateParams, $location, Authentication, Evenements, Users, fileReader) {
		$scope.authentication = Authentication;
        $scope.guests = Users.query();
        /*global Google */

        /* users Filtered by guest, see if he's guest or not*/
        $scope.UserFilterGuest = function(eve) {
            return function( user ) {
                for(var i = 0; i < eve.guests.length; i++){
                    if(user._id === eve.guests[i]._id){
                        return true;
                    }
                }
            };
        };

        /* users Filtered by mine, see if I am invited or if I created the event*/
        $scope.EventsFilterMine = function() {
            return function( eve ) {
                for(var i = 0; i < eve.guests.length; i++){
                    if(Authentication.user._id === eve.guests[i] || Authentication.user._id === eve.user._id){
                        return true;
                    }
                }
            };
        };

        $scope.googleMapPointer = function(){
            // This example adds a search box to a map, using the Google Place Autocomplete
// feature. People can enter geographical searches. The search box will return a
// pick list containing a mix of places and predicted search terms.
            var map;
            var input;
            function initialize() {
                var markers = [];

                var mapOptions = {
                    zoom: 8,
                    center: new google.maps.LatLng(-34.397, 150.644)
                };

                map = new google.maps.Map(document.getElementById('map-canvas'),
                    mapOptions);

                var defaultBounds = new google.maps.LatLngBounds(
                    new google.maps.LatLng(-33.8902, 151.1759),
                    new google.maps.LatLng(-33.8474, 151.2631));
                    map.fitBounds(defaultBounds);

                // Create the search box and link it to the UI element.
                input = (document.getElementById('pac-input'));
                map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

                var searchBox = new google.maps.places.SearchBox((input));

                // Listen for the event fired when the user selects an item from the
                // pick list. Retrieve the matching places for that item.
                google.maps.event.addListener(searchBox, 'places_changed', function() {
                    var places = searchBox.getPlaces();

                    if (places.length === 0) {
                        return;
                    }
                    var i;
                    var marker;
                    for (i = 0, marker; marker = markers[i]; i++) {
                        marker.setMap(null);
                    }

                    // For each place, get the icon, place name, and location.
                    markers = [];
                    var bounds = new google.maps.LatLngBounds();
                    var i;
                    var place;
                    for (i = 0, place; place = places[i]; i++) {
                        var image = {
                            url: place.icon,
                            size: new google.maps.Size(71, 71),
                            origin: new google.maps.Point(0, 0),
                            anchor: new google.maps.Point(17, 34),
                            scaledSize: new google.maps.Size(25, 25)
                        };

                        // Create a marker for each place.
                        var marker = new google.maps.Marker({
                            map: map,
                            icon: image,
                            title: place.name,
                            position: place.geometry.location
                        });

                        markers.push(marker);

                        bounds.extend(place.geometry.location);

                        $scope.placeName = place.name;
                        $scope.lat = place.geometry.location.A;
                        $scope.long = place.geometry.location.F;
                        alert($scope.long);
                        alert($scope.placeName);
                    }

                    map.fitBounds(bounds);
                });

                // Bias the SearchBox results towards places that are within the bounds of the
                // current map's viewport.
                google.maps.event.addListener(map, 'bounds_changed', function() {
                    var bounds = map.getBounds();
                    searchBox.setBounds(bounds);
                });
            }
            /*initialize();*/
            google.maps.event.addDomListener(window, 'load', initialize);
        };

        // Get cover image for the event
        $scope.getFile = function () {
            $scope.progress = 0;
            fileReader.readAsDataUrl($scope.file, $scope)
                .then(function(result) {
                    $scope.imageSrc = result;
                    var imageSrcSplit = result.split(';base64'); // return data:image/*
                    var imageTypeSplit = imageSrcSplit[0].split('image/'); // return * the type of the image
                    $scope.imageContentType = imageTypeSplit[1];
                    var i = new Image();
                    i.src = result;
                    $scope.originalWidth = i.width;
                    $scope.originalHeight = i.height;
                });
        };

        $scope.$on('fileProgress', function(e, progress) {
            $scope.progress = progress.loaded / progress.total;
        });

        // Display the create page
        $scope.createDisplay = function() {
            $scope.selection = [];

            // helper method to get the selected
            $scope.selectedGuests = function selectedGuests() {
                return filterFilter($scope.guests, { selected: true });
            };

            // watch for changes
            $scope.$watch('guests|filter:{selected:true}', function (nv) {
                $scope.selection = nv.map(function (guest) {
                    return guest._id;
                });
            }, true);
        };

		$scope.create = function() {
			// Create new Evenement object

            var beginDate  = $scope.evenement.beginDate;
            var beginTime  = $scope.evenement.beginTime;

            beginDate = beginDate.split('-');
            var begin1 = new Date();
            var begin2 = begin1.getTimezoneOffset();
            var beginCurrentUTCTimeStamp = (new Date(beginDate[1]+' '+beginDate[1]+', '+beginDate[0]+' '+beginTime).getTime());
            var beginUTC0TS = beginCurrentUTCTimeStamp + (begin2*60000);

            var endDate  = $scope.evenement.endDate;
            var endTime  = $scope.evenement.endTime;
            endDate = endDate.split('-');
            var end1 = new Date();
            var end2 = end1.getTimezoneOffset();
            var endCurrentUTCTimeStamp = (new Date(endDate[1]+' '+endDate[1]+', '+endDate[0]+' '+endTime).getTime());
            var endUTC0TS = endCurrentUTCTimeStamp + (end2*60000);

            var evenement = new Evenements ({
				name: this.evenement.name,
				description: this.evenement.description,
                guests:[],
                beginTimestamp: beginUTC0TS,
                endTimestamp: endUTC0TS,
                localisation: [{
                    name: $scope.placeName,
                    lat: $scope.lat,
                    long: $scope.long
                }],
                coverImage: [{
                    contentType: $scope.imageContentType,
                    width: $scope.originalWidth,
                    height: $scope.originalHeight,
                    dataUrl: $scope.imageSrc
                }]
			});

            for (var j = 0; j < $scope.selection.length; j++){
                evenement.guests.push({_id: $scope.selection[j]});
            }

            alert(JSON.stringify(evenement));

			// Redirect after save
			evenement.$save(function(response) {
				$location.path('evenements/' + response._id);

				// Clear form fields
				$scope.name = '';
			}, function(errorResponse) {
                alert('aie');
                $scope.error = errorResponse.data.message;
			});
		};

		// Remove existing Evenement
		$scope.remove = function(evenement) {
			if ( evenement ) {
				evenement.$remove();

				for (var i in $scope.evenements) {
					if ($scope.evenements [i] === evenement) {
						$scope.evenements.splice(i, 1);
					}
				}
			} else {
				$scope.evenement.$remove(function() {
					$location.path('evenements');
				});
			}
		};

        $scope.addGuest = function() {
            var evenement = $scope.evenement;

            evenement.$update(function() {
                $location.path('evenements/' + evenement._id);
            }, function(errorResponse) {
                $scope.error = errorResponse.data.message;
            });
        };

		// Update existing Evenement
		$scope.update = function() {
			var evenement = $scope.evenement;

			evenement.$update(function() {
				$location.path('evenements/' + evenement._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Find a list of Evenements
		$scope.find = function() {
			$scope.evenements = Evenements.query();
            $scope.users = Users.query();
        };

		// Find existing Evenement
		$scope.findOne = function() {
			$scope.evenement = Evenements.get({
				evenementId: $stateParams.evenementId
			});
            $scope.users = Users.query();

        };
	}
]);

angular.module('evenements').directive('ngFileSelect',function(){
    return {
        link: function($scope,el){
            el.bind('change', function(e){
                $scope.file = (e.srcElement || e.target).files[0];
                $scope.getFile();
            });
        }
    };
});<commit_msg>set GOOGLE API 2<commit_after>'use strict';

// Evenements controller
angular.module('evenements').controller('EvenementsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Evenements', 'Users', 'fileReader',
	function($scope, $stateParams, $location, Authentication, Evenements, Users, fileReader) {
		$scope.authentication = Authentication;
        $scope.guests = Users.query();
        /*global Google */

        /* users Filtered by guest, see if he's guest or not*/
        $scope.UserFilterGuest = function(eve) {
            return function( user ) {
                for(var i = 0; i < eve.guests.length; i++){
                    if(user._id === eve.guests[i]._id){
                        return true;
                    }
                }
            };
        };

        /* users Filtered by mine, see if I am invited or if I created the event*/
        $scope.EventsFilterMine = function() {
            return function( eve ) {
                for(var i = 0; i < eve.guests.length; i++){
                    if(Authentication.user._id === eve.guests[i] || Authentication.user._id === eve.user._id){
                        return true;
                    }
                }
            };
        };

        $scope.googleMapPointer = function(){
            // This example adds a search box to a map, using the Google Place Autocomplete
// feature. People can enter geographical searches. The search box will return a
// pick list containing a mix of places and predicted search terms.
            var map;
            var input;
            function initialize() {
                var markers = [];

                var mapOptions = {
                    zoom: 8,
                    center: new google.maps.LatLng(-34.397, 150.644)
                };

                map = new google.maps.Map(document.getElementById('map-canvas'),
                    mapOptions);

                var defaultBounds = new google.maps.LatLngBounds(
                    new google.maps.LatLng(-33.8902, 151.1759),
                    new google.maps.LatLng(-33.8474, 151.2631));
                    map.fitBounds(defaultBounds);

                // Create the search box and link it to the UI element.
                input = (document.getElementById('pac-input'));
                map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

                var searchBox = new google.maps.places.SearchBox((input));

                // Listen for the event fired when the user selects an item from the
                // pick list. Retrieve the matching places for that item.
                google.maps.event.addListener(searchBox, 'places_changed', function() {
                    var places = searchBox.getPlaces();

                    if (places.length === 0) {
                        return;
                    }
                    var i;
                    var marker;
                    for (i = 0; marker = markers[i]; i++) {
                        marker.setMap(null);
                    }

                    // For each place, get the icon, place name, and location.
                    markers = [];
                    var bounds = new google.maps.LatLngBounds();
                    var i;
                    var place;
                    for (i = 0; place = places[i]; i++) {
                        var image = {
                            url: place.icon,
                            size: new google.maps.Size(71, 71),
                            origin: new google.maps.Point(0, 0),
                            anchor: new google.maps.Point(17, 34),
                            scaledSize: new google.maps.Size(25, 25)
                        };

                        // Create a marker for each place.
                        var marker = new google.maps.Marker({
                            map: map,
                            icon: image,
                            title: place.name,
                            position: place.geometry.location
                        });

                        markers.push(marker);

                        bounds.extend(place.geometry.location);

                        $scope.placeName = place.name;
                        $scope.lat = place.geometry.location.A;
                        $scope.long = place.geometry.location.F;
                        alert($scope.long);
                        alert($scope.placeName);
                    }

                    map.fitBounds(bounds);
                });

                // Bias the SearchBox results towards places that are within the bounds of the
                // current map's viewport.
                google.maps.event.addListener(map, 'bounds_changed', function() {
                    var bounds = map.getBounds();
                    searchBox.setBounds(bounds);
                });
            }
            /*initialize();*/
            google.maps.event.addDomListener(window, 'load', initialize);
        };

        // Get cover image for the event
        $scope.getFile = function () {
            $scope.progress = 0;
            fileReader.readAsDataUrl($scope.file, $scope)
                .then(function(result) {
                    $scope.imageSrc = result;
                    var imageSrcSplit = result.split(';base64'); // return data:image/*
                    var imageTypeSplit = imageSrcSplit[0].split('image/'); // return * the type of the image
                    $scope.imageContentType = imageTypeSplit[1];
                    var i = new Image();
                    i.src = result;
                    $scope.originalWidth = i.width;
                    $scope.originalHeight = i.height;
                });
        };

        $scope.$on('fileProgress', function(e, progress) {
            $scope.progress = progress.loaded / progress.total;
        });

        // Display the create page
        $scope.createDisplay = function() {
            $scope.selection = [];

            // helper method to get the selected
            $scope.selectedGuests = function selectedGuests() {
                return filterFilter($scope.guests, { selected: true });
            };

            // watch for changes
            $scope.$watch('guests|filter:{selected:true}', function (nv) {
                $scope.selection = nv.map(function (guest) {
                    return guest._id;
                });
            }, true);
        };

		$scope.create = function() {
			// Create new Evenement object

            var beginDate  = $scope.evenement.beginDate;
            var beginTime  = $scope.evenement.beginTime;

            beginDate = beginDate.split('-');
            var begin1 = new Date();
            var begin2 = begin1.getTimezoneOffset();
            var beginCurrentUTCTimeStamp = (new Date(beginDate[1]+' '+beginDate[1]+', '+beginDate[0]+' '+beginTime).getTime());
            var beginUTC0TS = beginCurrentUTCTimeStamp + (begin2*60000);

            var endDate  = $scope.evenement.endDate;
            var endTime  = $scope.evenement.endTime;
            endDate = endDate.split('-');
            var end1 = new Date();
            var end2 = end1.getTimezoneOffset();
            var endCurrentUTCTimeStamp = (new Date(endDate[1]+' '+endDate[1]+', '+endDate[0]+' '+endTime).getTime());
            var endUTC0TS = endCurrentUTCTimeStamp + (end2*60000);

            var evenement = new Evenements ({
				name: this.evenement.name,
				description: this.evenement.description,
                guests:[],
                beginTimestamp: beginUTC0TS,
                endTimestamp: endUTC0TS,
                localisation: [{
                    name: $scope.placeName,
                    lat: $scope.lat,
                    long: $scope.long
                }],
                coverImage: [{
                    contentType: $scope.imageContentType,
                    width: $scope.originalWidth,
                    height: $scope.originalHeight,
                    dataUrl: $scope.imageSrc
                }]
			});

            for (var j = 0; j < $scope.selection.length; j++){
                evenement.guests.push({_id: $scope.selection[j]});
            }

            alert(JSON.stringify(evenement));

			// Redirect after save
			evenement.$save(function(response) {
				$location.path('evenements/' + response._id);

				// Clear form fields
				$scope.name = '';
			}, function(errorResponse) {
                alert('aie');
                $scope.error = errorResponse.data.message;
			});
		};

		// Remove existing Evenement
		$scope.remove = function(evenement) {
			if ( evenement ) {
				evenement.$remove();

				for (var i in $scope.evenements) {
					if ($scope.evenements [i] === evenement) {
						$scope.evenements.splice(i, 1);
					}
				}
			} else {
				$scope.evenement.$remove(function() {
					$location.path('evenements');
				});
			}
		};

        $scope.addGuest = function() {
            var evenement = $scope.evenement;

            evenement.$update(function() {
                $location.path('evenements/' + evenement._id);
            }, function(errorResponse) {
                $scope.error = errorResponse.data.message;
            });
        };

		// Update existing Evenement
		$scope.update = function() {
			var evenement = $scope.evenement;

			evenement.$update(function() {
				$location.path('evenements/' + evenement._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Find a list of Evenements
		$scope.find = function() {
			$scope.evenements = Evenements.query();
            $scope.users = Users.query();
        };

		// Find existing Evenement
		$scope.findOne = function() {
			$scope.evenement = Evenements.get({
				evenementId: $stateParams.evenementId
			});
            $scope.users = Users.query();

        };
	}
]);

angular.module('evenements').directive('ngFileSelect',function(){
    return {
        link: function($scope,el){
            el.bind('change', function(e){
                $scope.file = (e.srcElement || e.target).files[0];
                $scope.getFile();
            });
        }
    };
});<|endoftext|>


<commit_before>module.exports = require('jii');

// AUTO-GENERATED Package files list
require('./client/Request.js');
require('./client/Response.js');
require('./client/Router.js');
<commit_msg>drop namespaces<commit_after>module.exports = require('jii');

// AUTO-GENERATED Package files list
if (!process.env.JII_NO_NAMESPACE) {
    require('./client/Request.js');
    require('./client/Response.js');
    require('./client/Router.js');
}<|endoftext|>


<commit_before>'use strict';

angular.module('infographics').directive('addictions', [
  '$window',
  'd3Service',
  function($window, d3Service) {
    return {
      restrict: 'EA',
      scope: {
        isUpdated: '=',
        graphData: '='
      },
      link: function postLink($scope, $element, $attrs) {
        d3Service.d3().then(function(d3) {
          // Returns a flattened hierarchy containing all leaf nodes under the root.
          function classes(root) {
            var classesArray= [];

            function recurse(name, node) {
              if (node.children) node.children.forEach(function(child) { recurse(node.name, child); });
              else classesArray.push({
                packageName: name,
                className: node.name,
                value: node.size,
                nodeId: node.nodeId
              });
            }

            recurse(null, root);
            return {children: classesArray};
          }

          var margin = parseInt($attrs.margin) || 100;

          var svg = d3.select($element[0])
            .append('svg')
            .style('width', '100%')
            .attr('class', 'addictions');

          // Browser onresize event
          $window.onresize = function() {
            $scope.$apply();
          };

          // Watch for resize event
          $scope.$watch(function() {
            return angular.element($window)[0].innerWidth;
          }, function() {
            $scope.render($scope.data);
          });

          $scope.$watch('isUpdated', function(newVals) {
            if (newVals) {
              $scope.isUpdated = false;
              return $scope.render($scope.data);
            }
            $scope.isUpdated = false;
          });

          $scope.render = function(data) {
            svg.selectAll('*').remove();

            var diameter = $element[0].offsetWidth - margin,
              format = d3.format(',d'),
              color = d3.scale.category10();

            color = function(addiction) {
              var colors = {
                Alimentation: '#EF4836',
                Alcool: '#663399',
                Sommeil: '#913D88',
                Travail: '#4183D7',
                Technologie: '#336E7B',
                Shopping: '#4ECDC4',
                Culture: '#87D37C',
                Sorties: '#26A65B',
                Jeux: '#F89406',
                Sport: '#F5AB35',
                Sexe: '#6C7A89',
                Drogue: '#95A5A6'
              }

              return colors[addiction]
            }

            var bubble = d3.layout.pack()
              .sort(null)
              .size([diameter, diameter])
              .padding(1.5);

            var node = svg.selectAll('.node')
              .data(bubble.nodes(classes($scope.graphData))
              .filter(function(d) { return !d.children; }))
            .enter().append('g')
              .attr('class', 'node')
              .attr('transform', function(d) { return 'translate(' + d.x + ',' + d.y + ')'; });

            node.append('title')
              .text(function(d) { return d.className + ': ' + format(d.value); });

            node.append('circle')
              .attr('r', function(d) { return d.r; })
              .style('fill', function(d) { return color(d.packageName); });

            node.append('text')
              .attr('dy', '.3em')
              .style('text-anchor', 'middle')
              .text(function(d) { return d.className.substring(0, d.r / 3); });

            node.on('click', function (d) {
              $scope.$emit('NODE_CLICKED', d);
            });

            svg.attr('height', diameter + 'px');
          };
        });
      }
    };
  }
]);
<commit_msg>fixed syntax<commit_after>'use strict';

angular.module('infographics').directive('addictions', [
  '$window',
  'd3Service',
  function($window, d3Service) {
    return {
      restrict: 'EA',
      scope: {
        isUpdated: '=',
        graphData: '='
      },
      link: function postLink($scope, $element, $attrs) {
        d3Service.d3().then(function(d3) {
          // Returns a flattened hierarchy containing all leaf nodes under the root.
          function classes(root) {
            var classesArray= [];

            function recurse(name, node) {
              if (node.children) node.children.forEach(function(child) { recurse(node.name, child); });
              else classesArray.push({
                packageName: name,
                className: node.name,
                value: node.size,
                nodeId: node.nodeId
              });
            }

            recurse(null, root);
            return {children: classesArray};
          }

          var margin = parseInt($attrs.margin) || 100;

          var svg = d3.select($element[0])
            .append('svg')
            .style('width', '100%')
            .attr('class', 'addictions');

          // Browser onresize event
          $window.onresize = function() {
            $scope.$apply();
          };

          // Watch for resize event
          $scope.$watch(function() {
            return angular.element($window)[0].innerWidth;
          }, function() {
            $scope.render($scope.data);
          });

          $scope.$watch('isUpdated', function(newVals) {
            if (newVals) {
              $scope.isUpdated = false;
              return $scope.render($scope.data);
            }
            $scope.isUpdated = false;
          });

          $scope.render = function(data) {
            svg.selectAll('*').remove();

            var diameter = $element[0].offsetWidth - margin,
              format = d3.format(',d'),
              color = d3.scale.category10();

            color = function(addiction) {
              var colors = {
                Alimentation: '#EF4836',
                Alcool: '#663399',
                Sommeil: '#913D88',
                Travail: '#4183D7',
                Technologie: '#336E7B',
                Shopping: '#4ECDC4',
                Culture: '#87D37C',
                Sorties: '#26A65B',
                Jeux: '#F89406',
                Sport: '#F5AB35',
                Sexe: '#6C7A89',
                Drogue: '#95A5A6'
              };

              return colors[addiction];
            };

            var bubble = d3.layout.pack()
              .sort(null)
              .size([diameter, diameter])
              .padding(1.5);

            var node = svg.selectAll('.node')
              .data(bubble.nodes(classes($scope.graphData))
              .filter(function(d) { return !d.children; }))
            .enter().append('g')
              .attr('class', 'node')
              .attr('transform', function(d) { return 'translate(' + d.x + ',' + d.y + ')'; });

            node.append('title')
              .text(function(d) { return d.className + ': ' + format(d.value); });

            node.append('circle')
              .attr('r', function(d) { return d.r; })
              .style('fill', function(d) { return color(d.packageName); });

            node.append('text')
              .attr('dy', '.3em')
              .style('text-anchor', 'middle')
              .text(function(d) { return d.className.substring(0, d.r / 3); });

            node.on('click', function (d) {
              $scope.$emit('NODE_CLICKED', d);
            });

            svg.attr('height', diameter + 'px');
          };
        });
      }
    };
  }
]);
<|endoftext|>


<commit_before>'use strict';

angular.module('projects').controller('ProjectEditController', ['$scope', '$stateParams', '$location', 'Authentication', 'Projects', '$http', '$mdToast', '$mdDialog', '$timeout', '$rootScope', 'RESOURCE_DOMAIN',
	function($scope, $stateParams, $location, Authentication, Projects, $http, $mdToast, $mdDialog, $timeout, $rootScope, RESOURCE_DOMAIN) {
		$scope.members = true;
		$scope.estimated = false;
		$scope.goTo = function(route) {
			$location.path(route);
		};

		$scope.authentication = Authentication;
		$scope.userIndex = -1;
		var project = {'projectId': $stateParams.projectId};
		$http({method:'POST', url:RESOURCE_DOMAIN + '/project', data: project}).success(function(data) {
			if (data.length !== 0) {
				var tmp = data[0];
				for (var u in tmp.users) {
					if (tmp.users[u] === $scope.authentication.user.username) {
						$scope.userIndex = u;
					}
				}

				if ($scope.userIndex === -1) {
					var toast = $mdToast.simple()
					.content('Not authorised to estimate')
					.action('')
					.highlightAction(false)
					.position($scope.getToastPosition());
					$mdToast.show(toast);
				}
			}
		});

		$scope.rootIsEmpty = function() {
			if ($scope.project.$resolved !== false) {
				if ($scope.project.children.length < 1) {
					return true;
				} else {
					return false;
				}
			}
		};

		$scope.initUsers = function(scope) {
			// console.log('Hello: ' + users);
			$http.get('/users/getUsers').success(function(users) {
				scope.people = [];
				for (var i in users) {
					var tempIsEstimator = false;
					for (var j = 0; j < scope.project.users.length; ++j) {
						if (users[i].username === scope.project.users[j]) {
							tempIsEstimator = true;
						}
					}
					scope.people.push({
						username : users[i].username,
						isEstimator : tempIsEstimator
					});
				}
			});
		};

		$scope.showAddEstimatorDialogBox = function(ev) {
			var newScope = $scope.$new();
			$mdDialog.show({
				controller: DialogController,
				templateUrl: 'modules/projects/views/add-estimator.client.view.html',
				parent: angular.element(document.body),
				targetEvent: ev,
				scope: newScope
			});
		};

		$scope.updateEstimators = function() {
			console.log($scope.people);
			var add = [];
			var remove = [];

			for (var k = 0; k < $scope.project.users.length; ++k) {
				remove.push(k);
			}

			for (var i = 0; i < $scope.people.length; ++i) {
				if ($scope.people[i].isEstimator === true) {
					console.log("Is True: " + $scope.people[i].username);
					var found = false;
					// console.log("To add: ");
					// console.log($scope.people[i]);
					for (var j = 0; j < $scope.project.users.length; ++j) {
						// console.log("Current Users: " + $scope.project.users[j]);
						if ($scope.project.users[j] === $scope.people[i].username) {
							// console.log("FOUND");
							console.log("Is equal to user: " + $scope.people[i].username);
							var index = remove.indexOf(j);
							if (index > -1) {
								console.log("Splicing at: " + index + " for " + $scope.people[i].username);
								remove.splice(index, 1);
							}

							found = true;
							break;
						}
					}

					if (found === false) {
						add.push($scope.people[i]);
					}
				}
			}
			console.log("Add:");
			console.log(add);
			console.log("Remove:");
			console.log(remove);

			$scope.removeEstimatorsFromProject(remove);
			// $scope.addEstimatorsToProject(add);

			$scope.saveProject();
		};

		$scope.removeEstimatorsFromProject = function(removeArr) {
			$scope.project.users.splice(removeArr[0], 1);
			$scope.removeEstimatorsRecursiveDescent($scope.project.children[0], removeArr);
		};

		$scope.removeEstimatorsRecursiveDescent = function(node, removeArr) {
			node.estimations.splice(removeArr[0], 1);
			for (var i = 0; i < node.nodes.length; ++i) {
				console.log("Going deeper");
				$scope.removeEstimatorsRecursiveDescent(node.nodes[i], removeArr);
			}
		};

		$scope.addEstimatorsToProject = function(addArr) {

		};

		$scope.owner = function() {
			if ($scope.project.$resolved !== false) {
				if ($scope.project.owner === $scope.authentication.user.username) {
					return true;
				} else {
					return false;
				}
			}
		};

		$scope.estimator = function() {
			if ($scope.userIndex === -1) {
				return false;
			} else {
				return true;
			}
		};

		$scope.submitEstimation = function() {
			$scope.saveProject();
			$scope.estimated = true;
			$scope.determineEstimations();
		};

		$scope.determineEstimations = function() {
			for (var i = 0; i < $scope.project.users.length; ++i) {
				if ($scope.project.children[0].estimations[i] === null) {
					// An estimator still hasn't estimated
					return;
				}
			}
			$scope.sendEstimationReport();
		};

		$scope.sendEstimationReport = function() {
			$http({method:'POST', url:RESOURCE_DOMAIN + '/reports', data: $scope.project}).success(function(data) {

			});
		};

		$scope.openForEstimation = function() {
			var confirm = $mdDialog.confirm()
			.parent(angular.element(document.body))
			.title('Are you sure you want to open the project for estimations?')
			.content('This will allow estimators to estimate, but will lock the project tree to its current state.')
			.ariaLabel('Open for estimation')
			.ok('Yes')
			.cancel('No');
			$mdDialog.show(confirm).then(function() {
				$timeout(function() {
					$scope.project.openForEstimation = true;
					$scope.saveProject();

					var project = {'projectId': $scope.project._id};

					$http({method:'POST', url:RESOURCE_DOMAIN + '/sendInvites', data: project}).success(function(data) {

					});
				});
			}, function() {
			});
		};

		$scope.isOpenForEstimation = function() {
			if ($scope.project.$resolved !== false) {
				return $scope.project.openForEstimation;
			} else {
				return false;
			}
		};

		$scope.addRootNode = function() {
			// initialise estimations array
			var estimationsArr = [];
			for (var i in $scope.project.users) {
				estimationsArr.push(null);
			}
			$scope.project.children.push({id: 'node', title:'Root Node', nodes: [], collapsed : false, estimations : estimationsArr});
		};

		$scope.update = function() {
			var project = $scope.project;

			project.$update(function() {
				$location.path('projects/' + project._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		$scope.find = function() {
			$scope.projects = Projects.query();
		};

		// Find existing Project
		$scope.findOne = function() {
			$scope.project = Projects.get({
				projectId: $stateParams.projectId
			}, function() {
				if ($scope.project.children[0].estimations[$scope.userIndex] === null) {
					$scope.estimated = false;
				} else {
					$scope.estimated = true;
				}
			});
		};

		$scope.newSubItem = function(scope) {
			// console.log(scope.project.users);
			var nodeData = scope.$modelValue;
			// console.log(nodeData);
			var estimationsArr = [];
			for (var i in scope.project.users) {
				// console.log(i);
				estimationsArr.push(null);
			}
			nodeData.nodes.push({
				id: nodeData.id * 10 + nodeData.nodes.length,
				title: nodeData.title + '.' + (nodeData.nodes.length + 1),
				nodes: [],
				collapsed : false,
				estimations : estimationsArr
			});
		};

		$scope.undoToolTip = function(node, removeNode, newSubItem) {
			//debugger;
			var tree = $.extend(true, [], $scope.project.children);

			removeNode(node);

			var toast = $mdToast.simple()
				.content('Node deleted')
				.action('UNDO')
				.highlightAction(false)
				.position($scope.getToastPosition());
			$mdToast.show(toast).then(function() {
				$scope.project.children = $.extend(true, [], tree);
			});
		};

		$scope.toastPosition = {
			bottom: true,
			top: false,
			left: false,
			right: true
		};

		$scope.getToastPosition = function() {
			return Object.keys($scope.toastPosition)
			.filter(function(pos) { return $scope.toastPosition[pos]; })
			.join(' ');
		};

		$scope.saveProject = function() {
			$scope.project.$update(function(response) {
				$mdToast.show(
					$mdToast.simple()
					.content('Project saved')
					.position($scope.getToastPosition())
					.hideDelay(3000)
				);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		$scope.querySearch = function(query) {
			//console.log(query);
			var results = query ? $scope.projects.filter(createFilterFor(query)) : $scope.projects, deferred;
			return results;
		};

		$scope.searchTextChange = function(text) {
			console.log('Text changed to ' + text);
		};

		$scope.selectedItemChange = function(item) {
			console.log(item);
			$scope.goTo('/projects/' + item._id + '/edit');
		};

		var createFilterFor = function(query) {
			var lowercaseQuery = angular.lowercase(query);
			return function filterFn(item) {
				//console.log(item);
				var name = angular.lowercase(item.name);
				return (name.indexOf(lowercaseQuery) === 0);
			};
		};

		$scope.collapseAll = function() {
			$scope.$broadcast('collapseAll');
		};

		$scope.expandAll = function() {
			$scope.$broadcast('expandAll');
		};

		function DialogController($scope, $mdDialog) {
			$scope.hide = function() {
				$mdDialog.hide();
			};
			$scope.cancel = function() {
				$mdDialog.cancel();
			};
		}

		$scope.showDescriptionDialog = function(ev, node) {
			$scope.currentNode = node;

			$scope.setCurrentNode(node, function() {
				var newScope = $scope.$new();

				$mdDialog.show({
					controller: DialogController,
					templateUrl: 'modules/projects/views/description.dialog.client.view.html',
					parent: angular.element(document.body),
					targetEvent: ev,
					scope: newScope
				});
			});
		};

		$scope.updateLocalTree = function(scope) {
			var count = $scope.userIndex;
			var currnode = $scope.project.children[0];
			var result;

			$scope.getEstimation(currnode, count, function(res) {
				result = res;
			});
		};

		$scope.getEstimation = function(node, userNum, callback) {
			if (node.nodes.length <= 0) {
				callback(node.estimations[userNum]);
			} else {
				node.estimations[userNum] = null;
				for (var i in node.nodes) {
					$scope.getEstimation(node.nodes[i], userNum, function(result) {
						if (node.estimations[userNum] === null) {
							node.estimations[userNum] = parseInt(result);
						} else {
							node.estimations[userNum] += parseInt(result);
						}
						callback(parseInt(result));
					});
				}
			}
		};

		$scope.currentNode = undefined;

		$scope.setCurrentNode = function(node, callback) {
			$scope.currentNode = node;

			if (callback !== undefined) {
				callback();
			}
		};

		$scope.$on('$locationChangeStart', function(event, newUrl, oldUrl) {
			if (!$scope.confirm) {
				event.preventDefault();
				//console.log(newUrl);
				var confirm = $mdDialog.confirm()
				.parent(angular.element(document.body))
				.title('Are you sure you want to leave this page?')
				.content('All unsaved changes will be lost.')
				.ariaLabel('Yes')
				.ok('Yes')
				.cancel('No')
				.targetEvent(event);
				$mdDialog.show(confirm).then(function() {
					newUrl = newUrl.split('#!');
					$scope.goTo(newUrl[1]);
					$scope.confirm = true;
					//$scope.saveProject();
				}, function() {});
			}
		});
	}
]);
<commit_msg>Owner now can not be removed from estimators for a project<commit_after>'use strict';

angular.module('projects').controller('ProjectEditController', ['$scope', '$stateParams', '$location', 'Authentication', 'Projects', '$http', '$mdToast', '$mdDialog', '$timeout', '$rootScope', 'RESOURCE_DOMAIN',
	function($scope, $stateParams, $location, Authentication, Projects, $http, $mdToast, $mdDialog, $timeout, $rootScope, RESOURCE_DOMAIN) {
		$scope.members = true;
		$scope.estimated = false;
		$scope.goTo = function(route) {
			$location.path(route);
		};

		$scope.authentication = Authentication;
		$scope.userIndex = -1;
		var project = {'projectId': $stateParams.projectId};
		$http({method:'POST', url:RESOURCE_DOMAIN + '/project', data: project}).success(function(data) {
			if (data.length !== 0) {
				var tmp = data[0];
				for (var u in tmp.users) {
					if (tmp.users[u] === $scope.authentication.user.username) {
						$scope.userIndex = u;
					}
				}

				if ($scope.userIndex === -1) {
					var toast = $mdToast.simple()
					.content('Not authorised to estimate')
					.action('')
					.highlightAction(false)
					.position($scope.getToastPosition());
					$mdToast.show(toast);
				}
			}
		});

		$scope.rootIsEmpty = function() {
			if ($scope.project.$resolved !== false) {
				if ($scope.project.children.length < 1) {
					return true;
				} else {
					return false;
				}
			}
		};

		$scope.initUsers = function(scope) {
			// console.log('Hello: ' + users);
			$http.get('/users/getUsers').success(function(users) {
				scope.people = [];
				for (var i in users) {
					var tempIsEstimator = false;
					for (var j = 0; j < scope.project.users.length; ++j) {
						if (users[i].username === scope.project.users[j]) {
							tempIsEstimator = true;
						}
					}
					// does not add owner of the project
					// prevents deleting owner from users
					if (users[i].username !== scope.project.owner) {
						scope.people.push({
							username : users[i].username,
							isEstimator : tempIsEstimator
						});
					}
				}
			});
		};

		$scope.showAddEstimatorDialogBox = function(ev) {
			var newScope = $scope.$new();
			$mdDialog.show({
				controller: DialogController,
				templateUrl: 'modules/projects/views/add-estimator.client.view.html',
				parent: angular.element(document.body),
				targetEvent: ev,
				scope: newScope
			});
		};

		$scope.updateEstimators = function() {
			console.log($scope.people);
			var add = [];
			var remove = [];

			for (var k = 0; k < $scope.project.users.length; ++k) {
				remove.push(k);
			}

			for (var i = 0; i < $scope.people.length; ++i) {
				if ($scope.people[i].isEstimator === true) {
					console.log("Is True: " + $scope.people[i].username);
					var found = false;
					// console.log("To add: ");
					// console.log($scope.people[i]);
					for (var j = 0; j < $scope.project.users.length; ++j) {
						// console.log("Current Users: " + $scope.project.users[j]);
						if ($scope.project.users[j] === $scope.people[i].username) {
							// console.log("FOUND");
							console.log("Is equal to user: " + $scope.people[i].username);
							var index = remove.indexOf(j);
							if (index > -1) {
								console.log("Splicing at: " + index + " for " + $scope.people[i].username);
								remove.splice(index, 1);
							}

							found = true;
							break;
						}
					}

					if (found === false) {
						add.push($scope.people[i]);
					}
				}
			}
			console.log("Add:");
			console.log(add);
			console.log("Remove:");
			console.log(remove);

			$scope.removeEstimatorsFromProject(remove);
			// $scope.addEstimatorsToProject(add);

			$scope.saveProject();
		};

		$scope.removeEstimatorsFromProject = function(removeArr) {
			$scope.project.users.splice(removeArr[0], 1);
			$scope.removeEstimatorsRecursiveDescent($scope.project.children[0], removeArr);
		};

		$scope.removeEstimatorsRecursiveDescent = function(node, removeArr) {
			node.estimations.splice(removeArr[0], 1);
			for (var i = 0; i < node.nodes.length; ++i) {
				console.log("Going deeper");
				$scope.removeEstimatorsRecursiveDescent(node.nodes[i], removeArr);
			}
		};

		$scope.addEstimatorsToProject = function(addArr) {

		};

		$scope.owner = function() {
			if ($scope.project.$resolved !== false) {
				if ($scope.project.owner === $scope.authentication.user.username) {
					return true;
				} else {
					return false;
				}
			}
		};

		$scope.estimator = function() {
			if ($scope.userIndex === -1) {
				return false;
			} else {
				return true;
			}
		};

		$scope.submitEstimation = function() {
			$scope.saveProject();
			$scope.estimated = true;
			$scope.determineEstimations();
		};

		$scope.determineEstimations = function() {
			for (var i = 0; i < $scope.project.users.length; ++i) {
				if ($scope.project.children[0].estimations[i] === null) {
					// An estimator still hasn't estimated
					return;
				}
			}
			$scope.sendEstimationReport();
		};

		$scope.sendEstimationReport = function() {
			$http({method:'POST', url:RESOURCE_DOMAIN + '/reports', data: $scope.project}).success(function(data) {

			});
		};

		$scope.openForEstimation = function() {
			var confirm = $mdDialog.confirm()
			.parent(angular.element(document.body))
			.title('Are you sure you want to open the project for estimations?')
			.content('This will allow estimators to estimate, but will lock the project tree to its current state.')
			.ariaLabel('Open for estimation')
			.ok('Yes')
			.cancel('No');
			$mdDialog.show(confirm).then(function() {
				$timeout(function() {
					$scope.project.openForEstimation = true;
					$scope.saveProject();

					var project = {'projectId': $scope.project._id};

					$http({method:'POST', url:RESOURCE_DOMAIN + '/sendInvites', data: project}).success(function(data) {

					});
				});
			}, function() {
			});
		};

		$scope.isOpenForEstimation = function() {
			if ($scope.project.$resolved !== false) {
				return $scope.project.openForEstimation;
			} else {
				return false;
			}
		};

		$scope.addRootNode = function() {
			// initialise estimations array
			var estimationsArr = [];
			for (var i in $scope.project.users) {
				estimationsArr.push(null);
			}
			$scope.project.children.push({id: 'node', title:'Root Node', nodes: [], collapsed : false, estimations : estimationsArr});
		};

		$scope.update = function() {
			var project = $scope.project;

			project.$update(function() {
				$location.path('projects/' + project._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		$scope.find = function() {
			$scope.projects = Projects.query();
		};

		// Find existing Project
		$scope.findOne = function() {
			$scope.project = Projects.get({
				projectId: $stateParams.projectId
			}, function() {
				if ($scope.project.children[0].estimations[$scope.userIndex] === null) {
					$scope.estimated = false;
				} else {
					$scope.estimated = true;
				}
			});
		};

		$scope.newSubItem = function(scope) {
			// console.log(scope.project.users);
			var nodeData = scope.$modelValue;
			// console.log(nodeData);
			var estimationsArr = [];
			for (var i in scope.project.users) {
				// console.log(i);
				estimationsArr.push(null);
			}
			nodeData.nodes.push({
				id: nodeData.id * 10 + nodeData.nodes.length,
				title: nodeData.title + '.' + (nodeData.nodes.length + 1),
				nodes: [],
				collapsed : false,
				estimations : estimationsArr
			});
		};

		$scope.undoToolTip = function(node, removeNode, newSubItem) {
			//debugger;
			var tree = $.extend(true, [], $scope.project.children);

			removeNode(node);

			var toast = $mdToast.simple()
				.content('Node deleted')
				.action('UNDO')
				.highlightAction(false)
				.position($scope.getToastPosition());
			$mdToast.show(toast).then(function() {
				$scope.project.children = $.extend(true, [], tree);
			});
		};

		$scope.toastPosition = {
			bottom: true,
			top: false,
			left: false,
			right: true
		};

		$scope.getToastPosition = function() {
			return Object.keys($scope.toastPosition)
			.filter(function(pos) { return $scope.toastPosition[pos]; })
			.join(' ');
		};

		$scope.saveProject = function() {
			$scope.project.$update(function(response) {
				$mdToast.show(
					$mdToast.simple()
					.content('Project saved')
					.position($scope.getToastPosition())
					.hideDelay(3000)
				);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		$scope.querySearch = function(query) {
			//console.log(query);
			var results = query ? $scope.projects.filter(createFilterFor(query)) : $scope.projects, deferred;
			return results;
		};

		$scope.searchTextChange = function(text) {
			console.log('Text changed to ' + text);
		};

		$scope.selectedItemChange = function(item) {
			console.log(item);
			$scope.goTo('/projects/' + item._id + '/edit');
		};

		var createFilterFor = function(query) {
			var lowercaseQuery = angular.lowercase(query);
			return function filterFn(item) {
				//console.log(item);
				var name = angular.lowercase(item.name);
				return (name.indexOf(lowercaseQuery) === 0);
			};
		};

		$scope.collapseAll = function() {
			$scope.$broadcast('collapseAll');
		};

		$scope.expandAll = function() {
			$scope.$broadcast('expandAll');
		};

		function DialogController($scope, $mdDialog) {
			$scope.hide = function() {
				$mdDialog.hide();
			};
			$scope.cancel = function() {
				$mdDialog.cancel();
			};
		}

		$scope.showDescriptionDialog = function(ev, node) {
			$scope.currentNode = node;

			$scope.setCurrentNode(node, function() {
				var newScope = $scope.$new();

				$mdDialog.show({
					controller: DialogController,
					templateUrl: 'modules/projects/views/description.dialog.client.view.html',
					parent: angular.element(document.body),
					targetEvent: ev,
					scope: newScope
				});
			});
		};

		$scope.updateLocalTree = function(scope) {
			var count = $scope.userIndex;
			var currnode = $scope.project.children[0];
			var result;

			$scope.getEstimation(currnode, count, function(res) {
				result = res;
			});
		};

		$scope.getEstimation = function(node, userNum, callback) {
			if (node.nodes.length <= 0) {
				callback(node.estimations[userNum]);
			} else {
				node.estimations[userNum] = null;
				for (var i in node.nodes) {
					$scope.getEstimation(node.nodes[i], userNum, function(result) {
						if (node.estimations[userNum] === null) {
							node.estimations[userNum] = parseInt(result);
						} else {
							node.estimations[userNum] += parseInt(result);
						}
						callback(parseInt(result));
					});
				}
			}
		};

		$scope.currentNode = undefined;

		$scope.setCurrentNode = function(node, callback) {
			$scope.currentNode = node;

			if (callback !== undefined) {
				callback();
			}
		};

		$scope.$on('$locationChangeStart', function(event, newUrl, oldUrl) {
			if (!$scope.confirm) {
				event.preventDefault();
				//console.log(newUrl);
				var confirm = $mdDialog.confirm()
				.parent(angular.element(document.body))
				.title('Are you sure you want to leave this page?')
				.content('All unsaved changes will be lost.')
				.ariaLabel('Yes')
				.ok('Yes')
				.cancel('No')
				.targetEvent(event);
				$mdDialog.show(confirm).then(function() {
					newUrl = newUrl.split('#!');
					$scope.goTo(newUrl[1]);
					$scope.confirm = true;
					//$scope.saveProject();
				}, function() {});
			}
		});
	}
]);
<|endoftext|>


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

var program = require('commander');
var prompt = require('prompt');
var fs = require('fs');
var util = require('util');
var chalk = require('chalk');
var Q = require('q');
var log4js = require('log4js');

var log = log4js.getLogger();

if (fs.existsSync('./log4js.json')) {
  log4js.configure('./log4js.json');
} else if(process.env["LOG4JS_CONFIG"] !== undefined) {

} else {
  log4js.configure({
    appenders: [
      {
        type: 'console' ,
        level: 'INFO',
        layout: { type:"pattern", pattern: " %[%m%]" }
      },
    ]
  })
  log.setLevel('INFO');
}

var constants = {
  configJsonName: "accessapi-config.json"
};

function status(text) {
  var argsArray = Array.prototype.slice.call(arguments);
  log.info.apply(log, argsArray);
  if (log.isInfoEnabled==false) {
    var str = util.format.apply(null,argsArray);
    process.stdout.write(str);
    process.stdout.write('\n');
  }
}
function fail(text) {
  var argsArray = Array.prototype.slice.call(arguments);
  log.fatal.apply(log, argsArray);
  if (log.isFatalEnabled==false) {
    var str = util.format.apply(null,argsArray);
    process.stderr.write(str);
    process.stderr.write('\n');
  }
}

program
  .name('update')

program
  .option('--config <file>', 'a config file to use. defaults to using ./accessapi-config.json', 'accessapi-config.json')
  .option('-i,--instance', 'instance (required if multiple instances defined in the config file)')
  .option('--stdin', 'read input from stdin')
  .option('--as', 'set type of asset to be one of: developercs (updates body field) or binary (updates binary data). others defined later. this option used with file input or --stdin')
  .option('--field <field>', 'update using a specific field name, use when updating from a file or stdin without json')
  .option('--runPostInput','run post input plugin for the asset\'s template', false)
  .option('--runPostSave', 'run post save plugin on the asset\'s template', false)
  .arguments("<assetPath> [inputFile]")
  .action(function (assetPath, inputFile) {
    program.assetPath = assetPath;
    program.inputFile = inputFile;
  })

program
  .parse(process.argv)

log.debug('program.config',program.config);
log.debug('program.assetPath',program.assetPath);

function getContent (program, encoding) {
  if (log.isDebugEnabled) log.debug('begin reading content');
  var deferred = Q.defer();
  var collector = Q.defer();

  if (program.stdin) {
    log.debug('reading content from stdin');

    var stdin = process.stdin;
    var stdout = process.stdout;

    var inputChunks = [];

    stdin.on('data', function (data) {
      if (log.isDebugEnabled) log.debug('chunk:',data);
      if (Buffer.isBuffer(data)) data = data.toString('utf8');
      inputChunks.push(data);
    });

    stdin.on('end', function () {
      var contentStr = (inputChunks.length == 1 ? inputChunks[0] : inputChunks.join(""));

      try {
        var parsedData = JSON.parse(contentStr);
        collector.resolve(parsedData);
        return;
      }
      catch(ex) { }

      if (program.field !== undefined) {
        parsedData = {};
        parsedData[program.field] = contentStr;
        collector.resolve(parsedData);
      }

    });

  }

  else //read from file
  {
    //read file name from program.args[2]
    log.debug('reading from file=%s', program.inputFile);
    return Q.nfcall(fs.readFile, program.inputFile, { 'encoding': 'utf8' });
  }

  collector.then((content)=>{

    if(Buffer.isBuffer(content) || typeof content === 'string') {
      log.debug('content is buffer or string. program.field=%s', program.field);
      if (program.field == undefined) {
        fail('Content wasnt parseable as json, and no --field parameter specified.');
        program.help();
      }
    }

    if(Buffer.isBuffer(content)) {
      fieldsJson = {};
      fieldsJson[program.field] = content.toString('utf8');
    }
    if(typeof content === 'string') {
      fieldsJson = {};
      fieldsJson[program.field] = content;
    }

    deferred.resolve(fieldsJson);
  }, (err) => {
    deferred.reject(err);
  })

  return deferred.promise;
}

main = function () {

var exitcode=-1;

  if (typeof program.assetPath === 'undefined') {
    fail('no assetPath specified.');
    exitcode=1;
  }

  if (program.inputFile == undefined && program.stdin == undefined) {
    fail('no inputFile specified and --stdin not specified.  Cannot update.');
    exitcode=1;
  }

  if(exitcode>0) { program.help();process.exit(exitcode); }

  log.debug('Loading config from %s.', program.config);
  if (fs.existsSync(program.config)==false) {
    fail('Failed to load config from %s: file doesn\'t exist.', program.config);
    process.exit(1);
  }

  //var reader = require('./accessapi-json-config-reader');
  var accessapiConfig = JSON.parse(fs.readFileSync(program.config));

  log.debug('accessapiConfig:', accessapiConfig);

  status(`Instance: ${accessapiConfig.instance}   Sign in as: ${accessapiConfig.username}`);
  status(`Updating: ${program.assetPath}`);

  var accessapi = require('crownpeak-accessapi');
  accessapi.setConfig(accessapiConfig);

  status('');
  status('Authenticating.');
  accessapi.auth().then(function (data) {

    var assetIdOrPath = program.assetPath;

    log.debug('calling AssetExists');
    accessapi.AssetExists(assetIdOrPath).then(function (existsResp) {

      //existsResp documented http://developer.crownpeak.com/Documentation/AccessAPI/AssetController/Methods/Exists(AssetExistsRequest).html
      var workflowAssetId = existsResp.json.assetId;

      getContent(program).then(function (fieldsJson) {

        if(log.isDebugEnabled) {
          log.debug('fieldsJson from getContent:', fieldsJson);
        }

        var options={};
        if(program.runPostInput != undefined)
          options.runPostInput = program.runPostInput;

        if(program.runPostSave != undefined)
          options.runPostSave = program.runPostSave;

        log.debug('calling AssetUpdate. options=%j', options);
        accessapi.AssetUpdate(workflowAssetId, fieldsJson, null, options).then(function() {
          status('Success updating %s.', program.assetPath);
        })

      });

    });

  }, function(err) {
    fail('Authentication failure: %s', err.resultCode);
  }).catch(function (err) {
    log.error("error occurred:", err);
  }).done();

}();
<commit_msg>general checkin<commit_after>#!/usr/bin/env node

var program = require('commander');
var prompt = require('prompt');
var fs = require('fs');
var util = require('util');
var chalk = require('chalk');
var Q = require('q');
var log4js = require('log4js');

var log = log4js.getLogger();

process.on('exit', () => { process.exit(0); })

if (fs.existsSync('./log4js.json')) {
  log4js.configure('./log4js.json');
} else if(process.env["LOG4JS_CONFIG"] !== undefined) {

} else {
  log4js.configure({
    appenders: [
      {
        type: 'console' ,
        level: 'INFO',
        layout: { type:"pattern", pattern: " %[%m%]" }
      },
    ]
  })
  log.setLevel('INFO');
}

var constants = {
  configJsonName: "accessapi-config.json"
};

function status(text) {
  var argsArray = Array.prototype.slice.call(arguments);
  log.info.apply(log, argsArray);
  if (log.isInfoEnabled==false) {
    var str = util.format.apply(null,argsArray);
    process.stdout.write(str);
    process.stdout.write('\n');
  }
}
function fail(text) {
  var argsArray = Array.prototype.slice.call(arguments);
  log.fatal.apply(log, argsArray);
  if (log.isFatalEnabled==false) {
    var str = util.format.apply(null,argsArray);
    process.stderr.write(str);
    process.stderr.write('\n');
  }
}

program
  .name('update')

program
  .option('--config <file>', 'a config file to use. defaults to using ./accessapi-config.json', 'accessapi-config.json')
  .option('-i,--instance', 'instance (required if multiple instances defined in the config file)')
  .option('--stdin', 'read input from stdin')
  .option('--as', 'set type of asset to be one of: developercs (updates body field) or binary (updates binary data). others defined later. this option used with file input or --stdin')
  .option('--field <field>', 'update using a specific field name, use when updating from a file or stdin without json')
  .option('--runPostInput','run post input plugin for the asset\'s template', false)
  .option('--runPostSave', 'run post save plugin on the asset\'s template', false)
  .arguments("<assetPath> [inputFile]")
  .action(function (assetPath, inputFile) {
    program.assetPath = assetPath;
    if(program.field === undefined)
      program.inputFile = inputFile;
    else
      program.fieldvalue = inputFile;
  })

program
  .parse(process.argv)

log.debug('program.config',program.config);
log.debug('program.assetPath',program.assetPath);

function getContent (program, encoding) {
  if (log.isDebugEnabled) log.debug('begin reading content');
  var deferred = Q.defer();
  var collector = Q.defer();

  if (program.stdin) {
    log.debug('reading content from stdin');

    var stdin = process.stdin;
    var stdout = process.stdout;

    var inputChunks = [];

    stdin.on('data', function (data) {
      if (log.isDebugEnabled) log.debug('chunk:',data);
      if (Buffer.isBuffer(data)) data = data.toString('utf8');
      inputChunks.push(data);
    });

    stdin.on('end', function () {
      var contentStr = (inputChunks.length == 1 ? inputChunks[0] : inputChunks.join(""));

      try {
        var parsedData = JSON.parse(contentStr);
        collector.resolve(parsedData);
        return;
      }
      catch(ex) { }

      if (program.field !== undefined) {
        parsedData = {};
        parsedData[program.field] = contentStr;
        collector.resolve(parsedData);
      }

      collector.then((content)=>{

        if(Buffer.isBuffer(content) || typeof content === 'string') {
          log.debug('content is buffer or string. program.field=%s', program.field);
          if (program.field == undefined) {
            fail('Content wasnt parseable as json, and no --field parameter specified.');
            program.help();
          }
        }

        if(Buffer.isBuffer(content)) {
          fieldsJson = {};
          fieldsJson[program.field] = content.toString('utf8');
        }
        if(typeof content === 'string') {
          fieldsJson = {};
          fieldsJson[program.field] = content;
        }

        deferred.resolve(fieldsJson);
      }, (err) => {
        deferred.reject(err);
      })

    });

  } else if(program.field !== undefined) {
    log.debug('set field: %s to value: "%s".', program.field, program.fieldvalue);
    if(program.fieldvalue !== undefined) {
      var fields = {};
      fields[program.field] = program.fieldvalue;
      deferred.resolve(fields);
    } else {
      deferred.resolve({});
    }
  }
  else //read from file
  {
    //read file name from program.args[2]
    log.debug('reading from file=%s', program.inputFile);
    return Q.nfcall(fs.readFile, program.inputFile, { 'encoding': 'utf8' });
  }

  return deferred.promise;
}

main = function () {

var exitcode=-1;

  if (typeof program.assetPath === 'undefined') {
    fail('no assetPath specified.');
    exitcode=1;
  }

  if (program.inputFile == undefined && program.field == undefined && program.stdin == undefined) {
    fail('no inputFile specified and --stdin not specified.  Cannot update.');
    exitcode=1;
  }

  if(exitcode>0) { program.help();process.exit(exitcode); }

  log.debug('Loading config from %s.', program.config);
  if (fs.existsSync(program.config)==false) {
    fail('Failed to load config from %s: file doesn\'t exist.', program.config);
    process.exit(1);
  }

  //var reader = require('./accessapi-json-config-reader');
  var accessapiConfig = JSON.parse(fs.readFileSync(program.config));

  log.debug('accessapiConfig:', accessapiConfig);

  status(`Instance: ${accessapiConfig.instance}   Sign in as: ${accessapiConfig.username}`);
  status(`Updating: ${program.assetPath}`);

  var accessapi = require('crownpeak-accessapi');
  accessapi.setConfig(accessapiConfig);

  status('');
  status('Authenticating.');
  accessapi.auth().then(function (data) {

    var assetIdOrPath = program.assetPath;

    log.debug('calling AssetExists');
    accessapi.AssetExists(assetIdOrPath).then(function (existsResp) {

      //existsResp documented http://developer.crownpeak.com/Documentation/AccessAPI/AssetController/Methods/Exists(AssetExistsRequest).html
      var workflowAssetId = existsResp.json.assetId;

      getContent(program).then(function (fieldsJson) {

        if(log.isDebugEnabled) {
          log.debug('fieldsJson from getContent:', fieldsJson);
        }

        var options={};
        if(program.runPostInput != undefined)
          options.runPostInput = program.runPostInput;

        if(program.runPostSave != undefined)
          options.runPostSave = program.runPostSave;

        log.debug('calling AssetUpdate. options=%j', options);
        accessapi.AssetUpdate(workflowAssetId, fieldsJson, null, options).then(function() {
          status('Success updating %s.', program.assetPath);
        })

      });

    });

  }, function(err) {
    fail('Authentication failure: %s', err.resultCode);
  }).catch(function (err) {
    log.error("error occurred:", err);
  }).done();

}();
<|endoftext|>


<commit_before>;(function(undefined) {
  'use strict';

  if (typeof sigma === 'undefined')
    throw 'sigma is not declared';

  /**
   * Sigma ForceAtlas2.5 Supervisor
   * =============================
   *
   * Author: Guillaume Plique (Yomguithereal)
   * Version: 0.1
   */

  /**
   * Feature detection
   * ------------------
   */
  var webWorkers = 'Worker' in window;

  /**
   * Supervisor Object
   * ------------------
   */
  function Supervisor(sigInst, options) {
    var _this = this,
        workerFn = sigInst.getForceAtlas2Worker();

    // Window URL Polyfill
    window.URL = window.URL || window.webkitURL;

    // Properties
    this.sigInst = sigInst;
    this.graph = this.sigInst.graph;
    this.ppn = 10;
    this.ppe = 3;
    this.config = {};

    // State
    this.started = false;
    this.running = false;

    // Web worker or classic DOM events?
    if (webWorkers) {
      var blob = this.makeBlob(workerFn);
      this.worker = new Worker(URL.createObjectURL(blob));

      // Post Message Polyfill
      this.worker.postMessage =
        this.worker.webkitPostMessage || this.worker.postMessage;
    }
    else {

      // TODO: do we crush?
      eval(workerFn);
    }

    // Worker message receiver
    var msgName = (this.worker) ? 'message' : 'newCoords';
    (this.worker || document).addEventListener(msgName, function(e) {

      // Retrieving data
      _this.nodesByteArray = new Float32Array(e.data.nodes);

      // If ForceAtlas2 is running, we act accordingly
      if (_this.running) {

        // Applying layout
        _this.applyLayoutChanges();

        // Send data back to worker and loop
        _this.sendByteArrayToWorker();

        // Rendering graph
        _this.sigInst.refresh();
      }
    });

    // Filling byteArrays
    this.graphToByteArrays();
  }

  Supervisor.prototype.makeBlob = function(workerFn) {
    var blob;

    try {
      blob = new Blob([workerFn], {type: 'application/javascript'});
    }
    catch (e) {
      window.BlobBuilder = window.BlobBuilder ||
                           window.WebKitBlobBuilder ||
                           window.MozBlobBuilder;

      blob = new BlobBuilder();
      blob.append(workerFn);
      blob = blob.getBlob();
    }

    return blob;
  };

  Supervisor.prototype.graphToByteArrays = function() {
    var nodes = this.graph.nodes(),
        edges = this.graph.edges(),
        nbytes = nodes.length * this.ppn,
        ebytes = edges.length * this.ppe,
        nIndex = {},
        i,
        j,
        l;

    // Allocating Byte arrays with correct nb of bytes
    this.nodesByteArray = new Float32Array(nbytes);
    this.edgesByteArray = new Float32Array(ebytes);

    // Iterate through nodes
    for (i = j = 0, l = nodes.length; i < l; i++) {

      // Populating index
      nIndex[nodes[i].id] = j;

      // Populating byte array
      this.nodesByteArray[j] = nodes[i].x;
      this.nodesByteArray[j + 1] = nodes[i].y;
      this.nodesByteArray[j + 2] = 0;
      this.nodesByteArray[j + 3] = 0;
      this.nodesByteArray[j + 4] = 0;
      this.nodesByteArray[j + 5] = 0;
      this.nodesByteArray[j + 6] = 1 + this.graph.degree(nodes[i].id);
      this.nodesByteArray[j + 7] = 1;
      this.nodesByteArray[j + 8] = nodes[i].size;
      this.nodesByteArray[j + 9] = 0;
      j += this.ppn;
    }

    // Iterate through edges
    for (i = j = 0, l = edges.length; i < l; i++) {
      this.edgesByteArray[j] = nIndex[edges[i].source];
      this.edgesByteArray[j + 1] = nIndex[edges[i].target];
      this.edgesByteArray[j + 2] = edges[i].weight || 0;
      j += this.ppe;
    }
  };

  // TODO: make a better send function
  Supervisor.prototype.applyLayoutChanges = function() {
    var nodes = this.graph.nodes(),
        j = 0,
        realIndex;

    // Moving nodes
    for (var i = 0, l = this.nodesByteArray.length; i < l; i += this.ppn) {
      nodes[j].x = this.nodesByteArray[i];
      nodes[j].y = this.nodesByteArray[i + 1];
      j++;
    }
  };

  Supervisor.prototype.sendByteArrayToWorker = function(action, config) {
    var content = {
      action: action || 'loop',
      nodes: this.nodesByteArray.buffer
    };

    var buffers = [this.nodesByteArray.buffer];

    if (action === 'start') {
      content.config = this.config || {};
      content.edges = this.edgesByteArray.buffer;
      buffers.push(this.edgesByteArray.buffer);
    }

    if (webWorkers)
      this.worker.postMessage(content, buffers);
    else
      window.postMessage(content, '*');
  };

  Supervisor.prototype.start = function() {
    if (this.running)
      return;

    this.running = true;

    if (!this.started) {

      // Sending init message to worker
      this.sendByteArrayToWorker('start');
      this.started = true;
    }
    else {
      this.sendByteArrayToWorker();
    }
  };

  Supervisor.prototype.stop = function() {
    if (!this.running)
      return;

    this.running = false;
  };

  // TODO: kill polyfill when worker is not true worker
  Supervisor.prototype.killWorker = function() {
    this.worker.terminate();
  };

  Supervisor.prototype.configure = function(config) {

    // Setting configuration
    this.config = config;

    if (!this.started)
      return;

    var data = {action: 'config', config: this.config};

    if (webWorkers)
      this.worker.postMessage(data);
    else
      window.postMessage(data, '*');
  };

  /**
   * Interface
   * ----------
   */
  var supervisor = null;

  sigma.prototype.startForceAtlas2 = function(config) {

    // Create supervisor if undefined
    if (!supervisor)
      supervisor = new Supervisor(this);

    // Start algorithm
    supervisor.start(config);

    return this;
  };

  sigma.prototype.stopForceAtlas2 = function() {
    if (!supervisor)
      return this;

    // Pause algorithm
    supervisor.stop();

    return this;
  };

  sigma.prototype.killForceAtlas2 = function() {
    if (!supervisor)
      return this;

    // Stop Algorithm
    supervisor.stop();

    // Kill Worker
    supervisor.killWorker();

    // Kill supervisor
    supervisor = null;

    return this;
  };

  sigma.prototype.configForceAtlas2 = function(config) {
    if (!supervisor)
      supervisor = new Supervisor(this);

    supervisor.configure(config);

    return this;
  };

  sigma.prototype.isForceAtlas2Running = function(config) {
    return supervisor && supervisor.running;
  };
}).call(this);
<commit_msg>deactivate edgequad when FA2 is running<commit_after>;(function(undefined) {
  'use strict';

  if (typeof sigma === 'undefined')
    throw 'sigma is not declared';

  /**
   * Sigma ForceAtlas2.5 Supervisor
   * =============================
   *
   * Author: Guillaume Plique (Yomguithereal)
   * Version: 0.1
   */

  /**
   * Feature detection
   * ------------------
   */
  var webWorkers = 'Worker' in window;

  /**
   * Supervisor Object
   * ------------------
   */
  function Supervisor(sigInst, options) {
    var _this = this,
        workerFn = sigInst.getForceAtlas2Worker();

    // Window URL Polyfill
    window.URL = window.URL || window.webkitURL;

    // Properties
    this.sigInst = sigInst;
    this.graph = this.sigInst.graph;
    this.ppn = 10;
    this.ppe = 3;
    this.config = {};

    // State
    this.started = false;
    this.running = false;

    // Web worker or classic DOM events?
    if (webWorkers) {
      var blob = this.makeBlob(workerFn);
      this.worker = new Worker(URL.createObjectURL(blob));

      // Post Message Polyfill
      this.worker.postMessage =
        this.worker.webkitPostMessage || this.worker.postMessage;
    }
    else {

      // TODO: do we crush?
      eval(workerFn);
    }

    // Worker message receiver
    var msgName = (this.worker) ? 'message' : 'newCoords';
    (this.worker || document).addEventListener(msgName, function(e) {

      // Retrieving data
      _this.nodesByteArray = new Float32Array(e.data.nodes);

      // If ForceAtlas2 is running, we act accordingly
      if (_this.running) {

        // Applying layout
        _this.applyLayoutChanges();

        // Send data back to worker and loop
        _this.sendByteArrayToWorker();

        // Rendering graph
        _this.sigInst.refresh();
      }
    });

    // Filling byteArrays
    this.graphToByteArrays();
  }

  Supervisor.prototype.makeBlob = function(workerFn) {
    var blob;

    try {
      blob = new Blob([workerFn], {type: 'application/javascript'});
    }
    catch (e) {
      window.BlobBuilder = window.BlobBuilder ||
                           window.WebKitBlobBuilder ||
                           window.MozBlobBuilder;

      blob = new BlobBuilder();
      blob.append(workerFn);
      blob = blob.getBlob();
    }

    return blob;
  };

  Supervisor.prototype.graphToByteArrays = function() {
    var nodes = this.graph.nodes(),
        edges = this.graph.edges(),
        nbytes = nodes.length * this.ppn,
        ebytes = edges.length * this.ppe,
        nIndex = {},
        i,
        j,
        l;

    // Allocating Byte arrays with correct nb of bytes
    this.nodesByteArray = new Float32Array(nbytes);
    this.edgesByteArray = new Float32Array(ebytes);

    // Iterate through nodes
    for (i = j = 0, l = nodes.length; i < l; i++) {

      // Populating index
      nIndex[nodes[i].id] = j;

      // Populating byte array
      this.nodesByteArray[j] = nodes[i].x;
      this.nodesByteArray[j + 1] = nodes[i].y;
      this.nodesByteArray[j + 2] = 0;
      this.nodesByteArray[j + 3] = 0;
      this.nodesByteArray[j + 4] = 0;
      this.nodesByteArray[j + 5] = 0;
      this.nodesByteArray[j + 6] = 1 + this.graph.degree(nodes[i].id);
      this.nodesByteArray[j + 7] = 1;
      this.nodesByteArray[j + 8] = nodes[i].size;
      this.nodesByteArray[j + 9] = 0;
      j += this.ppn;
    }

    // Iterate through edges
    for (i = j = 0, l = edges.length; i < l; i++) {
      this.edgesByteArray[j] = nIndex[edges[i].source];
      this.edgesByteArray[j + 1] = nIndex[edges[i].target];
      this.edgesByteArray[j + 2] = edges[i].weight || 0;
      j += this.ppe;
    }
  };

  // TODO: make a better send function
  Supervisor.prototype.applyLayoutChanges = function() {
    var nodes = this.graph.nodes(),
        j = 0,
        realIndex;

    // Moving nodes
    for (var i = 0, l = this.nodesByteArray.length; i < l; i += this.ppn) {
      nodes[j].x = this.nodesByteArray[i];
      nodes[j].y = this.nodesByteArray[i + 1];
      j++;
    }
  };

  Supervisor.prototype.sendByteArrayToWorker = function(action, config) {
    var content = {
      action: action || 'loop',
      nodes: this.nodesByteArray.buffer
    };

    var buffers = [this.nodesByteArray.buffer];

    if (action === 'start') {
      content.config = this.config || {};
      content.edges = this.edgesByteArray.buffer;
      buffers.push(this.edgesByteArray.buffer);
    }

    if (webWorkers)
      this.worker.postMessage(content, buffers);
    else
      window.postMessage(content, '*');
  };

  Supervisor.prototype.start = function() {
    if (this.running)
      return;

    this.running = true;

    // Do not refresh edgequadtree during layout:
    var k,
        c;
    for (k in this.sigInst.cameras) {
      c = this.sigInst.cameras[k];
      c.edgequadtree._enabled = false;
    }

    if (!this.started) {

      // Sending init message to worker
      this.sendByteArrayToWorker('start');
      this.started = true;
    }
    else {
      this.sendByteArrayToWorker();
    }
  };

  Supervisor.prototype.stop = function() {
    if (!this.running)
      return;

    // Allow to refresh edgequadtree:
    var k,
        c,
        bounds;
    for (k in this.sigInst.cameras) {
      c = this.sigInst.cameras[k];
      c.edgequadtree._enabled = true;

      // Find graph boundaries:
      bounds = sigma.utils.getBoundaries(
        this.graph,
        c.readPrefix
      );

      // Refresh edgequadtree:
      if (c.settings('drawEdges'))
        c.edgequadtree.index(this.sigInst.graph, {
          prefix: c.readPrefix,
          bounds: {
            x: bounds.minX,
            y: bounds.minY,
            width: bounds.maxX - bounds.minX,
            height: bounds.maxY - bounds.minY
          }
        });
    }

    this.running = false;
  };

  // TODO: kill polyfill when worker is not true worker
  Supervisor.prototype.killWorker = function() {
    this.worker.terminate();
  };

  Supervisor.prototype.configure = function(config) {

    // Setting configuration
    this.config = config;

    if (!this.started)
      return;

    var data = {action: 'config', config: this.config};

    if (webWorkers)
      this.worker.postMessage(data);
    else
      window.postMessage(data, '*');
  };

  /**
   * Interface
   * ----------
   */
  var supervisor = null;

  sigma.prototype.startForceAtlas2 = function(config) {

    // Create supervisor if undefined
    if (!supervisor)
      supervisor = new Supervisor(this);

    // Start algorithm
    supervisor.start(config);

    return this;
  };

  sigma.prototype.stopForceAtlas2 = function() {
    if (!supervisor)
      return this;

    // Pause algorithm
    supervisor.stop();

    return this;
  };

  sigma.prototype.killForceAtlas2 = function() {
    if (!supervisor)
      return this;

    // Stop Algorithm
    supervisor.stop();

    // Kill Worker
    supervisor.killWorker();

    // Kill supervisor
    supervisor = null;

    return this;
  };

  sigma.prototype.configForceAtlas2 = function(config) {
    if (!supervisor)
      supervisor = new Supervisor(this);

    supervisor.configure(config);

    return this;
  };

  sigma.prototype.isForceAtlas2Running = function(config) {
    return supervisor && supervisor.running;
  };
}).call(this);
<|endoftext|>


<commit_before>const School = require('../../../../src/services/school/model').schoolModel;

let createdSchoolIds = [];

const create = (app) => async ({
	name = `HPI-Testschule-${new Date().getTime()}`,
	address = {},
	fileStorageType,
	systems = [],
	federalState,
	ldapSchoolIdentifier,
	createdAt = Date.now(),
	updatedAt = Date.now(),
	experimental = false,
	pilot = false,
	currentYear,
	schoolGroupId,
	documentBaseDirType,
	// eslint-disable-next-line camelcase
	logo_dataUrl,
	purpose = 'test',
	rssFeeds = [],
	features = [],
	customYears = [],
	inMaintenanceSince = undefined,
} = {}) => {
	if (systems && systems.length === 0) {
		const localSystem = (await app.service('systems').find({ query: { type: 'local' }, paginate: false }))[0];
		systems.push(localSystem._id);
	}
	const school = await School.create({
		name,
		address,
		fileStorageType,
		systems,
		federalState,
		ldapSchoolIdentifier,
		documentBaseDirType,
		createdAt,
		schoolGroupId,
		customYears,
		updatedAt,
		experimental,
		pilot,
		currentYear,
		// eslint-disable-next-line camelcase
		logo_dataUrl,
		purpose,
		rssFeeds,
		features,
		inMaintenanceSince,
	});
	createdSchoolIds.push(school._id);
	return school;
};

const cleanup = async () => {
	await School.deleteMany({ _id: { $in: createdSchoolIds } });
	createdSchoolIds = [];
};

module.exports = (app) => ({
	create: create(app),
	cleanup,
	info: createdSchoolIds,
});
<commit_msg>User service instead of model to create test schools<commit_after>const School = require('../../../../src/services/school/model').schoolModel;

let createdSchoolIds = [];

const create = (app) => async ({
	name = `HPI-Testschule-${new Date().getTime()}`,
	address = {},
	fileStorageType,
	systems = [],
	federalState,
	ldapSchoolIdentifier,
	createdAt = Date.now(),
	updatedAt = Date.now(),
	experimental = false,
	pilot = false,
	currentYear,
	schoolGroupId,
	documentBaseDirType,
	// eslint-disable-next-line camelcase
	logo_dataUrl,
	purpose = 'test',
	rssFeeds = [],
	features = [],
	customYears = [],
	inMaintenanceSince = undefined,
} = {}) => {
	if (systems && systems.length === 0) {
		const localSystem = (await app.service('systems').find({ query: { type: 'local' }, paginate: false }))[0];
		systems.push(localSystem._id);
	}
	const school = await app.service('schools').create({
		name,
		address,
		fileStorageType,
		systems,
		federalState,
		ldapSchoolIdentifier,
		documentBaseDirType,
		createdAt,
		schoolGroupId,
		customYears,
		updatedAt,
		experimental,
		pilot,
		currentYear,
		// eslint-disable-next-line camelcase
		logo_dataUrl,
		purpose,
		rssFeeds,
		features,
		inMaintenanceSince,
	});
	createdSchoolIds.push(school._id);
	return school;
};

const cleanup = async () => {
	await School.deleteMany({ _id: { $in: createdSchoolIds } });
	createdSchoolIds = [];
};

module.exports = (app) => ({
	create: create(app),
	cleanup,
	info: createdSchoolIds,
});
<|endoftext|>