<commit_before>/**
 * The simplest representation of a date.
 */
function Simple() {

  // If arguments passed in, try and parse the simple date
  if(arguments.length > 0) {
    this._parse(arguments[0]);
  } else {
    // Note that all dates and times are UTC internally!
    var date = new Date();
    this._year = date.getUTCFullYear();
    this._month = date.getUTCMonth();
    this._day = date.getUTCDay();
    this._hours = date.getUTCHours();
    this._minutes = date.getUTCMinutes();
    this._seconds = date.getUTCSeconds();
    this._tzHours = 0;
    this._tzMinutes = 0;
  }
}

/**
 * Parse a simple date.
 * This function also does strict validation
 */
Simple.prototype._parse = function(str) {

  var end = str.length;
      offset = 0;

  // There is a minimum length of 5 characters
  if(str.length < 5) throw new Error('Invalid Date');

  // Extract and validate year
  var year = str.substr(offset,5);
  if(year.match(/^[+-][0-9]{4}$/) === null) {
    throw new Error('Invalid Date: Malformed year');
  }
  this._year = parseInt(year);
  offset += 5;

  if(offset == end) {
    return;
  }

  // If there is time
  if(str.charAt(offset) == 'T') {
    return this._parseTime(str.substr(offset+1));
  }

  if(str.charAt(offset) != '-') {
    throw new Error('Invalid Date: Malformed year-month separator');
  }

  if(end-offset < 3) {
    throw new Error('Invalid Date: Malformed month');
  }

  // Extract and validate month
  var month = str.substr(offset+1,2);
  if(month.match(/^(0[1-9]|1[0-2])$/) === null) {
    throw new Error('Invalid Date: Malformed month');
  }
  this._month = parseInt(month);
  offset += 3;

  if(offset == end) {
    return;
  }

  // If there is time
  if(str.charAt(offset) == 'T') {
    return this._parseTime(str.substr(offset+1));
  }

  if(str.charAt(offset) != '-') {
    throw new Error('Invalid Date: Malformed month-day separator');
  }

  if(end-offset < 3) {
    throw new Error('Invalid Date: Malformed day');
  }

  // Extract and validate day
  var day = str.substr(offset+1,2);
  switch(this._month) {
    case 1:
    case 3:
    case 5:
    case 6:
    case 8:
    case 10:
    case 12:
      if(day.match(/^(0[1-9]|[1-2][0-9]|3[0-1])$/) === null) {
        throw new Error('Invalid Date: Malformed day (31 in '+this._month+')');
      }
      break;
    case 4:
    case 7:
    case 9:
    case 11:
      if(day.match(/^(0[1-9]|[1-2][0-9]|30)$/) === null) {
        throw new Error('Invalid Date: Malformed day (30 in '+this._month+')');
      }
      break;
    case 2:
      var leapyear;
      if(this._year % 4 != 0) {
        leapyear = false;
      } else if(this._year % 100 != 0) {
        leapyear = true;
      } else if(this._year % 400 != 0) {
        leapyear = false;
      } else {
        leapyear = true;
      }
      if(leapyear) {
        if(day.match(/^(0[1-9]|1[0-9]|2[0-9])$/) === null) {
          throw new Error('Invalid Date: Malformed day (29 in '+this._month+' - leapyear)');
        }
      } else {
        if(day.match(/^(0[1-9]|1[0-9]|2[0-8])$/) === null) {
          throw new Error('Invalid Date: Malformed day (28 in '+this._month+')');
        }
      }
      break;
  }
  //if(month.match(/^(0[0-9]|1[0-2])$/) === null) throw new Error('Invalid Date: Malformed month');
  this._day = parseInt(day);
  offset += 3;

  if(offset == end) return;

  // If there is time
  if(str.charAt(offset) == 'T') {
    return this._parseTime(str.substr(offset+1));
  } else {
    throw new Error('Invalid Date');
  }

}

Simple.prototype._parseTime = function(str) {

  var offset = 0,
      end = str.length,
      flag24 = false;

  // There is a minimum length of 2 characters
  if(str.length < 2) throw new Error('Invalid Date: Malformed hours');

  // Extract and validate hours
  var hours = str.substr(offset,2);
  if(hours.match(/^([0-1][0-9]|2[0-3])$/) === null) {
    if(hours == '24') {
      flag24 = true;
    } else {
      throw new Error('Invalid Date: Malformed hours');
    }
  }
  this._hours = parseInt(hours);
  offset += 2;

  if(offset == end) {
    return;
  }

  // If there is timezone offset
  if(str.charAt(offset) == '+' || str.charAt(offset) == '-' || str.charAt(offset) == 'Z') {
    return this._parseTimezone(str.substr(offset));
  }

  if(str.charAt(offset) != ':') {
    throw new Error('Invalid Date: Malformed hour-minute separator');
  }

  if(end-offset < 3) {
    throw new Error('Invalid Date: Malformed minutes');
  }

  var minutes = str.substr(offset+1,2);
  if(minutes.match(/^[0-5][0-9]$/) === null) {
    throw new Error('Invalid Date: Malformed minutes');
  }
  if(flag24 && minutes != '00') {
    throw new Error('Invalid Date: Hour od 24 requires 00 minutes');
  }
  this._minutes = parseInt(minutes);
  offset += 3;

  if(offset == end) {
    return;
  }

  // If there is timezone offset
  if(str.charAt(offset) == '+' || str.charAt(offset) == '-' || str.charAt(offset) == 'Z') {
    return this._parseTimezone(str.substr(offset));
  }

  if(str.charAt(offset) != ':') {
    throw new Error('Invalid Date: Malformed minute-second separator');
  }

  if(end-offset < 3) {
    throw new Error('Invalid Date: Malformed seconds');
  }

  var seconds = str.substr(offset+1,2);
  if(seconds.match(/^[0-5][0-9]$/) === null) {
    throw new Error('Invalid Date: Malformed seconds');
  }
  if(flag24 && seconds != '00') {
    throw new Error('Invalid Date: Hour od 24 requires 00 seconds');
  }
  this._seconds = parseInt(seconds);
  offset += 3;

  if(offset == end) {
    return;
  }

  // If there is timezone offset
  if(str.charAt(offset) == '+' || str.charAt(offset) == '-' || str.charAt(offset) == 'Z') {
    return this._parseTimezone(str.substr(offset));
  } else {
    throw new Error('Invalid Date: Malformed Time');
  }

}

Simple.prototype._parseTimezone = function(str) {

  var offset = 0,
      end = str.length;

  // If Z we're done
  if(str.charAt(0) == 'Z') {
    if(str.length == 1) {
      this._tzHours = 0;
      this._tzMinutes = 0;
      return;
    } else {
      throw new Error('Invalid Date: malformed timezone');
    }
  }

  if(end-offset < 3) {
    throw new Error('Invalid Date: Malformed timezone');
  }

  var tzHours = str.substr(offset,3);
  if(tzHours.match(/^[+-]([0-1][0-9]|2[0-3])$/) === null) {
    throw new Error('Invalid Date: Malformed timezone hours');
  }
  this._tzHours = parseInt(tzHours);
  offset += 3;

  if(offset == end) {
    return;
  }

  if(str.charAt(offset) != ':') {
    throw new Error('Invalid Date: Malformed timezone hour-minute separator');
  }

  if(end-offset < 3) {
    throw new Error('Invalid Date: Malformed timezone minutes');
  }

  var tzMinutes = str.substr(offset+1,2);
  if(tzMinutes.match(/^[0-5][0-9]$/) === null) {
    throw new Error('Invalid Date: Malformed timezone minutes');
  }
  this._tzMinutes = parseInt(tzMinutes);
  offset += 3;

  if(offset == end) {
    return;
  } else {
    throw new Error('Invalid Date: Malformed timezone');
  }

}

/**
 * Return single.
 */
Simple.prototype.getType = function() {
  return 'single';
}

/**
 * A simple date is not approximate.
 */
Simple.prototype.isApproximate = function() {
  return false;
}

/**
 * Return the year as a number.
 */
Simple.prototype.getYear = function() {
  return this._year;
}

/**
 * Return the month as a number.
 */
Simple.prototype.getMonth = function() {
  return this._month;
}

/**
 * Return the day as a number.
 */
Simple.prototype.getDay = function() {
  return this._day;
}

/**
 * Return the hours as a number.
 */
Simple.prototype.getHours = function() {
  return this._hours;
}

/**
 * Return the minutes as a number.
 */
Simple.prototype.getMinutes = function() {
  return this._minutes;
}

/**
 * Return the seconds as a number.
 */
Simple.prototype.getSeconds = function() {
  return this._seconds;
}

/**
 * Return the timezone hours as a number.
 */
Simple.prototype.getTZHours = function() {
  return this._tzHours;
}

/**
 * Return the timezone minutes as a number.
 */
Simple.prototype.getTZMinutes = function() {
  return this._tzMinutes;
}

module.exports = Simple;<commit_msg>refactor to use daysinmonth function<commit_after>var Util = require('./util.js');
/**
 * The simplest representation of a date.
 */
function Simple() {

  // If arguments passed in, try and parse the simple date
  if(arguments.length > 0) {
    this._parse(arguments[0]);
  } else {
    // Note that all dates and times are UTC internally!
    var date = new Date();
    this._year = date.getUTCFullYear();
    this._month = date.getUTCMonth();
    this._day = date.getUTCDay();
    this._hours = date.getUTCHours();
    this._minutes = date.getUTCMinutes();
    this._seconds = date.getUTCSeconds();
    this._tzHours = 0;
    this._tzMinutes = 0;
  }
}

/**
 * Parse a simple date.
 * This function also does strict validation
 */
Simple.prototype._parse = function(str) {

  var end = str.length;
      offset = 0;

  // There is a minimum length of 5 characters
  if(str.length < 5) throw new Error('Invalid Date');

  // Extract and validate year
  var year = str.substr(offset,5);
  if(year.match(/^[+-][0-9]{4}$/) === null) {
    throw new Error('Invalid Date: Malformed year');
  }
  this._year = parseInt(year);
  offset += 5;

  if(offset == end) {
    return;
  }

  // If there is time
  if(str.charAt(offset) == 'T') {
    return this._parseTime(str.substr(offset+1));
  }

  if(str.charAt(offset) != '-') {
    throw new Error('Invalid Date: Malformed year-month separator');
  }

  if(end-offset < 3) {
    throw new Error('Invalid Date: Malformed month');
  }

  // Extract and validate month
  var month = str.substr(offset+1,2);
  if(month.match(/^(0[1-9]|1[0-2])$/) === null) {
    throw new Error('Invalid Date: Malformed month');
  }
  this._month = parseInt(month);
  offset += 3;

  if(offset == end) {
    return;
  }

  // If there is time
  if(str.charAt(offset) == 'T') {
    return this._parseTime(str.substr(offset+1));
  }

  if(str.charAt(offset) != '-') {
    throw new Error('Invalid Date: Malformed month-day separator');
  }

  if(end-offset < 3) {
    throw new Error('Invalid Date: Malformed day');
  }

  // Extract and validate day
  var day = str.substr(offset+1,2);
  var daysInMonth = Util.daysInMonth(this._month, this._year);

  switch(daysInMonth) {
    case 31:
      if(day.match(/^(0[1-9]|[1-2][0-9]|3[0-1])$/) === null) {
        throw new Error('Invalid Date: Malformed day (31 in '+this._month+')');
      }
      break;
    case 30:
      if(day.match(/^(0[1-9]|[1-2][0-9]|30)$/) === null) {
        throw new Error('Invalid Date: Malformed day (30 in '+this._month+')');
      }
      break;
    case 29:
      if(day.match(/^(0[1-9]|1[0-9]|2[0-9])$/) === null) {
        throw new Error('Invalid Date: Malformed day (29 in '+this._month+' - leapyear)');
      }
      break;
    case 28:
      if(day.match(/^(0[1-9]|1[0-9]|2[0-8])$/) === null) {
        throw new Error('Invalid Date: Malformed day (28 in '+this._month+')');
      }
      break;
  }
  this._day = parseInt(day);
  offset += 3;

  if(offset == end) return;

  // If there is time
  if(str.charAt(offset) == 'T') {
    return this._parseTime(str.substr(offset+1));
  } else {
    throw new Error('Invalid Date');
  }

}

Simple.prototype._parseTime = function(str) {

  var offset = 0,
      end = str.length,
      flag24 = false;

  // There is a minimum length of 2 characters
  if(str.length < 2) throw new Error('Invalid Date: Malformed hours');

  // Extract and validate hours
  var hours = str.substr(offset,2);
  if(hours.match(/^([0-1][0-9]|2[0-3])$/) === null) {
    if(hours == '24') {
      flag24 = true;
    } else {
      throw new Error('Invalid Date: Malformed hours');
    }
  }
  this._hours = parseInt(hours);
  offset += 2;

  if(offset == end) {
    return;
  }

  // If there is timezone offset
  if(str.charAt(offset) == '+' || str.charAt(offset) == '-' || str.charAt(offset) == 'Z') {
    return this._parseTimezone(str.substr(offset));
  }

  if(str.charAt(offset) != ':') {
    throw new Error('Invalid Date: Malformed hour-minute separator');
  }

  if(end-offset < 3) {
    throw new Error('Invalid Date: Malformed minutes');
  }

  var minutes = str.substr(offset+1,2);
  if(minutes.match(/^[0-5][0-9]$/) === null) {
    throw new Error('Invalid Date: Malformed minutes');
  }
  if(flag24 && minutes != '00') {
    throw new Error('Invalid Date: Hour od 24 requires 00 minutes');
  }
  this._minutes = parseInt(minutes);
  offset += 3;

  if(offset == end) {
    return;
  }

  // If there is timezone offset
  if(str.charAt(offset) == '+' || str.charAt(offset) == '-' || str.charAt(offset) == 'Z') {
    return this._parseTimezone(str.substr(offset));
  }

  if(str.charAt(offset) != ':') {
    throw new Error('Invalid Date: Malformed minute-second separator');
  }

  if(end-offset < 3) {
    throw new Error('Invalid Date: Malformed seconds');
  }

  var seconds = str.substr(offset+1,2);
  if(seconds.match(/^[0-5][0-9]$/) === null) {
    throw new Error('Invalid Date: Malformed seconds');
  }
  if(flag24 && seconds != '00') {
    throw new Error('Invalid Date: Hour od 24 requires 00 seconds');
  }
  this._seconds = parseInt(seconds);
  offset += 3;

  if(offset == end) {
    return;
  }

  // If there is timezone offset
  if(str.charAt(offset) == '+' || str.charAt(offset) == '-' || str.charAt(offset) == 'Z') {
    return this._parseTimezone(str.substr(offset));
  } else {
    throw new Error('Invalid Date: Malformed Time');
  }

}

Simple.prototype._parseTimezone = function(str) {

  var offset = 0,
      end = str.length;

  // If Z we're done
  if(str.charAt(0) == 'Z') {
    if(str.length == 1) {
      this._tzHours = 0;
      this._tzMinutes = 0;
      return;
    } else {
      throw new Error('Invalid Date: malformed timezone');
    }
  }

  if(end-offset < 3) {
    throw new Error('Invalid Date: Malformed timezone');
  }

  var tzHours = str.substr(offset,3);
  if(tzHours.match(/^[+-]([0-1][0-9]|2[0-3])$/) === null) {
    throw new Error('Invalid Date: Malformed timezone hours');
  }
  this._tzHours = parseInt(tzHours);
  offset += 3;

  if(offset == end) {
    return;
  }

  if(str.charAt(offset) != ':') {
    throw new Error('Invalid Date: Malformed timezone hour-minute separator');
  }

  if(end-offset < 3) {
    throw new Error('Invalid Date: Malformed timezone minutes');
  }

  var tzMinutes = str.substr(offset+1,2);
  if(tzMinutes.match(/^[0-5][0-9]$/) === null) {
    throw new Error('Invalid Date: Malformed timezone minutes');
  }
  this._tzMinutes = parseInt(tzMinutes);
  offset += 3;

  if(offset == end) {
    return;
  } else {
    throw new Error('Invalid Date: Malformed timezone');
  }

}

/**
 * Return single.
 */
Simple.prototype.getType = function() {
  return 'single';
}

/**
 * A simple date is not approximate.
 */
Simple.prototype.isApproximate = function() {
  return false;
}

/**
 * Return the year as a number.
 */
Simple.prototype.getYear = function() {
  return this._year;
}

/**
 * Return the month as a number.
 */
Simple.prototype.getMonth = function() {
  return this._month;
}

/**
 * Return the day as a number.
 */
Simple.prototype.getDay = function() {
  return this._day;
}

/**
 * Return the hours as a number.
 */
Simple.prototype.getHours = function() {
  return this._hours;
}

/**
 * Return the minutes as a number.
 */
Simple.prototype.getMinutes = function() {
  return this._minutes;
}

/**
 * Return the seconds as a number.
 */
Simple.prototype.getSeconds = function() {
  return this._seconds;
}

/**
 * Return the timezone hours as a number.
 */
Simple.prototype.getTZHours = function() {
  return this._tzHours;
}

/**
 * Return the timezone minutes as a number.
 */
Simple.prototype.getTZMinutes = function() {
  return this._tzMinutes;
}

module.exports = Simple;<|endoftext|>


<commit_before>/**
 * @ngdoc service
 * @name Vocab
 * @description
 * Handles getting and parsing the pre-defined vocabularies
 */
angular.module('locApp.modules.profile.services').factory('Vocab', function($q, $http, localStorageService, Server) {
    vocab = {};

    var choosenResource = -1;
    var choosenProperty = -1;

    var vocabResourceData = [];
    var vocabPropertyData = [];

    var languageList = [];

    // Takes in the rdf JSON object and puts a list of resources
    // to save to local storage
    var buildResources = function(rdfResources) {
        var resourceData = [];

        if(!Array.isArray(rdfResources) && rdfResources !== undefined) {
            var data = {};

            if(rdfResources.label != null) {
               data.label = rdfResources.label.__text.toString();
            }
            else {
                data.label = "";
            }

            data.comment = (rdfResources.comment != null) ? rdfResources.comment.__text.toString() : "";
            data.uri = rdfResources["_rdf:about"];
            resourceData.push(data);
            return resourceData;
        }

        angular.forEach(rdfResources, function(value) {
            var data = {};

            if(value.label === undefined) {
                value.label = null;
            }
            if(value.label != null) {
               data.label = value.label.__text.toString();
            }
            else {
                data.label = "";
            }

            data.comment = (value.comment != null) ? value.comment.__text.toString() : "";
            data.uri = value["_rdf:about"];
            resourceData.push(data);
        });

        return resourceData;
    };

    var buildProperties = function(rdfProperties) {
        var propertyData = [];

        if(!Array.isArray(rdfProperties) && rdfProperties !== undefined) {
            var data = {};

            if(rdfProperties.label != null) {
               data.label = rdfProperties.label.__text.toString();
            }
            else {
                data.label = "";
            }

            data.comment = (rdfProperties.comment != null) ? rdfProperties.comment.__text.toString() : "";
            data.uri = rdfProperties["_rdf:about"];
            propertyData.push(data);
            return propertyData;
        }

        angular.forEach(rdfProperties, function(value) {
            var data = {};
            if(value.label === undefined) {
                value.label = null;
            }
            if(value.label != null) {
               data.label = value.label.__text.toString();
            }
            else {
                data.label = "";
            }

            data.comment = (value.comment != null) ? value.comment.__text.toString() : "";
            data.uri = value["_rdf:about"];
            propertyData.push(data);
        });

        return propertyData;
    };

    // Method that will set the vocab data for each list.
    var _setVocabData = function(name, url, properties, resources) {
        var item = $q.defer();
        console.log(name);
        console.log(url);

        Server.get(url,{},false)
        .then(function(response) {
            // if a vocab file is empty then we will pass over it and return.
            if(response === undefined || response === "") {
                item.reject("No data");
                return;
            }

            // set the local storage with this data
            var jsonObj = response.json;

            var resource = {};
            var property = {};

            resource.key = name;
            resource.value = buildResources(jsonObj.RDF.Class);
            resources.push(resource);

            property.key = name;
            property.value = buildProperties(jsonObj.RDF.Property);
            properties.push(property);

            // Resolve the queue
            item.resolve("Finished");
        });

        return item.promise;
    };

    // Method to set the local storage of resource and properties
    var _setLocalStorage = function(resources, properties) {
        localStorageService.set("resourceReference", resources);
        localStorageService.set("propertyReference", properties);
        // Set Vocab data
        vocabResourceData = resources;
        vocabPropertyData = properties;
    };

    /**
     * @ngdoc function
     * @name setVocabData
     * @description
     * Gets the vocab data and adds them to the local machine.
     */
    vocab.setVocabData = function() {
        // if the local storage has expired, gather the data and set it up again
        // TODO: make this connect to the real RDF

        // const vurl = '/verso/api/configs?filter[where][configType]=vocabulary&filter[fields][name]=true&filter[fields][id]=true&filter[where][name][neq]=Languages';
        const vurl = '/verso/api/configs?filter[where][configType]=ontology';

        Server.get(vurl, {}, false)
        .then(function(response){
            var listLength = 0;
            var returnNumber = 0;
            var resources = [];
            var properties = [];

            // loop through the list of vocabs and gather up the data.
            angular.forEach(response, function(value) {
                var url = '/profile-edit/server/whichrt?uri=' + value.json.url;

                // test that we hvae a key and this isn't a comment.
                if(value.id != null) {
                    listLength++;
                    _setVocabData(value.json.label, url, properties, resources)
                        .then(function() {
                            returnNumber++;

                            // Set local storage once we have all the data.
                            if(returnNumber >= listLength) {
                                _setLocalStorage(resources, properties);
                            }
                        }, function() {
                            returnNumber++;
                        });
                }

            });
        });
    };

    /**
     * @ngdoc function
     * @name retrieveVocabData
     * @description
     * Sets vocabResourceData and vocabPropertyData with current data. Called
     * when the app first runs.
     */
    vocab.retrieveVocabData = function() {
        // returns the vocab data
        var lsDate = localStorageService.get('date');
        var currDate = new Date(lsDate);
        var beginDate = new Date();
        var endDate = new Date();

        beginDate.setDate(beginDate.getDate() - 7);
        endDate.setDate(endDate.getDate() + 7);

        if(!lsDate || !(currDate >= beginDate && currDate <= endDate)) {
            localStorageService.clearAll();
            vocab.setVocabData();
            localStorageService.set('date', (new Date()).toDateString());
        }
        else {
            vocabResourceData = localStorageService.get("resourceReference");
            vocabPropertyData = localStorageService.get("propertyReference");
        }
    };

    /**
     * @ngdoc function
     * @name updateChosenResource
     * @description
     * Gets the resource data to use to update the resource that is open on
     * the page
     * @param {Number} resourceNumber - the number of the resource to update
     * @returns {Array} - The resource data
     */
    vocab.updateChosenResource = function(resourceNumber) {
        choosenResource = resourceNumber;

        vocab.fillData = fillResource;

        return vocabResourceData;
    };

    /**
     * @ngdoc function
     * @name updateChosenProperty
     * @description
     * Gets the property data to use to update the property template that is
     * open on the page
     * @param {Number} resourceNumber - the resource template number
     * @param {Number} propertyNumber - the property template number
     * @returns {Array} - the property template data
     */
    vocab.updateChosenProperty = function(item) {
        choosenProperty = item;

        vocab.fillData = fillProperty;

        return vocabPropertyData;
    };

    vocab.getLanguages = function() {
        var queue = $q.defer();

        if(languageList.length > 0) {
            queue.resolve(languageList);
        }
        else {
            Server.get('/verso/api/configs?filter[where][configType]=vocabulary&filter[where][name]=Languages', {}, false)
            .then(function(response) {
                var jsonObj = response[0].json;

                var data = jsonObj.RDF.MADSScheme.hasTopMemberOfMADSScheme;
                var language;

                for(var i = 0; i < data.length; i++) {
                    language = data[i].Language;
                    if(typeof(language.label[0]) !== 'undefined') {
                        //Make sure it's the English name of the language
                        if(language.label[0]["_xml:lang"] === "en") {
                            languageList.push({key: language.label[0].__text,
                                value: language["_rdf:about"]});
                        } else {
                            for(var j = 0; j < language.label.length; j++) {
                                if(language.label[j]["_xml:lang"] === "en") {
                                    languageList.push({key: language.label[j].__text,
                                        value: language["_rdf:about"]});
                                }
                            }
                        }
                    } else if(typeof(language.label) !== 'undefined') {
                        languageList.push({key: language.label.__text,
                            value: language["_rdf:about"]});
                    } else {
                        languageList.push({key: language["_rdf:about"],
                            value: language["_rdf:about"]});
                    }
                }
                queue.resolve(languageList);
            });
        }

        return queue.promise;

    };

    fillResource = function(vocab) {
        var resource = choosenResource;
        resource.resourceURI = vocab.uri;
        resource.resourceLabel = vocab.label;
        resource.remark = vocab.comment;

    };

    fillProperty = function(vocab) {
        var property = choosenProperty;
        property.propertyURI = vocab.uri;
        property.propertyLabel = vocab.label;
        property.remark = vocab.comment;

    };

    return vocab;
});<commit_msg>Parse rdf response with x2js.<commit_after>/**
 * @ngdoc service
 * @name Vocab
 * @description
 * Handles getting and parsing the pre-defined vocabularies
 */
angular.module('locApp.modules.profile.services').factory('Vocab', function($q, $http, localStorageService, Server) {
    vocab = {};

    var choosenResource = -1;
    var choosenProperty = -1;

    var vocabResourceData = [];
    var vocabPropertyData = [];

    var languageList = [];

    // Takes in the rdf JSON object and puts a list of resources
    // to save to local storage
    var buildResources = function(rdfResources) {
        var resourceData = [];

        if(!Array.isArray(rdfResources) && rdfResources !== undefined) {
            var data = {};

            if(rdfResources.label != null) {
               data.label = rdfResources.label.__text.toString();
            }
            else {
                data.label = "";
            }

            data.comment = (rdfResources.comment != null) ? rdfResources.comment.__text.toString() : "";
            data.uri = rdfResources["_rdf:about"];
            resourceData.push(data);
            return resourceData;
        }

        angular.forEach(rdfResources, function(value) {
            var data = {};

            if(value.label === undefined) {
                value.label = null;
            }
            if(value.label != null) {
               data.label = value.label.__text.toString();
            }
            else {
                data.label = "";
            }

            data.comment = (value.comment != null) ? value.comment.__text.toString() : "";
            data.uri = value["_rdf:about"];
            resourceData.push(data);
        });

        return resourceData;
    };

    var buildProperties = function(rdfProperties) {
        var propertyData = [];

        if(!Array.isArray(rdfProperties) && rdfProperties !== undefined) {
            var data = {};

            if(rdfProperties.label != null) {
               data.label = rdfProperties.label.__text.toString();
            }
            else {
                data.label = "";
            }

            data.comment = (rdfProperties.comment != null) ? rdfProperties.comment.__text.toString() : "";
            data.uri = rdfProperties["_rdf:about"];
            propertyData.push(data);
            return propertyData;
        }

        angular.forEach(rdfProperties, function(value) {
            var data = {};
            if(value.label === undefined) {
                value.label = null;
            }
            if(value.label != null) {
               data.label = value.label.__text.toString();
            }
            else {
                data.label = "";
            }

            data.comment = (value.comment != null) ? value.comment.__text.toString() : "";
            data.uri = value["_rdf:about"];
            propertyData.push(data);
        });

        return propertyData;
    };

    // Method that will set the vocab data for each list.
    var _setVocabData = function(name, url, properties, resources) {
        var item = $q.defer();
        console.log(name);
        console.log(url);

        Server.get(url,{},false)
        .then(function(response) {
            // if a vocab file is empty then we will pass over it and return.
            if(response === undefined || response === "") {
                item.reject("No data");
                return;
            }
            var parser = new X2JS();
            var xjson = parser.xml_str2json(response);
            console.log(xjson);

            // set the local storage with this data
            var resource = {};
            var property = {};

            resource.key = name;
            resource.value = buildResources(xjson.RDF.Class);
            resources.push(resource);

            property.key = name;
            property.value = buildProperties(xjson.RDF.Property);
            properties.push(property);

            // Resolve the queue
            item.resolve("Finished");
        });

        return item.promise;
    };

    // Method to set the local storage of resource and properties
    var _setLocalStorage = function(resources, properties) {
        localStorageService.set("resourceReference", resources);
        localStorageService.set("propertyReference", properties);
        // Set Vocab data
        vocabResourceData = resources;
        vocabPropertyData = properties;
    };

    /**
     * @ngdoc function
     * @name setVocabData
     * @description
     * Gets the vocab data and adds them to the local machine.
     */
    vocab.setVocabData = function() {
        // if the local storage has expired, gather the data and set it up again
        // TODO: make this connect to the real RDF

        // const vurl = '/verso/api/configs?filter[where][configType]=vocabulary&filter[fields][name]=true&filter[fields][id]=true&filter[where][name][neq]=Languages';
        const vurl = '/verso/api/configs?filter[where][configType]=ontology';

        Server.get(vurl, {}, false)
        .then(function(response){
            var listLength = 0;
            var returnNumber = 0;
            var resources = [];
            var properties = [];

            // loop through the list of vocabs and gather up the data.
            angular.forEach(response, function(value) {
                var url = '/profile-edit/server/whichrt?uri=' + value.json.url;

                // test that we hvae a key and this isn't a comment.
                if(value.id != null) {
                    listLength++;
                    _setVocabData(value.json.label, url, properties, resources)
                        .then(function() {
                            returnNumber++;

                            // Set local storage once we have all the data.
                            if(returnNumber >= listLength) {
                                _setLocalStorage(resources, properties);
                            }
                        }, function() {
                            returnNumber++;
                        });
                }

            });
        });
    };

    /**
     * @ngdoc function
     * @name retrieveVocabData
     * @description
     * Sets vocabResourceData and vocabPropertyData with current data. Called
     * when the app first runs.
     */
    vocab.retrieveVocabData = function() {
        // returns the vocab data
        var lsDate = localStorageService.get('date');
        var currDate = new Date(lsDate);
        var beginDate = new Date();
        var endDate = new Date();

        beginDate.setDate(beginDate.getDate() - 7);
        endDate.setDate(endDate.getDate() + 7);

        if(!lsDate || !(currDate >= beginDate && currDate <= endDate)) {
            localStorageService.clearAll();
            vocab.setVocabData();
            localStorageService.set('date', (new Date()).toDateString());
        }
        else {
            vocabResourceData = localStorageService.get("resourceReference");
            vocabPropertyData = localStorageService.get("propertyReference");
        }
    };

    /**
     * @ngdoc function
     * @name updateChosenResource
     * @description
     * Gets the resource data to use to update the resource that is open on
     * the page
     * @param {Number} resourceNumber - the number of the resource to update
     * @returns {Array} - The resource data
     */
    vocab.updateChosenResource = function(resourceNumber) {
        choosenResource = resourceNumber;

        vocab.fillData = fillResource;

        return vocabResourceData;
    };

    /**
     * @ngdoc function
     * @name updateChosenProperty
     * @description
     * Gets the property data to use to update the property template that is
     * open on the page
     * @param {Number} resourceNumber - the resource template number
     * @param {Number} propertyNumber - the property template number
     * @returns {Array} - the property template data
     */
    vocab.updateChosenProperty = function(item) {
        choosenProperty = item;

        vocab.fillData = fillProperty;

        return vocabPropertyData;
    };

    vocab.getLanguages = function() {
        var queue = $q.defer();

        if(languageList.length > 0) {
            queue.resolve(languageList);
        }
        else {
            Server.get('/verso/api/configs?filter[where][configType]=vocabulary&filter[where][name]=Languages', {}, false)
            .then(function(response) {
                var jsonObj = response[0].json;

                var data = jsonObj.RDF.MADSScheme.hasTopMemberOfMADSScheme;
                var language;

                for(var i = 0; i < data.length; i++) {
                    language = data[i].Language;
                    if(typeof(language.label[0]) !== 'undefined') {
                        //Make sure it's the English name of the language
                        if(language.label[0]["_xml:lang"] === "en") {
                            languageList.push({key: language.label[0].__text,
                                value: language["_rdf:about"]});
                        } else {
                            for(var j = 0; j < language.label.length; j++) {
                                if(language.label[j]["_xml:lang"] === "en") {
                                    languageList.push({key: language.label[j].__text,
                                        value: language["_rdf:about"]});
                                }
                            }
                        }
                    } else if(typeof(language.label) !== 'undefined') {
                        languageList.push({key: language.label.__text,
                            value: language["_rdf:about"]});
                    } else {
                        languageList.push({key: language["_rdf:about"],
                            value: language["_rdf:about"]});
                    }
                }
                queue.resolve(languageList);
            });
        }

        return queue.promise;

    };

    fillResource = function(vocab) {
        var resource = choosenResource;
        resource.resourceURI = vocab.uri;
        resource.resourceLabel = vocab.label;
        resource.remark = vocab.comment;

    };

    fillProperty = function(vocab) {
        var property = choosenProperty;
        property.propertyURI = vocab.uri;
        property.propertyLabel = vocab.label;
        property.remark = vocab.comment;

    };

    return vocab;
});<|endoftext|>


<commit_before>
define(function() {

    return function() {
        /*
         * API-draft:
         *
         * $('button').colorselector({
              color: '#ff0000'  // current selection
         *    palette: ['#fe8843', '#48cd45', ...],  // theme palette
         *    change: function(new_color) { }  // called after user closed popup
         * });
         */
        $.fn.colorselector = function(opts) {
            $('.color-selector').remove();
            var btn = $(this),
                popup = $('
')
                    .addClass('color-selector')
                    .css({
                        left: btn.offset().left - 70,
                        top: btn.offset().top - 40 // 30px = body.padding-top
                    })
                    .appendTo('body'),
                palette = $('
').addClass('palette').appendTo(popup),
                lightness = $('
').addClass('color-axis lightness').appendTo(popup),
                saturation = $('
').addClass('color-axis saturation').appendTo(popup),
                hue = $('
').addClass('color-axis hue').appendTo(popup),
                bottom = $('
').addClass('footer').appendTo(popup),
                hexTf = $('<input type="text" />').addClass('hex').appendTo(bottom),
                okBtn = $('<button />').html('').addClass('btn btn-small ok').appendTo(bottom);

            addcol(opts.color, bottom);

            // initialize palette colors
            $.each(opts.palette, function(i, color) {
                addcol(color, palette);
            });

            setColor(opts.color);

            function closePopup() {
                popup.remove();
                if (_.isFunction(opts.change)) opts.change(opts.color);
            }

            hexTf.change(function() { setColor(hexTf.val()); });
            okBtn.click(closePopup);

            setTimeout(function() {
                $('body').one('click', body_click);
            }, 300);

            function setColor(hex, cont) {
                var lch = chroma.color(hex).lch(),
                    center = [60, 50, lch[2]],
                    spread_ = [55, 50, 70],
                    steps = [7, 7, 7],
                    steps2 = [6, 6, 6];

                opts.color = hex;
                _.each([lightness, saturation, hue], function(cnt, i) {
                    if (cont != cnt || cont == hue) {
                        cnt.html('');
                        var values = spread(center[i], spread_[i], steps[i], steps2[i]);
                        // shift center to match color
                        center[i] += lch[i] - dw.utils.nearest(values, lch[i]);
                        _.each(spread(center[i], spread_[i], steps[i], steps2[i]), function(x) {
                            var lch_ = lch.slice(0);
                            lch_[i] = x;
                            addcol(chroma.lch(lch_).hex(), cnt);
                        });
                    }
                });
                hexTf.val(hex).css({
                    background: hex,
                    'border-color': chroma.color(hex).darker().hex(),
                    color: chroma.luminance(hex) > 0.45 ? '#000' : '#fff'
                });
                $('.color', popup).removeClass('selected').removeClass('inverted');
                $('.color', popup)
                    .filter(function(i,e) { return $(e).data('color') == hex; })
                    .addClass('selected');
                if ($('.color.selected', hue).length > 2) {
                    $('.color.selected', hue).removeClass('selected');
                }
                $('.color.selected', popup)
                    .filter(function(i,e) {
                        return chroma.luminance($(e).data('color')) < 0.05;
                    }).addClass('inverted');
                if (_.isFunction(opts.change)) opts.change(opts.color);
            }

            function spread(center, width, num, num2, exp) {
                var r = [center], s = width / num, a = 0;
                num2 = _.isUndefined(num2) ? num : num2;
                exp = exp || 1;
                while (num-- > 0) {
                    a += s;
                    r.unshift(center - a);
                    if (num2-- > 0) r.push(center + a);
                }
                return r;
            }

            function addcol(color, cont) {
                $('
')
                    .addClass('color')
                    .data('color', color)
                    .css('background', color)
                    .click(function(evt) {
                        var c = $(evt.target);
                        setColor(c.data('color'), cont);
                        // stop propagation so body.click won't fire
                        evt.stopPropagation();
                    })
                    .dblclick(function(evt) {
                        var c = $(evt.target);
                        opts.color = c.data('color');
                        closePopup();
                    })
                    .appendTo(cont);
            }

            function body_click(evt) {
                var el = $(evt.target);
                if (!el.is('.color-selector') && el.parents('.color-selector').length === 0) {
                    popup.remove();
                } else {
                    $('body').one('click', body_click);
                }
            }
        };
    };

});<commit_msg>made color selector ready for new chroma.js<commit_after>
define(['chroma'], function(chroma) {

    return function() {
        /*
         * API-draft:
         *
         * $('button').colorselector({
              color: '#ff0000'  // current selection
         *    palette: ['#fe8843', '#48cd45', ...],  // theme palette
         *    change: function(new_color) { }  // called after user closed popup
         * });
         */
        $.fn.colorselector = function(opts) {
            $('.color-selector').remove();
            var btn = $(this),
                popup = $('
')
                    .addClass('color-selector')
                    .css({
                        left: btn.offset().left - 70,
                        top: btn.offset().top - 40 // 30px = body.padding-top
                    })
                    .appendTo('body'),
                palette = $('
').addClass('palette').appendTo(popup),
                lightness = $('
').addClass('color-axis lightness').appendTo(popup),
                saturation = $('
').addClass('color-axis saturation').appendTo(popup),
                hue = $('
').addClass('color-axis hue').appendTo(popup),
                bottom = $('
').addClass('footer').appendTo(popup),
                hexTf = $('<input type="text" />').addClass('hex').appendTo(bottom),
                okBtn = $('<button />').html('').addClass('btn btn-small ok').appendTo(bottom);

            addcol(opts.color, bottom);

            // initialize palette colors
            $.each(opts.palette, function(i, color) {
                addcol(color, palette);
            });

            setColor(opts.color);

            function closePopup() {
                popup.remove();
                if (_.isFunction(opts.change)) opts.change(opts.color);
            }

            hexTf.change(function() { setColor(hexTf.val()); });
            okBtn.click(closePopup);

            setTimeout(function() {
                $('body').one('click', body_click);
            }, 300);

            function setColor(hex, cont) {
                hex = hex || opts.palette[0];
                var lch = chroma(hex).lch(),
                    center = [60, 50, lch[2]],
                    spread_ = [55, 50, 70],
                    steps = [7, 7, 7],
                    steps2 = [6, 6, 6];

                opts.color = hex;
                _.each([lightness, saturation, hue], function(cnt, i) {
                    if (cont != cnt || cont == hue) {
                        cnt.html('');
                        var values = spread(center[i], spread_[i], steps[i], steps2[i]);
                        // shift center to match color
                        center[i] += lch[i] - dw.utils.nearest(values, lch[i]);
                        _.each(spread(center[i], spread_[i], steps[i], steps2[i]), function(x) {
                            var lch_ = lch.slice(0);
                            lch_[i] = x;
                            addcol(chroma.lch(lch_).hex(), cnt);
                        });
                    }
                });
                hexTf.val(hex).css({
                    background: hex,
                    'border-color': chroma(hex).darker().hex(),
                    color: chroma(hex).luminance() > 0.45 ? '#000' : '#fff'
                });
                $('.color', popup).removeClass('selected').removeClass('inverted');
                $('.color', popup)
                    .filter(function(i,e) { return $(e).data('color') == hex; })
                    .addClass('selected');
                if ($('.color.selected', hue).length > 2) {
                    $('.color.selected', hue).removeClass('selected');
                }
                $('.color.selected', popup)
                    .filter(function(i,e) {
                        return chroma($(e).data('color')).luminance() < 0.05;
                    }).addClass('inverted');
                if (_.isFunction(opts.change)) opts.change(opts.color);
            }

            function spread(center, width, num, num2, exp) {
                var r = [center], s = width / num, a = 0;
                num2 = _.isUndefined(num2) ? num : num2;
                exp = exp || 1;
                while (num-- > 0) {
                    a += s;
                    r.unshift(center - a);
                    if (num2-- > 0) r.push(center + a);
                }
                return r;
            }

            function addcol(color, cont) {
                $('
')
                    .addClass('color')
                    .data('color', color)
                    .css('background', color)
                    .click(function(evt) {
                        var c = $(evt.target);
                        setColor(c.data('color'), cont);
                        // stop propagation so body.click won't fire
                        evt.stopPropagation();
                    })
                    .dblclick(function(evt) {
                        var c = $(evt.target);
                        opts.color = c.data('color');
                        closePopup();
                    })
                    .appendTo(cont);
            }

            function body_click(evt) {
                var el = $(evt.target);
                if (!el.is('.color-selector') && el.parents('.color-selector').length === 0) {
                    popup.remove();
                } else {
                    $('body').one('click', body_click);
                }
            }
        };
    };

});
<|endoftext|>


<commit_before>var slugify = require('slugify2'),
  async = require('async');

exports = module.exports = {
  'groupBlogs': function (kabam) {
    var GroupBlogsSchema = new kabam.mongoose.Schema({
      'groupId': kabam.mongoose.Schema.Types.ObjectId,
      'title': String,
      'description': String,
      'keywords': String,
      'contentPublic': String,
      'contentForMembers': String,
      'createdAt': {type: Date, default: new Date()}
    });
    GroupBlogsSchema.index({ groupId: 1, createdAt: 1});
    return kabam.mongoConnection.model('groupBlogs', GroupBlogsSchema);
  },
  'groupMessages': function (kabam) {
    var GroupMessagesSchema = new kabam.mongoose.Schema({
      'groupId': kabam.mongoose.Schema.Types.ObjectId,
      'userId': kabam.mongoose.Schema.Types.ObjectId,
      'message': String,
      'user': { type: kabam.mongoose.Schema.Types.ObjectId, ref: 'User' },
      'createdAt': {type: Date, default: new Date()}
    });

    GroupMessagesSchema.index({ groupId: 1, createdAt: 1});
    return kabam.mongoConnection.model('groupMessages', GroupMessagesSchema);
  },
  'groups': function (kabam) {
    var GroupsSchema = new kabam.mongoose.Schema({
        'name': {
          type: String,
          trim: true,
          index: true
        },
        'uri': {
          type: String,
          trim: true,
          index: true
        },
        //0 - world, 1 - school, 2 - course/association, 3 - group
        'tier': {type: Number, min: 0, max: 3},

        'school_id': kabam.mongoose.Schema.Types.ObjectId,

        'course_id': kabam.mongoose.Schema.Types.ObjectId,

        'descriptionPublic': String,
        'descriptionForMembers': String,

        'members': [
          {
            'user': { type: kabam.mongoose.Schema.Types.ObjectId, ref: 'User' },
            'role': String
          }
        ],

        'isOpenToAll': {type: Boolean, default: false},
        'isOpenToParent': {type: Boolean, default: false} //maybe we do not need it?
      },
      {
        toObject: { getters: true, virtuals: true }, //http://mongoosejs.com/docs/api.html#document_Document-toObject
        toJSON: { getters: true, virtuals: true }
      }
    );

    GroupsSchema.index({ name: 1, uri: 1, school_id: 1, course_id: 1 });

    GroupsSchema.methods.findRoleInThisGroup = function (user) {
      var role = 'visitor';
      this.members.map(function (member) {
        if (member.user.toString() == user._id.toString()) {
          role = member.role;
        } else {
          if (member.user._id && member.user._id.toString() == user._id.toString()) {
            role = member.role;
          }
        }
      });
      return role;
    };

    GroupsSchema.methods.checkRights = function (user, callback) {
      var thisGroup = this;
      if (!user) {
        callback(null, 'visitor');//non authorized user is visitor
        return;
      }

      if (user.root) {
        callback(null, 'admin'); //hierarchy admins are admins of every group
        return;
      }

      if (user.hasRole('hadmin')) {
        callback(null, 'admin'); //roots are admins are admins of every group
        return;
      }

      if (user.hasRole('helpdesk')) { //helpdesk is member of every group
        callback(null, 'member');
        return;
      }

      async.parallel({
        'inSchool': function (cb) {
          if (this.school_id) {
            Groups.findOne({'_id': this.school_id}, function (err, schoolFound) {
              cb(err, schoolFound.findRoleInThisGroup(user));
            });
          } else {
            cb(null);
          }
        },
        'inCourse': function (cb) {
          if (this.course_id) {
            Groups.findOne({'_id': this.course_id}, function (err, courseFound) {
              cb(err, courseFound.findRoleInThisGroup(user));
            });
          } else {
            cb(null);
          }
        },
        'inThisGroup': function (cb) {
          cb(null, thisGroup.findRoleInThisGroup(user));
        }
      }, function (err, roles) {
        //school
        if (thisGroup.tier === 1) {
          callback(err, roles.inThisGroup);
        }

        //for course // association
        //if user is admin of school, he is admin of every course of school
        if (thisGroup.tier === 2) {
          if (roles.inSchool === 'admin' || roles.inThisGroup === 'admin') {
            callback(err, 'admin');
          } else {
            callback(err, roles.inThisGroup);
          }
        }

        //for students group
        //if user is admin of school/course, he is admin of every in course group
        if (thisGroup.tier === 3) {
          if (roles.inSchool === 'admin' || roles.inCourse === 'admin' || roles.inThisGroup === 'admin') {
            callback(err, 'admin');
          } else {
            callback(err, roles.inThisGroup);
          }
        }
      });
    };

    GroupsSchema.methods.invite = function (user, role, callback) {
      var userIsNotMember = true;
      this.members.map(function (member) {
        if (member.user.toString() === user._id.toString()) { //we do not populate users here, so it works like it...
          userIsNotMember = false;
        }
      });
      if (userIsNotMember) {
        this.members.push({
          'user': user._id,
          'role': role
        });
        this.save(callback);
      } else {
        callback(new Error('User is already in this group!'));
      }
    };

    GroupsSchema.methods.ban = function (user, callback) {
      for (var i = 0; i < this.members.length; i++) {
        if (member.user.toString() === user._id.toString()) {//we do not populate users here, so it works like it...
          this.members.splice(i, 1);
          break;
        }
      }
      this.save(callback);
    };

    GroupsSchema.methods.inviteAdmin = function (usernameOrEmailOrUserObject, callback) {
      this.invite(usernameOrEmailOrUserObject, 'admin', callback);
    };

    GroupsSchema.methods.inviteMember = function (usernameOrEmailOrUserObject, callback) {
      this.invite(usernameOrEmailOrUserObject, 'member', callback);
    };

    GroupsSchema.methods.getParent = function (callback) {
      switch (this.tier) {
        case 2:
          Groups.findOne({'_id': this.school_id, tier: 1}, callback);
          break;
        case 3:
          Groups.findOne({'_id': this.course_id, tier: 2}, callback);
          break;
        default:
          callback(null, null);
      }
    };

    GroupsSchema.methods.getChildren = function (callback) {
      switch (this.tier) {
        case 1:
          Groups.find({'school_id': this._id, tier: 2}, callback);
          break;
        case 2:
          Groups.find({'course_id': this._id, tier: 3}, callback);
          break;
        default:
          callback(null, null);
      }
    };

    //get recent messages in this group
    GroupsSchema.methods.getMessages = function (limit, offset, callback) {
      if (!parseInt(offset) > 0) {
        offset = 0;
      }
      if (!parseInt(limit) > 0) {
        limit = 20;
      }

      kabam.model.groupMessages.find({'groupId': this._id})
        .populate('user')
        .limit(limit)
        .skip(offset)
        .sort('createdAt')
        .exec(callback);
    };

    //get blog entries suitable for this particular user
    GroupsSchema.methods.getBlog = function (role, callback) {
      kabam.model.groupBlogs
        .find({'groupId':this._id})
        .sort('createdAt')
        .exec(function(err,blogs){
          if(err) {
            callback(err);
          } else {
            var blogProcessed = blogs.map(function(blog){
              if(role === 'admin' || role === 'member'){
                return {
                  'title':blog.title,
                  'description':blog.description,
                  'contentPublic':blog.contentPublic,
                  'contentForMembers':blog.contentForMembers,
                  'createdAt':blog.createdAt
                };
              } else {
                return {
                  'title':blog.title,
                  'description':blog.description,
                  'contentPublic':blog.contentPublic,
                  'createdAt':blog.createdAt
                };
              }
            });
            callback(null,blogProcessed);
          }
        });
    };

    //export group as JSON object that can be viewed by this particular user
    GroupsSchema.methods.export = function (user, callback) {
      var thisGroup = this;

      thisGroup.checkRights(user, function (err, role) {
        if (err) {
          callback(err);
        } else {
          async.parallel(
            {
              'name': function (cb) {
                cb(null, thisGroup.name);
              },
              '_id': function (cb) {
                cb(null, thisGroup._id);
              },
              'parent': function (cb) {
                thisGroup.getParent(cb);
              },
              'uri': function (cb) {
                cb(null, thisGroup.uri);
              },
              'blog': function (cb) {
                thisGroup.getBlog(role,cb);
              },
              'members': function (cb) {
                cb(null, thisGroup.members);
              },
              'children': function (cb) {
                thisGroup.getChildren(cb);
              },
              'parentUri': function (cb) {
                cb(null, thisGroup.parentUri);
              },
              'childrenUri': function (cb) {
                cb(null, thisGroup.childrenUri);
              },
              'messages': function (cb) {
                if (role === 'admin' || role === 'member') {
                  thisGroup.getMessages(30, 0, cb);
                } else {
                  cb(null, null);
                }
              },
              'isAdmin': function (cb) {
                cb(null, (role === 'admin'));
              },
              'isMember': function (cb) {
                cb(null, (role === 'member' || role === 'admin'));
              },
              'isOpenToAll': function (cb) {
                cb(null, thisGroup.isOpenToAll);
              },
              'homepage': function (cb) {
                switch (role) {
                  case 'admin':
                    cb(null, {
                      'role': 'administrator',
                      'descriptionPublic': thisGroup.descriptionPublic,
                      'descriptionForMembers': thisGroup.descriptionForMembers
                    });
                    break;
                  case 'member':
                    cb(null, {
                      'role': 'member',
                      'descriptionPublic': thisGroup.descriptionPublic,
                      'descriptionForMembers': thisGroup.descriptionForMembers
                    });
                    break;

                  default: //visitor.. or something other
                    cb(null, {
                      'role': 'visitor',
                      'descriptionPublic': thisGroup.descriptionPublic
                    });
                }
              }
            }, callback);
        }
      });
    };

    GroupsSchema.statics.findGroup = function (schoolUri, courseUri, groupUri, callback) {
      var groups = this;

      if (schoolUri && !courseUri && !groupUri && typeof callback === 'function') {
        //we try to find school by school uri
        groups
          .findOne({'uri': schoolUri, 'tier': 1})
          .populate('members.user')
          .exec(function (err, schoolFound) {
            if (err) {
              callback(err);
            } else {
              if (schoolFound) {
                schoolFound.parentUri = null;
                schoolFound.childrenUri = '/h/' + schoolFound.uri;
                callback(null, schoolFound);
              } else {
                callback(null, null);
              }
            }
          });
        return;
      }

      if (schoolUri && courseUri && !groupUri && typeof callback === 'function') {
        async.waterfall(
          [
            function (cb) {
              groups.findOne({'uri': schoolUri, 'tier': 1})
                .populate('members.user')
                .exec(function (err, schoolFound) {
                  cb(err, schoolFound);
                });
            },
            function (school, cb) {
              if (school && school._id) {//school found
                groups.findOne({'uri': courseUri, 'tier': 2, 'school_id': school._id})
                  .populate('members.user')
                  .exec(function (err, courseFound) {
                    cb(err, school, courseFound);
                  });
              } else {
                cb(null, null, null)
              }

            },
            function (school, course, cb) {
              if (course) {
                course.school = school;
                course.parentUri = '/h/' + school.uri;
                course.childrenUri = '/h/' + school.uri + '/' + course.uri;
                cb(null, course);
              } else {
                cb(null, null);
              }
            }
          ], callback);
        return;
      }

      if (schoolUri && courseUri && groupUri && typeof callback === 'function') {
        async.waterfall(
          [
            function (cb) {
              groups.findOne({'uri': schoolUri, 'tier': 1})
                .populate('members.user')
                .exec(function (err, schoolFound) {
                  cb(err, schoolFound);
                });
            },
            function (school, cb) {
              if (school && school._id) {//school found
                groups.findOne({'uri': courseUri, 'tier': 2, 'school_id': school._id})
                  .populate('members.user')
                  .exec(function (err, courseFound) {
                    cb(err, school, courseFound);
                  });
              } else {
                cb(null, null, null)
              }
            },
            function (school, course, cb) {
              if (school && course && school._id && course._id) {
                groups.findOne({'uri': groupUri, 'tier': 3, 'school_id': school._id, 'course_id': course._id})
                  .populate('members.user')
                  .exec(function (err, groupFound) {
                    cb(err, school, course, groupFound);
                  });
              } else {
                cb(null, null, null, null);
              }
            },
            function (school, course, group, cb) {
              if (group) {
                group.school = school;
                group.course = course;
                group.parentUri = '/h/' + school.uri + '/' + course.uri;
                group.childrenUri = null;
                cb(null, group);
              } else {
                cb(null, null);
              }
            }
          ], callback);
        return;
      }
    };

    var Groups = kabam.mongoConnection.model('groups', GroupsSchema);
    return Groups;
  }};
<commit_msg>[feature] - placeholder for creating blog entries<commit_after>var slugify = require('slugify2'),
  async = require('async');

exports = module.exports = {
  'groupBlogs': function (kabam) {
    var GroupBlogsSchema = new kabam.mongoose.Schema({
      'groupId': kabam.mongoose.Schema.Types.ObjectId,
      'title': String,
      'description': String,
      'keywords': String,
      'contentPublic': String,
      'contentForMembers': String,
      'createdAt': {type: Date, default: new Date()}
    });
    GroupBlogsSchema.index({ groupId: 1, createdAt: 1});
    return kabam.mongoConnection.model('groupBlogs', GroupBlogsSchema);
  },
  'groupMessages': function (kabam) {
    var GroupMessagesSchema = new kabam.mongoose.Schema({
      'groupId': kabam.mongoose.Schema.Types.ObjectId,
      'userId': kabam.mongoose.Schema.Types.ObjectId,
      'message': String,
      'user': { type: kabam.mongoose.Schema.Types.ObjectId, ref: 'User' },
      'createdAt': {type: Date, default: new Date()}
    });

    GroupMessagesSchema.index({ groupId: 1, createdAt: 1});
    return kabam.mongoConnection.model('groupMessages', GroupMessagesSchema);
  },
  'groups': function (kabam) {
    var GroupsSchema = new kabam.mongoose.Schema({
        'name': {
          type: String,
          trim: true,
          index: true
        },
        'uri': {
          type: String,
          trim: true,
          index: true
        },
        //0 - world, 1 - school, 2 - course/association, 3 - group
        'tier': {type: Number, min: 0, max: 3},

        'school_id': kabam.mongoose.Schema.Types.ObjectId,

        'course_id': kabam.mongoose.Schema.Types.ObjectId,

        'descriptionPublic': String,
        'descriptionForMembers': String,

        'members': [
          {
            'user': { type: kabam.mongoose.Schema.Types.ObjectId, ref: 'User' },
            'role': String
          }
        ],

        'isOpenToAll': {type: Boolean, default: false},
        'isOpenToParent': {type: Boolean, default: false} //maybe we do not need it?
      },
      {
        toObject: { getters: true, virtuals: true }, //http://mongoosejs.com/docs/api.html#document_Document-toObject
        toJSON: { getters: true, virtuals: true }
      }
    );

    GroupsSchema.index({ name: 1, uri: 1, school_id: 1, course_id: 1 });

    GroupsSchema.methods.findRoleInThisGroup = function (user) {
      var role = 'visitor';
      this.members.map(function (member) {
        if (member.user.toString() == user._id.toString()) {
          role = member.role;
        } else {
          if (member.user._id && member.user._id.toString() == user._id.toString()) {
            role = member.role;
          }
        }
      });
      return role;
    };

    GroupsSchema.methods.checkRights = function (user, callback) {
      var thisGroup = this;
      if (!user) {
        callback(null, 'visitor');//non authorized user is visitor
        return;
      }

      if (user.root) {
        callback(null, 'admin'); //hierarchy admins are admins of every group
        return;
      }

      if (user.hasRole('hadmin')) {
        callback(null, 'admin'); //roots are admins are admins of every group
        return;
      }

      if (user.hasRole('helpdesk')) { //helpdesk is member of every group
        callback(null, 'member');
        return;
      }

      async.parallel({
        'inSchool': function (cb) {
          if (this.school_id) {
            Groups.findOne({'_id': this.school_id}, function (err, schoolFound) {
              cb(err, schoolFound.findRoleInThisGroup(user));
            });
          } else {
            cb(null);
          }
        },
        'inCourse': function (cb) {
          if (this.course_id) {
            Groups.findOne({'_id': this.course_id}, function (err, courseFound) {
              cb(err, courseFound.findRoleInThisGroup(user));
            });
          } else {
            cb(null);
          }
        },
        'inThisGroup': function (cb) {
          cb(null, thisGroup.findRoleInThisGroup(user));
        }
      }, function (err, roles) {
        //school
        if (thisGroup.tier === 1) {
          callback(err, roles.inThisGroup);
        }

        //for course // association
        //if user is admin of school, he is admin of every course of school
        if (thisGroup.tier === 2) {
          if (roles.inSchool === 'admin' || roles.inThisGroup === 'admin') {
            callback(err, 'admin');
          } else {
            callback(err, roles.inThisGroup);
          }
        }

        //for students group
        //if user is admin of school/course, he is admin of every in course group
        if (thisGroup.tier === 3) {
          if (roles.inSchool === 'admin' || roles.inCourse === 'admin' || roles.inThisGroup === 'admin') {
            callback(err, 'admin');
          } else {
            callback(err, roles.inThisGroup);
          }
        }
      });
    };

    GroupsSchema.methods.invite = function (user, role, callback) {
      var userIsNotMember = true;
      this.members.map(function (member) {
        if (member.user.toString() === user._id.toString()) { //we do not populate users here, so it works like it...
          userIsNotMember = false;
        }
      });
      if (userIsNotMember) {
        this.members.push({
          'user': user._id,
          'role': role
        });
        this.save(callback);
      } else {
        callback(new Error('User is already in this group!'));
      }
    };

    GroupsSchema.methods.ban = function (user, callback) {
      for (var i = 0; i < this.members.length; i++) {
        if (member.user.toString() === user._id.toString()) {//we do not populate users here, so it works like it...
          this.members.splice(i, 1);
          break;
        }
      }
      this.save(callback);
    };

    GroupsSchema.methods.inviteAdmin = function (usernameOrEmailOrUserObject, callback) {
      this.invite(usernameOrEmailOrUserObject, 'admin', callback);
    };

    GroupsSchema.methods.inviteMember = function (usernameOrEmailOrUserObject, callback) {
      this.invite(usernameOrEmailOrUserObject, 'member', callback);
    };

    GroupsSchema.methods.getParent = function (callback) {
      switch (this.tier) {
        case 2:
          Groups.findOne({'_id': this.school_id, tier: 1}, callback);
          break;
        case 3:
          Groups.findOne({'_id': this.course_id, tier: 2}, callback);
          break;
        default:
          callback(null, null);
      }
    };

    GroupsSchema.methods.getChildren = function (callback) {
      switch (this.tier) {
        case 1:
          Groups.find({'school_id': this._id, tier: 2}, callback);
          break;
        case 2:
          Groups.find({'course_id': this._id, tier: 3}, callback);
          break;
        default:
          callback(null, null);
      }
    };

    //get recent messages in this group
    GroupsSchema.methods.getMessages = function (limit, offset, callback) {
      if (!parseInt(offset) > 0) {
        offset = 0;
      }
      if (!parseInt(limit) > 0) {
        limit = 20;
      }

      kabam.model.groupMessages.find({'groupId': this._id})
        .populate('user')
        .limit(limit)
        .skip(offset)
        .sort('createdAt')
        .exec(callback);
    };

    //post blog entry
    GroupsSchema.methods.createBlogEntry = function(user,blogEntry,callback){
      this.checkRights(user,function(err,role){
        if(role === 'admin'){ //only admin can create new blog entries
          kabam.model.groupBlogs.create({
            'title':blogEntry.title,
            'description':blogEntry.description,
            'contentPublic':blogEntry.contentPublic,
            'contentForMembers':blogEntry.contentForMembers
          },callback);
        } else {
          callback(new Error('You are not admin of this group!'));
        }
      });
    }

    GroupsSchema.methods.updateBlogEntry = function(user,blogEntryId,blogEntry,callback){

    }
    GroupsSchema.methods.deleteBlogEntry = function(user,blogEntryId,callback){}

    //get blog entries suitable for this particular user
    GroupsSchema.methods.getBlog = function (role, callback) {
      kabam.model.groupBlogs
        .find({'groupId':this._id})
        .sort('createdAt')
        .exec(function(err,blogs){
          if(err) {
            callback(err);
          } else {
            var blogProcessed = blogs.map(function(blog){
              if(role === 'admin' || role === 'member'){
                return {
                  'title':blog.title,
                  'description':blog.description,
                  'contentPublic':blog.contentPublic,
                  'contentForMembers':blog.contentForMembers,
                  'createdAt':blog.createdAt
                };
              } else {
                return {
                  'title':blog.title,
                  'description':blog.description,
                  'contentPublic':blog.contentPublic,
                  'createdAt':blog.createdAt
                };
              }
            });
            callback(null,blogProcessed);
          }
        });
    };

    //export group as JSON object that can be viewed by this particular user
    GroupsSchema.methods.export = function (user, callback) {
      var thisGroup = this;

      thisGroup.checkRights(user, function (err, role) {
        if (err) {
          callback(err);
        } else {
          async.parallel(
            {
              'name': function (cb) {
                cb(null, thisGroup.name);
              },
              '_id': function (cb) {
                cb(null, thisGroup._id);
              },
              'parent': function (cb) {
                thisGroup.getParent(cb);
              },
              'uri': function (cb) {
                cb(null, thisGroup.uri);
              },
              'blog': function (cb) {
                thisGroup.getBlog(role,cb);
              },
              'members': function (cb) {
                cb(null, thisGroup.members);
              },
              'children': function (cb) {
                thisGroup.getChildren(cb);
              },
              'parentUri': function (cb) {
                cb(null, thisGroup.parentUri);
              },
              'childrenUri': function (cb) {
                cb(null, thisGroup.childrenUri);
              },
              'messages': function (cb) {
                if (role === 'admin' || role === 'member') {
                  thisGroup.getMessages(30, 0, cb);
                } else {
                  cb(null, null);
                }
              },
              'isAdmin': function (cb) {
                cb(null, (role === 'admin'));
              },
              'isMember': function (cb) {
                cb(null, (role === 'member' || role === 'admin'));
              },
              'isOpenToAll': function (cb) {
                cb(null, thisGroup.isOpenToAll);
              },
              'homepage': function (cb) {
                switch (role) {
                  case 'admin':
                    cb(null, {
                      'role': 'administrator',
                      'descriptionPublic': thisGroup.descriptionPublic,
                      'descriptionForMembers': thisGroup.descriptionForMembers
                    });
                    break;
                  case 'member':
                    cb(null, {
                      'role': 'member',
                      'descriptionPublic': thisGroup.descriptionPublic,
                      'descriptionForMembers': thisGroup.descriptionForMembers
                    });
                    break;

                  default: //visitor.. or something other
                    cb(null, {
                      'role': 'visitor',
                      'descriptionPublic': thisGroup.descriptionPublic
                    });
                }
              }
            }, callback);
        }
      });
    };

    GroupsSchema.statics.findGroup = function (schoolUri, courseUri, groupUri, callback) {
      var groups = this;

      if (schoolUri && !courseUri && !groupUri && typeof callback === 'function') {
        //we try to find school by school uri
        groups
          .findOne({'uri': schoolUri, 'tier': 1})
          .populate('members.user')
          .exec(function (err, schoolFound) {
            if (err) {
              callback(err);
            } else {
              if (schoolFound) {
                schoolFound.parentUri = null;
                schoolFound.childrenUri = '/h/' + schoolFound.uri;
                callback(null, schoolFound);
              } else {
                callback(null, null);
              }
            }
          });
        return;
      }

      if (schoolUri && courseUri && !groupUri && typeof callback === 'function') {
        async.waterfall(
          [
            function (cb) {
              groups.findOne({'uri': schoolUri, 'tier': 1})
                .populate('members.user')
                .exec(function (err, schoolFound) {
                  cb(err, schoolFound);
                });
            },
            function (school, cb) {
              if (school && school._id) {//school found
                groups.findOne({'uri': courseUri, 'tier': 2, 'school_id': school._id})
                  .populate('members.user')
                  .exec(function (err, courseFound) {
                    cb(err, school, courseFound);
                  });
              } else {
                cb(null, null, null)
              }

            },
            function (school, course, cb) {
              if (course) {
                course.school = school;
                course.parentUri = '/h/' + school.uri;
                course.childrenUri = '/h/' + school.uri + '/' + course.uri;
                cb(null, course);
              } else {
                cb(null, null);
              }
            }
          ], callback);
        return;
      }

      if (schoolUri && courseUri && groupUri && typeof callback === 'function') {
        async.waterfall(
          [
            function (cb) {
              groups.findOne({'uri': schoolUri, 'tier': 1})
                .populate('members.user')
                .exec(function (err, schoolFound) {
                  cb(err, schoolFound);
                });
            },
            function (school, cb) {
              if (school && school._id) {//school found
                groups.findOne({'uri': courseUri, 'tier': 2, 'school_id': school._id})
                  .populate('members.user')
                  .exec(function (err, courseFound) {
                    cb(err, school, courseFound);
                  });
              } else {
                cb(null, null, null)
              }
            },
            function (school, course, cb) {
              if (school && course && school._id && course._id) {
                groups.findOne({'uri': groupUri, 'tier': 3, 'school_id': school._id, 'course_id': course._id})
                  .populate('members.user')
                  .exec(function (err, groupFound) {
                    cb(err, school, course, groupFound);
                  });
              } else {
                cb(null, null, null, null);
              }
            },
            function (school, course, group, cb) {
              if (group) {
                group.school = school;
                group.course = course;
                group.parentUri = '/h/' + school.uri + '/' + course.uri;
                group.childrenUri = null;
                cb(null, group);
              } else {
                cb(null, null);
              }
            }
          ], callback);
        return;
      }
    };

    var Groups = kabam.mongoConnection.model('groups', GroupsSchema);
    return Groups;
  }};
<|endoftext|>


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

angular.module('app')
    .factory('http', function ($http, $q, $cookieStore, $rootScope) {

        var customHeaders = {};
        var http = {};

        if ($cookieStore.get('token') === '' || angular.isUndefined($cookieStore.get('token')))
            customHeaders = {
                'Accept': 'application/json',
                'Content-type': 'application/json'
            };
        else {
            customHeaders = {
                'Accept': 'application/json',
                'Content-type': 'application/json',
                'Authorization': 'Bearer ' + $cookieStore.get('token')
            };
        }

        http.get = function (url) {
            //console.log(customHeaders);

            if (url.indexOf("/scripts/") > -1 || url.indexOf("/version/") > -1) {
                customHeaders['Accept'] = 'text/plain';
                customHeaders['Content-type'] = 'text/plain';

            } else {
                customHeaders['Accept'] = 'application/json';
                customHeaders['Content-type'] = 'application/json';

            }

            customHeaders['project-id'] = $cookieStore.get('project').id;
            //console.log(customHeaders);
            //console.log($cookieStore.get('project'));

            return $http({
                url: url,
                method: 'GET',
                headers: customHeaders
            })
        };

        http.getRC = function (url) {
            //console.log(customHeaders);

            customHeaders['Accept'] = 'application/octet-stream';
            customHeaders['Content-type'] = 'application/octet-stream';

            customHeaders['project-id'] = $cookieStore.get('project').id;
            //console.log(customHeaders);
            //console.log($cookieStore.get('project'));

            return $http({
                url: url,
                method: 'GET',
                headers: customHeaders
            })
        };

        http.getPlain = function (url) {
            //console.log(customHeaders);

            customHeaders['Accept'] = 'application/json';
            customHeaders['Content-type'] = 'application/json';

            //customHeaders['project-id'] = $cookieStore.get('project').id;
            //console.log(customHeaders);
            //console.log($cookieStore.get('project'));

            return $http({
                url: url,
                method: 'GET',
                //headers: customHeaders
            })
        };

        http.post = function (url, data) {
            customHeaders['Accept'] = 'application/json';
            customHeaders['Content-type'] = 'application/json';
            customHeaders['project-id'] = $cookieStore.get('project').id;
            //console.log(data);
            $('#modalSend').modal('show');
            return $http({
                url: url,
                method: 'POST',
                data: data,
                headers: customHeaders
            });

        };
        http.postPlain = function (url, data) {
            customHeaders['project-id'] = $cookieStore.get('project').id;
            customHeaders['Accept'] = 'text/plain';
            customHeaders['Content-type'] = 'text/plain';
            //console.log(data);
            $('#modalSend').modal('show');
            return $http({
                url: url,
                method: 'POST',
                data: data,
                headers: customHeaders
            });

        };
        http.postLog = function (url) {
            customHeaders['project-id'] = $cookieStore.get('project').id;
            $('#modalSend').modal('show');
            //console.log(url);
            return $.ajax({
                url: url,
                type: 'post',
                headers: customHeaders,
                dataType: 'json'
            });

        };
        http.postXML = function (url, data) {
            $('#modalSend').modal('show');
            return $http({
                url: url,
                dataType: 'xml',
                method: 'POST',
                data: data,
                headers: {
                    "Content-Type": "application/xml"
                }

            });
        };
        http.put = function (url, data) {
            customHeaders['project-id'] = $cookieStore.get('project').id;
            $('#modalSend').modal('show');
            if (url.indexOf("/scripts/") > -1) {
                customHeaders['Content-type'] = 'text/plain';
                customHeaders['Accept'] = 'text/plain';
            } else {
                customHeaders['Accept'] = 'application/json';
                customHeaders['Content-type'] = 'application/json';
            }

            return $http({
                url: url,
                method: 'PUT',
                data: data,
                headers: customHeaders
            });
        };

        http.delete = function (url) {
            customHeaders['project-id'] = $cookieStore.get('project').id;
            //console.log(customHeaders);
            $('#modalSend').modal('show');
            return $http({
                url: url,
                method: 'DELETE',
                headers: customHeaders
            });
        };

        http.syncGet = function (url) {
            var deferred = $q.defer();
            http.get(url).success(function (data, status) {
                deferred.resolve(data);
            });
            return deferred.promise;
        };

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

angular.module('app')
    .factory('http', function ($http, $q, $cookieStore, $rootScope) {

        var customHeaders = {};
        var http = {};

        if ($cookieStore.get('token') === '' || angular.isUndefined($cookieStore.get('token')))
            customHeaders = {
                'Accept': 'application/json',
                'Content-type': 'application/json'
            };
        else {
            customHeaders = {
                'Accept': 'application/json',
                'Content-type': 'application/json',
                'Authorization': 'Bearer ' + $cookieStore.get('token')
            };
        }

        http.get = function (url) {
            //console.log(customHeaders);

            if (url.indexOf("/scripts/") > -1 || url.indexOf("/version/") > -1) {
                customHeaders['Accept'] = 'text/plain';
                customHeaders['Content-type'] = 'text/plain';

            } else {
                customHeaders['Accept'] = 'application/json';
                customHeaders['Content-type'] = 'application/json';

            }

            customHeaders['project-id'] = $cookieStore.get('project').id;
            //console.log(customHeaders);
            //console.log($cookieStore.get('project'));

            return $http({
                url: url,
                method: 'GET',
                headers: customHeaders
            })
        };

        http.getRC = function (url) {
            //console.log(customHeaders);

            customHeaders['Accept'] = 'application/octet-stream';
            customHeaders['Content-type'] = 'application/octet-stream';

            customHeaders['project-id'] = $cookieStore.get('project').id;
            //console.log(customHeaders);
            //console.log($cookieStore.get('project'));

            return $http({
                url: url,
                method: 'GET',
                headers: customHeaders
            })
        };

        http.getPlain = function (url) {
            //console.log(customHeaders);

            customHeaders['Accept'] = 'application/json';
            customHeaders['Content-type'] = 'application/json';

            //customHeaders['project-id'] = $cookieStore.get('project').id;
            //console.log(customHeaders);
            //console.log($cookieStore.get('project'));

            return $http({
                url: url,
                method: 'GET',
                //headers: customHeaders
            })
        };

        http.post = function (url, data) {
            customHeaders['Accept'] = 'application/json';
            customHeaders['Content-type'] = 'application/json';
            customHeaders['project-id'] = $cookieStore.get('project').id;
            //console.log(data);
            $('#modalSend').modal('show');
            return $http({
                url: url,
                method: 'POST',
                data: data,
                headers: customHeaders
            });

        };
        http.postPlain = function (url, data) {
            customHeaders['project-id'] = $cookieStore.get('project').id;
            customHeaders['Accept'] = 'text/plain';
            customHeaders['Content-type'] = 'text/plain';
            //console.log(data);
            $('#modalSend').modal('show');
            return $http({
                url: url,
                method: 'POST',
                data: data,
                headers: customHeaders
            });

        };
        http.postLog = function (url) {
            customHeaders['project-id'] = $cookieStore.get('project').id;
            $('#modalSend').modal('show');
            //console.log(url);
            return $.ajax({
                url: url,
                type: 'post',
                headers: customHeaders,
                dataType: 'json'
            });

        };
        http.postXML = function (url, data) {
            $('#modalSend').modal('show');
            return $http({
                url: url,
                dataType: 'xml',
                method: 'POST',
                data: data,
                headers: {
                    "Content-Type": "application/xml"
                }

            });
        };
        http.put = function (url, data) {
            customHeaders['project-id'] = $cookieStore.get('project').id;
            $('#modalSend').modal('show');
            if (url.indexOf("/scripts/") > -1) {
                customHeaders['Content-type'] = 'text/plain';
                customHeaders['Accept'] = 'text/plain';
            } else {
                customHeaders['Accept'] = 'application/json';
                customHeaders['Content-type'] = 'application/json';
            }

            return $http({
                url: url,
                method: 'PUT',
                data: data,
                headers: customHeaders
            });
        };

        http.delete = function (url) {
            customHeaders['project-id'] = $cookieStore.get('project').id;
            customHeaders['Content-type'] = 'application/json';
            customHeaders['Accept'] = 'application/json';
            //console.log(customHeaders);
            $('#modalSend').modal('show');
            return $http({
                url: url,
                method: 'DELETE',
                headers: customHeaders
            });
        };

        http.syncGet = function (url) {
            var deferred = $q.defer();
            http.get(url).success(function (data, status) {
                deferred.resolve(data);
            });
            return deferred.promise;
        };

        return http;
    })
;
<|endoftext|>