Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- angular.module('priooo')
- .service('Api', ['$http', 'appConstants', 'Misc', 'Session', 'Debug', function($http, appConstants, Misc, Session, Debug) {
- var absolutePath = Misc.getServerPath();
- absolutePath += "rest-public/";
- var etags = {};
- var allowed = {};
- function buildURI(uri, addTeamId) {
- var path = absolutePath;
- var authObj = Session.get('authObj');
- var api = false;
- if(uri.indexOf('api/') > -1){
- api = true;
- path = path.replace("rest-public/", "api/");
- uri = uri.slice(4, uri.length)
- }
- if(!authObj) return path + uri;
- if(addTeamId === true && !api && authObj.team.id > 0 && !uri.startsWith("users/") && !uri.startsWith("tasks/") && !uri.startsWith("backlogitems/") && !uri.startsWith("comments/")) {
- if(uri.indexOf("?") > -1) {
- var uri_parts = uri.split("?");
- uri_parts[0] += "/" + authObj.team.id;
- uri = uri_parts.join("?");
- }
- else {
- uri += "/" + authObj.team.id;
- }
- }
- if(uri.indexOf("?") < 0)
- return path + uri + "?token=" + authObj.AccessToken;
- else
- return path + uri + "&token=" + authObj.AccessToken;
- }
- $http.defaults.headers.post["Content-Type"] = "application/json";
- $http.defaults.timeout = 5000;
- this.Get = function (uri, callback, error, skipEtag) {
- var skipEtag = (skipEtag===true);
- /*if(etags.hasOwnProperty(uri)) {
- $http.defaults.headers.common['If-None-Match'] = etags[uri]; //Set previously cached ETag
- }*/
- return $http.get(buildURI(uri, true), (etags.hasOwnProperty(uri) && !skipEtag) ? { headers: {'If-None-Match': etags[uri]} } : {}).then(function(response) {
- console.log('uri: ', uri);
- console.log('response: ', response);
- if(callback && typeof callback === 'function') {
- if(response.headers("etag")) {
- etags[uri] = response.headers("etag");
- }
- if(response.headers("allow")) {
- allowed[uri] = response.headers("allow");
- }
- callback(response.data);
- }
- }, function(response){ errorException(response, error); });
- };
- this.Post = function () { // uri, object, callback, error || uri, object, headers, callback, error
- var args = Array.prototype.slice.call(arguments);
- var uri = args.shift();
- var object = JSON.stringify(args.shift() || {});
- var headers = {};
- if(args.length == 3) {
- headers = args.shift();
- }
- var callback = args.shift();
- var error = args.shift();
- return $http.post(buildURI(uri), object, {
- headers: headers,
- transformRequest: angular.identity,
- }).then(function(response){
- if(callback && typeof callback === 'function') {
- etags[uri] = response.headers("etag");
- callback(response.data);
- }
- }, function(response){ errorException(response, error); });
- };
- this.Put = function (uri, object, callback, error) {
- if(object == null) object = {};
- return $http.put(buildURI(uri), JSON.stringify(object)).then(function(response){
- if(callback && typeof callback === 'function') {
- etags[uri] = response.headers("etag");
- callback(response.data);
- }
- }, function(response){ errorException(response, error); });
- };
- this.Delete = function (uri, callback, error) {
- return $http({url:buildURI(uri), method: "delete" }).then(function(response){
- if(callback && typeof callback === 'function') {
- etags[uri] = response.headers("etag");
- callback(response.data);
- }
- }, function(response){ errorException(response, error); });
- };
- var errorException = function (response, callback) {
- if(response.status != 304) {
- var status = (response.status > 0) ? " " + response.status + " error" : "n unknown error";
- if(response.status == 404 || response.status == 500) {
- var config = response.config;
- var debug = " url["+config.url+"] method["+config.method+"]";
- if(config.data && config.data != "") debug += " data["+config.data+"]";
- Debug.warn("A" + status + " occurred, please notify a system administrator!" + '\n' + debug);
- }
- else{
- Debug.info("A" + status + " occured.", response);
- }
- if(callback && typeof callback === 'function') {
- callback(response.data, response.status, response.statusText);
- }
- }
- };
- //Getters
- this.errorException = errorException;
- this.absolutePath = absolutePath;
- this.etags = etags;
- this.flushCache = function() {
- etags = {};
- allowed = {};
- };
- this.getAllowed = function(path) {
- if(path == undefined)
- return allowed;
- else
- return allowed[path] || false;
- };
- }]).service('Poller', ['Api', 'appConstants', 'Debug','$timeout', '$rootScope', function(Api, appConstants, Debug, $timeout, $rootScope) {
- var data = {};
- this.createPollerObject = function(uri, callback) {
- this.uri = uri;
- this.waiting = true;
- this.pollerInterval = appConstants["poller.interval"];
- this.fired = 0;
- this.errorList = [];
- this.addError = function() {
- this.errorList.push({
- time: (new Date()).getTime(),
- fired: this.fired
- });
- if(this.errorList.length > 10)
- this.errorList.shift();
- };
- this.getLastError = function() {
- return this.errorList[this.errorList.length-1];
- };
- this.ai = {
- list: [],
- avg: 0,
- push: function(obj) {
- this.list.push(obj);
- if(this.list.length == 5) {
- var tmp = 0;
- for (var i = this.list.length - 1; i >= 0; i--) {
- tmp += this.list[i];
- }
- this.avg = Math.round((tmp / this.list.length) / 100 ) * 100;
- this.list = [];
- return this.avg;
- }
- }
- };
- this.started = function() {return (this.poller) ? true : false;};
- this.stop = function() {
- if(!this.started()) return;
- this.ai.list = [];
- this.ai.avg = 0;
- if(this.waiting)
- clearTimeout(this.poller);
- else
- clearInterval(this.poller);
- this.waiting = true;
- delete this.poller;
- };
- this.fn = function(runOnce) {
- var runOnce = !!runOnce;
- var poller = data[uri];
- Api.Get(uri, callback, function() {
- poller.addError();
- var e = 0;
- for(x in poller.errorList) {
- var y = poller.errorList[x];
- if(poller.fired == y.fired || poller.fired-1 == y.fired || poller.fired-2 == y.fired)
- e++;
- }
- Debug.info("Encountered unhandeled exception, poller["+uri+"] eventId["+poller.fired+"] retries["+e+"]");
- if(e < 3) return;
- Debug.warn("Max retries reached. Stopping poller ["+uri+"]", poller);
- runOnce = true;
- data[uri].stop();
- }).then(function() {
- $rootScope.$broadcast('poller-ran');
- if(runOnce) return;
- poller.fired++;
- var p = data[uri];
- if(p && p.waiting)
- p.start();
- });
- };
- this.run = function() {
- this.fn(true);
- };
- this.start = function() {
- if(this.started() && !this.waiting) return;
- if(this.waiting) {
- var now = new Date().getTime();
- if(this.lastPolled) {
- var timeBetweenLastPolledAndNow = now - this.lastPolled;
- var interval = this.ai.push(timeBetweenLastPolledAndNow);
- if(interval > 0 && interval > this.pollerInterval) {
- this.setInterval(interval, false);
- this.waitForResponse(false);
- return;
- }
- }
- this.poller = setTimeout(this.fn, this.pollerInterval);
- this.lastPolled = now;
- }
- else
- this.poller = setInterval(this.fn, this.pollerInterval);
- };
- this.setInterval = function(interval, restart) {
- var restart = (!restart || restart === false) ? false : true;
- Debug.info("Interval for " + this.uri + " changed to [" + interval + "] restart ["+restart+"]");
- this.pollerInterval = interval;
- if(restart)
- this.restart();
- };
- this.waitForResponse = function(bool) {
- this.stop();
- delete this.lastPolled;
- this.waiting = !!bool;
- if(bool != this.waiting)
- Debug.info("waitForResponse for " + this.uri + " changed to: " + bool);
- this.start();
- };
- this.restart = function() {
- this.stop();
- this.start();
- };
- },
- this.changeInterval = function(uri, interval) {
- data[uri].waitForResponse(true);
- data[uri].setInterval(interval, false);
- },
- this.add = function (uri, callback, autoStart, interval) {
- var poller = new this.createPollerObject(uri, callback);
- data[uri] = poller;
- if(!!autoStart)
- poller.fn();
- if(interval && interval > 1500)
- poller.setInterval(interval);
- return poller;
- },
- this.remove = function (uri) {
- data[uri].stop();
- delete data[uri];
- },
- this.get = function (uri) {
- return data[uri];
- },
- this.getAll = function () {
- var list = [];
- for(uri in data) {
- list.push(uri);
- }
- return list;
- };
- this.waitFor = function(uri, callback){
- if(typeof uri === "string"){
- var poller = data[uri];
- Debug.log("Waiting for poller for uri ["+uri+"]");
- var retries = 5;
- check = function(){
- if(!poller.fired > 0 && retries > -1){
- retries--;
- Debug.log("Poller ["+uri+"]hasn't fired, retrying with ["+retries+"]");
- $timeout(check,500);
- }
- else if(poller.fired > 0){
- Debug.log("Poller ["+uri+"]has fired ["+poller.fired+"]");
- callback();
- }
- };
- check();
- }
- else if(Array.isArray(uri)){
- var isLoaded = [];
- for(x in uri){
- var poller = data[uri[x]];
- var retries = 5;
- check = function(){
- if(!poller.fired > 0 && retries > -1){
- retries--;
- Debug.log("Poller ["+uri[x]+"] hasn't fired, retrying with ["+retries+"]");
- $timeout(check,500);
- }
- else if(poller.fired > 0){
- Debug.log("Poller ["+uri[x]+"] has fired ["+poller.fired+"]");
- var obj = {};
- obj[poller] = true
- isLoaded.push(obj);
- }
- };
- check();
- }
- if(isLoaded.length == uri.length){
- callback();
- }
- };
- };
- }]).service('Notification', ['$rootScope', '$timeout', function($rootScope, $timeout) {
- Tinycon.setOptions({
- background: '#f03d25'
- });
- this.list = [];
- this.count = 0;
- this.add = function(icon, title, msg, fn) {
- var obj = {
- icon: icon,
- title: title,
- message: (msg) ? msg : false,
- fn: (fn) ? fn: false,
- time: new Date().getTime()
- };
- this.list.unshift(obj);
- obj.id = this.list.length;
- this.count++;
- Tinycon.setBubble(this.count);
- };
- this.get = function(id) {
- for (var i = 0; i < this.list.length; i++) {
- var notification = this.list[i];
- if(notification.id == id) {
- if(notification.fn) {
- $timeout(function(){
- notification.fn.apply(this, notification);
- }, 50);
- }
- return notification;
- }
- }
- return false;
- };
- this.resetCount = function() {
- Tinycon.setBubble(0);
- this.count = 0;
- };
- this.getCount = function() {
- return this.count;
- };
- this.getLatest = function(amount) {
- if(amount < 1) amount = 1;
- return this.list.slice(0, amount);
- };
- }]).service('Cookies', ['Debug','Misc', '$cookies', function(Debug, Misc, $cookies) {
- var date = new Date();
- date.setDate(date.getDate() + 7);
- this.options = {
- expires: date,
- path: '/'
- };
- this.get = function(key) {
- return $cookies.getObject(key);
- };
- this.set = function(key, value) {
- if(key == 'authObj'){ // Default time for login is 24h
- var d = new Date();
- d.setDate(d.getDate() + 1);
- $cookies.putObject(key, value, {
- expires: d,
- path: '/'
- });
- }
- else {
- $cookies.putObject(key, value, this.options);
- }
- };
- this.remove = function(key) {
- $cookies.remove(key, {path: '/'});
- };
- this.clear = function() {
- for(key in $cookies.getAll()) {
- if(!key.startsWith("_"))
- this.remove(key);
- }
- };
- }]).service('Session', ['Debug', function(Debug) {
- this.get = function(key) {
- //Debug.log(key, sessionStorage.getItem(key), sessionStorage.getItem(key) == null, sessionStorage.getItem(key) == "null");
- return JSON.parse(sessionStorage.getItem(key));
- };
- this.set = function(key, value) {
- sessionStorage.setItem(key, JSON.stringify(value));
- };
- this.remove = function(key) {
- sessionStorage.removeItem(key);
- };
- this.clear = function() {
- sessionStorage.clear();
- };
- }]).service('DateUtil', function() {
- this.nextMonth = function(date) {
- return new Date(date.getFullYear(), date.getMonth()+1, 0);
- };
- this.nextQuarter = function(date) {
- return new Date(date.getFullYear(), (Math.floor(date.getMonth() / 3)+1)*3, 0);
- };
- this.nextYear = function(date) {
- return new Date(date.getFullYear()+1, 0, 0);
- };
- this.getMonth = function(time) {
- var date = new Date(time);
- var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
- return months[date.getMonth()];
- };
- this.getQuarter = function(time) {
- var date = new Date(time);
- var Q = ["Q1", "Q2", "Q3", "Q4"];
- return Q[Math.floor(date.getMonth() / 3)];
- };
- this.format = function(t) {
- var time = new Date(t);
- return time.getDate() + "-" + (time.getMonth()+1) + "-" + time.getFullYear();
- };
- }).filter('ucfirst', function() {
- return function(s) {
- return (angular.isString(s) && s.length > 0) ? s[0].toUpperCase() + s.substr(1).toLowerCase() : s;
- };
- }).filter('tagString', function() {
- return function(tagList) {
- if(!tagList || tagList.length == 0) return;
- var returnStr = "";
- for(x in tagList) {
- returnStr += tagList[x].name + ", ";
- }
- if(returnStr.length > 0)
- return returnStr.substring(0, returnStr.length-2);
- else
- return "";
- };
- }).filter('tagFilter', function() {
- return function(backlogitems, $scope) {
- if(backlogitems.length < 1) return [];
- var filter = $scope.filteredTags;
- var returnList;
- returnList = [];
- for(x in backlogitems) {
- var pbi = backlogitems[x];
- var remove = 0;
- if(pbi.tags){
- for(y in pbi.tags) {
- if(filter.indexOf(pbi.tags[y].name) != -1) {
- remove++;
- };
- };
- };
- if(remove >= filter.length){
- returnList.push(pbi);
- };
- };
- return returnList;
- };
- })
- .filter("containsTag", function() {
- return function (tags, tag) {
- for(x in tags) {
- if(tag.name==tags[x].name)
- return true;
- }
- return false;
- };
- }).service('Debug', function() {
- var level = 0;
- var inGroup = false;
- this.getLevel = function() {
- return level;
- };
- this.setLevel = function(l) {
- l = Math.min(3, Math.max(0, l));
- console.info(this.head() + " Setting DEBUG level to ["+l+"]");
- level = l;
- };
- this.head = function() { return moment().format("DD-MM-YYYY HH:mm:ss") + " -"; },
- this.log = function() {
- if(level < 3) return;
- var args = arguments || [];
- var func = window.console.log;
- if(!inGroup)
- Array.prototype.unshift.call(args, this.head());
- try {
- func.apply(window.console, args);
- } catch (e) {
- for(var a in args)
- console.log(args[a]);
- };
- };
- this.group = function() {
- var args = arguments || [];
- var title = Array.prototype.shift.call(args);
- inGroup = true;
- window.console.group(this.head() + " " + title);
- if(args.length > 0) { //Loop through args and close group after...
- for(var a in args)
- console.log(args[a]);
- this.groupEnd();
- }
- };
- this.groupEnd = function() {
- inGroup = false;
- window.console.groupEnd();
- };
- this.info = function() {
- if(level < 2) return;
- var args = arguments || [];
- var func = window.console.info;
- if(!inGroup)
- Array.prototype.unshift.call(args, this.head());
- try {
- func.apply(window.console, args);
- } catch (e) {
- for(var a in args)
- console.info(args[a]);
- };
- };
- this.warn = function(a) {
- if(level < 1) return;
- var args = arguments || [];
- var func = window.console.warn;
- if(!inGroup)
- Array.prototype.unshift.call(args, this.head());
- try {
- func.apply(window.console, args);
- } catch (e) {
- for(var a in args)
- console.warn(args[a]);
- };
- };
- this.error = function(a) {
- var args = arguments || [];
- var func = window.console.error;
- if(!inGroup)
- Array.prototype.unshift.call(args, this.head());
- try {
- func.apply(window.console, args);
- } catch (e) {
- for(var a in args)
- console.error(args[a]);
- };
- };
- })
- .service('ConditionChecker', ['$rootScope', "Debug", "$state", function($rootScope, Debug, $state) {
- var ConditionChecker = this;
- function log(message){
- Debug.log("[ Condition Checker ] - " + message);
- }
- function singlePossibility(condition, item){
- var possible = true;
- if(condition["role"]){
- if(!(ConditionChecker.isRole(condition["role"]["role"]))){
- possible = false;
- }
- }
- if(condition["amountIs"]){
- for(var name in condition["amountIs"]){
- if( !(ConditionChecker.amount({name:name, operator: '==', amount:condition["amountIs"][name]})) ){
- possible = false;
- }
- }
- }
- if(condition["seen"]){
- var expectedAmount = condition["seen"]["seen"];
- var actualAmount = item.amountSeen || 0;
- log("Seen itself ? Expected: " + expectedAmount + " Actual: " + actualAmount);
- if(actualAmount > expectedAmount ){
- possible = false;
- }
- }
- return possible;
- }
- function checkCondition(condition, item){
- var met = true;
- var type = condition["OR"] ? "OR" : "AND";
- if(type === "OR"){
- met = false;
- for (var property in condition["OR"]) {
- if (condition["OR"].hasOwnProperty(property)) {
- var sub = condition["OR"][property];
- if(checkSingleCondition(sub, item)){
- met = true;
- break;
- }
- }
- }
- }
- else {
- met = checkSingleCondition(condition, item);
- }
- return met;
- }
- function checkSingleCondition(condition, item){
- if(condition["amountIs"]){
- for(var name in condition["amountIs"]){
- if( !(ConditionChecker.amount({name:name, operator: '==', amount:condition["amountIs"][name]})) ){
- return false;
- }
- }
- }
- if(condition["amountLess"]){
- for(var name in condition["amountLess"]){
- if( !(ConditionChecker.amount({name:name, operator: '<', amount:condition["amountLess"][name]})) ){
- return false;
- }
- }
- }
- if(condition["amountMore"]){
- for(var name in condition["amountMore"]){
- if( !(ConditionChecker.amount({name:name, operator: '>', amount:condition["amountMore"][name]})) ){
- return false;
- }
- }
- }
- if(condition["balloon"]){
- var balloons = condition["balloon"];
- for(var x in balloons){
- if(!(ConditionChecker.hasSeenBalloon(balloons[x]))){
- return false;
- }
- }
- }
- if(condition["role"]){
- if(!(ConditionChecker.isRole(condition["role"]["role"]))){
- return false;
- }
- }
- if(condition["state"]){
- if(!(ConditionChecker.activeState(condition["state"]["state"]))){
- return false;
- }
- }
- if(condition["seen"]){
- var expectedAmount = condition["seen"]["seen"];
- var actualAmount = item.amountSeen || 0;
- if(actualAmount > expectedAmount ){
- return false;
- }
- }
- return true;
- }
- this.canContinue = function(conditions, item){
- var possible = true;
- if(conditions && !(conditions.length))
- return false;
- for(var i=0; i < conditions.length; i++){
- var condition = conditions[i];
- var type = condition["OR"] ? "OR" : "AND";
- if(type === "OR"){
- var sPossible = false;
- for (var property in condition["OR"]) {
- if (condition["OR"].hasOwnProperty(property)) {
- var sub = condition["OR"][property];
- if(singlePossibility(sub, item)){
- sPossible = true;
- }
- }
- }
- if(!sPossible){
- possible = false;
- }
- }
- else {
- if(!(singlePossibility(condition, item))){
- possible = false;
- }
- }
- }
- return possible;
- };
- this.execute = function(conditions, item){
- var met = true;
- if(conditions && !(conditions.length))
- return false;
- for(var i=0; i < conditions.length; i++){
- var condition = conditions[i];
- if(!checkCondition(condition, item)){
- met = false;
- }
- }
- return met;
- };
- this.amount = function(condition){
- var name = condition.name.toLowerCase();
- var amount = condition.amount;
- var operator = condition.operator;
- var expression;
- switch(name){
- case 'backlogitems':
- expression = $rootScope[name].length;
- break;
- case 'backlogitems_status_concept':
- case 'backlogitems_status_refinement':
- case 'backlogitems_status_ready':
- var backlogitemsWithStatus = 0;
- var status = name.split("_")[name.split("_").length-1].toLowerCase();
- for(x=0; x < $rootScope.backlogitems.length; x++){
- var pbi = $rootScope.backlogitems[x];
- if(pbi.status.name.toLowerCase() === status){
- backlogitemsWithStatus++;
- }
- };
- expression = backlogitemsWithStatus;
- break;
- case 'goals':
- case 'epics':
- if($rootScope["epics"] && $rootScope["epics"].length == 1 && $rootScope["epics"][0].id == 0){
- // Sometimes a 'no-goal'/'no-epic' pops up in $rootScope, they appear with id 0, we do not count these so decrease by one
- expression = $rootScope["epics"].length-1;
- }
- else {
- expression = $rootScope["epics"].length;
- }
- case 'tags':
- expression = Object.keys($rootScope[name]).length;
- break;
- case 'sprints_future':
- expression = $rootScope.sprints.future.length;
- break;
- case 'sprints_historic':
- expression = $rootScope.sprints.historic.length;
- break;
- case 'sprints_current':
- expression = $rootScope.sprints.current.active === undefined ? 0 : $rootScope.sprints.current.active;
- break;
- }
- log("Amount " + name + "... Actual: " + expression + " " + operator + " " + amount + " (expected)");
- switch(operator){
- case '>':
- return expression > amount;
- case '<':
- return expression < amount;
- case '==':
- return expression == amount;
- }
- };
- this.activeState = function(stateName){
- var actualState = $state.current.name;
- log("Active state checking... expected: " + stateName + " actual: " + actualState);
- return actualState == stateName;
- };
- this.isRole = function(roleId){
- //return $rootScope.authObj.role.id == roleId;
- var role = $rootScope.authObj.role.id === 4 ? 1 : $rootScope.authObj.role.id;
- log("Role, expected: "+roleId+" actual: " + role);
-             return role == roleId;
- };
- this.hasSeenBalloon = function(name){
- log("Has seen balloon " + name + " ? " + $rootScope.balloons[name] && $rootScope.balloons[name].amountSeen > 0);
- return $rootScope.balloons[name] && $rootScope.balloons[name].amountSeen > 0;
- };
- }]).service('SweetAlert', function() {
- this.defaultSettings = {
- confirmButtonColor: "#449d44"
- };
- this.Input = function(option, callback) {
- var options = angular.copy(this.defaultSettings);
- options.showCancelButton = true;
- options.type = "input";
- for(x in option) options[x] = option[x];
- if($('.confirm-all')) $('.confirm-all').remove();
- swal(options, callback);
- };
- this.Confirm = function(option, callback) {
- var options = angular.copy(this.defaultSettings);
- options.showCancelButton = true;
- options.type = "warning";
- options.title = "Are you sure?";
- for(x in option) options[x] = option[x];
- if($('.confirm-all')) $('.confirm-all').remove();
- swal(options, callback);
- };
- this.Info = function(option, callback) {
- var options = angular.copy(this.defaultSettings);
- options.type = "info";
- for(x in option) options[x] = option[x];
- if($('.confirm-all')) $('.confirm-all').remove();
- swal(options, callback);
- };
- this.Success = function(option, callback) {
- var options = angular.copy(this.defaultSettings);
- options.type = "success";
- for(x in option) options[x] = option[x];
- if($('.confirm-all')) $('.confirm-all').remove();
- swal(options, callback);
- };
- this.Warning = function(option, callback) {
- var options = angular.copy(this.defaultSettings);
- options.type = "warning";
- for(x in option) options[x] = option[x];
- if($('.confirm-all')) $('.confirm-all').remove();
- swal(options, callback);
- };
- this.Error = function(option, callback) {
- var options = angular.copy(this.defaultSettings);
- options.type = "error";
- for(x in option) options[x] = option[x];
- if($('.confirm-all')) $('.confirm-all').remove();
- swal(options, callback);
- };
- }).filter('markDown', function() {
- return function(input) {
- if(!input) return;
- input = input.replace(/(?:\r\n|\r|\n)/g, '<br />');
- input = input.replace(/\[(.*?)\]\((.+?)\)/g, function(matchStr ,var1 ,var2) {
- if(var2.startsWith("http")){
- return '<a target="_blank" href="'+var2+'" alt="'+var1+'">'+var1+'</a>';
- }
- else {
- return '<a ui-sref="'+var2+'" alt="'+var1+'">'+var1+'</a>';
- }
- });
- return input;
- };
- }).factory('backlogitemService', ['$rootScope', 'Api', 'SweetAlert', 'Poller', '$uibModal', 'Debug', function($rootScope, Api, SweetAlert, Poller, $uibModal, Debug) {
- return {
- getExpanded : function(biid, callback){
- Api.Get("backlogitems/"+biid+"?expanded=all", function(result) {
- for(var x=0; x < result.backlogitem.tasks.length; x++){
- var task = result.backlogitem.tasks[x];
- task.name = htmlDecode(task.name);
- }
- if(!result.backlogitem.description) result.backlogitem.description = "";
- if(!result.backlogitem.acceptance_criteria) result.backlogitem.acceptance_criteria = "";
- result.backlogitem.getDate = function(key) {
- return moment(this[key], "YYYY-MM-DD HH:mm:ss").valueOf();
- };
- callback(result.backlogitem);
- });
- },
- clone : function(pbi, event){
- event.stopPropagation();
- var biid = pbi.id ? pbi.id : pbi.biid;
- Api.Post("api/backlogitems/clone/" + biid, false, function(){
- SweetAlert.Success({
- title: "Success",
- text : "Your duplicated backlogitem has been placed on the bottom of the backlog."
- });
- Poller.get("api/backlogs/"+$rootScope.authObj.backlog.id+"/items").run();
- Poller.get("api/subscriptions/"+$rootScope.authObj.subscription.id+"/products/"+ $rootScope.authObj.product.id).run();
- });
- },
- edit : function(pbi, event){
- event.stopPropagation();
- var biid = pbi.id ? pbi.id : pbi.biid;
- $rootScope.editPBImodal = $uibModal.open({
- controller: "BacklogitemCtrl",
- templateUrl: 'views/modals/editBacklogitem.html',
- backdrop: false,
- resolve : {
- biid : function(){
- return biid;
- }
- },
- windowClass: "fullscreen-modal",
- });
- },
- delete : function(pbi, event){
- event.stopPropagation();
- var biid = pbi.id ? pbi.id : pbi.biid;
- SweetAlert.Confirm({title: "Are you sure you want to delete this backlogitem?", text: pbi.name}, function(boolean) {
- Debug.info("Removing backlogitem ["+biid+"]", boolean);
- if (boolean == true) {
- Api.Delete("backlogitems/"+biid, function(result) {
- for(x in $rootScope.backlogitems)
- if($rootScope.backlogitems[x].id == biid)
- $rootScope.backlogitems.splice(x, 1);
- for(x in $rootScope.sprints.current.backlogitems)
- if($rootScope.sprints.current.backlogitems[x].id == biid)
- $rootScope.sprints.current.backlogitems.splice(x, 1);
- Poller.get("api/backlogs/"+$rootScope.authObj.backlog.id+"/items").run();
- Poller.get("api/subscriptions/"+$rootScope.authObj.subscription.id+"/products/"+ $rootScope.authObj.product.id).run();
- });
- }
- });
- },
- split : function(pbi, event){
- event.stopPropagation();
- var biid = pbi.id ? pbi.id : pbi.biid;
- $rootScope.splitPBImodal = $uibModal.open({
- templateUrl: 'views/splitBacklogitem.html',
- controller: 'SplitPBIctrl',
- backdrop: 'static',
- size: 'lg',
- resolve : {
- biid : function(){
- return biid;
- }
- }
- });
- },
- add : function(epicId){
- $rootScope.addPBImodal = $uibModal.open({
- templateUrl: 'views/modals/addBacklogitem.html',
- controller: 'AddBacklogitemCtrl',
- backdrop: false,
- resolve : { // Resolve 'injects' value (item & type) as a ctrl dependency, like $scope, SweetAlert, etc!
- epicId : function(){
- return epicId;
- }
- },
- windowClass: "fullscreen-modal"
- })
- }
- }
- }]).factory('authService', ['$rootScope', '$http', 'Idle', '$state', 'Misc', 'Session', 'Api', 'Debug', 'appConstants', 'Cookies',
- function($rootScope, $http, Idle, $state, Misc, Session, Api, Debug, appConstants, Cookies) {
- this.getPermissions = function(path) {
- var permissions = {c:false, r:true, u:false, d:false};
- var methods = Api.getAllowed(path);
- if(methods) {
- methods = methods.split(",");
- methods.splice(-2); //Remove options and head;
- for(i in methods) {
- if(methods[i] == "POST")
- permissions.c = true;
- if(methods[i] == "GET")
- permissions.r = true;
- if(methods[i] == "PUT")
- permissions.u = true;
- if(methods[i] == "DELETE")
- permissions.d = true;
- }
- }
- return permissions;
- };
- this.hasAccess = function(path, type) {
- var permissions = this.getPermissions(path);
- switch(type) {
- case "c":
- case "create":
- return permissions.c;
- break;
- case "r":
- case "read":
- return permissions.r;
- break;
- case "u":
- case "update":
- return permissions.u;
- break;
- case "d":
- case "delete":
- return permissions.d;
- break;
- default:
- return false;
- };
- };
- return {
- getPermissions: this.getPermissions,
- hasAccess: this.hasAccess,
- hasSubscriptionOwnerPermissions: function() {
- return $rootScope.authObj.role.id === 4;
- },
- hasProductownerPermissions: function() {
- return $rootScope.authObj.role.id === 1 || $rootScope.authObj.role.id === 4;
- },
- hasStakeholderPermissions: function() {
- return $rootScope.authObj.role.id === 3;
- },
- hasDeveloperPermissions: function() {
- return $rootScope.authObj.role.id === 2;
- },
- login: function(email, password, callback) {
- if(email != "anonymous") {
- Api.Post("api/login", {loginDetails: {email: email, password: password}}, function(response) {
- if(response && response.loginDetails) {
- var data = response.loginDetails;
- data.user.email = email;
- data.user = Misc.populateMember(data.user);
- Cookies.set('authObj', data);
- Session.set('authObj', data);
- $state.go(data.user.pref_state);
- $rootScope.logoRoll();
- if($rootScope.loginModal)
- $rootScope.loginModal.close();
- //if(data.user.firstLogin)
- // $rootScope.showTipsAndTricks();
- }
- }, function(data, status) {
- var errorMessage = "An unknown error occurred...";
- if(data && data.loginDetails && data.loginDetails.result)
- errorMessage = data.loginDetails.result;
- if(data && data.login)
- errorMessage = data;
- callback(errorMessage, status);
- });
- }
- },
- updateUser: function(data) {
- var authObj = Session.get('authObj') || Cookies.get('authObj');
- for(x in data) {
- if(data.hasOwnProperty(x))
- authObj['user'][x] = data[x];
- }
- Cookies.set('authObj', authObj);
- Session.set('authObj', authObj);
- },
- getUser: function() {
- var authObj = Session.get('authObj') || Cookies.get('authObj');
- if(authObj != null && authObj != "null") {
- authObj.getName = function() { return this.user.firstname + " " + this.user.lastname; };
- return authObj;
- }
- return false;
- },
- loggedin: function(redirect) {
- var authObj = Session.get('authObj') || Cookies.get('authObj');
- if(authObj != null && authObj != "null") {
- Session.set('authObj', authObj);
- $rootScope.authObj = authObj;
- return true;
- }
- else if(redirect) {
- $state.go("landingspage");
- }
- return false;
- },
- logout: function() {
- $rootScope.permissions = undefined;
- $rootScope.backlogitems = undefined;
- $rootScope.sprints = undefined;
- $rootScope.theme = 0;
- $rootScope.members = undefined;
- $rootScope.tags = undefined;
- $rootScope.roles = undefined;
- $rootScope.notifications = undefined;
- $rootScope.balloons = undefined;
- $rootScope.epics = undefined;
- $rootScope.goals = undefined;
- $rootScope.backlogHealth = undefined;
- appConstants.init = 0;
- Api.flushCache();
- Session.clear();
- Cookies.clear();
- Idle.unwatch();
- }
- };
- }]).factory('md5', ['Debug', function (Debug) {
- function md5cycle(x, k) {
- var a = x[0], b = x[1], c = x[2], d = x[3];
- a = ff(a, b, c, d, k[0], 7, -680876936);
- d = ff(d, a, b, c, k[1], 12, -389564586);
- c = ff(c, d, a, b, k[2], 17, 606105819);
- b = ff(b, c, d, a, k[3], 22, -1044525330);
- a = ff(a, b, c, d, k[4], 7, -176418897);
- d = ff(d, a, b, c, k[5], 12, 1200080426);
- c = ff(c, d, a, b, k[6], 17, -1473231341);
- b = ff(b, c, d, a, k[7], 22, -45705983);
- a = ff(a, b, c, d, k[8], 7, 1770035416);
- d = ff(d, a, b, c, k[9], 12, -1958414417);
- c = ff(c, d, a, b, k[10], 17, -42063);
- b = ff(b, c, d, a, k[11], 22, -1990404162);
- a = ff(a, b, c, d, k[12], 7, 1804603682);
- d = ff(d, a, b, c, k[13], 12, -40341101);
- c = ff(c, d, a, b, k[14], 17, -1502002290);
- b = ff(b, c, d, a, k[15], 22, 1236535329);
- a = gg(a, b, c, d, k[1], 5, -165796510);
- d = gg(d, a, b, c, k[6], 9, -1069501632);
- c = gg(c, d, a, b, k[11], 14, 643717713);
- b = gg(b, c, d, a, k[0], 20, -373897302);
- a = gg(a, b, c, d, k[5], 5, -701558691);
- d = gg(d, a, b, c, k[10], 9, 38016083);
- c = gg(c, d, a, b, k[15], 14, -660478335);
- b = gg(b, c, d, a, k[4], 20, -405537848);
- a = gg(a, b, c, d, k[9], 5, 568446438);
- d = gg(d, a, b, c, k[14], 9, -1019803690);
- c = gg(c, d, a, b, k[3], 14, -187363961);
- b = gg(b, c, d, a, k[8], 20, 1163531501);
- a = gg(a, b, c, d, k[13], 5, -1444681467);
- d = gg(d, a, b, c, k[2], 9, -51403784);
- c = gg(c, d, a, b, k[7], 14, 1735328473);
- b = gg(b, c, d, a, k[12], 20, -1926607734);
- a = hh(a, b, c, d, k[5], 4, -378558);
- d = hh(d, a, b, c, k[8], 11, -2022574463);
- c = hh(c, d, a, b, k[11], 16, 1839030562);
- b = hh(b, c, d, a, k[14], 23, -35309556);
- a = hh(a, b, c, d, k[1], 4, -1530992060);
- d = hh(d, a, b, c, k[4], 11, 1272893353);
- c = hh(c, d, a, b, k[7], 16, -155497632);
- b = hh(b, c, d, a, k[10], 23, -1094730640);
- a = hh(a, b, c, d, k[13], 4, 681279174);
- d = hh(d, a, b, c, k[0], 11, -358537222);
- c = hh(c, d, a, b, k[3], 16, -722521979);
- b = hh(b, c, d, a, k[6], 23, 76029189);
- a = hh(a, b, c, d, k[9], 4, -640364487);
- d = hh(d, a, b, c, k[12], 11, -421815835);
- c = hh(c, d, a, b, k[15], 16, 530742520);
- b = hh(b, c, d, a, k[2], 23, -995338651);
- a = ii(a, b, c, d, k[0], 6, -198630844);
- d = ii(d, a, b, c, k[7], 10, 1126891415);
- c = ii(c, d, a, b, k[14], 15, -1416354905);
- b = ii(b, c, d, a, k[5], 21, -57434055);
- a = ii(a, b, c, d, k[12], 6, 1700485571);
- d = ii(d, a, b, c, k[3], 10, -1894986606);
- c = ii(c, d, a, b, k[10], 15, -1051523);
- b = ii(b, c, d, a, k[1], 21, -2054922799);
- a = ii(a, b, c, d, k[8], 6, 1873313359);
- d = ii(d, a, b, c, k[15], 10, -30611744);
- c = ii(c, d, a, b, k[6], 15, -1560198380);
- b = ii(b, c, d, a, k[13], 21, 1309151649);
- a = ii(a, b, c, d, k[4], 6, -145523070);
- d = ii(d, a, b, c, k[11], 10, -1120210379);
- c = ii(c, d, a, b, k[2], 15, 718787259);
- b = ii(b, c, d, a, k[9], 21, -343485551);
- x[0] = add32(a, x[0]);
- x[1] = add32(b, x[1]);
- x[2] = add32(c, x[2]);
- x[3] = add32(d, x[3]);
- }
- function cmn(q, a, b, x, s, t) {
- a = add32(add32(a, q), add32(x, t));
- return add32((a << s) | (a >>> (32 - s)), b);
- }
- function ff(a, b, c, d, x, s, t) {
- return cmn((b & c) | ((~b) & d), a, b, x, s, t);
- }
- function gg(a, b, c, d, x, s, t) {
- return cmn((b & d) | (c & (~d)), a, b, x, s, t);
- }
- function hh(a, b, c, d, x, s, t) {
- return cmn(b ^ c ^ d, a, b, x, s, t);
- }
- function ii(a, b, c, d, x, s, t) {
- return cmn(c ^ (b | (~d)), a, b, x, s, t);
- }
- function md51(s) {
- txt = '';
- var n = s.length,
- state = [1732584193, -271733879, -1732584194, 271733878], i;
- for (i=64; i<=s.length; i+=64) {
- md5cycle(state, md5blk(s.substring(i-64, i)));
- }
- s = s.substring(i-64);
- var tail = [0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0];
- for (i=0; i<s.length; i++)
- tail[i>>2] |= s.charCodeAt(i) << ((i%4) << 3);
- tail[i>>2] |= 0x80 << ((i%4) << 3);
- if (i > 55) {
- md5cycle(state, tail);
- for (i=0; i<16; i++) tail[i] = 0;
- }
- tail[14] = n*8;
- md5cycle(state, tail);
- return state;
- }
- /* there needs to be support for Unicode here,
- * unless we pretend that we can redefine the MD-5
- * algorithm for multi-byte characters (perhaps
- * by adding every four 16-bit characters and
- * shortening the sum to 32 bits). Otherwise
- * I suggest performing MD-5 as if every character
- * was two bytes--e.g., 0040 0025 = @%--but then
- * how will an ordinary MD-5 sum be matched?
- * There is no way to standardize text to something
- * like UTF-8 before transformation; speed cost is
- * utterly prohibitive. The JavaScript standard
- * itself needs to look at this: it should start
- * providing access to strings as preformed UTF-8
- * 8-bit unsigned value arrays.
- */
- function md5blk(s) { /* I figured global was faster. */
- var md5blks = [], i; /* Andy King said do it this way. */
- for (i=0; i<64; i+=4) {
- md5blks[i>>2] = s.charCodeAt(i)
- + (s.charCodeAt(i+1) << 8)
- + (s.charCodeAt(i+2) << 16)
- + (s.charCodeAt(i+3) << 24);
- }
- return md5blks;
- }
- var hex_chr = '0123456789abcdef'.split('');
- function rhex(n) {
- var s='', j=0;
- for(; j<4; j++)
- s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F];
- return s;
- }
- function hex(x) {
- for (var i=0; i<x.length; i++)
- x[i] = rhex(x[i]);
- return x.join('');
- }
- function md5(s) {
- return hex(md51(s));
- }
- /* this function is much faster,
- so if possible we use it. Some IEs
- are the only ones I know of that
- need the idiotic second function,
- generated by an if clause. */
- function add32(a, b) {
- return (a + b) & 0xFFFFFFFF;
- }
- if (md5('hello') != '5d41402abc4b2a76b9719d911017c592') {
- Debug.info('Incapable browser detected...');
- function add32(x, y) {
- var lsw = (x & 0xFFFF) + (y & 0xFFFF),
- msw = (x >> 16) + (y >> 16) + (lsw >> 16);
- return (msw << 16) | (lsw & 0xFFFF);
- }
- }
- return {
- encode: function (input, forceLowerCase) {
- input = (forceLowerCase === false) ? input : input.toLowerCase(); //Defaults to true
- return hex(md51(input));
- }
- };
- }]).factory('Base64', function () {
- var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
- return {
- encode: function (input) {
- var output = "";
- var chr1, chr2, chr3 = "";
- var enc1, enc2, enc3, enc4 = "";
- var i = 0;
- do {
- chr1 = input.charCodeAt(i++);
- chr2 = input.charCodeAt(i++);
- chr3 = input.charCodeAt(i++);
- enc1 = chr1 >> 2;
- enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
- enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
- enc4 = chr3 & 63;
- if (isNaN(chr2)) {
- enc3 = enc4 = 64;
- } else if (isNaN(chr3)) {
- enc4 = 64;
- }
- output = output +
- keyStr.charAt(enc1) +
- keyStr.charAt(enc2) +
- keyStr.charAt(enc3) +
- keyStr.charAt(enc4);
- chr1 = chr2 = chr3 = "";
- enc1 = enc2 = enc3 = enc4 = "";
- } while (i < input.length);
- return output;
- },
- decode: function (input) {
- var output = "";
- var chr1, chr2, chr3 = "";
- var enc1, enc2, enc3, enc4 = "";
- var i = 0;
- // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
- var base64test = /[^A-Za-z0-9\+\/\=]/g;
- if (base64test.exec(input)) {
- console.error("There were invalid base64 characters in the input text.\n" +
- "Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='\n" +
- "Expect errors in decoding.");
- }
- input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
- do {
- enc1 = keyStr.indexOf(input.charAt(i++));
- enc2 = keyStr.indexOf(input.charAt(i++));
- enc3 = keyStr.indexOf(input.charAt(i++));
- enc4 = keyStr.indexOf(input.charAt(i++));
- chr1 = (enc1 << 2) | (enc2 >> 4);
- chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
- chr3 = ((enc3 & 3) << 6) | enc4;
- output = output + String.fromCharCode(chr1);
- if (enc3 != 64) {
- output = output + String.fromCharCode(chr2);
- }
- if (enc4 != 64) {
- output = output + String.fromCharCode(chr3);
- }
- chr1 = chr2 = chr3 = "";
- enc1 = enc2 = enc3 = enc4 = "";
- } while (i < input.length);
- return output;
- }
- };
- }).service('Misc', ['appConstants', 'Debug', 'md5', function(appConstants, Debug, md5) {
- this.populateMember = function(member) {
- if(member.firstname == undefined || member.lastname == undefined) {
- member.avatar = "images/avatar-placeholder.png";
- }
- else {
- member.fullname = member.firstname + " " + member.lastname;
- var bits = member.fullname.split(" "); //Strange method right? It's 'cus of surname prefixes!
- member.initials = (bits[0].charAt(0) + bits[bits.length-1].charAt(0)).toUpperCase();
- var i = getNum(bits[0].charAt(0)) + getNum(bits[bits.length-1].charAt(0));
- var colors = ["#f44336", "#e91e63", "#9c27b0", "#673ab7", "#3f51b5", "#2196f3", "#03a9f4", "#00bcd4", "#009688", "#4caf50", "#8bc34a", "#cddc39", "#ffeb3b", "#ffc107", "#ff9800", "#ff5722", "#795548", "#9e9e9e", "#607d8b"];
- member.color = colors[Math.floor(colors.length / 52 * i)];
- function getNum(a) { return parseInt(a, 36)-9; };
- member.avatar = 'https://gravatar.com/avatar/' + md5.encode(member.email) + '?d=blank';
- }
- return member;
- };
- this.getStage = function() {
- var stage = appConstants.stage;
- if(!stage) {
- switch (window.location.origin.split("//")[1]) {
- case "priooo.com":
- stage = "PRD";
- break;
- case "test.priooo.com":
- stage = "TST";
- break;
- case "demo.priooo.com":
- stage = "ACC";
- break;
- case "demo":
- case "localhost":
- case "priooo.dev":
- case "localhost:8081":
- case "localhost:8080":
- case "demo:8081":
- case "dev":
- stage = "LOC";
- break;
- default:
- stage = "PRD";
- break;
- }
- }
- return stage;
- };
- this.isDemo = function(){
- return window.location.origin.split("//")[1] === "demo.priooo.com" || window.location.origin.split("//")[1] === "demo" || window.location.origin.split("//")[1] === "demo:8081"
- };
- this.getServerPath = function() {
- var absolutePath = appConstants.server;
- if(!absolutePath) {
- absolutePath = window.location.origin;
- if(absolutePath.indexOf('priooo.dev') >= 0)
- absolutePath = "http://localhost:8080";
- if(this.getStage() == "LOC")
- absolutePath += "/iaf4asap";
- }
- if(absolutePath && absolutePath.slice(-1) != "/") absolutePath += "/";
- return absolutePath;
- };
- this.getUserAgent = function(){
- var ua = window.navigator.userAgent;
- var msie = ua.indexOf('MSIE ');
- if (msie > 0) {
- // IE 10 or older => return version number
- return 'Internet Explorer ' + parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
- }
- var trident = ua.indexOf('Trident/');
- if (trident > 0) {
- // IE 11 => return version number
- var rv = ua.indexOf('rv:');
- return 'Internet Explorer ' + parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);;
- }
- var edge = ua.indexOf('Edge/');
- if (edge > 0) {
- // Edge (IE 12+) => return version number
- return 'Edge';
- }
- if((navigator.userAgent.indexOf("Opera") || navigator.userAgent.indexOf('OPR')) != -1 ) {
- return 'Opera';
- }
- if(navigator.userAgent.indexOf("Chrome") != -1 ){
- return 'Chrome';
- }
- if(navigator.userAgent.indexOf("Safari") != -1){
- return 'Safari';
- }
- if(navigator.userAgent.indexOf("Firefox") != -1 ){
- return 'Firefox';
- }
- // other browser
- return 'Unknown';
- };
- this.isMobile = function() {
- return ( navigator.userAgent.match(/Android/i)
- || navigator.userAgent.match(/webOS/i)
- || navigator.userAgent.match(/iPhone/i)
- || navigator.userAgent.match(/iPad/i)
- || navigator.userAgent.match(/iPod/i)
- || navigator.userAgent.match(/BlackBerry/i)
- || navigator.userAgent.match(/Windows Phone/i)
- ) ? true : false;
- };
- this.compare_version = function(v1, v2, operator) {
- // See for more info: http://locutus.io/php/info/version_compare/
- var i, x, compare = 0;
- var vm = {
- 'dev': -6,
- 'alpha': -5,
- 'a': -5,
- 'beta': -4,
- 'b': -4,
- 'RC': -3,
- 'rc': -3,
- '#': -2,
- 'p': 1,
- 'pl': 1
- };
- var _prepVersion = function (v) {
- v = ('' + v).replace(/[_\-+]/g, '.');
- v = v.replace(/([^.\d]+)/g, '.$1.').replace(/\.{2,}/g, '.');
- return (!v.length ? [-8] : v.split('.'));
- };
- var _numVersion = function (v) {
- return !v ? 0 : (isNaN(v) ? vm[v] || -7 : parseInt(v, 10));
- };
- v1 = _prepVersion(v1);
- v2 = _prepVersion(v2);
- x = Math.max(v1.length, v2.length);
- for (i = 0; i < x; i++) {
- if (v1[i] === v2[i]) {
- continue;
- }
- v1[i] = _numVersion(v1[i]);
- v2[i] = _numVersion(v2[i]);
- if (v1[i] < v2[i]) {
- compare = -1;
- break;
- } else if (v1[i] > v2[i]) {
- compare = 1;
- break;
- }
- }
- if (!operator) {
- return compare;
- }
- switch (operator) {
- case '>':
- case 'gt':
- return (compare > 0);
- case '>=':
- case 'ge':
- return (compare >= 0);
- case '<=':
- case 'le':
- return (compare <= 0);
- case '===':
- case '=':
- case 'eq':
- return (compare === 0);
- case '<>':
- case '!==':
- case 'ne':
- return (compare !== 0);
- case '':
- case '<':
- case 'lt':
- return (compare < 0);
- default:
- return null;
- }
- };
- }]).service('Alert', ['$timeout', 'Session', function($timeout, Session) {
- this.add = function(level, message, non_repeditive) {
- if(non_repeditive === true)
- if(this.checkIfExists(message))
- return;
- var type;
- switch(level) {
- case "info":
- case 1:
- type = "fa fa-info";
- break;
- case "warning":
- case 2:
- type = "fa fa-warning";
- break;
- case "severe":
- case 3:
- type = "fa fa-times";
- break;
- default:
- type = "fa fa-info";
- break;
- }
- var list = this.get(true);
- var obj = {
- type: type,
- message: message,
- time: new Date().getTime()
- };
- list.unshift(obj);
- obj.id = list.length;
- Session.set("Alert", list);
- //sessionStorage.setItem("Alert", JSON.stringify(list));
- };
- this.get = function(preserveList) {
- //var list = JSON.parse(sessionStorage.getItem("Alert"));
- var list = Session.get("Alert");
- if(preserveList == undefined) Session.set("Alert", []); //sessionStorage.setItem("Alert", JSON.stringify([])); //Clear after retreival
- return (list != null) ? list : [];
- };
- this.getCount = function() {
- return this.get(true).length || 0;
- };
- this.checkIfExists = function(message) {
- var list = this.get(true);
- if(list.length > 0) {
- for (var i = 0; i < list.length; i++) {
- if(list[i].message == message) {
- return true;
- }
- }
- }
- return false;
- };
- }]).config(['$httpProvider', function($httpProvider) {
- $httpProvider.interceptors.push(['$rootScope', 'appConstants', '$q', '$location', 'Session', 'Misc', 'Debug', function($rootScope, appConstants, $q, $location, Session, Misc, Debug) {
- return {
- responseError: function(rejection) {
- if(rejection.config && rejection.config.url && rejection.config.url.indexOf(Misc.getServerPath()) < 0) return;
- switch (rejection.status) {
- case -1:
- //idle on back iets van resume polling?!?!?
- //console.log(appConstants.init, rejection);
- //Debug.warn("Something odd happened?!?!");
- //registerError(rejection);
- /*sessionStorage.setItem("authObj", null);
- if(appConstants.init == 1) {
- if(rejection.config.headers["Authorization"] != undefined) {
- Alert.add(1, "Wrong password...", true);
- }
- }
- if(appConstants.init == 2) {
- if($location.path().indexOf("login") < 0)
- sessionStorage.setItem('location', $location.path() || "status");
- Alert.add(1, "Connection to the server was lost, please reauthenticate!", true);
- }
- $location.path("login");*/
- break;
- case 401:
- if(rejection.config.url.indexOf('/login') > -1) break;
- appConstants.init = 0;
- Session.clear();
- //var deferred = $q.defer();
- //$rootScope.$broadcast('event:auth-loginRequired', rejection);
- $location.path("logout");
- //return deferred.promise;
- break;
- case 403:
- //$rootScope.$broadcast('event:auth-forbidden', rejection);
- break;
- }
- // otherwise, default behaviour
- return $q.reject(rejection);
- }
- };
- }]);
- }]);
Add Comment
Please, Sign In to add comment