<commit_before>// Globals
var PROXY = "https://databox.me/,system/proxy?uri={uri}";
var AUTH_PROXY = "https://rww.io/auth-proxy?uri=";
var TIMEOUT = 90000;
var DEBUG = true;

// Namespaces
var RDF = $rdf.Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#");
var RDFS = $rdf.Namespace("http://www.w3.org/2000/01/rdf-schema#");
var FOAF = $rdf.Namespace("http://xmlns.com/foaf/0.1/");
var OWL = $rdf.Namespace("http://www.w3.org/2002/07/owl#");
var SPACE = $rdf.Namespace("http://www.w3.org/ns/pim/space#");

$rdf.Fetcher.crossSiteProxyTemplate=PROXY;

// Angular
angular.module( 'App', [
  'App.about',
  'App.login',
  'App.view',
  'App.edit',
  'App.share',
  'ui.router'
])

.config( function AppConfig ( $stateProvider, $urlRouterProvider ) {
  $urlRouterProvider.otherwise( 'edit/profile' );
  $stateProvider.state( 'home', {
    url: '/',
    views: {
      "main": {
        controller: 'MainCtrl'
      }
    },
    data:{ pageTitle: 'Home' }
  });
})

.run( function run () {
})

.controller( 'MainCtrl', function MainCtrl ( $scope, $location, $http, $timeout, $state ) {
  $scope.appuri = window.location.host+window.location.pathname;
  $scope.loginButtonText = 'Login';
  $scope.webid = '';

  $scope.profile = {};
  $scope.profile.loading = false;
  $scope.authenticated = false;

  $scope.ProfileElement = function(s) {
    this.locked = false;
    this.failed = false;
    this.picker = false;
    this.statement = angular.copy(s);
    this.value = this.prev = '';
    if (s && s['object']['value']) {
      var val = s['object']['value']
      if (val.indexOf('tel:') >= 0) {
        val = val.slice(4, val.length);
      } else if (val.indexOf('mailto:') >= 0) {
        val = val.slice(7, val.length);
      }
      this.value = val;
      this.prev = val;
    }
  };

  $scope.ProfileElement.prototype.updateObject = function(update, force) {
    // do not update if value hasn't changed
    if (this.value == this.prev && !force) {
      return;
    }

    if (!this.failed) {
      this.prev = angular.copy(this.value);
    }
    var oldS = angular.copy(this.statement);
    if (this.statement) {
      if (this.statement['object']['termType'] == 'literal') {
        this.statement['object']['value'] = this.value;
      } else if (this.statement['object']['termType'] == 'symbol') {
        val = this.value;
        if (this.statement['predicate'].compareTerm(FOAF('mbox')) == 0) {
          val = "mailto:"+val;
        } else if (this.statement['predicate'].compareTerm(FOAF('phone')) == 0) {
          val = "tel:"+val;
        }
        this.statement['object']['uri'] = val;
        this.statement['object']['value'] = val;
      }
    }

    if (update) {
      this.locked = true;
      var query = '';
      var graphURI = '';
      if (oldS && oldS['object']['value'].length > 0) {
        var query = "DELETE DATA { " + oldS.toNT() + " }";
        if (oldS['why'] && oldS['why']['value'].length > 0) {
          graphURI = oldS['why']['value'];
        } else {
          graphURI = oldS['subject']['value'];
        }
        // add separator
        if (this.value.length > 0) {
          query += " ;\n";
        }
      }
      if (this.value.length > 0) {
        // should ask the user where the new triple should be saved
        query += "INSERT DATA { " + this.statement.toNT() + " }";
        if (graphURI.length == 0) {
          if (this.statement && this.statement['why']['value'].length > 0) {
            graphURI = this.statement['why']['value'];
          } else {
            graphURI = this.statement['subject']['value'];
          }
        }
      }

      // send PATCH request
      if (graphURI && graphURI.length > 0) {
        var that = this;
        $http({
          method: 'PATCH',
          url: graphURI,
          headers: {
            'Content-Type': 'application/sparql-update'
          },
          withCredentials: true,
          data: query
        }).success(function(data, status, headers) {
          $scope.saveCredentials();
          that.locked = false;
          Notifier.success('Profile updated!');
        }).error(function(data, status, headers) {
          that.locked = false;
          that.failed = true;
          that.statement = oldS;
          Notifier.error('Could not update profile: HTTP '+status);
          console.log(data);
        });
      }
    }
  };

  // Load a user's profile
  // string uri  - URI of resource containing profile information
  // bool authenticated - whether the user was previously authenticated or now
  // bool loadMore - whether it loads extended profile documents
  $scope.getProfile = function(uri, authenticated, loadMore) {
    if (!$scope.profile) {
      $scope.profile = {};
    }
    if (!$scope.profile.webid || $scope.profile.webid.length == 0) {
      $scope.profile.webid = uri;
    }
    var g = $rdf.graph();
    var f = $rdf.fetcher(g, TIMEOUT);

    var docURI = (uri.indexOf('#') >= 0)?uri.slice(0, uri.indexOf('#')):uri;
    var webidRes = $rdf.sym($scope.profile.webid);
    $scope.profile.loading = true;
    if (authenticated) {
      $scope.authenticated = true;
    }
    // fetch user data
    f.nowOrWhenFetched(docURI,undefined,function(ok, body, xhr) {
      if (!ok) {
        console.log('Warning - profile not found.');
        Notifier.error('Failed to fetch profile. HTTP '+xhr.status);
        $scope.profile.fullname = uri;
        $scope.profile.loading = false;
        $scope.loginButtonText = "Login";
        $scope.$apply();
      } else {
        if (xhr && xhr.getResponseHeader('User') && xhr.getResponseHeader('User') == uri) {
          $scope.profile.owner = true;
        } else if (authenticated) {
          $scope.profile.owner = true;
        }
        // set time of loading
        if (!$scope.profile.date) {
          $scope.profile.date = Date.now();
        }
        // save docURI to list of sources
        if (!$scope.profile.sources) {
          $scope.profile.sources = [];
        }
        if ($scope.profile.sources.indexOf(docURI) < 0) {
          $scope.profile.sources.push(docURI);
        }

        // try to fetch additional data from sameAs, seeAlso and preferenceFile
        if (!loadMore) {
          var sameAs = g.statementsMatching(webidRes, OWL('sameAs'), undefined);
          if (sameAs.length > 0) {
            sameAs.forEach(function(same){
              $scope.getProfile(same['object']['value'], false, true);
            });
          }
          var seeAlso = g.statementsMatching(webidRes, OWL('seeAlso'), undefined);
          if (seeAlso.length > 0) {
            seeAlso.forEach(function(see){
              $scope.getProfile(see['object']['value'], false, true);
            });
          }
          var prefs = g.statementsMatching(webidRes, SPACE('preferencesFile'), undefined);
          if (prefs.length > 0) {
            prefs.forEach(function(pref){
              if (pref['object']['value']) {
                $scope.getProfile(pref['object']['value'], false, true);
              }
            });
          }
        }

        // get info
        var fullname = g.statementsMatching(webidRes, FOAF('name'), undefined)[0];
        if (!fullname || fullname['object']['value'].length == 0) {
          fullname = $rdf.st(webidRes, FOAF('name'), $rdf.lit(''), $rdf.sym(''));
        }
        if (!$scope.profile.fullname) {
          $scope.profile.fullname = new $scope.ProfileElement(fullname);
        }
        // Firstname
        var firstname = g.statementsMatching(webidRes, FOAF('givenName'), undefined)[0];
        if (!firstname || firstname['object']['value'].length == 0) {
          firstname = $rdf.st(webidRes, FOAF('givenName'), $rdf.lit(''), $rdf.sym(''));
        }
        if (!$scope.profile.firstname) {
          $scope.profile.firstname = new $scope.ProfileElement(firstname);
        }
        // Lastname
        var lastname = g.statementsMatching(webidRes, FOAF('familyName'), undefined)[0];
        if (!lastname || lastname['object']['value'].length == 0) {
          lastname = $rdf.st(webidRes, FOAF('familyName'), $rdf.lit(''), $rdf.sym(''));
        }
        if (!$scope.profile.lastname) {
          $scope.profile.lastname = new $scope.ProfileElement(lastname);
        }
        // Nickname
        var nick = g.statementsMatching(webidRes, FOAF('nick'), undefined)[0];
        if (!nick || nick['object']['value'].length == 0) {
          nick = $rdf.st(webidRes, FOAF('nick'), $rdf.lit(''), $rdf.sym(''));
        }
        if (!$scope.profile.nick) {
          $scope.profile.nick = new $scope.ProfileElement(nick);
        }

        // Get profile picture
        var img = g.statementsMatching(webidRes, FOAF('img'), undefined)[0];
        var pic;
        if (img) {
          pic = img;
        } else {
          // check if profile uses depic instead
          var depic = g.statementsMatching(webidRes, FOAF('depiction'), undefined)[0];
          if (depic) {
            pic = depic;
          }
        }
        if (!pic || pic['object']['value'].length == 0) {
          pic = $rdf.st(webidRes, FOAF('img'), $rdf.sym(''), $rdf.sym(''));
        }
        if (!$scope.profile.picture) {
          $scope.profile.picture = new $scope.ProfileElement(pic);
        }
        // Phones
        var phones = g.statementsMatching(webidRes, FOAF('phone'), undefined);
        if (phones.length > 0) {
          phones.forEach(function(phone){
            if (!$scope.profile.phones) {
              $scope.profile.phones = [];
            }
            $scope.profile.phones.push(new $scope.ProfileElement(phone));
          });
        }

        // Emails
        var emails = g.statementsMatching(webidRes, FOAF('mbox'), undefined);
        if (emails.length > 0) {
          emails.forEach(function(email){
            if (!$scope.profile.emails) {
              $scope.profile.emails = [];
            }
            $scope.profile.emails.push(new $scope.ProfileElement(email));
          });
        }

        // Blogs
        var blogs = g.statementsMatching(webidRes, FOAF('weblog'), undefined);
        if (blogs.length > 0) {
          blogs.forEach(function(blog){
            if (!$scope.profile.blogs) {
              $scope.profile.blogs = [];
            }
            $scope.profile.blogs.push(new $scope.ProfileElement(blog));
          });
        }

        // Homepages
        var homepages = g.statementsMatching(webidRes, FOAF('homepage'), undefined);
        if (homepages.length > 0) {
          homepages.forEach(function(homepage){
            if (!$scope.profile.homepages) {
              $scope.profile.homepages = [];
            }
            $scope.profile.homepages.push(new $scope.ProfileElement(homepage));
          });
        }

        // Workpages
        var workpages = g.statementsMatching(webidRes, FOAF('workplaceHomepage'), undefined);
         if (workpages.length > 0) {
          workpages.forEach(function(workpage){
            if (!$scope.profile.workpages) {
              $scope.profile.workpages = [];
            }
            $scope.profile.workpages.push(new $scope.ProfileElement(workpage));
          });
        }

        $scope.profile.loading = false;
        $scope.$apply();

        // debug
        if (authenticated) {
          $scope.loginButtonText = "Login";
          var authUser = ($scope.profile.fullname.value)?" as "+$scope.profile.fullname.value:"";
          Notifier.success('Authenticated'+authUser);
          $scope.saveCredentials(true);
        }
      }
    });
  };

  $scope.saveCredentials = function (redirect) {
    var app = {
      profile: {
        webid: $scope.profile.webid,
        owner: $scope.profile.owner,
        date: $scope.profile.date
      },
      authenticated: $scope.authenticated
    };
    sessionStorage.setItem($scope.appuri, JSON.stringify(app));
    // redirect to view page
    if (redirect) {
      // switch to view once it's available
      $state.go('editProfile');
    }
  };

  $scope.login = function() {
    $scope.loginButtonText = 'Loggin in...';
    $http({
      method: 'HEAD',
      url: "https://rww.io/",
      withCredentials: true
    }).success(function(data, status, headers) {
      // add dir to local list
      var user = headers('User');
      if (user && user.length > 0 && user.slice(0,4) == 'http') {
        $scope.profile.webid = user;
        $scope.getProfile(user, true);
        $scope.loginButtonText = 'Logged in';
      } else {
        Notifier.warning('WebID-TLS authentication failed.');
        console.log('WebID-TLS authentication failed.');
      }
    }).error(function(data, status, headers) {
      Notifier.error('Could not connect to auth server: HTTP '+status);
      console.log('Could not connect to auth server: HTTP '+status);
      $scope.loginButtonText = 'Login done';
    });
  };

  // Logout WebID (only works in Firefox and IE)
  $scope.logout = function () {
    if (document.all == null) {
      if (window.crypto) {
          try{
              window.crypto.logout(); //firefox ok -- no need to follow the link
          } catch (err) {//Safari, Opera, Chrome -- try with tis session breaking
          }
      }
    } else { // MSIE 6+
      document.execCommand('ClearAuthenticationCache');
    }

    // clear sessionStorage
    $scope.clearLocalCredentials();
    $scope.profile = {};
    $scope.authenticated = false;
    $state.go('view', {}, {redirect: true});
  };

  // clear sessionStorage
  $scope.clearLocalCredentials = function () {
    sessionStorage.removeItem($scope.appuri);
  };

  $scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){
    if (angular.isDefined(toState.data.pageTitle)) {
      $scope.pageTitle = toState.data.pageTitle;
    }
  });

  // initialize by retrieving user info from sessionStorage
  // retrieve from sessionStorage
  if (sessionStorage.getItem($scope.appuri)) {
    var app = JSON.parse(sessionStorage.getItem($scope.appuri));
    if (app) {
      if (!$scope.profile) {
        $scope.profile = {};
      }
      // don't let session data become stale (24h validity)
      var dateValid = app.profile.date + 1000 * 60 * 60 * 24;
      if (Date.now() < dateValid) {
        $scope.profile = app.profile;
        $scope.authenticated = app.authenticated;
        $scope.getProfile(app.profile.webid);
      } else {
        console.log("Deleting profile because of date");
        sessionStorage.removeItem($scope.appuri);
      }
    } else {
      // clear sessionStorage in case there was a change to the data structure
      console.log("Deleting profile because of structure");
      sessionStorage.removeItem($scope.appuri);
    }
  }

  var webid = getParam('webid');
  if (webid && webid.length > 0 && !$scope.profile.webid) {
    $scope.webid = webid;
    $scope.getProfile(webid, false);
  }
})
//simple directive to display list of channels
.directive('profileCard',function(){
    return {
      replace : true,
      restrict : 'E',
      templateUrl: 'app/profileCard.tpl.html'
    };
})

//simple directive to display list of channels
.directive('spinner',function(){
    return {
      replace : true,
      restrict : 'E',
      templateUrl: 'app/spinner.tpl.html'
    };
});
<commit_msg>Reverted to rww.io for proxy<commit_after>// Globals
var PROXY = "https://rww.io/proxy?uri={uri}";
var AUTH_PROXY = "https://rww.io/auth-proxy?uri=";
var TIMEOUT = 90000;
var DEBUG = true;

// Namespaces
var RDF = $rdf.Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#");
var RDFS = $rdf.Namespace("http://www.w3.org/2000/01/rdf-schema#");
var FOAF = $rdf.Namespace("http://xmlns.com/foaf/0.1/");
var OWL = $rdf.Namespace("http://www.w3.org/2002/07/owl#");
var SPACE = $rdf.Namespace("http://www.w3.org/ns/pim/space#");

$rdf.Fetcher.crossSiteProxyTemplate=PROXY;

// Angular
angular.module( 'App', [
  'App.about',
  'App.login',
  'App.view',
  'App.edit',
  'App.share',
  'ui.router'
])

.config( function AppConfig ( $stateProvider, $urlRouterProvider ) {
  $urlRouterProvider.otherwise( 'edit/profile' );
  $stateProvider.state( 'home', {
    url: '/',
    views: {
      "main": {
        controller: 'MainCtrl'
      }
    },
    data:{ pageTitle: 'Home' }
  });
})

.run( function run () {
})

.controller( 'MainCtrl', function MainCtrl ( $scope, $location, $http, $timeout, $state ) {
  $scope.appuri = window.location.host+window.location.pathname;
  $scope.loginButtonText = 'Login';
  $scope.webid = '';

  $scope.profile = {};
  $scope.profile.loading = false;
  $scope.authenticated = false;

  $scope.ProfileElement = function(s) {
    this.locked = false;
    this.failed = false;
    this.picker = false;
    this.statement = angular.copy(s);
    this.value = this.prev = '';
    if (s && s['object']['value']) {
      var val = s['object']['value']
      if (val.indexOf('tel:') >= 0) {
        val = val.slice(4, val.length);
      } else if (val.indexOf('mailto:') >= 0) {
        val = val.slice(7, val.length);
      }
      this.value = val;
      this.prev = val;
    }
  };

  $scope.ProfileElement.prototype.updateObject = function(update, force) {
    // do not update if value hasn't changed
    if (this.value == this.prev && !force) {
      return;
    }

    if (!this.failed) {
      this.prev = angular.copy(this.value);
    }
    var oldS = angular.copy(this.statement);
    if (this.statement) {
      if (this.statement['object']['termType'] == 'literal') {
        this.statement['object']['value'] = this.value;
      } else if (this.statement['object']['termType'] == 'symbol') {
        val = this.value;
        if (this.statement['predicate'].compareTerm(FOAF('mbox')) == 0) {
          val = "mailto:"+val;
        } else if (this.statement['predicate'].compareTerm(FOAF('phone')) == 0) {
          val = "tel:"+val;
        }
        this.statement['object']['uri'] = val;
        this.statement['object']['value'] = val;
      }
    }

    if (update) {
      this.locked = true;
      var query = '';
      var graphURI = '';
      if (oldS && oldS['object']['value'].length > 0) {
        var query = "DELETE DATA { " + oldS.toNT() + " }";
        if (oldS['why'] && oldS['why']['value'].length > 0) {
          graphURI = oldS['why']['value'];
        } else {
          graphURI = oldS['subject']['value'];
        }
        // add separator
        if (this.value.length > 0) {
          query += " ;\n";
        }
      }
      if (this.value.length > 0) {
        // should ask the user where the new triple should be saved
        query += "INSERT DATA { " + this.statement.toNT() + " }";
        if (graphURI.length == 0) {
          if (this.statement && this.statement['why']['value'].length > 0) {
            graphURI = this.statement['why']['value'];
          } else {
            graphURI = this.statement['subject']['value'];
          }
        }
      }

      // send PATCH request
      if (graphURI && graphURI.length > 0) {
        var that = this;
        $http({
          method: 'PATCH',
          url: graphURI,
          headers: {
            'Content-Type': 'application/sparql-update'
          },
          withCredentials: true,
          data: query
        }).success(function(data, status, headers) {
          $scope.saveCredentials();
          that.locked = false;
          Notifier.success('Profile updated!');
        }).error(function(data, status, headers) {
          that.locked = false;
          that.failed = true;
          that.statement = oldS;
          Notifier.error('Could not update profile: HTTP '+status);
          console.log(data);
        });
      }
    }
  };

  // Load a user's profile
  // string uri  - URI of resource containing profile information
  // bool authenticated - whether the user was previously authenticated or now
  // bool loadMore - whether it loads extended profile documents
  $scope.getProfile = function(uri, authenticated, loadMore) {
    if (!$scope.profile) {
      $scope.profile = {};
    }
    if (!$scope.profile.webid || $scope.profile.webid.length == 0) {
      $scope.profile.webid = uri;
    }
    var g = $rdf.graph();
    var f = $rdf.fetcher(g, TIMEOUT);

    var docURI = (uri.indexOf('#') >= 0)?uri.slice(0, uri.indexOf('#')):uri;
    var webidRes = $rdf.sym($scope.profile.webid);
    $scope.profile.loading = true;
    if (authenticated) {
      $scope.authenticated = true;
    }
    // fetch user data
    f.nowOrWhenFetched(docURI,undefined,function(ok, body, xhr) {
      if (!ok) {
        console.log('Warning - profile not found.');
        Notifier.error('Failed to fetch profile. HTTP '+xhr.status);
        $scope.profile.fullname = uri;
        $scope.profile.loading = false;
        $scope.loginButtonText = "Login";
        $scope.$apply();
      } else {
        if (xhr && xhr.getResponseHeader('User') && xhr.getResponseHeader('User') == uri) {
          $scope.profile.owner = true;
        } else if (authenticated) {
          $scope.profile.owner = true;
        }
        // set time of loading
        if (!$scope.profile.date) {
          $scope.profile.date = Date.now();
        }
        // save docURI to list of sources
        if (!$scope.profile.sources) {
          $scope.profile.sources = [];
        }
        if ($scope.profile.sources.indexOf(docURI) < 0) {
          $scope.profile.sources.push(docURI);
        }

        // try to fetch additional data from sameAs, seeAlso and preferenceFile
        if (!loadMore) {
          var sameAs = g.statementsMatching(webidRes, OWL('sameAs'), undefined);
          if (sameAs.length > 0) {
            sameAs.forEach(function(same){
              $scope.getProfile(same['object']['value'], false, true);
            });
          }
          var seeAlso = g.statementsMatching(webidRes, OWL('seeAlso'), undefined);
          if (seeAlso.length > 0) {
            seeAlso.forEach(function(see){
              $scope.getProfile(see['object']['value'], false, true);
            });
          }
          var prefs = g.statementsMatching(webidRes, SPACE('preferencesFile'), undefined);
          if (prefs.length > 0) {
            prefs.forEach(function(pref){
              if (pref['object']['value']) {
                $scope.getProfile(pref['object']['value'], false, true);
              }
            });
          }
        }

        // get info
        var fullname = g.statementsMatching(webidRes, FOAF('name'), undefined)[0];
        if (!fullname || fullname['object']['value'].length == 0) {
          fullname = $rdf.st(webidRes, FOAF('name'), $rdf.lit(''), $rdf.sym(''));
        }
        if (!$scope.profile.fullname) {
          $scope.profile.fullname = new $scope.ProfileElement(fullname);
        }
        // Firstname
        var firstname = g.statementsMatching(webidRes, FOAF('givenName'), undefined)[0];
        if (!firstname || firstname['object']['value'].length == 0) {
          firstname = $rdf.st(webidRes, FOAF('givenName'), $rdf.lit(''), $rdf.sym(''));
        }
        if (!$scope.profile.firstname) {
          $scope.profile.firstname = new $scope.ProfileElement(firstname);
        }
        // Lastname
        var lastname = g.statementsMatching(webidRes, FOAF('familyName'), undefined)[0];
        if (!lastname || lastname['object']['value'].length == 0) {
          lastname = $rdf.st(webidRes, FOAF('familyName'), $rdf.lit(''), $rdf.sym(''));
        }
        if (!$scope.profile.lastname) {
          $scope.profile.lastname = new $scope.ProfileElement(lastname);
        }
        // Nickname
        var nick = g.statementsMatching(webidRes, FOAF('nick'), undefined)[0];
        if (!nick || nick['object']['value'].length == 0) {
          nick = $rdf.st(webidRes, FOAF('nick'), $rdf.lit(''), $rdf.sym(''));
        }
        if (!$scope.profile.nick) {
          $scope.profile.nick = new $scope.ProfileElement(nick);
        }

        // Get profile picture
        var img = g.statementsMatching(webidRes, FOAF('img'), undefined)[0];
        var pic;
        if (img) {
          pic = img;
        } else {
          // check if profile uses depic instead
          var depic = g.statementsMatching(webidRes, FOAF('depiction'), undefined)[0];
          if (depic) {
            pic = depic;
          }
        }
        if (!pic || pic['object']['value'].length == 0) {
          pic = $rdf.st(webidRes, FOAF('img'), $rdf.sym(''), $rdf.sym(''));
        }
        if (!$scope.profile.picture) {
          $scope.profile.picture = new $scope.ProfileElement(pic);
        }
        // Phones
        var phones = g.statementsMatching(webidRes, FOAF('phone'), undefined);
        if (phones.length > 0) {
          phones.forEach(function(phone){
            if (!$scope.profile.phones) {
              $scope.profile.phones = [];
            }
            $scope.profile.phones.push(new $scope.ProfileElement(phone));
          });
        }

        // Emails
        var emails = g.statementsMatching(webidRes, FOAF('mbox'), undefined);
        if (emails.length > 0) {
          emails.forEach(function(email){
            if (!$scope.profile.emails) {
              $scope.profile.emails = [];
            }
            $scope.profile.emails.push(new $scope.ProfileElement(email));
          });
        }

        // Blogs
        var blogs = g.statementsMatching(webidRes, FOAF('weblog'), undefined);
        if (blogs.length > 0) {
          blogs.forEach(function(blog){
            if (!$scope.profile.blogs) {
              $scope.profile.blogs = [];
            }
            $scope.profile.blogs.push(new $scope.ProfileElement(blog));
          });
        }

        // Homepages
        var homepages = g.statementsMatching(webidRes, FOAF('homepage'), undefined);
        if (homepages.length > 0) {
          homepages.forEach(function(homepage){
            if (!$scope.profile.homepages) {
              $scope.profile.homepages = [];
            }
            $scope.profile.homepages.push(new $scope.ProfileElement(homepage));
          });
        }

        // Workpages
        var workpages = g.statementsMatching(webidRes, FOAF('workplaceHomepage'), undefined);
         if (workpages.length > 0) {
          workpages.forEach(function(workpage){
            if (!$scope.profile.workpages) {
              $scope.profile.workpages = [];
            }
            $scope.profile.workpages.push(new $scope.ProfileElement(workpage));
          });
        }

        $scope.profile.loading = false;
        $scope.$apply();

        // debug
        if (authenticated) {
          $scope.loginButtonText = "Login";
          var authUser = ($scope.profile.fullname.value)?" as "+$scope.profile.fullname.value:"";
          Notifier.success('Authenticated'+authUser);
          $scope.saveCredentials(true);
        }
      }
    });
  };

  $scope.saveCredentials = function (redirect) {
    var app = {
      profile: {
        webid: $scope.profile.webid,
        owner: $scope.profile.owner,
        date: $scope.profile.date
      },
      authenticated: $scope.authenticated
    };
    sessionStorage.setItem($scope.appuri, JSON.stringify(app));
    // redirect to view page
    if (redirect) {
      // switch to view once it's available
      $state.go('editProfile');
    }
  };

  $scope.login = function() {
    $scope.loginButtonText = 'Loggin in...';
    $http({
      method: 'HEAD',
      url: "https://rww.io/",
      withCredentials: true
    }).success(function(data, status, headers) {
      // add dir to local list
      var user = headers('User');
      if (user && user.length > 0 && user.slice(0,4) == 'http') {
        $scope.profile.webid = user;
        $scope.getProfile(user, true);
        $scope.loginButtonText = 'Logged in';
      } else {
        Notifier.warning('WebID-TLS authentication failed.');
        console.log('WebID-TLS authentication failed.');
      }
    }).error(function(data, status, headers) {
      Notifier.error('Could not connect to auth server: HTTP '+status);
      console.log('Could not connect to auth server: HTTP '+status);
      $scope.loginButtonText = 'Login done';
    });
  };

  // Logout WebID (only works in Firefox and IE)
  $scope.logout = function () {
    if (document.all == null) {
      if (window.crypto) {
          try{
              window.crypto.logout(); //firefox ok -- no need to follow the link
          } catch (err) {//Safari, Opera, Chrome -- try with tis session breaking
          }
      }
    } else { // MSIE 6+
      document.execCommand('ClearAuthenticationCache');
    }

    // clear sessionStorage
    $scope.clearLocalCredentials();
    $scope.profile = {};
    $scope.authenticated = false;
    $state.go('view', {}, {redirect: true});
  };

  // clear sessionStorage
  $scope.clearLocalCredentials = function () {
    sessionStorage.removeItem($scope.appuri);
  };

  $scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){
    if (angular.isDefined(toState.data.pageTitle)) {
      $scope.pageTitle = toState.data.pageTitle;
    }
  });

  // initialize by retrieving user info from sessionStorage
  // retrieve from sessionStorage
  if (sessionStorage.getItem($scope.appuri)) {
    var app = JSON.parse(sessionStorage.getItem($scope.appuri));
    if (app) {
      if (!$scope.profile) {
        $scope.profile = {};
      }
      // don't let session data become stale (24h validity)
      var dateValid = app.profile.date + 1000 * 60 * 60 * 24;
      if (Date.now() < dateValid) {
        $scope.profile = app.profile;
        $scope.authenticated = app.authenticated;
        $scope.getProfile(app.profile.webid);
      } else {
        console.log("Deleting profile because of date");
        sessionStorage.removeItem($scope.appuri);
      }
    } else {
      // clear sessionStorage in case there was a change to the data structure
      console.log("Deleting profile because of structure");
      sessionStorage.removeItem($scope.appuri);
    }
  }

  var webid = getParam('webid');
  if (webid && webid.length > 0 && !$scope.profile.webid) {
    $scope.webid = webid;
    $scope.getProfile(webid, false);
  }
})
//simple directive to display list of channels
.directive('profileCard',function(){
    return {
      replace : true,
      restrict : 'E',
      templateUrl: 'app/profileCard.tpl.html'
    };
})

//simple directive to display list of channels
.directive('spinner',function(){
    return {
      replace : true,
      restrict : 'E',
      templateUrl: 'app/spinner.tpl.html'
    };
});
<|endoftext|>


<commit_before>Router.route('home', {
  path: '/:newsLimit?',
  template: 'Home',
  data: function() {
    var news = [{
      dateTime: 'December 19, 2014',
      text: 'December Devshop SF: Advances in MongoDB scalability, Meteor + Polymer, reactive MySQL, and more'
    }, {
      dateTime: 'December 10, 2014',
      text: 'Meteor Day Recap: 4,259 developers at 134 meetups on one day'
    }, {
      dateTime: 'December 9, 2014',
      text: 'Meteor 1.0.1: security fix for allow/deny rules'
    }, {
      dateTime: 'October 28, 2014',
      text: 'Meteor 1.0'
    }];
    return {
      news: news.slice(0, this.params.newsLimit)
    };
  }
});

Router.route('aboutUs');<commit_msg>Use regular expression for 'home' router path.<commit_after>Router.route('home', {
  path: /^\/news\/(\d*)/,
  template: 'Home',
  data: function() {
    var news = [{
      dateTime: 'December 19, 2014',
      text: 'December Devshop SF: Advances in MongoDB scalability, Meteor + Polymer, reactive MySQL, and more'
    }, {
      dateTime: 'December 10, 2014',
      text: 'Meteor Day Recap: 4,259 developers at 134 meetups on one day'
    }, {
      dateTime: 'December 9, 2014',
      text: 'Meteor 1.0.1: security fix for allow/deny rules'
    }, {
      dateTime: 'October 28, 2014',
      text: 'Meteor 1.0'
    }];
    return {
      news: news.slice(0, this.params[0])
    };
  }
});

Router.route('aboutUs');<|endoftext|>


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

// Declare app level module which depends on views, and components
    angular.module('mesero', ['oc.lazyLoad',
        'ngRoute',
        //'ngAnimate',
        'angular-jwt',
        'auth0',
        'mvUtils',
        'mvAutocomplete',
        'mvUsuarios',
        'mvUsuariosAdministracion',
        'mvClientesAdministracion',
        'mvProveedoresAdministracion',
        'mvSucursales',
        'mvSucursalesAdministracion',
        'mvUploads',
        'mvProductos',
        'mvProductosAdministracion',
        'mvCategoriasAdministracion',
        'mvProductoTipoAdministracion',
        'mvStocks',
        'mvMovimientos',
        'mvCajas',
        'mvCobros',
        'mvResumenCajaDiaria',
        'mvAbrirCerrarCaja',
        'mvReportes',
        'mvReporteTraslado',
        'mvContacts',
        'mvEncomiendas',
        'mvTraslado',
        'mvDeudores',
        'mvAvisos',
        'mvAvisosAdministracion',
        'mvNotificaciones',
        'mvComandas',
        'mvMonitor',
        'mvEnvios',
        'mvMesas',
        'mvMesasAdministracion',
        'mvPedidosAdministracion',
        'mvPedidosDetalles',
        'LangTables',
        'acHelper',
    ]).config(['$locationProvider', '$routeProvider', function ($locationProvider, $routeProvider) {
        $locationProvider.hashPrefix('!');

        $routeProvider.otherwise({redirectTo: '/'});

        /*
        $routeProvider.when('/settings/controles', {
            templateUrl: 'controles/controles.html',
            controller: 'ControlesCtrl',
            //data: {requiresLogin: false},
            resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                    // you can lazy load files for an existing module
                    return $ocLazyLoad.load('controles/controles.js');
                }]
            }
        });
        */

        $routeProvider.when('/caja/cobros', {
            templateUrl: 'cobros/cobros.html',
            controller: 'CobrosCtrl',
            data: {requiresLogin: true},
            resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                    // you can lazy load files for an existing module
                    return $ocLazyLoad.load('cobros/cobros.js');
                }]
            }
        });

        $routeProvider.when('/caja/abrir_cerrar_caja', {
            templateUrl: 'abrir_cerrar_caja/abrir_cerrar_caja.html',
            controller: 'AbrirCerrarCajaCtrl',
            data: {requiresLogin: true},
            resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                    // you can lazy load files for an existing module
                    return $ocLazyLoad.load('abrir_cerrar_caja/abrir_cerrar_caja.js');
                }]
            }
        });

        $routeProvider.when('/caja/gastos', {
            templateUrl: 'gastos/gastos.html',
            controller: 'GastosCtrl',
            data: {requiresLogin: true},
            resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                    // you can lazy load files for an existing module
                    return $ocLazyLoad.load('gastos/gastos.js');
                }]
            }
        });

        $routeProvider.when('/caja/depositos', {
            templateUrl: 'depositos/depositos.html',
            controller: 'DepositosCtrl',
            data: {requiresLogin: true},
            resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                    // you can lazy load files for an existing module
                    return $ocLazyLoad.load('depositos/depositos.js');
                }]
            }
        });

        $routeProvider.when('/caja/movimientos', {
            templateUrl: 'movimientos/movimientos.html',
            controller: 'MovimientoCtrl',
            data: {requiresLogin: true},
            resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                    // you can lazy load files for an existing module
                    return $ocLazyLoad.load('movimientos/movimientos.js');
                }]
            }
        });

        $routeProvider.when('/caja/detalle_caja', {
            templateUrl: 'detalle_caja/detalle_caja.html',
            controller: 'DetalleCajaCtrl',
            data: {requiresLogin: true},
            resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                    // you can lazy load files for an existing module
                    return $ocLazyLoad.load('detalle_caja/detalle_caja.js');
                }]
            }
        });

        $routeProvider.when('/settings/clientes', {
            templateUrl: 'clientes/clientes.html',
            controller: 'ClienteCtrl',
            data: {requiresLogin: true},
            resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                    // you can lazy load files for an existing module
                    return $ocLazyLoad.load('clientes/clientes.js');
                }]
            }
        });

        $routeProvider.when('/settings/proveedores', {
            templateUrl: 'proveedores/proveedores.html',
            controller: 'ProveedoresCtrl',
            data: {requiresLogin: true},
            resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                    // you can lazy load files for an existing module
                    return $ocLazyLoad.load('proveedores/proveedores.js');
                }]
            }
        });

        $routeProvider.when('/settings/usuarios', {
            templateUrl: 'usuarios/usuarios.html',
            controller: 'UsuariosCtrl',
            data: {requiresLogin: true},
            resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                    // you can lazy load files for an existing module
                    return $ocLazyLoad.load('usuarios/usuarios.js');
                }]
            }
        });

        $routeProvider.when('/settings/productos', {
            templateUrl: 'productos/productos.html',
            controller: 'ProductosCtrl',
            data: {requiresLogin: true},
            resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                    // you can lazy load files for an existing module
                    return $ocLazyLoad.load('productos/productos.js');
                }]
            }
        });

        $routeProvider.when('/settings/sucursales', {
            templateUrl: 'sucursales/sucursales.html',
            controller: 'SucursalesCtrl',
            data: {requiresLogin: true},
            resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                    // you can lazy load files for an existing module
                    return $ocLazyLoad.load('sucursales/sucursales.js');
                }]
            }
        });

        $routeProvider.when('/settings/categorias', {
            templateUrl: 'categorias/categorias.html',
            controller: 'CategoriasCtrl',
            data: {requiresLogin: true},
            resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                    // you can lazy load files for an existing module
                    return $ocLazyLoad.load('categorias/categorias.js');
                }]
            }
        });

        $routeProvider.when('/settings/productostipo', {
            templateUrl: 'productostipo/productostipo.html',
            controller: 'ProductosTipoCtrl',
            data: {requiresLogin: true},
            resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                    // you can lazy load files for an existing module
                    return $ocLazyLoad.load('productostipo/productostipo.js');
                }]
            }
        });

        $routeProvider.when('/settings/avisos', {
            templateUrl: 'avisos/avisos.html',
            controller: 'AvisosCtrl',
            data: {requiresLogin: true},
            resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                    // you can lazy load files for an existing module
                    return $ocLazyLoad.load('avisos/avisos.js');
                }]
            }
        });

        $routeProvider.when('/settings/salon', {
            templateUrl: 'salon/salon.html',
            controller: 'SalonCtrl',
            data: {requiresLogin: true},
            resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                    // you can lazy load files for an existing module
                    return $ocLazyLoad.load('salon/salon.js');
                }]
            }
        });

        $routeProvider.when('/working', {
            templateUrl: 'working/working.html',
            controller: 'WorkingCtrl',
            data: {requiresLogin: false},
            resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                    // you can lazy load files for an existing module
                    return $ocLazyLoad.load('working/working.js');
                }]
            }
        });

        $routeProvider.when('/login', {
            templateUrl: 'login/login.html',
            controller: 'LoginController',
            data: {requiresLogin: false},
            resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                    // you can lazy load files for an existing module
                    return $ocLazyLoad.load('login/login.js');
                }]
            }
        });

        $routeProvider.when('/reportes/deudores', {
            templateUrl: 'deudores/deudores.html',
            controller: 'DeudoresCtrl',
            data: {requiresLogin: true},
            resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                    // you can lazy load files for an existing module
                    return $ocLazyLoad.load('deudores/deudores.js');
                }]
            }
        });

        $routeProvider.when('/reportes/pedidos', {
            templateUrl: 'pedidos/pedidos.html',
            controller: 'PedidosCtrl',
            data: {requiresLogin: true},
            resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                    // you can lazy load files for an existing module
                    return $ocLazyLoad.load('pedidos/pedidos.js');
                }]
            }
        });

        $routeProvider.when('/cocina/comandas', {
            templateUrl: 'comandas/comandas.html',
            controller: 'ComandasCtrl',
            data: {requiresLogin: true},
            resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                    // you can lazy load files for an existing module
                    return $ocLazyLoad.load('comandas/comandas.js');
                }]
            }
        });

    }]).controller('AppCtrl', AppCtrl);

    AppCtrl.$inject = ['$scope', '$location'];
    function AppCtrl($scope, $location) {

        var vm = this;
        vm.hideLoader = true;
        vm.sub_menu_mobile_open = false;

        vm.goToPagina = goToPagina;

        function goToPagina(page) {
            $location.path(page);
        }

    }

})();
<commit_msg>Mateo<commit_after>(function () {
    'use strict';

// Declare app level module which depends on views, and components
    angular.module('mesero', ['oc.lazyLoad',
        'ngRoute',
        //'ngAnimate',
        'angular-jwt',
        'auth0',
        'mvUtils',
        'mvAutocomplete',
        'mvUsuarios',
        'mvUsuariosAdministracion',
        'mvClientesAdministracion',
        'mvProveedoresAdministracion',
        'mvSucursales',
        'mvSucursalesAdministracion',
        'mvUploads',
        'mvProductos',
        'mvProductosAdministracion',
        'mvCategoriasAdministracion',
        'mvProductoTipoAdministracion',
        'mvStocks',
        'mvMovimientos',
        'mvCajas',
        'mvCobros',
        'mvResumenCajaDiaria',
        'mvAbrirCerrarCaja',
        'mvReportes',
        'mvReporteTraslado',
        'mvContacts',
        'mvEncomiendas',
        'mvTraslado',
        'mvDeudores',
        'mvAvisos',
        'mvAvisosAdministracion',
        'mvNotificaciones',
        'mvComandas',
        'mvMonitor',
        'mvEnvios',
        'mvMesas',
        'mvMesasAdministracion',
        'mvPedidosAdministracion',
        'mvPedidosDetalles',
        'LangTables',
        'acHelper',
    ]).config(['$locationProvider', '$routeProvider', function ($locationProvider, $routeProvider) {
        $locationProvider.hashPrefix('!');

        $routeProvider.otherwise({redirectTo: '/'});

        /*
        $routeProvider.when('/settings/controles', {
            templateUrl: 'controles/controles.html',
            controller: 'ControlesCtrl',
            //data: {requiresLogin: false},
            resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                    // you can lazy load files for an existing module
                    return $ocLazyLoad.load('controles/controles.js');
                }]
            }
        });
        */

        $routeProvider.when('/caja/cobros', {
            templateUrl: 'cobros/cobros.html',
            controller: 'CobrosCtrl',
            data: {requiresLogin: true},
            resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                    // you can lazy load files for an existing module
                    return $ocLazyLoad.load('cobros/cobros.js');
                }]
            }
        });

        $routeProvider.when('/caja/abrir_cerrar_caja', {
            templateUrl: 'abrir_cerrar_caja/abrir_cerrar_caja.html',
            controller: 'AbrirCerrarCajaCtrl',
            data: {requiresLogin: true},
            resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                    // you can lazy load files for an existing module
                    return $ocLazyLoad.load('abrir_cerrar_caja/abrir_cerrar_caja.js');
                }]
            }
        });

        $routeProvider.when('/caja/gastos', {
            templateUrl: 'gastos/gastos.html',
            controller: 'GastosCtrl',
            data: {requiresLogin: true},
            resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                    // you can lazy load files for an existing module
                    return $ocLazyLoad.load('gastos/gastos.js');
                }]
            }
        });

        $routeProvider.when('/caja/depositos', {
            templateUrl: 'depositos/depositos.html',
            controller: 'DepositosCtrl',
            data: {requiresLogin: true},
            resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                    // you can lazy load files for an existing module
                    return $ocLazyLoad.load('depositos/depositos.js');
                }]
            }
        });

        $routeProvider.when('/caja/movimientos', {
            templateUrl: 'movimientos/movimientos.html',
            controller: 'MovimientoCtrl',
            data: {requiresLogin: true},
            resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                    // you can lazy load files for an existing module
                    return $ocLazyLoad.load('movimientos/movimientos.js');
                }]
            }
        });

        $routeProvider.when('/caja/detalle_caja', {
            templateUrl: 'detalle_caja/detalle_caja.html',
            controller: 'DetalleCajaCtrl',
            data: {requiresLogin: true},
            resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                    // you can lazy load files for an existing module
                    return $ocLazyLoad.load('detalle_caja/detalle_caja.js');
                }]
            }
        });

        $routeProvider.when('/settings/clientes', {
            templateUrl: 'clientes/clientes.html',
            controller: 'ClienteCtrl',
            data: {requiresLogin: true},
            resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                    // you can lazy load files for an existing module
                    return $ocLazyLoad.load('clientes/clientes.js');
                }]
            }
        });

        $routeProvider.when('/settings/proveedores', {
            templateUrl: 'proveedores/proveedores.html',
            controller: 'ProveedoresCtrl',
            data: {requiresLogin: true},
            resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                    // you can lazy load files for an existing module
                    return $ocLazyLoad.load('proveedores/proveedores.js');
                }]
            }
        });

        $routeProvider.when('/settings/usuarios', {
            templateUrl: 'usuarios/usuarios.html',
            controller: 'UsuariosCtrl',
            data: {requiresLogin: true},
            resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                    // you can lazy load files for an existing module
                    return $ocLazyLoad.load('usuarios/usuarios.js');
                }]
            }
        });

        $routeProvider.when('/settings/productos', {
            templateUrl: 'productos/productos.html',
            controller: 'ProductosCtrl',
            data: {requiresLogin: true},
            resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                    // you can lazy load files for an existing module
                    return $ocLazyLoad.load('productos/productos.js');
                }]
            }
        });

        $routeProvider.when('/settings/sucursales', {
            templateUrl: 'sucursales/sucursales.html',
            controller: 'SucursalesCtrl',
            data: {requiresLogin: true},
            resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                    // you can lazy load files for an existing module
                    return $ocLazyLoad.load('sucursales/sucursales.js');
                }]
            }
        });

        $routeProvider.when('/settings/categorias', {
            templateUrl: 'categorias/categorias.html',
            controller: 'CategoriasCtrl',
            data: {requiresLogin: true},
            resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                    // you can lazy load files for an existing module
                    return $ocLazyLoad.load('categorias/categorias.js');
                }]
            }
        });

        $routeProvider.when('/settings/productostipo', {
            templateUrl: 'productostipo/productostipo.html',
            controller: 'ProductosTipoCtrl',
            data: {requiresLogin: true},
            resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                    // you can lazy load files for an existing module
                    return $ocLazyLoad.load('productostipo/productostipo.js');
                }]
            }
        });

        $routeProvider.when('/settings/avisos', {
            templateUrl: 'avisos/avisos.html',
            controller: 'AvisosCtrl',
            data: {requiresLogin: true},
            resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                    // you can lazy load files for an existing module
                    return $ocLazyLoad.load('avisos/avisos.js');
                }]
            }
        });

        $routeProvider.when('/settings/salon', {
            templateUrl: 'salon/salon.html',
            controller: 'SalonCtrl',
            data: {requiresLogin: true},
            resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                    // you can lazy load files for an existing module
                    return $ocLazyLoad.load('salon/salon.js');
                }]
            }
        });

        $routeProvider.when('/working', {
            templateUrl: 'working/working.html',
            controller: 'WorkingCtrl',
            data: {requiresLogin: false},
            resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                    // you can lazy load files for an existing module
                    return $ocLazyLoad.load('working/working.js');
                }]
            }
        });

        $routeProvider.when('/login', {
            templateUrl: 'login/login.html',
            controller: 'LoginController',
            data: {requiresLogin: false},
            resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                    // you can lazy load files for an existing module
                    return $ocLazyLoad.load('login/login.js');
                }]
            }
        });

        $routeProvider.when('/reportes/deudores', {
            templateUrl: 'deudores/deudores.html',
            controller: 'DeudoresCtrl',
            data: {requiresLogin: true},
            resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                    // you can lazy load files for an existing module
                    return $ocLazyLoad.load('deudores/deudores.js');
                }]
            }
        });

        $routeProvider.when('/reportes/pedidos', {
            templateUrl: 'pedidos/pedidos.html',
            controller: 'PedidosCtrl',
            data: {requiresLogin: true},
            resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                    // you can lazy load files for an existing module
                    return $ocLazyLoad.load('pedidos/pedidos.js');
                }]
            }
        });

        $routeProvider.when('/cocina/comandas', {
            templateUrl: 'comandas/comandas.html',
            controller: 'ComandasCtrl',
            data: {requiresLogin: true},
            resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                    // you can lazy load files for an existing module
                    return $ocLazyLoad.load('comandas/comandas.js');
                }]
            }
        });

    }]).controller('AppCtrl', AppCtrl);

    AppCtrl.$inject = ['$scope', '$location'];
    function AppCtrl($scope, $location) {

        var vm = this;
        vm.hideLoader = true;
        vm.sub_menu_mobile_open = false;

        vm.goToPagina = goToPagina;

        function goToPagina(page) {
            $location.path(page);
        }

    }

})();
<|endoftext|>


<commit_before>//
// Copyright (c) 2014 by Ark.com. All Rights Reserved.
// Created by Vitaly Aminev <v@aminev.me>
//

var _ArkAPIKeyPlaceholder = 'your-ark-api-key';

angular.module('ArkSDK.config', [])
  // In the production mode you have to specify API key here
  .value('ArkAPIKey', _globalArkAPIKey || _ArkAPIKeyPlaceholder)
  // list of available networks
  .constant('ArkAvailableNetworks', {
    'AngelList': 'angellist',
    'Behance': 'behance',
    'Blogger': 'blogger',
    'Care2.com': 'care2',
    'Cruncbase': 'crunchbase',
    'deviantART': 'deviantart',
    'Dribbble': 'dribbble',
    'Facebook': 'facebook',
    'Flavors.me': 'flavorsme',
    'Flickr': 'flickr',
    'FourSquare': 'foursquare',
    'GitHub': 'github',
    'Google+': 'googleplus',
    'Hacker News': 'hackernews',
    'Instagram': 'instagram',
    'Keek': 'keek',
    'Last.fm': 'lastfm',
    'LinkedIn': 'linkedin',
    'Meetup': 'meetup',
    'Newsle': 'newsle',
    'Pinterest': 'pinterest',
    '500px.com': '500px',
    'Quora': 'quora',
    'SoundCloud': 'soundcloud',
    'StackOverflow': 'stackoverflow',
    'Spotify': 'spotify',
    'Sprasivai.ru': 'sprashivairu',
    'Svpply': 'svpply',
    'Tumblr': 'tumblr',
    'Twitter': 'twitter',
    'VK': 'vk',
    'Vimeo': 'vimeo',
    'Wanelo': 'wanelo',
    'WordPress': 'wordpress',
    'Xing': 'xing',
    'Ya.ru': 'yaru',
    'Yelp': 'yelp',
    'Youtube': 'youtube'
  });

angular.module('ArkSDK', [
    'restangular',
    'ArkSDK.config'
  ]);

// Restangular service that uses Bing
angular.module('ArkSDK')
  .factory('ArkRestangular', [
    'Restangular',
    'ArkAPIKey',
    function (Restangular, ArkAPIKey) {
      return Restangular.withConfig(function(RestangularConfigurer) {

        if (_ArkAPIKeyPlaceholder !== ArkAPIKey) {
          RestangularConfigurer.setDefaultHeaders({"x-ark-token": ArkAPIKey});
        } else {
          var warn =  'Please, specify your own API KEY\n' +
                      'It can be done by adding this code to your module\n' +
                      'angular.module(\'ArkSDK.config\').config(["$provide", function ($provide) {\n' +
                      ' $provide.decorator(\'ArkAPIKey\', function () {\n' +
                      '   return \'real-ark-token\';\n' +
                      ' });\n' +
                      '}]);\n' +
                      '\n' +
                      'Or by setting `window._globalArkAPIKey = `your-arpi-key`;';
          console.error(warn);
        }

        RestangularConfigurer.setBaseUrl('https://ng.ark.com/api/1');

        // If you need to disable caching - do it here
        RestangularConfigurer.setDefaultHttpFields({cache: true});
      });
    }
  ]);
<commit_msg>fix _globalArkAPIKey<commit_after>//
// Copyright (c) 2014 by Ark.com. All Rights Reserved.
// Created by Vitaly Aminev <v@aminev.me>
//

var _ArkAPIKeyPlaceholder = 'your-ark-api-key';

angular.module('ArkSDK.config', [])
  // In the production mode you have to specify API key here
  .value('ArkAPIKey', window._globalArkAPIKey || _ArkAPIKeyPlaceholder)
  // list of available networks
  .constant('ArkAvailableNetworks', {
    'AngelList': 'angellist',
    'Behance': 'behance',
    'Blogger': 'blogger',
    'Care2.com': 'care2',
    'Cruncbase': 'crunchbase',
    'deviantART': 'deviantart',
    'Dribbble': 'dribbble',
    'Facebook': 'facebook',
    'Flavors.me': 'flavorsme',
    'Flickr': 'flickr',
    'FourSquare': 'foursquare',
    'GitHub': 'github',
    'Google+': 'googleplus',
    'Hacker News': 'hackernews',
    'Instagram': 'instagram',
    'Keek': 'keek',
    'Last.fm': 'lastfm',
    'LinkedIn': 'linkedin',
    'Meetup': 'meetup',
    'Newsle': 'newsle',
    'Pinterest': 'pinterest',
    '500px.com': '500px',
    'Quora': 'quora',
    'SoundCloud': 'soundcloud',
    'StackOverflow': 'stackoverflow',
    'Spotify': 'spotify',
    'Sprasivai.ru': 'sprashivairu',
    'Svpply': 'svpply',
    'Tumblr': 'tumblr',
    'Twitter': 'twitter',
    'VK': 'vk',
    'Vimeo': 'vimeo',
    'Wanelo': 'wanelo',
    'WordPress': 'wordpress',
    'Xing': 'xing',
    'Ya.ru': 'yaru',
    'Yelp': 'yelp',
    'Youtube': 'youtube'
  });

angular.module('ArkSDK', [
    'restangular',
    'ArkSDK.config'
  ]);

// Restangular service that uses Bing
angular.module('ArkSDK')
  .factory('ArkRestangular', [
    'Restangular',
    'ArkAPIKey',
    function (Restangular, ArkAPIKey) {
      return Restangular.withConfig(function(RestangularConfigurer) {

        if (_ArkAPIKeyPlaceholder !== ArkAPIKey) {
          RestangularConfigurer.setDefaultHeaders({"x-ark-token": ArkAPIKey});
        } else {
          var warn =  'Please, specify your own API KEY\n' +
                      'It can be done by adding this code to your module\n' +
                      'angular.module(\'ArkSDK.config\').config(["$provide", function ($provide) {\n' +
                      ' $provide.decorator(\'ArkAPIKey\', function () {\n' +
                      '   return \'real-ark-token\';\n' +
                      ' });\n' +
                      '}]);\n' +
                      '\n' +
                      'Or by setting `window._globalArkAPIKey = `your-arpi-key`;';
          console.error(warn);
        }

        RestangularConfigurer.setBaseUrl('https://ng.ark.com/api/1');

        // If you need to disable caching - do it here
        RestangularConfigurer.setDefaultHttpFields({cache: true});
      });
    }
  ]);
<|endoftext|>


<commit_before>var assert = require('chai').assert;
var nodemock = require('nodemock');
var Deferred = require('jsdeferred').Deferred;
var express = require('express');

var utils = require('./test-utils');

var adaptor = require('../index');
var model = require('../lib/model');
var Connection = require('../lib/backend/connection').Connection;

suite('Adaption for express application', function() {
  suite('REST API registeration', function() {
    var testPlugin = {
      api: new model.REST({
        path: '/path/to/api',
        toBackend: function() { return 'api requested'; },
        toClient: function() { return 'api OK'; }
      })
    };

    var connection;
    var application;
    var server;

    setup(function(done) {
      connection = utils.createMockedBackendConnection(utils.socketIoDefaultCommandsModule);
      application = express();
      utils.setupServer(application)
        .next(function(newServer) {
          server = newServer;
          done();
        });
    });

    teardown(function() {
      if (connection) {
        utils.readyToDestroyMockedConnection(connection);
        connection = undefined;
      }
      if (server) {
        server.close();
        server = undefined;
      }
    });

    test('to the document root', function(done) {
      var onReceive = {};
      connection
        .mock('emitMessage')
          .takes('api', 'api requested', function() {}, { 'timeout': null })
          .ctrl(2, onReceive);

      application.kotoumi({
        prefix:     '',
        connection: connection,
        plugins:    [testPlugin]
      });

      var responseBody;
      Deferred
        .wait(0.01)
        .next(function() {
          utils.get('/path/to/api')
            .next(function(response) {
              responseBody = response.body;
            });
        })
        .wait(0.01)
        .next(function() {
          onReceive.trigger(null, { body: 'API OK?' });
        })
        .wait(0.01)
        .next(function() {
          assert.equal(responseBody, 'api OK');
          done();
        })
        .error(function(error) {
          done(error);
        });
    });

    test('under specified path', function(done) {
      var onReceive = {};
      connection
        .mock('emitMessage')
          .takes('api', 'api requested', function() {}, { 'timeout': null })
          .ctrl(2, onReceive);

      application.kotoumi({
        prefix:     '/path/to/kotoumi',
        connection: connection,
        plugins:    [testPlugin]
      });

      var responseBody;
      Deferred
        .wait(0.01)
        .next(function() {
          utils.get('/path/to/kotoumi/path/to/api')
            .next(function(response) {
              responseBody = response.body;
            });
        })
        .wait(0.01)
        .next(function() {
          onReceive.trigger(null, { body: 'API OK?' });
        })
        .wait(0.01)
        .next(function() {
          assert.equal(responseBody, 'api OK');
          done();
        })
        .error(function(error) {
          done(error);
        });
    });
  });

  suite('Socket.IO API registeration', function() {
    var connection;
    var server;
    var clientSocket;

    teardown(function() {
      if (connection) {
        utils.readyToDestroyMockedConnection(connection);
        connection = undefined;
      }
      if (clientSocket) {
        clientSocket.disconnect();
        clientSocket = undefined;
      }
      if (server) {
        server.close();
        server = undefined;
      }
    });

    test('front to back', function(done) {
      connection = utils.createMockedBackendConnection(utils.socketIoDefaultCommandsModule)
        .mock('emitMessage')
          .takes('search',
                 { requestMessage: true },
                 function() {},
                 { timeout: 10 * 1000 });

      var application = express();
      utils.setupServer(application)
        .next(function(newServer) {
          server = newServer;
          application.kotoumi({
            connection: connection,
            server:     server
          });

          return utils.createClientSocket();
        })
        .next(function(newClientSocket) {
          clientSocket = newClientSocket;
          clientSocket.emit('search', { requestMessage: true });
        })
        .wait(0.01)
        .next(function() {
          connection.assertThrows();
          done();
        })
        .error(function(error) {
          done(error);
        });
    });

    test('back to front', function(done) {
      var onResponse = {};
      connection = utils.createMockedBackendConnection(utils.socketIoDefaultCommandsModule)
        .mock('emitMessage')
          .takes('search',
                 { requestMessage: true },
                 function() {},
                 { timeout: 10 * 1000 })
          .ctrl(2, onResponse);

      var clientReceiver = nodemock
            .mock('receive')
            .takes({ searchResult: true });

      var application = express();
      utils.setupServer(application)
        .next(function(newServer) {
          server = newServer;
          application.kotoumi({
            connection: connection,
            server:     server
          });

          return utils.createClientSocket();
        })
        .next(function(newClientSocket) {
          clientSocket = newClientSocket;

          clientSocket.on('search.result', function(data) {
            clientReceiver.receive(data);
          });
          clientSocket.emit('search', { requestMessage: true });
        })
        .wait(0.1)
        .next(function() {
          connection.assertThrows();
          var envelope = {
            type:       'search.result',
            statusCode: 200,
            body:       { searchResult: true}
          };
          onResponse.trigger(envelope);
        })
        .wait(0.01)
        .next(function() {
          clientReceiver.assertThrows();
          done();
        })
        .error(function(error) {
          done(error);
        });
    });
  });
});

<commit_msg>Update definition of stub plugins for the new plugin system<commit_after>var assert = require('chai').assert;
var nodemock = require('nodemock');
var Deferred = require('jsdeferred').Deferred;
var express = require('express');

var utils = require('./test-utils');

var adaptor = require('../index');
var model = require('../lib/model');
var Connection = require('../lib/backend/connection').Connection;

suite('Adaption for express application', function() {
  suite('REST API registeration', function() {
    var testPlugin = {
      api: new model.REST({
        path: '/path/to/api',
        toBackend: function(event, request) { return [event, 'api requested']; },
        toClient: function(event, data) { return [event, 'api OK']; }
      })
    };

    var connection;
    var application;
    var server;

    setup(function(done) {
      connection = utils.createMockedBackendConnection(utils.socketIoDefaultCommandsModule);
      application = express();
      utils.setupServer(application)
        .next(function(newServer) {
          server = newServer;
          done();
        });
    });

    teardown(function() {
      if (connection) {
        utils.readyToDestroyMockedConnection(connection);
        connection = undefined;
      }
      if (server) {
        server.close();
        server = undefined;
      }
    });

    test('to the document root', function(done) {
      var onReceive = {};
      connection = connection
        .mock('emitMessage')
          .takes('api', 'api requested', function() {}, { 'timeout': null })
          .ctrl(2, onReceive);

      application.kotoumi({
        prefix:     '',
        connection: connection,
        plugins:    [testPlugin]
      });

      var responseBody;
      Deferred
        .wait(0.01)
        .next(function() {
          utils.get('/path/to/api')
            .next(function(response) {
              responseBody = response.body;
            });
        })
        .wait(0.01)
        .next(function() {
          connection.assertThrows();
          onReceive.trigger(null, { body: 'API OK?' });
        })
        .wait(0.01)
        .next(function() {
          assert.equal(responseBody, 'api OK');
          done();
        })
        .error(function(error) {
          done(error);
        });
    });

    test('under specified path', function(done) {
      var onReceive = {};
      connection = connection
        .mock('emitMessage')
          .takes('api', 'api requested', function() {}, { 'timeout': null })
          .ctrl(2, onReceive);

      application.kotoumi({
        prefix:     '/path/to/kotoumi',
        connection: connection,
        plugins:    [testPlugin]
      });

      var responseBody;
      Deferred
        .wait(0.01)
        .next(function() {
          utils.get('/path/to/kotoumi/path/to/api')
            .next(function(response) {
              responseBody = response.body;
            });
        })
        .wait(0.01)
        .next(function() {
          connection.assertThrows();
          onReceive.trigger(null, { body: 'API OK?' });
        })
        .wait(0.01)
        .next(function() {
          assert.equal(responseBody, 'api OK');
          done();
        })
        .error(function(error) {
          done(error);
        });
    });
  });

  suite('Socket.IO API registeration', function() {
    var connection;
    var server;
    var clientSocket;

    teardown(function() {
      if (connection) {
        utils.readyToDestroyMockedConnection(connection);
        connection = undefined;
      }
      if (clientSocket) {
        clientSocket.disconnect();
        clientSocket = undefined;
      }
      if (server) {
        server.close();
        server = undefined;
      }
    });

    test('front to back', function(done) {
      connection = utils.createMockedBackendConnection(utils.socketIoDefaultCommandsModule)
        .mock('emitMessage')
          .takes('search',
                 { requestMessage: true },
                 function() {},
                 { timeout: 10 * 1000 });

      var application = express();
      utils.setupServer(application)
        .next(function(newServer) {
          server = newServer;
          application.kotoumi({
            connection: connection,
            server:     server
          });

          return utils.createClientSocket();
        })
        .next(function(newClientSocket) {
          clientSocket = newClientSocket;
          clientSocket.emit('search', { requestMessage: true });
        })
        .wait(0.01)
        .next(function() {
          connection.assertThrows();
          done();
        })
        .error(function(error) {
          done(error);
        });
    });

    test('back to front', function(done) {
      var onResponse = {};
      connection = utils.createMockedBackendConnection(utils.socketIoDefaultCommandsModule)
        .mock('emitMessage')
          .takes('search',
                 { requestMessage: true },
                 function() {},
                 { timeout: 10 * 1000 })
          .ctrl(2, onResponse);

      var clientReceiver = nodemock
            .mock('receive')
            .takes({ searchResult: true });

      var application = express();
      utils.setupServer(application)
        .next(function(newServer) {
          server = newServer;
          application.kotoumi({
            connection: connection,
            server:     server
          });

          return utils.createClientSocket();
        })
        .next(function(newClientSocket) {
          clientSocket = newClientSocket;

          clientSocket.on('search.result', function(data) {
            clientReceiver.receive(data);
          });
          clientSocket.emit('search', { requestMessage: true });
        })
        .wait(0.1)
        .next(function() {
          connection.assertThrows();
          var envelope = {
            type:       'search.result',
            statusCode: 200,
            body:       { searchResult: true}
          };
          onResponse.trigger(envelope);
        })
        .wait(0.01)
        .next(function() {
          clientReceiver.assertThrows();
          done();
        })
        .error(function(error) {
          done(error);
        });
    });
  });
});

<|endoftext|>


<commit_before>/**
 * test Constructor.extend() with natives
 *
 * YES!  You can extend native constructors, provided you are aware of a couple things.
 * In this set of tests, we'll use extend to subclass the Array constructor and provide workarounds for
 * for constructor initialization and [[Class]] dependent methods (toString()).
 *
 * BUT ~ 2 tests provided by @Raynos2 show that modifying the length property directly has side-
 * effects (like clobbering the array).
 *
 */

var test = require('tape');
var Constructor = require('../../src/Constructor.js').Constructor;

/*
 * FIXTURE - fairly complete example of extending the native built-in Arrays.
 *
 * NOTE:  the first argument here should be the Array constructor.
 */
var SubArray = Constructor.extend(Array, {
  constructor: function () {
    this.parent();

    // stolen from kangax (http://bit.ly/W66vQW)
    this.push.apply(this, arguments);
  },

  // borrowed from kangax (http://bit.ly/W66vQW)
  last: function () {
    return this[this.length - 1];
  },

  /**
   * @method toString - must be defined explicitly
   *
   * kangax (http://bit.ly/W66vQW), David Herman in Effective JavaScript (item 40, pp. 106ff), and some
   * learning tests tell us that the Array.prototype.toString() method fails on objects whose
   * constructor is not really an Array - due to the internal use of [[Class]] by JavaScript engine -
   * so we'll have to shim it.  For IE 6-8 we have to return an Array instance directly.
   */
  toString: function () {

    var delimiter = '';
    var comma = ',';
    var arrayString = '';

    for (var i = 0; i < this.length; i += 1) {
        arrayString += delimiter + this[i];

        delimiter = comma;
    }

    return arrayString;
  },

  /**
   * @method concat - must be defined explicitly
   *
   * Array.concat works on the Array object and returns a new Array - we have to do the same thing,
   * which is to return a new SubArray.  And that means we have to shim it.
   */
  concat: function () {

    var instance = new this.constructor();

    for (var i = 0; i < this.length; i += 1) {
        instance.push(this[i]);
    }
    for (i = 0; i < arguments.length; i += 1) {
        instance.push(arguments[i]);
    }

    return instance;
  },
});

test('SubArray - verify the toString() fix', function (t) {

  var b = new SubArray('first', 'middle', 'last');

  t.strictEqual(b.toString(), 'first,middle,last');
  t.end();
});

test('SubArray - verify the concat fix', function (t) {

  var b = new SubArray('first');

  b = b.concat('last');

  t.strictEqual(b.last(), 'last');
  t.end();
});

test('SubArray - verify custom method - last', function (t) {

  var b = new SubArray('first', 'middle', 'last');

  t.strictEqual(b.last(), 'last');
  t.end();
});

test('SubArray - index access', function (t) {

  var b = new SubArray('first', 'middle', 'last');

  t.strictEqual(b[0], 'first');
  t.strictEqual(b[1], 'middle');
  t.strictEqual(b[2], 'last');
  t.end();
});

// failing tests offered by @Raynos2 ~ converted to "passing" by expecting exceptions
test('SubArray - length append', function (t) {

  var b = new SubArray(0, 1);

  var len = b.length;

  b[2] = 2;

  try {
    if (b.length === len) {
      throw new Error('length not modified');
    }
    t.fail('length somehow modified');
  } catch (e) {
    t.pass(e.message);
  }

  t.end();
});

// failing tests offered by @Raynos2 ~ converted to "passing" by expecting exceptions
test('SubArray - length reset', function (t) {

  var b = new SubArray(0, 1);

  b.length = 0;

  try {
    if ("0" in b) {
      throw new Error('zero not removed');
    }
    t.fail('resetting length somehow removed zero');
  } catch (e) {
    t.pass(e.message);
  }

  try {
    if (typeof b[0] !== 'undefined') {
      throw new Error('zero not undefined');
    }
    t.fail('resetting length somehow undefined zero');
  } catch (e) {
    t.pass(e.message);
  }

  t.end();
});

test('SubArray - length after create', function (t) {

  var b = new SubArray('first', 'middle', 'last');

  t.strictEqual(b.length, 3);
  t.end();
});

test('SubArray - reverse', function (t) {

  var b = new SubArray('first', 'middle', 'last');

  t.strictEqual(b.reverse().last(), 'first');
  t.end();
});

test('SubArray - sort', function (t) {

  var b = new SubArray('first', 'middle', 'last');

  t.strictEqual(b.sort().last(), 'middle');
  t.end();
});

test('SubArray - shift', function (t) {

  var b = new SubArray('first', 'middle', 'last');

  b.shift();

  t.strictEqual(b[0], 'middle');
  t.strictEqual(b.length, 2);
  t.end();
});

test('SubArray - pop', function (t) {

  var b = new SubArray('first', 'middle', 'last');

  t.strictEqual(b.pop(), 'last');
  t.end();
});

test('SubArray - push', function (t) {

  var b = new SubArray('first');

  b.push('last');

  t.strictEqual(b.last(), 'last');
  t.strictEqual(b.length, 2);
  t.end();
});

test('SubArray - splice', function (t) {

  var b = new SubArray('first');

  b.splice(1, 1, 'last');

  t.strictEqual(b.last(), 'last');
  t.end();
});

test('SubArray - unshift', function (t) {

  var b = new SubArray('first');

  b.unshift('last');

  t.strictEqual(b.last(), 'first');
  t.end();
});

/* template */
/*
test('$1 should return $2', function (t) {
  t.plan(1);
  t.fail('next test to implement');
});
*/
<commit_msg>subarray tostring hack for IE 6-8 - comment fix<commit_after>/**
 * test Constructor.extend() with natives
 *
 * YES!  You can extend native constructors, provided you are aware of a couple things.
 * In this set of tests, we'll use extend to subclass the Array constructor and provide workarounds for
 * for constructor initialization and [[Class]] dependent methods (toString()).
 *
 * BUT ~ 2 tests provided by @Raynos2 show that modifying the length property directly has side-
 * effects (like clobbering the array).
 *
 */

var test = require('tape');
var Constructor = require('../../src/Constructor.js').Constructor;

/*
 * FIXTURE - fairly complete example of extending the native built-in Arrays.
 *
 * NOTE:  the first argument here should be the Array constructor.
 */
var SubArray = Constructor.extend(Array, {
  constructor: function () {
    this.parent();

    // stolen from kangax (http://bit.ly/W66vQW)
    this.push.apply(this, arguments);
  },

  // borrowed from kangax (http://bit.ly/W66vQW)
  last: function () {
    return this[this.length - 1];
  },

  /**
   * @method toString - must be defined explicitly
   *
   * kangax (http://bit.ly/W66vQW), David Herman in Effective JavaScript (item 40, pp. 106ff), and some
   * learning tests tell us that the Array.prototype.toString() method fails on objects whose
   * constructor is not really an Array - due to the internal use of [[Class]] by JavaScript engine -
   * so we'll have to shim it, using an output string directly.
   */
  toString: function () {

    var delimiter = '';
    var comma = ',';
    var arrayString = '';

    for (var i = 0; i < this.length; i += 1) {
        arrayString += delimiter + this[i];

        delimiter = comma;
    }

    return arrayString;
  },

  /**
   * @method concat - must be defined explicitly
   *
   * Array.concat works on the Array object and returns a new Array - we have to do the same thing,
   * which is to return a new SubArray.  And that means we have to shim it.
   */
  concat: function () {

    var instance = new this.constructor();

    for (var i = 0; i < this.length; i += 1) {
        instance.push(this[i]);
    }
    for (i = 0; i < arguments.length; i += 1) {
        instance.push(arguments[i]);
    }

    return instance;
  },
});

test('SubArray - verify the toString() fix', function (t) {

  var b = new SubArray('first', 'middle', 'last');

  t.strictEqual(b.toString(), 'first,middle,last');
  t.end();
});

test('SubArray - verify the concat fix', function (t) {

  var b = new SubArray('first');

  b = b.concat('last');

  t.strictEqual(b.last(), 'last');
  t.end();
});

test('SubArray - verify custom method - last', function (t) {

  var b = new SubArray('first', 'middle', 'last');

  t.strictEqual(b.last(), 'last');
  t.end();
});

test('SubArray - index access', function (t) {

  var b = new SubArray('first', 'middle', 'last');

  t.strictEqual(b[0], 'first');
  t.strictEqual(b[1], 'middle');
  t.strictEqual(b[2], 'last');
  t.end();
});

// failing tests offered by @Raynos2 ~ converted to "passing" by expecting exceptions
test('SubArray - length append', function (t) {

  var b = new SubArray(0, 1);

  var len = b.length;

  b[2] = 2;

  try {
    if (b.length === len) {
      throw new Error('length not modified');
    }
    t.fail('length somehow modified');
  } catch (e) {
    t.pass(e.message);
  }

  t.end();
});

// failing tests offered by @Raynos2 ~ converted to "passing" by expecting exceptions
test('SubArray - length reset', function (t) {

  var b = new SubArray(0, 1);

  b.length = 0;

  try {
    if ("0" in b) {
      throw new Error('zero not removed');
    }
    t.fail('resetting length somehow removed zero');
  } catch (e) {
    t.pass(e.message);
  }

  try {
    if (typeof b[0] !== 'undefined') {
      throw new Error('zero not undefined');
    }
    t.fail('resetting length somehow undefined zero');
  } catch (e) {
    t.pass(e.message);
  }

  t.end();
});

test('SubArray - length after create', function (t) {

  var b = new SubArray('first', 'middle', 'last');

  t.strictEqual(b.length, 3);
  t.end();
});

test('SubArray - reverse', function (t) {

  var b = new SubArray('first', 'middle', 'last');

  t.strictEqual(b.reverse().last(), 'first');
  t.end();
});

test('SubArray - sort', function (t) {

  var b = new SubArray('first', 'middle', 'last');

  t.strictEqual(b.sort().last(), 'middle');
  t.end();
});

test('SubArray - shift', function (t) {

  var b = new SubArray('first', 'middle', 'last');

  b.shift();

  t.strictEqual(b[0], 'middle');
  t.strictEqual(b.length, 2);
  t.end();
});

test('SubArray - pop', function (t) {

  var b = new SubArray('first', 'middle', 'last');

  t.strictEqual(b.pop(), 'last');
  t.end();
});

test('SubArray - push', function (t) {

  var b = new SubArray('first');

  b.push('last');

  t.strictEqual(b.last(), 'last');
  t.strictEqual(b.length, 2);
  t.end();
});

test('SubArray - splice', function (t) {

  var b = new SubArray('first');

  b.splice(1, 1, 'last');

  t.strictEqual(b.last(), 'last');
  t.end();
});

test('SubArray - unshift', function (t) {

  var b = new SubArray('first');

  b.unshift('last');

  t.strictEqual(b.last(), 'first');
  t.end();
});

/* template */
/*
test('$1 should return $2', function (t) {
  t.plan(1);
  t.fail('next test to implement');
});
*/
<|endoftext|>


<commit_before>import { assert } from 'chai';
import { addAction } from '../util/database';
import server from '../../.dist/lib/server';

describe('New model', () => {

    before(() => {
        return server.start();
    });

    after(() => {
        return server.stop();
    });

    beforeEach(() => {
        return addAction('CLEAR_ALL_DATA');
    });

});
<commit_msg>Test adding a model<commit_after>import { assert } from 'chai';
import { addAction } from '../util/database';
import { post } from '../util/mock-client';
import server from '../../.dist/lib/server';
import ModelStore from '../../.dist/store/model-store';

describe('New model', () => {

    before(() => {
        return server.start();
    });

    after(() => {
        return server.stop();
    });

    beforeEach(() => {
        return addAction('CLEAR_ALL_DATA');
    });

    it('should add a model', () => {
        assert.lengthOf(ModelStore.getModels(), 0);
        return post('model', {
            name: 'Widget',
            description: 'A widget',
            manufacturer: 'The Factory',
            vendor: 'The Store',
            location: 'The shelf',
            isFaulty: false,
            faultDescription: '',
            price: 3.50,
            count: 10
        }).then(response => {
            assert.lengthOf(ModelStore.getModels(), 1);
            let model = ModelStore.getModelByAddress(response.address);
            assert.deepEqual(response, model);
            delete response.address;
            assert.deepEqual(response, {
                name: 'Widget',
                description: 'A widget',
                manufacturer: 'The Factory',
                vendor: 'The Store',
                location: 'The shelf',
                isFaulty: false,
                faultDescription: '',
                price: 3.50,
                count: 10
            });
        });
    });

});
<|endoftext|>