<commit_before>module.exports = function(grunt) {
  var rewriteRulesSnippet = require('grunt-connect-rewrite/lib/utils').rewriteRequest;

  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    uglify: {
      options: {
        banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n',
        // When using AngularJS you have to disable the mangle option.
        mangle: false
      },
      build: {
        files: {
          'build/anol.min.js': ['build/anol.js'],
          'build/orka.min.js': ['build/orka.js']
        }
      }
    },
    jshint: {
      files: [ 'Gruntfile.js', 'anol/modules/**/*.js', 'orka/modules/**/*.js' ],
      options: {
        globals: {
          jQuery: true,
          console: true,
          module: true
        }
      }
    },
    concat: {
      options: {
        separator: ';'
      },
      anolDev: {
        src: [
          'anol/modules/module.js',
          'anol/modules/**/module.js',
          'anol/modules/**/*.js'
        ],
        dest: 'build/<%= pkg.name %>.js'
      },
      anolDist: {
        src: [
          'anol/libs/jquery/jquery-2.1.1.min.js',
          'anol/libs/angular/angular.min.js',
          'anol/libs/ol3/ol3.min.js',
          'anol/modules/module.js',
          'anol/modules/**/module.js',
          'anol/modules/**/*.js',
          '!anol/**/angular-mocks.js',
          '!anol/test/**/*.*',
          '!anol/**/*-debug.js'
        ],
        dest: 'build/<%= pkg.name %>.js'
      },
      orkaDev: {
        src: [
          'orka/modules/**/module.js',
          'orka/modules/**/*.js'
        ],
        dest: 'build/orka.js'
      },
      orkaDist: {
        src: [
          'orka/libs/**/*.js',
          'orka/modules/**/module.js',
          'orka/modules/**/*.js',
          '!orka/**/angular-mocks.js',
          '!orka/test/**/*.*',
          '!orka/**/*-debug.js'
        ],
        dest: 'build/orka.js'
      }
    },
    clean: {
      temp: {
        src: [ 'build' ]
      }
    },
    configureRewriteRules: {
      options: {
          rulesProvider: 'connect.rules'
      }
    },
    connect: {
      server: {
        options: {
          hostname: '*',
          port: 7000,
          middleware: function (connect, options) {
            var middlewares = [];

            // RewriteRules support
            middlewares.push(rewriteRulesSnippet);

            if (!Array.isArray(options.base)) {
              options.base = [options.base];
            }

            var directory = options.directory || options.base[options.base.length - 1];
            options.base.forEach(function (base) {
              // Serve static files.
              middlewares.push(connect.static(base));
            });

            // Make directory browse-able.
            middlewares.push(connect.directory(directory));

            return middlewares;
          }
        }
      },
      rules: [{
        from: '^/(.*)/anol/(.*)$',
        to: '/anol/$2'
      }, {
        from: '^/(.*)/orka/(.*)$',
        to: '/orka/$2'
      }, {
        from: '^/(.*)/static/(.*)$',
        to: '/static/$2'
      }, {
        from: '^/(.*)/build/(.*)$',
        to: '/build/$2'
      }, {
        from: '^/(.*)/config.js$',
        to: '/config.js'
      }, {
        from: '^/api/(.*)$',
        to: '/docs/$1'
      }, {
        from: '^(.*)/$',
        to: '/'
      }]
    },
    watch: {
      scripts: {
        files: ['anol/modules/**/*.js', 'orka/modules/**/*.js'],
        tasks: ['clean', 'ngdocs', 'concat:anolDev', 'concat:orkaDev'],
        options: {
          spawn: false,
        },
      },
    },
    html2js: {
      main: {
        src: ['anol/**/templates/*.html', 'orka/**/templates/*.html'],
        dest: 'build/templates.js'
      },
    },
    karma: {
        unit: {
          configFile: 'anol/karma.conf.js',
        }
    },
    ngdocs: {
      options: {
        dest: 'docs',
        html5Mode: false,
        startPage: '/api/',
        title: 'ORKaApp API Documentation'
      },
      anolApi: {
        title: 'AnOl API',
        src: ['anol/modules/**/*.js'],
      },
      orkaApi: {
        title: 'ORKa API',
        src: ['orka/modules/**/*.js'],
      }
    }
  });

  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-connect');
  grunt.loadNpmTasks('grunt-connect-rewrite');
  grunt.loadNpmTasks('grunt-common-html2js');

  grunt.loadNpmTasks('grunt-karma');
  grunt.loadNpmTasks('grunt-ngdocs');

  grunt.registerTask('dev', ['html2js', 'ngdocs', 'concat:anolDev', 'concat:orkaDev', 'configureRewriteRules', 'connect:server', 'watch:scripts']);
  grunt.registerTask('build', ['jshint', 'concat:anolDist', 'concat:orkaDist', 'uglify', 'ngdocs']);
  grunt.registerTask('default', ['jshint', 'concat']);
  grunt.registerTask('test', ['karma:unit']);
  grunt.registerTask('build_doc', ['ngdocs']);
};<commit_msg>Used ngmin in dist build chain. Used ngtemplates for templates<commit_after>module.exports = function(grunt) {
  var rewriteRulesSnippet = require('grunt-connect-rewrite/lib/utils').rewriteRequest;

  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    uglify: {
      options: {
        banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n',
        // When using AngularJS you have to disable the mangle option.
        mangle: true
      },
      build: {
        files: {
          'build/anol.min.js': ['build/anol.js'],
          'build/orka.min.js': ['build/orka.js']
        }
      }
    },
    jshint: {
      files: [ 'Gruntfile.js', 'anol/modules/**/*.js', 'orka/modules/**/*.js' ],
      options: {
        globals: {
          jQuery: true,
          console: true,
          module: true
        }
      }
    },
    ngmin: {
      anolDist: {
        src: [
          'anol/modules/module.js',
          'anol/modules/**/module.js',
          'anol/modules/**/*.js',
          '!anol/**/angular-mocks.js',
          '!anol/test/**/*.*',
          '!anol/**/*-debug.js'
        ],
        dest: 'build/anol.ngmin.js'
      },
      orkaDist: {
        src: [
          'orka/modules/**/module.js',
          'orka/modules/**/*.js',
          '!orka/**/angular-mocks.js',
          '!orka/test/**/*.*',
          '!orka/**/*-debug.js',
          'config.js',
          'controller.js',
          'init.js'
        ],
        dest: 'build/orka.ngmin.js'
      }
    },
    concat: {
      options: {
        separator: ';'
      },
      anolDev: {
        src: [
          'anol/modules/module.js',
          'anol/modules/**/module.js',
          'anol/modules/**/*.js'
        ],
        dest: 'build/<%= pkg.name %>.js'
      },
      anolDist: {
        src: [
          'anol/libs/jquery/jquery-2.1.1.min.js',
          'anol/libs/angular/angular.min.js',
          'anol/libs/ol3/ol.custom.min.js',
          'build/anol.ngmin.js'
        ],
        dest: 'build/anol.js'
      },
      orkaDev: {
        src: [
          'orka/modules/**/module.js',
          'orka/modules/**/*.js'
        ],
        dest: 'build/orka.js'
      },
      orkaDist: {
        src: [
          'orka/libs/**/*.js',
          'build/orka.ngmin.js'
        ],
        dest: 'build/orka.js'
      }
    },
    clean: {
      temp: {
        src: [ 'build' ]
      }
    },
    configureRewriteRules: {
      options: {
          rulesProvider: 'connect.rules'
      }
    },
    connect: {
      server: {
        options: {
          hostname: '*',
          port: 7000,
          middleware: function (connect, options) {
            var middlewares = [];

            // RewriteRules support
            middlewares.push(rewriteRulesSnippet);

            if (!Array.isArray(options.base)) {
              options.base = [options.base];
            }

            var directory = options.directory || options.base[options.base.length - 1];
            options.base.forEach(function (base) {
              // Serve static files.
              middlewares.push(connect.static(base));
            });

            // Make directory browse-able.
            middlewares.push(connect.directory(directory));

            return middlewares;
          }
        }
      },
      rules: [{
        from: '^/(.*)/anol/(.*)$',
        to: '/anol/$2'
      }, {
        from: '^/(.*)/orka/(.*)$',
        to: '/orka/$2'
      }, {
        from: '^/(.*)/static/(.*)$',
        to: '/static/$2'
      }, {
        from: '^/(.*)/build/(.*)$',
        to: '/build/$2'
      }, {
        from: '^/api/(.*)$',
        to: '/docs/$1'
      }, {
        from: '^(.*)/$',
        to: '/'
      }]
    },
    watch: {
      scripts: {
        files: ['anol/modules/**/*.js', 'orka/modules/**/*.js'],
        tasks: ['clean', 'ngdocs', 'concat:anolDev', 'concat:orkaDev'],
        options: {
          spawn: false,
        },
      },
    },
    html2js: {
      main: {
        src: ['anol/**/templates/*.html', 'orka/**/templates/*.html'],
        dest: 'build/templates.js'
      },
    },
    karma: {
        unit: {
          configFile: 'anol/karma.conf.js',
        }
    },
    ngdocs: {
      options: {
        dest: 'docs',
        html5Mode: false,
        startPage: '/api/',
        title: 'ORKaApp API Documentation'
      },
      anolApi: {
        title: 'AnOl API',
        src: ['anol/modules/**/*.js'],
      },
      orkaApi: {
        title: 'ORKa API',
        src: ['orka/modules/**/*.js'],
      }
    },
    ngtemplates:  {
      orkaApp: {
        src: ['anol/**/templates/*.html', 'orka/**/templates/*.html'],
        dest: 'build/templates.js'
      }
    }
  });

  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-connect');
  grunt.loadNpmTasks('grunt-connect-rewrite');
  grunt.loadNpmTasks('grunt-angular-templates');
  grunt.loadNpmTasks('grunt-ngmin');

  grunt.loadNpmTasks('grunt-karma');
  grunt.loadNpmTasks('grunt-ngdocs');

  grunt.registerTask('dev', ['ngtemplates', 'ngdocs', 'concat:anolDev', 'concat:orkaDev', 'configureRewriteRules', 'connect:server', 'watch:scripts']);
  grunt.registerTask('build', ['clean', 'jshint', 'ngtemplates', 'ngmin:anolDist', 'concat:anolDist', 'ngmin:orkaDist', 'concat:orkaDist', 'uglify']);
  grunt.registerTask('default', ['jshint', 'concat']);
  grunt.registerTask('test', ['karma:unit']);
  grunt.registerTask('build_doc', ['ngdocs']);
};
<|endoftext|>


<commit_before>/*
Copyright 2017 Vector Creations Ltd
Copyright 2018, 2019 New Vector Ltd
Copyright 2019 The Matrix.org Foundation C.I.C.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import {logger} from "../../../src/logger";
import * as utils from "../../../src/utils";
import {MemoryCryptoStore} from "../../../src/crypto/store/memory-crypto-store";
import {DeviceList} from "../../../src/crypto/DeviceList";

const signedDeviceList = {
    "failures": {},
    "device_keys": {
        "@test1:sw1v.org": {
            "HGKAWHRVJQ": {
                "signatures": {
                    "@test1:sw1v.org": {
                        "ed25519:HGKAWHRVJQ":
                            "8PB450fxKDn5s8IiRZ2N2t6MiueQYVRLHFEzqIi1eLdxx1w" +
                            "XEPC1/1Uz9T4gwnKlMVAKkhB5hXQA/3kjaeLABw",
                    },
                },
                "user_id": "@test1:sw1v.org",
                "keys": {
                    "ed25519:HGKAWHRVJQ":
                        "0gI/T6C+mn1pjtvnnW2yB2l1IIBb/5ULlBXi/LXFSEQ",
                    "curve25519:HGKAWHRVJQ":
                        "mbIZED1dBsgIgkgzxDpxKkJmsr4hiWlGzQTvUnQe3RY",
                },
                "algorithms": [
                    "m.olm.v1.curve25519-aes-sha2",
                    "m.megolm.v1.aes-sha2",
                ],
                "device_id": "HGKAWHRVJQ",
                "unsigned": {},
            },
        },
    },
};

describe('DeviceList', function() {
    let downloadSpy;
    let cryptoStore;
    let deviceLists = [];

    beforeEach(function() {
        deviceLists = [];

        downloadSpy = jest.fn();
        cryptoStore = new MemoryCryptoStore();
    });

    afterEach(function() {
        for (const dl of deviceLists) {
            dl.stop();
        }
    });

    function createTestDeviceList() {
        const baseApis = {
            downloadKeysForUsers: downloadSpy,
        };
        const mockOlm = {
            verifySignature: function(key, message, signature) {},
        };
        const dl = new DeviceList(baseApis, cryptoStore, mockOlm);
        deviceLists.push(dl);
        return dl;
    }

    it("should successfully download and store device keys", function() {
        const dl = createTestDeviceList();

        dl.startTrackingDeviceList('@test1:sw1v.org');

        const queryDefer1 = utils.defer();
        downloadSpy.mockReturnValue(queryDefer1.promise);

        const prom1 = dl.refreshOutdatedDeviceLists();
        expect(downloadSpy).toHaveBeenCalledWith(['@test1:sw1v.org'], {});
        queryDefer1.resolve(utils.deepCopy(signedDeviceList));

        return prom1.then(() => {
            const storedKeys = dl.getRawStoredDevicesForUser('@test1:sw1v.org');
            expect(Object.keys(storedKeys)).toEqual(['HGKAWHRVJQ']);
        });
    });

    it("should have an outdated devicelist on an invalidation while an " +
       "update is in progress", function() {
        const dl = createTestDeviceList();

        dl.startTrackingDeviceList('@test1:sw1v.org');

        const queryDefer1 = utils.defer();
        downloadSpy.mockReturnValue(queryDefer1.promise);

        const prom1 = dl.refreshOutdatedDeviceLists();
        expect(downloadSpy).toHaveBeenCalledWith(['@test1:sw1v.org'], {});
        downloadSpy.mockReset();

        // outdated notif arrives while the request is in flight.
        const queryDefer2 = utils.defer();
        downloadSpy.mockReturnValue(queryDefer2.promise);

        dl.invalidateUserDeviceList('@test1:sw1v.org');
        dl.refreshOutdatedDeviceLists();

        dl.saveIfDirty().then(() => {
            // the first request completes
            queryDefer1.resolve({
                device_keys: {
                    '@test1:sw1v.org': {},
                },
            });
            return prom1;
        }).then(() => {
            // uh-oh; user restarts before second request completes. The new instance
            // should know we never got a complete device list.
            logger.log("Creating new devicelist to simulate app reload");
            downloadSpy.mockReset();
            const dl2 = createTestDeviceList();
            const queryDefer3 = utils.defer();
            downloadSpy.mockReturnValue(queryDefer3.promise);

            const prom3 = dl2.refreshOutdatedDeviceLists();
            expect(downloadSpy).toHaveBeenCalledWith(['@test1:sw1v.org'], {});

            queryDefer3.resolve(utils.deepCopy(signedDeviceList));

            // allow promise chain to complete
            return prom3;
        }).then(() => {
            const storedKeys = dl.getRawStoredDevicesForUser('@test1:sw1v.org');
            expect(Object.keys(storedKeys)).toEqual(['HGKAWHRVJQ']);
        });
    });
});
<commit_msg>Fix tests<commit_after>/*
Copyright 2017 Vector Creations Ltd
Copyright 2018, 2019 New Vector Ltd
Copyright 2019 The Matrix.org Foundation C.I.C.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import {logger} from "../../../src/logger";
import * as utils from "../../../src/utils";
import {MemoryCryptoStore} from "../../../src/crypto/store/memory-crypto-store";
import {DeviceList} from "../../../src/crypto/DeviceList";

const signedDeviceList = {
    "failures": {},
    "device_keys": {
        "@test1:sw1v.org": {
            "HGKAWHRVJQ": {
                "signatures": {
                    "@test1:sw1v.org": {
                        "ed25519:HGKAWHRVJQ":
                            "8PB450fxKDn5s8IiRZ2N2t6MiueQYVRLHFEzqIi1eLdxx1w" +
                            "XEPC1/1Uz9T4gwnKlMVAKkhB5hXQA/3kjaeLABw",
                    },
                },
                "user_id": "@test1:sw1v.org",
                "keys": {
                    "ed25519:HGKAWHRVJQ":
                        "0gI/T6C+mn1pjtvnnW2yB2l1IIBb/5ULlBXi/LXFSEQ",
                    "curve25519:HGKAWHRVJQ":
                        "mbIZED1dBsgIgkgzxDpxKkJmsr4hiWlGzQTvUnQe3RY",
                },
                "algorithms": [
                    "m.olm.v1.curve25519-aes-sha2",
                    "m.megolm.v1.aes-sha2",
                ],
                "device_id": "HGKAWHRVJQ",
                "unsigned": {},
            },
        },
    },
};

describe('DeviceList', function() {
    let downloadSpy;
    let cryptoStore;
    let deviceLists = [];

    beforeEach(function() {
        deviceLists = [];

        downloadSpy = jest.fn();
        cryptoStore = new MemoryCryptoStore();
    });

    afterEach(function() {
        for (const dl of deviceLists) {
            dl.stop();
        }
    });

    function createTestDeviceList() {
        const baseApis = {
            downloadKeysForUsers: downloadSpy,
            getUserId: () => '@test1:sw1v.org',
            deviceId: 'HGKAWHRVJQ',
        };
        const mockOlm = {
            verifySignature: function(key, message, signature) {},
        };
        const dl = new DeviceList(baseApis, cryptoStore, mockOlm);
        deviceLists.push(dl);
        return dl;
    }

    it("should successfully download and store device keys", function() {
        const dl = createTestDeviceList();

        dl.startTrackingDeviceList('@test1:sw1v.org');

        const queryDefer1 = utils.defer();
        downloadSpy.mockReturnValue(queryDefer1.promise);

        const prom1 = dl.refreshOutdatedDeviceLists();
        expect(downloadSpy).toHaveBeenCalledWith(['@test1:sw1v.org'], {});
        queryDefer1.resolve(utils.deepCopy(signedDeviceList));

        return prom1.then(() => {
            const storedKeys = dl.getRawStoredDevicesForUser('@test1:sw1v.org');
            expect(Object.keys(storedKeys)).toEqual(['HGKAWHRVJQ']);
        });
    });

    it("should have an outdated devicelist on an invalidation while an " +
       "update is in progress", function() {
        const dl = createTestDeviceList();

        dl.startTrackingDeviceList('@test1:sw1v.org');

        const queryDefer1 = utils.defer();
        downloadSpy.mockReturnValue(queryDefer1.promise);

        const prom1 = dl.refreshOutdatedDeviceLists();
        expect(downloadSpy).toHaveBeenCalledWith(['@test1:sw1v.org'], {});
        downloadSpy.mockReset();

        // outdated notif arrives while the request is in flight.
        const queryDefer2 = utils.defer();
        downloadSpy.mockReturnValue(queryDefer2.promise);

        dl.invalidateUserDeviceList('@test1:sw1v.org');
        dl.refreshOutdatedDeviceLists();

        dl.saveIfDirty().then(() => {
            // the first request completes
            queryDefer1.resolve({
                device_keys: {
                    '@test1:sw1v.org': {},
                },
            });
            return prom1;
        }).then(() => {
            // uh-oh; user restarts before second request completes. The new instance
            // should know we never got a complete device list.
            logger.log("Creating new devicelist to simulate app reload");
            downloadSpy.mockReset();
            const dl2 = createTestDeviceList();
            const queryDefer3 = utils.defer();
            downloadSpy.mockReturnValue(queryDefer3.promise);

            const prom3 = dl2.refreshOutdatedDeviceLists();
            expect(downloadSpy).toHaveBeenCalledWith(['@test1:sw1v.org'], {});

            queryDefer3.resolve(utils.deepCopy(signedDeviceList));

            // allow promise chain to complete
            return prom3;
        }).then(() => {
            const storedKeys = dl.getRawStoredDevicesForUser('@test1:sw1v.org');
            expect(Object.keys(storedKeys)).toEqual(['HGKAWHRVJQ']);
        });
    });
});
<|endoftext|>


<commit_before>/**
 * Copyright 2013 Graz University of Technodebugy - KTI (Knowledge Technodebugies Institute)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var MockupNS = MockupNS || "http://eval.bp/";
var MockupLog = MockupLog || require('logger').get('Mockup');
var MockupTimeout = MockupTimeout || 100;

var SSMockupUserEvents = [
    {
        'uri': 'sss:#ue01',
        'type': 'createPrivateCollection',
        'resource': MockupNS + 'coll/resource01',
        'user': MockupNS + 'user/christoph',
        'content': 'Create Private Collection',
        'timestamp': '2013-11-15T15:30:20+02:00'
    },
    {
        'uri': 'sss:#ue02',
        'type': 'renamePrivateCollection',
        'resource': MockupNS + 'coll/resource01',
        'user': MockupNS + 'user/christoph',
        'content': 'Rename Private Collection',
        'timestamp': '2013-11-15T16:50:20+02:00'
    },
    {
        'uri': 'sss:#ue07',
        'type': 'renamePrivateCollection',
        'resource': MockupNS + 'coll/resource03',
        'user': MockupNS + 'user/christoph',
        'content': 'Rename Private Collection',
        'timestamp': '2013-11-15T17:00:20+02:00'
    },
    {
        'uri': 'sss:#ue03',
        'type': 'removePrivateCollection',
        'resource': MockupNS + 'coll/resource01',
        'user': MockupNS + 'user/christoph',
        'content': 'Remove Private Collection',
        'timestamp': '2013-11-15T17:30:20+02:00'
    },
    {
        'uri': 'sss:#ue04',
        'type': 'createSharedCollection',
        'resource': MockupNS + 'coll/resource02',
        'user': MockupNS + 'user/maria',
        'content': 'Create Shared Collection',
        'timestamp': '2013-11-15T15:40:20+02:00'
    },
    {
        'uri': 'sss:#ue05',
        'type': 'renameSharedCollection',
        'resource': MockupNS + 'coll/resource02',
        'user': MockupNS + 'user/maria',
        'content': 'Rename Shared Collection',
        'timestamp': '2013-11-15T16:20:20+02:00'
    },
    {
        'uri': 'sss:#ue06',
        'type': 'removeSharedCollection',
        'resource': MockupNS + 'coll/resource02',
        'user': MockupNS + 'user/maria',
        'content': 'Remove Shared Collection',
        'timestamp': '2013-11-15T17:40:20+02:00'
    },
    {
        'uri': 'sss:#useraction21',
        'type': 'createPrivateRecord',
        'resource': MockupNS + 'doc/document01',
        'user': MockupNS + 'user/peter',
        'content': 'Create Private Record',
        'timestamp': '2014-02-24T12:30:20+02:00'
    },
    {
        'uri': 'sss:#useraction22',
        'type': 'renamePrivateRecord',
        'resource': MockupNS + 'doc/document01',
        'user': MockupNS + 'user/peter',
        'content': 'Rename Private Record',
        'timestamp': '2013-11-15T16:50:20+02:00'
    },
    {
        'uri': 'sss:#useraction27',
        'type': 'renamePrivateRecord',
        'resource': MockupNS + 'doc/document03',
        'user': MockupNS + 'user/peter',
        'content': 'Rename Private Record',
        'timestamp': '2013-11-15T17:00:20+02:00'
    },
    {
        'uri': 'sss:#useraction23',
        'type': 'removePrivateRecord',
        'resource': MockupNS + 'doc/document01',
        'user': MockupNS + 'user/peter',
        'content': 'Remove Private Record',
        'timestamp': '2013-11-15T17:30:20+02:00'
    },
    {
        'uri': 'sss:#useraction24',
        'type': 'createSharedRecord',
        'resource': MockupNS + 'doc/document02',
        'user': MockupNS + 'user/peter',
        'content': 'Create Shared Record',
        'timestamp': '2013-11-15T15:40:20+02:00'
    },
    {
        'uri': 'sss:#useraction25',
        'type': 'renameSharedRecord',
        'resource': MockupNS + 'doc/document02',
        'user': MockupNS + 'user/peter',
        'content': 'Rename Shared Record',
        'timestamp': '2013-11-15T16:20:20+02:00'
    },
    {
        'uri': 'sss:#useraction26',
        'type': 'removeSharedRecord',
        'resource': MockupNS + 'doc/document02',
        'user': MockupNS + 'user/peter',
        'content': 'Remove Shared Record',
        'timestamp': '2013-11-15T17:40:20+02:00'
    }
];

/**write
 * Get user events
 *
 */
function SSUserEventsGet() {

    /**
     * Return mockup data.
     *
     * @method handle
     * @param {Function} resultHandler    handle server's response
     * @param {Function} errorHandler     handle an error response
     * @param {String}   user             user's label
     * @param {String}   key              user's application key
     * @param {Date}   startTime          only events after startTime
     * @param {Date}   endTime            only events before endTime
     */
    this.handle = function(resultHandler, errorHandler, user, key, forUser, resource, startTime, endTime) {
        var userEvents = [];
        var startTime = new Date(startTime);
        var endTime = new Date(endTime);
        MockupLog.debug("SSUSEREVENTSGET for " + forUser + " from " + startTime + " till " + endTime);
        for (var i = 0; i < SSMockupUserEvents.length; i++) {
            var event = SSMockupUserEvents[i];
            if (event['user'] != forUser)
                continue;
            if (startTime && new Date(event['timestamp']) < startTime)
                continue;
            if (endTime && new Date(event['timestamp']) > endTime)
                continue;
            userEvents.push(event);
        }
        setTimeout(function(){resultHandler({'uEs':userEvents});}, MockupTimeout);
    };
}
;

/**write
 * Get user events
 *
 */
function SSUserEventAdd() {

    /**
     * Return mockup data.
     *
     * @method handle
     * @param {Function} resultHandler    handle server's response
     * @param {Function} errorHandler     handle an error response
     * @param {String}   user             user's label
     * @param {String}   key              user's application key
     * @param {Date}   startTime          only events after startTime
     * @param {Date}   endTime            only events before endTime
     */
    this.handle = function(resultHandler, errorHandler, user, key, eventType, resource, content) {
        var userEvents = [];
        MockupLog.debug("SSUSEREVENTADD eventType ",  eventType, ", resource ", resource, ", content" , content);
        SSMockupUserEvents.push({
            'uri': MockupNS + ':#' + _.uniqueId('ue'),
            'type': eventType,
            'resource': resource,
            'user': user,
            'content': content,
            'timestamp': new Date().getTime()

        });
        setTimeout(function(){resultHandler({'worked':true});}, MockupTimeout);
    };
}
;
<commit_msg>updated Userevent mockup data to be more close<commit_after>/**
 * Copyright 2013 Graz University of Technodebugy - KTI (Knowledge Technodebugies Institute)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var MockupNS = MockupNS || "http://eval.bp/";
var MockupLog = MockupLog || require('logger').get('Mockup');
var MockupTimeout = MockupTimeout || 100;

var SSMockupUserEvents = [
    {
        'uri': 'sss:#ue01',
        'type': 'createPrivateCollection',
        'resource': MockupNS + 'coll/resource01',
        'user': MockupNS + 'user/christoph',
        'content': 'Create Private Collection',
        'timestamp': '2013-11-15T15:30:20+02:00'
    },
    {
        'uri': 'sss:#ue02',
        'type': 'renamePrivateCollection',
        'resource': MockupNS + 'coll/resource01',
        'user': MockupNS + 'user/christoph',
        'content': 'Rename Private Collection',
        'timestamp': '2013-11-15T16:50:20+02:00'
    },
    {
        'uri': 'sss:#ue07',
        'type': 'renamePrivateCollection',
        'resource': MockupNS + 'coll/resource03',
        'user': MockupNS + 'user/christoph',
        'content': 'Rename Private Collection',
        'timestamp': '2013-11-15T17:00:20+02:00'
    },
    {
        'uri': 'sss:#ue03',
        'type': 'removePrivateCollection',
        'resource': MockupNS + 'coll/resource01',
        'user': MockupNS + 'user/christoph',
        'content': 'Remove Private Collection',
        'timestamp': '2013-11-15T17:30:20+02:00'
    },
    {
        'uri': 'sss:#ue04',
        'type': 'createSharedCollection',
        'resource': MockupNS + 'coll/resource02',
        'user': MockupNS + 'user/maria',
        'content': 'Create Shared Collection',
        'timestamp': '2013-11-15T15:40:20+02:00'
    },
    {
        'uri': 'sss:#ue05',
        'type': 'renameSharedCollection',
        'resource': MockupNS + 'coll/resource02',
        'user': MockupNS + 'user/maria',
        'content': 'Rename Shared Collection',
        'timestamp': '2013-11-15T16:20:20+02:00'
    },
    {
        'uri': 'sss:#ue06',
        'type': 'removeSharedCollection',
        'resource': MockupNS + 'coll/resource02',
        'user': MockupNS + 'user/maria',
        'content': 'Remove Shared Collection',
        'timestamp': '2013-11-15T17:40:20+02:00'
    },
    {
        'uri': 'sss:#useraction21',
        'type': 'createPrivateRecord',
        'resource': MockupNS + 'doc/document01',
        'user': MockupNS + 'user/peter',
        'content': 'Create Private Record',
        'timestamp': '2014-02-24T12:30:20+02:00'
    },
    {
        'uri': 'sss:#useraction22',
        'type': 'renamePrivateRecord',
        'resource': MockupNS + 'doc/document01',
        'user': MockupNS + 'user/peter',
        'content': 'Rename Private Record',
        'timestamp': '2014-01-15T16:50:20+02:00'
    },
    {
        'uri': 'sss:#useraction27',
        'type': 'renamePrivateRecord',
        'resource': MockupNS + 'doc/document03',
        'user': MockupNS + 'user/peter',
        'content': 'Rename Private Record',
        'timestamp': '2014-01-15T17:00:20+02:00'
    },
    {
        'uri': 'sss:#useraction23',
        'type': 'removePrivateRecord',
        'resource': MockupNS + 'doc/document01',
        'user': MockupNS + 'user/peter',
        'content': 'Remove Private Record',
        'timestamp': '2014-01-15T17:30:20+02:00'
    },
    {
        'uri': 'sss:#useraction24',
        'type': 'createSharedRecord',
        'resource': MockupNS + 'doc/document02',
        'user': MockupNS + 'user/peter',
        'content': 'Create Shared Record',
        'timestamp': '2014-01-15T15:40:20+02:00'
    },
    {
        'uri': 'sss:#useraction25',
        'type': 'renameSharedRecord',
        'resource': MockupNS + 'doc/document02',
        'user': MockupNS + 'user/peter',
        'content': 'Rename Shared Record',
        'timestamp': '2014-01-15T16:20:20+02:00'
    },
    {
        'uri': 'sss:#useraction26',
        'type': 'removeSharedRecord',
        'resource': MockupNS + 'doc/document02',
        'user': MockupNS + 'user/peter',
        'content': 'Remove Shared Record',
        'timestamp': '2014-01-15T17:40:20+02:00'
    }
];

/**write
 * Get user events
 *
 */
function SSUserEventsGet() {

    /**
     * Return mockup data.
     *
     * @method handle
     * @param {Function} resultHandler    handle server's response
     * @param {Function} errorHandler     handle an error response
     * @param {String}   user             user's label
     * @param {String}   key              user's application key
     * @param {Date}   startTime          only events after startTime
     * @param {Date}   endTime            only events before endTime
     */
    this.handle = function(resultHandler, errorHandler, user, key, forUser, resource, startTime, endTime) {
        var userEvents = [];
        var startTime = new Date(startTime);
        var endTime = new Date(endTime);
        MockupLog.debug("SSUSEREVENTSGET for " + forUser + " from " + startTime + " till " + endTime);
        for (var i = 0; i < SSMockupUserEvents.length; i++) {
            var event = SSMockupUserEvents[i];
            if (event['user'] != forUser)
                continue;
            if (startTime && new Date(event['timestamp']) < startTime)
                continue;
            if (endTime && new Date(event['timestamp']) > endTime)
                continue;
            userEvents.push(event);
        }
        setTimeout(function(){resultHandler({'uEs':userEvents});}, MockupTimeout);
    };
}
;

/**write
 * Get user events
 *
 */
function SSUserEventAdd() {

    /**
     * Return mockup data.
     *
     * @method handle
     * @param {Function} resultHandler    handle server's response
     * @param {Function} errorHandler     handle an error response
     * @param {String}   user             user's label
     * @param {String}   key              user's application key
     * @param {Date}   startTime          only events after startTime
     * @param {Date}   endTime            only events before endTime
     */
    this.handle = function(resultHandler, errorHandler, user, key, eventType, resource, content) {
        var userEvents = [];
        MockupLog.debug("SSUSEREVENTADD eventType ",  eventType, ", resource ", resource, ", content" , content);
        SSMockupUserEvents.push({
            'uri': MockupNS + ':#' + _.uniqueId('ue'),
            'type': eventType,
            'resource': resource,
            'user': user,
            'content': content,
            'timestamp': new Date().getTime()

        });
        setTimeout(function(){resultHandler({'worked':true});}, MockupTimeout);
    };
}
;
<|endoftext|>


<commit_before>Package.describe({
  name: 'ffxsam:react-smartform',
  version: '0.7.0',
  summary: 'Smart form elements for React',
  git: 'https://github.com/ffxsam/meteor-react-smartform',
  documentation: 'README.md'
});

Package.onUse(function (api) {
  api.versionsFrom('1.2.1');
  api.use('ecmascript');
  api.use('react@0.14.1_1');
  api.use('react-meteor-data@0.2.3');
  api.use('meteorflux:dispatcher@1.2.0');
  api.use('meteorflux:reactive-state@1.1.1');
  api.addFiles([
    'lib/symbols.js',
    'lib/form-state.js',
    'lib/form-store.js',
    'components/SmartInput.jsx',
    'components/SmartError.jsx',
    'components/SmartForm.jsx'
  ], 'client');
  api.export('SmartForm', 'client');
});
<commit_msg>Syncing package version with GitHub release ver<commit_after>Package.describe({
  name: 'ffxsam:react-smartform',
  version: '0.7.2',
  summary: 'Smart form elements for React',
  git: 'https://github.com/ffxsam/meteor-react-smartform',
  documentation: 'README.md'
});

Package.onUse(function (api) {
  api.versionsFrom('1.2.1');
  api.use('ecmascript');
  api.use('react@0.14.1_1');
  api.use('react-meteor-data@0.2.3');
  api.use('meteorflux:dispatcher@1.2.0');
  api.use('meteorflux:reactive-state@1.1.1');
  api.addFiles([
    'lib/symbols.js',
    'lib/form-state.js',
    'lib/form-store.js',
    'components/SmartInput.jsx',
    'components/SmartError.jsx',
    'components/SmartForm.jsx'
  ], 'client');
  api.export('SmartForm', 'client');
});
<|endoftext|>


<commit_before>'use strict';

angular.module('arachne.resources')

.factory('CatalogEntry', ['$resource', 'arachneSettings',
function($resource, arachneSettings) {

    return $resource(arachneSettings.dataserviceUri + '/catalog/entry/:id', null, {
        update: { method:'PUT' },
        list: {
        	mehtod: 'GET',
        	url: arachneSettings.dataserviceUri + '/catalog/list/:entityId',
        	isArray: true
        }
    });

}]);<commit_msg>Fix typo.<commit_after>'use strict';

angular.module('arachne.resources')

.factory('CatalogEntry', ['$resource', 'arachneSettings',
function($resource, arachneSettings) {

    return $resource(arachneSettings.dataserviceUri + '/catalog/entry/:id', null, {
        update: { method:'PUT' },
        list: {
        	method: 'GET',
        	url: arachneSettings.dataserviceUri + '/catalog/list/:entityId',
        	isArray: true
        }
    });

}]);<|endoftext|>


<commit_before>Package.describe({
    summary: "Accounts Templates styled for Zurb Foundation.",
    version: "0.9.14",
    name: "splendido:accounts-templates-foundation",
    git: "https://github.com/splendido/accounts-templates-foundation.git",
});

Package.on_use(function(api, where) {
    api.versionsFrom("METEOR@0.9.2.2");

    api.use([
        "less",
        "templating",
    ], "client");

    api.use([
        "splendido:accounts-templates-core",
    ], ["client", "server"]);

    api.imply([
        "splendido:accounts-templates-core@0.9.14",
    ], ["client", "server"]);

    api.add_files([
        "lib/at_error.html",
        "lib/at_error.js",
        "lib/at_form.html",
        "lib/at_form.js",
        "lib/at_input.html",
        "lib/at_input.js",
        "lib/at_oauth.html",
        "lib/at_oauth.js",
        "lib/at_pwd_form.html",
        "lib/at_pwd_form.js",
        "lib/at_pwd_form_btn.html",
        "lib/at_pwd_form_btn.js",
        "lib/at_pwd_link.html",
        "lib/at_pwd_link.js",
        "lib/at_result.html",
        "lib/at_result.js",
        "lib/at_sep.html",
        "lib/at_sep.js",
        "lib/at_signin_link.html",
        "lib/at_signin_link.js",
        "lib/at_signup_link.html",
        "lib/at_signup_link.js",
        "lib/at_social.html",
        "lib/at_social.js",
        "lib/at_terms_link.html",
        "lib/at_terms_link.js",
        "lib/at_title.html",
        "lib/at_title.js",
        "lib/full_page_at_form.html",
        "lib/at_foundation.less"
    ], ["client"]);
});

Package.on_test(function(api) {
    api.use([
        "splendido:accounts-templates-foundation",
        "splendido:accounts-templates-core@0.9.14",
    ]);

    api.use([
        "accounts-password",
        "tinytest",
        "test-helpers"
    ], ["client", "server"]);

    api.add_files([
        "tests/tests.js"
    ], ["client", "server"]);
});<commit_msg>patch release - Bump to version 0.9.15<commit_after>Package.describe({
    summary: "Accounts Templates styled for Zurb Foundation.",
    version: "0.9.15",
    name: "splendido:accounts-templates-foundation",
    git: "https://github.com/splendido/accounts-templates-foundation.git",
});

Package.on_use(function(api, where) {
    api.versionsFrom("METEOR@0.9.2.2");

    api.use([
        "less",
        "templating",
    ], "client");

    api.use([
        "splendido:accounts-templates-core",
    ], ["client", "server"]);

    api.imply([
        "splendido:accounts-templates-core@0.9.15",
    ], ["client", "server"]);

    api.add_files([
        "lib/at_error.html",
        "lib/at_error.js",
        "lib/at_form.html",
        "lib/at_form.js",
        "lib/at_input.html",
        "lib/at_input.js",
        "lib/at_oauth.html",
        "lib/at_oauth.js",
        "lib/at_pwd_form.html",
        "lib/at_pwd_form.js",
        "lib/at_pwd_form_btn.html",
        "lib/at_pwd_form_btn.js",
        "lib/at_pwd_link.html",
        "lib/at_pwd_link.js",
        "lib/at_result.html",
        "lib/at_result.js",
        "lib/at_sep.html",
        "lib/at_sep.js",
        "lib/at_signin_link.html",
        "lib/at_signin_link.js",
        "lib/at_signup_link.html",
        "lib/at_signup_link.js",
        "lib/at_social.html",
        "lib/at_social.js",
        "lib/at_terms_link.html",
        "lib/at_terms_link.js",
        "lib/at_title.html",
        "lib/at_title.js",
        "lib/full_page_at_form.html",
        "lib/at_foundation.less"
    ], ["client"]);
});

Package.on_test(function(api) {
    api.use([
        "splendido:accounts-templates-foundation",
        "splendido:accounts-templates-core@0.9.15",
    ]);

    api.use([
        "accounts-password",
        "tinytest",
        "test-helpers"
    ], ["client", "server"]);

    api.add_files([
        "tests/tests.js"
    ], ["client", "server"]);
});<|endoftext|>


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

/**
 * Repository query
 */
var repoPathUrl = function() {
    return (Settings.BIPLUGIN5 ? "/repository"
                    : (Settings.BIPLUGIN ? "/pentahorepository2" : "/repository2"));
}

var RepositoryObject = Backbone.Model.extend( {
    url: function( ) {
        var segment = repoPathUrl() + "/resource";
        return encodeURI(Saiku.session.username + segment);
    }
} );

var RepositoryAclObject = Backbone.Model.extend( {
    url: function( ) {
        var segment = repoPathUrl() + "/resource/acl";
        return encodeURI(Saiku.session.username + segment);
    },
    parse: function(response) {
        if (response != "OK") {
            _.extend(this.attributes, response);
        }
    }
} );

var RepositoryZipExport = Backbone.Model.extend( {
    url: function( ) {
        var segment = repoPathUrl() + "/resource/zip";
        return encodeURI(Saiku.session.username) + segment;
    }
} );

var SavedQuery = Backbone.Model.extend({

    parse: function(response) {
        //console.log("response: " + response);
        //this.xml = response;
    },

    url: function() {
        var u = encodeURI(Saiku.session.username) + repoPathUrl() + "/resource";
        return u;
    },

    move_query_to_workspace: function(model, response) {
        var file = response;
        var filename = model.get('file');
        for (var key in Settings) {
            if (key.match("^PARAM")=="PARAM") {
                var variable = key.substring("PARAM".length, key.length);
                var Re = new RegExp("\\$\\{" + variable + "\\}","g");
                var Re2 = new RegExp("\\$\\{" + variable.toLowerCase() + "\\}","g");
                file = file.replace(Re,Settings[key]);
                file = file.replace(Re2,Settings[key]);

            }
        }
        var query = new Query({
            xml: file,
            formatter: Settings.CELLSET_FORMATTER
        },{
            name: filename
        });

        var tab = Saiku.tabs.add(new Workspace({ query: query }));
    }
});

/**
 * Repository adapter
 */
var Repository = Backbone.Collection.extend({
    model: SavedQuery,

    initialize: function(args, options) {
        if (options && options.dialog) {
            this.dialog = options.dialog;
        }
    },

    parse: function(response) {
        if (this.dialog) {
            this.dialog.populate(response);
        }
    },

    url: function() {
        var segment = repoPathUrl() + "?type=saiku";
        return encodeURI(Saiku.session.username + segment);
    }
});
<commit_msg>fix zip path<commit_after>/*
 *   Copyright 2012 OSBI Ltd
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

/**
 * Repository query
 */
var repoPathUrl = function() {
    return (Settings.BIPLUGIN5 ? "/repository"
                    : (Settings.BIPLUGIN ? "/pentahorepository2" : "/repository2"));
}

var RepositoryObject = Backbone.Model.extend( {
    url: function( ) {
        var segment = repoPathUrl() + "/resource";
        return encodeURI(Saiku.session.username + segment);
    }
} );

var RepositoryAclObject = Backbone.Model.extend( {
    url: function( ) {
        var segment = repoPathUrl() + "/resource/acl";
        return encodeURI(Saiku.session.username + segment);
    },
    parse: function(response) {
        if (response != "OK") {
            _.extend(this.attributes, response);
        }
    }
} );

var RepositoryZipExport = Backbone.Model.extend( {
    url: function( ) {
        var segment = repoPathUrl() + "/zip";
        return encodeURI(Saiku.session.username) + segment;
    }
} );

var SavedQuery = Backbone.Model.extend({

    parse: function(response) {
        //console.log("response: " + response);
        //this.xml = response;
    },

    url: function() {
        var u = encodeURI(Saiku.session.username) + repoPathUrl() + "/resource";
        return u;
    },

    move_query_to_workspace: function(model, response) {
        var file = response;
        var filename = model.get('file');
        for (var key in Settings) {
            if (key.match("^PARAM")=="PARAM") {
                var variable = key.substring("PARAM".length, key.length);
                var Re = new RegExp("\\$\\{" + variable + "\\}","g");
                var Re2 = new RegExp("\\$\\{" + variable.toLowerCase() + "\\}","g");
                file = file.replace(Re,Settings[key]);
                file = file.replace(Re2,Settings[key]);

            }
        }
        var query = new Query({
            xml: file,
            formatter: Settings.CELLSET_FORMATTER
        },{
            name: filename
        });

        var tab = Saiku.tabs.add(new Workspace({ query: query }));
    }
});

/**
 * Repository adapter
 */
var Repository = Backbone.Collection.extend({
    model: SavedQuery,

    initialize: function(args, options) {
        if (options && options.dialog) {
            this.dialog = options.dialog;
        }
    },

    parse: function(response) {
        if (this.dialog) {
            this.dialog.populate(response);
        }
    },

    url: function() {
        var segment = repoPathUrl() + "?type=saiku";
        return encodeURI(Saiku.session.username + segment);
    }
});
<|endoftext|>


<commit_before>(function() {

    if (typeof String.prototype.trim !== 'function') {
        String.prototype.trim = function() {
            return this.replace(/^\s+|\s+$/g, '');
        }
    }

    window.utils = {

        isEmpty: function(val) {
            return typeof val === 'undefined' || val === null || (val.toString && !val.toString().trim().length);
        },

        getObject: function(obj, where) {
            if (!obj) return obj;

            if (utils.isEmpty(where)) return obj;

            // Expect "where" as a dot notation name, so split "where" with a dot
            var keys = where.split('.');

            var key = keys[0];
            if (utils.isEmpty(obj[key])) return obj[key];

            var value = obj[key];
            for (var i = 1; i < keys.length; i++) {
                key = keys[i];
                value = value[key];

                if (utils.isEmpty(value)) return value;
            }

            return value;
        },

        createParamGet: function(data, keys) {
            if (!keys || !keys.length) {
                keys = Object.keys(data);
            }

            var pairs = [];
            for (var i = 0; i < keys.length; i++) {
                var key = keys[i];
                var value = utils.isEmpty(data[key]) ? '' : data[key];

                pairs.push(key + '=' + value);
            }

            return pairs.join('&');
        }

    };

})();

//read all in UMS
var wms = new WebMS(true);

//read card bluetooth ::: 03-02-2016 //xsam32 ref. R3-team
var THIDReader = new thaiIDReader(8030, true);

var convertDate = function(YYYYMMDD) {
    var d = YYYYMMDD[6] + "" + YYYYMMDD[7];
    var m = YYYYMMDD[4] + "" + YYYYMMDD[5];
    var y = YYYYMMDD[0] + "" + YYYYMMDD[1] + "" + YYYYMMDD[2] + "" + YYYYMMDD[3];
    return d + "/" + m + "/" + y;
};

function parseDataAndroid(res) {

    var info = res.data.info;
    return {
        CitizenID: info.ID,
        PrefixTH: info.titleNameTH,
        FirstNameTH: info.nameTH,
        MiddleNameTH: info.midNameTH,
        LastNameTH: info.lastNameTH,
        PrefixEN: info.titleNameEN,
        FirstNameEN: info.nameEN,
        MiddleNameEN: info.midNameEN,
        LastNameEN: info.lastNameEN,
        HomeNumber: info.addressNumber,
        Moo: info.mooNumber,
        Trok: info.trok,
        Soi: info.soi,
        Road: info.road,
        District: info.subDistrict,
        Amphur: info.district,
        Province: info.province,
        Sex: info.gender,
        BirthDay: convertDate(info.birthdayDate),
        IssueAt: info.department,
        IssueDay: convertDate(info.manufacturingDate),
        ExpireDay: convertDate(info.expiryDate),
        Photo: res.data.photo,
    };
}

function ReadCard_Android() {
    $('.idBtnReadCard_android').prop('disabled', true);
    wms.readAll(function(data) {
        $('.idBtnReadCard_android').prop('disabled', false);

        var args = parseDataAndroid(data);
        if ($('#ReadAuthorize').val() == 'true') {
            angular.element(document.getElementById('' + $('#divID').val())).scope().SetCardValue2(args);
        } else if ($('#ReadAuthorize').val() == 'readNewOwnerReadCard') {
            angular.element(document.getElementById('' + $('#divID').val())).scope().SetCardValue3(args);
            $('#btnReadCard3Close').click();
        } else if ($('#ReadAuthorize').val() == 'freeReadCard') {
            angular.element(document.getElementById('' + $('#divID').val())).scope().freeReadCard(args);
        } else {
            angular.element(document.getElementById('' + $('#divID').val())).scope().SetCardValue(args);
        }
    }, function(error) {
        //alert(JSON.stringify(error));
        console.log('error');
        console.log(error);

        $('.idBtnReadCard_android').prop('disabled', false);
        angular.element(document.getElementById('' + $('#divID').val())).scope().readCardError(error.message);
    });
};

function ReadBarcode_Android() {
    wms.readBarcode(function(response) {
        var txtBarCode = response.data.barcode;
        angular.element(document.getElementById('' + $('#divID').val())).scope().readBarcode(txtBarCode);
    }, function(error) {
        //alert(JSON.stringify(error));
        console.log('error');
        console.log(error);

        angular.element(document.getElementById('' + $('#divID').val())).scope().readCardError(error.message);
    });
};

function checkReadBarcode_Android() {
    var ua = navigator.userAgent.toLowerCase();
    var isAndroid = ua.indexOf("android") > -1; //&& ua.indexOf("mobile");
    if (isAndroid == true) {
        ReadBarcode_Android();
    }
};

function print_androidUMS(url) {
    // wms.printWeb(url, function(success){
    //     alert("Print SUCCESSFUL");
    // }, function(error){
    //     alert(error);
    // });
    // setTimeout(function(){
    // }, 3000);
    // var urlx = "http://sff-uat.true.th:8980/webui/PDFs/AfterSaleReport.pdf";
    var urlLCS = localStorage.getItem('urlx');
    var webContextPath = getContextPath();
    //var urlx = window.location.origin+window.location.pathname+"pdfCanvasV4.html?action=none&url=" + urlLCS;
    var urlx = "http://sff-uat.true.th:8980/webui/report/view/pdf/" + urlLCS + ".pdf";
    console.log(urlx);
    alert('Print URL:' + urlx);
    wms.printWeb(urlx, function(x) {
        //alert("Print SUCCESSFUL");
    }, function(x) {
        alert('Print ERROR : ' + JSON.stringify(x));
    });

}
<commit_msg>Test UMS print v0.3<commit_after>(function() {

    if (typeof String.prototype.trim !== 'function') {
        String.prototype.trim = function() {
            return this.replace(/^\s+|\s+$/g, '');
        }
    }

    window.utils = {

        isEmpty: function(val) {
            return typeof val === 'undefined' || val === null || (val.toString && !val.toString().trim().length);
        },

        getObject: function(obj, where) {
            if (!obj) return obj;

            if (utils.isEmpty(where)) return obj;

            // Expect "where" as a dot notation name, so split "where" with a dot
            var keys = where.split('.');

            var key = keys[0];
            if (utils.isEmpty(obj[key])) return obj[key];

            var value = obj[key];
            for (var i = 1; i < keys.length; i++) {
                key = keys[i];
                value = value[key];

                if (utils.isEmpty(value)) return value;
            }

            return value;
        },

        createParamGet: function(data, keys) {
            if (!keys || !keys.length) {
                keys = Object.keys(data);
            }

            var pairs = [];
            for (var i = 0; i < keys.length; i++) {
                var key = keys[i];
                var value = utils.isEmpty(data[key]) ? '' : data[key];

                pairs.push(key + '=' + value);
            }

            return pairs.join('&');
        }

    };

})();

//read all in UMS
var wms = new WebMS(true);

//read card bluetooth ::: 03-02-2016 //xsam32 ref. R3-team
var THIDReader = new thaiIDReader(8030, true);

var convertDate = function(YYYYMMDD) {
    var d = YYYYMMDD[6] + "" + YYYYMMDD[7];
    var m = YYYYMMDD[4] + "" + YYYYMMDD[5];
    var y = YYYYMMDD[0] + "" + YYYYMMDD[1] + "" + YYYYMMDD[2] + "" + YYYYMMDD[3];
    return d + "/" + m + "/" + y;
};

function parseDataAndroid(res) {

    var info = res.data.info;
    return {
        CitizenID: info.ID,
        PrefixTH: info.titleNameTH,
        FirstNameTH: info.nameTH,
        MiddleNameTH: info.midNameTH,
        LastNameTH: info.lastNameTH,
        PrefixEN: info.titleNameEN,
        FirstNameEN: info.nameEN,
        MiddleNameEN: info.midNameEN,
        LastNameEN: info.lastNameEN,
        HomeNumber: info.addressNumber,
        Moo: info.mooNumber,
        Trok: info.trok,
        Soi: info.soi,
        Road: info.road,
        District: info.subDistrict,
        Amphur: info.district,
        Province: info.province,
        Sex: info.gender,
        BirthDay: convertDate(info.birthdayDate),
        IssueAt: info.department,
        IssueDay: convertDate(info.manufacturingDate),
        ExpireDay: convertDate(info.expiryDate),
        Photo: res.data.photo,
    };
}

function ReadCard_Android() {
    $('.idBtnReadCard_android').prop('disabled', true);
    wms.readAll(function(data) {
        $('.idBtnReadCard_android').prop('disabled', false);

        var args = parseDataAndroid(data);
        if ($('#ReadAuthorize').val() == 'true') {
            angular.element(document.getElementById('' + $('#divID').val())).scope().SetCardValue2(args);
        } else if ($('#ReadAuthorize').val() == 'readNewOwnerReadCard') {
            angular.element(document.getElementById('' + $('#divID').val())).scope().SetCardValue3(args);
            $('#btnReadCard3Close').click();
        } else if ($('#ReadAuthorize').val() == 'freeReadCard') {
            angular.element(document.getElementById('' + $('#divID').val())).scope().freeReadCard(args);
        } else {
            angular.element(document.getElementById('' + $('#divID').val())).scope().SetCardValue(args);
        }
    }, function(error) {
        //alert(JSON.stringify(error));
        console.log('error');
        console.log(error);

        $('.idBtnReadCard_android').prop('disabled', false);
        angular.element(document.getElementById('' + $('#divID').val())).scope().readCardError(error.message);
    });
};

function ReadBarcode_Android() {
    wms.readBarcode(function(response) {
        var txtBarCode = response.data.barcode;
        angular.element(document.getElementById('' + $('#divID').val())).scope().readBarcode(txtBarCode);
    }, function(error) {
        //alert(JSON.stringify(error));
        console.log('error');
        console.log(error);

        angular.element(document.getElementById('' + $('#divID').val())).scope().readCardError(error.message);
    });
};

function checkReadBarcode_Android() {
    var ua = navigator.userAgent.toLowerCase();
    var isAndroid = ua.indexOf("android") > -1; //&& ua.indexOf("mobile");
    if (isAndroid == true) {
        ReadBarcode_Android();
    }
};

function print_androidUMS(url) {
    // wms.printWeb(url, function(success){
    //     alert("Print SUCCESSFUL");
    // }, function(error){
    //     alert(error);
    // });
    // setTimeout(function(){
    // }, 3000);
    // var urlx = "http://sff-uat.true.th:8980/webui/PDFs/AfterSaleReport.pdf";
    var urlLCS = localStorage.getItem('urlx');
    var webContextPath = getContextPath();
    //var urlx = window.location.origin+window.location.pathname+"pdfCanvasV4.html?action=none&url=" + urlLCS;
    var urlx = "http://sff-uat.true.th:8980" + urlLCS + ".pdf";
    // var urlx = "http://sff-uat.true.th:8980/webui/images/commons/readcard@2x.png";
    console.log(urlx);
    alert('Print URL:' + urlx);
    wms.printWeb(urlx, function(x) {
        //alert("Print SUCCESSFUL");
    }, function(x) {
        alert('Print ERROR : ' + JSON.stringify(x));
    });

}
<|endoftext|>


<commit_before>import EventEmitter from 'events';
import uniqueId from 'lodash.uniqueid';
import isObject from 'lodash.isobject';
import isFunction from 'lodash.isfunction';
import isUndefined from 'lodash.isundefined';
import uuidV4 from 'uuid/v4';

/**
 * Model identities
 */
export const identities = new Map();
/**
 * Flags for controlling mutation.
 * Flag index n must have value 2^n.
 * @example
 * this.set('active', value, UNSET_IF_FALSE);
 * this.set('active', value, UNSET_IF_FALSE + SET_SILENT);
 */
export const SET_SILENT = 1; // Don't dispatch event when setting.
export const UNSET_IF_FALSE = 2; // If value evaluates to Boolean False, unset property.
export const SOFT_UPDATE = 4; // During update, if no setter or model found, use set() silent.
export const RESET_REFERENCE = 8; // Reset this._data or this._items references in reset().
/**
 * Helper for checking flags, e.g. for Model.set().
 * @param {Integer} dec Sum of flags.
 * @param {Integer} flag Flag to check.
 * @return {boolean} True if flag is set.
 */
export function flagIsSet(dec, flag) {
    const binStr = (dec >>> 0).toString(2);
    const flagIndex = binStr.length - (flag >>> 0).toString(2).length;
    return binStr[flagIndex] === '1';
}
/**
 * Model
 */
export default class Model extends EventEmitter {
    /**
     * Model.constructor
     * @param {Object} data JSON serializable object.
     * @param {...} args Arguments passed to _getDefaults().
     */
    constructor(data = {}, ...args) {
        super();
        // Update with defaults
        this._withDefaults(data, ...args);
        // Validate data
        this._validate(data);
        // Valid, set
        this._data = data;
        // Store previous
        this._previousData = {};
        // Store modified
        this._modified = undefined;
        // Client id
        this._cid = this._getUniqueClientId();
    }
    /**
     * Get client id. Not persisted.
     * @return {String}
     */
    get cid() {
        return this._cid;
    }
    /**
     * Get uuid.
     * @return {String}
     */
    get uuid() {
        return this.get('uuid');
    }
    /**
     * Underlying data object for model.
     * @return {String} Model polymorphic identity.
     */
    getModelIdentity() {
        return this.get('identity');
    }
    /**
     * Underlying data object for model.
     * @return {Object} JSON serializable object.
     */
    getModelData() {
        return this._data;
    }
    /**
     * Get value of data.property.
     * @param {String} property Name of property.
     * @param {*} defaultValue Default value to return if property is undefined.
     * @return {*}
     */
    get(property, defaultValue) {
        return this.has(property) ? this._data[property] : defaultValue;
    }
    /**
     * Return previous value of property.
     * @param {String} property Name of property.
     * @return {*}
     */
    getPrevious(property) {
        return this._previousData[property];
    }
    /**
     * Check if property is set in data.
     * @param {String} property Name of property.
     * @return {boolean} True if set.
     */
    has(property) {
        return this._data.hasOwnProperty(property);
    }
    /**
     * Check if previous value of property is same
     * as current.
     * @param {list of strings} properties Names of properties.
     * @return {boolean} True if any of them has changed.
     */
    hasChanged(...properties) {
        for (let prop of properties) {
            if (this._previousData[prop] !== this._data[prop]) {
                return true;
            }
        }
        return false;
    }
    /**
     * Set value of data.property.
     * @param {String} property Name of property.
     * @param {*} value Anything JSON serializable.
     * @param {Integer} flags (@see constants).
     * @return {Model} The Model object.
     */
    set(property, value, flags = 0) {
        // Unset?
        if (flagIsSet(flags, UNSET_IF_FALSE) && Boolean(value) === false) {
            this.unset(property, flags);
            return;
        }
        // Previous value
        this._previousData[property] = this._data[property];
        // If property not set or value different
        if (!this.has(property) || this._data[property] !== value) {
            // Set new value
            this._data[property] = value;
            // Set modified
            this.updateModified();
        }
        // Dispatch change event, if not silent
        if (this.hasChanged(property) && !flagIsSet(flags, SET_SILENT)) {
            this.dispatchChange(property, value, this._previousData[property]);
        }
        // Return
        return this;
    }
    /**
     * Toggle boolean property.
     * @param {String} property Name of property.
     * @param {Integer} flags (@see constants).
     * @return {Model} The Model object.
     */
    toggle(property, flags = 0) {
        const current = this.get(property, false); // False if not set
        return this.set(property, !current, flags); // Set to !current
    }
    /**
     * Unset value of data.property.
     * @param {String} property Name of property.
     * @param {Integer} flags (@see constants).
     * @return {boolean} True if property found and unset.
     */
    unset(property, flags = 0) {
        // Previous value
        this._previousData[property] = this._data[property];
        // Present in _data
        const present = this._data.hasOwnProperty(property);
        // Delete from data
        delete this._data[property];
        // Has changed?
        if (this.hasChanged(property)) {
            // Set modified
            this.updateModified();
            // Dispatch change event, if not silent
            if (!flagIsSet(flags, SET_SILENT)) {
                this.dispatchChange(property, undefined, this._previousData[property]);
            }
        }
        // True if present and deleted.
        return present;
    }
    /**
     * Delete multiple properties from data.
     * @param {list of strings} properties
     * @return {Model} The Model object.
     */
    unsetMultiple(...properties) {
        for (let prop of properties) {
            this._previousData[prop] = this._data[prop];
            delete this._data[prop];
        }
        if (this.hasChanged(...properties)) {
            this.updateModified();
        }
        // Return
        return this;
    }
    /**
     * Reset underlying data object for model.
     * @param {Object}  data JSON serializable object.
     * @param {Integer} flags (@see constants).
     * @return {Model} The Model object.
     */
    reset(data, flags = 0) {
        data = data || {};
        // Keep identity and uuid
        const {uuid, identity} = this._data;
        Object.assign(data, {uuid, identity});
        // Update new data with defaults
        this._withDefaults(data);
        // If reset reference flag
        if (flagIsSet(flags, RESET_REFERENCE)) {
            // Reset data reference
            this._data = data;
            // Dispatch change event, if not silent
            if (!flagIsSet(flags, SET_SILENT)) {
                this.dispatchChange();
            }
        // else, reset properties but keep this reference (not recursive)
        } else {
            // Unset properties not in data
            Object.keys(this._data).forEach(property => {
                if (isUndefined(data[property])) {
                    this.unset(property, flags);
                }
            });
            // Recursive reset or updateProperty
            Object.keys(this._data).forEach(property => {
                // Check recursiveness
                let currentVal = this[property];
                if (currentVal && isFunction(currentVal.reset)) {
                    currentVal.reset(data[property], flags);
                // Just update
                } else {
                    this.updateProperty(property, data[property], flags);
                }
            });
        }
        // Validate
        this._validate(this._data);
        // Return
        return this;
    }
    /**
     * Recursively update model properties.
     * @param {Object} data JSON serializable object.
     * @param {Integer} flags (@see constants).
     * @return {Model} The Model object.
     */
    update(data, flags = 0) {
        // Iterate data dict
        Object.keys(data).forEach(prop => {
            this.updateProperty(prop, data[prop], flags);
        });
        // Set modified
        this.updateModified();
        // Notify if not silent. Dispatch for each property?
        if (!flagIsSet(flags, SET_SILENT)) {
            this.dispatchChange();
        }
        // Return
        return this;
    }
    /**
     * Update single property.
     * @param {String} property Name of property.
     * @param {*} value Anything JSON serializable.
     * @param {Integer} flags (@see constants).
     * @return {Model} The Model object.
     */
    updateProperty(property, value, flags = 0) {
        // Check if setter exists
        if (typeof this.__lookupSetter__(property) !== 'undefined') {
            this[property] = value;
            return this;
        }
        // No setter, check if getter returns model
        const currentVal = this[property];
        if (currentVal && isFunction(currentVal.update)) {
            // If yes, update recursively.
            currentVal.update(value, flags);
            return this;
        }
        // Soft update
        if (flagIsSet(flags, SOFT_UPDATE)) {
            return this.set(property, value, flags);
        }
        // If no setter or sub model, throw error.
        throw new Error('Could not update property "' + property + '" on ' + this.constructor.name + '.');
    }
    /**
     * Update modified timestamp.
     * @param {timestamp} modified Time of modification or undefined if now.
     * @return {Model} The Model object.
     */
    updateModified(modified) {
        this._modified = modified || Date.now();
        // Return
        return this;
    }
    /**
     * Return a copy of this model, with new uuids.
     * FIX: Better way to do this?
     * @return {Model} New instance of Model (or Model subclass).
     */
    copy() {
        // stringify data dict
        const jsonStr = JSON.stringify(this._data);
        // replace all uuids with new one's.
        const uuidRegexp = /"uuid":"........-....-....-....-............"/g;
        const newJsonStr = jsonStr.replace(uuidRegexp, () => {
            return '"uuid":"' + uuidV4() + '"';
        });
        // return instance of this
        const Constructor = this.constructor;
        return new Constructor(JSON.parse(newJsonStr));
    }
    /**
     * Interface for dispatching events.
     * Currently alias for EventEmitter.emit. May change.
     * @param {String} eventType Event type key.
     * @param {...} args Arguments passed to listeners.
     * @return {Model} The Model object.
     */
    dispatchEvent(eventType, ...args) {
        this.emit(eventType, ...[eventType, this].concat(args));
        // Return
        return this;
    }
    /**
     * Dispatch change events.
     * @param {String} property Name of property.
     * @param {*} newValue Anything JSON serializable.
     * @param {*} oldValue Anything JSON serializable.
     * @return {Model} The Model object.
     */
    dispatchChange(property, newValue, oldValue) {
        if (property) {
            this.dispatchEvent('change ' + property, newValue, oldValue);
        }
        return this.dispatchEvent('change');
    }
    /**
     * Alias for EventEmitter.addListener
     */
    addEventListener(event, listener) {
        this.addListener(event, listener);
        // Return
        return this;
    }
    /**
     * Alias for EventEmitter.removeListener
     */
    removeEventListener(event, listener) {
        this.removeListener(event, listener);
        // Return
        return this;
    }
    /**
     * Dispose model and sub models recursively.
     * Remove event listeners and delete references.
     * @return {Model} The Model object.
     */
    dispose() {
        // Remove event listeners
        this.removeAllListeners();
        // Check sub models on this, recursively
        Object.keys(this).forEach(attr => {
            if (isObject(this[attr]) && isFunction(this[attr].dispose)) {
                this[attr].dispose();
            }
        });
        // delete refs
        this._deleteReferences();
        // Return
        return this;
    }
    /**
     * Delete references set on model.
     */
    _deleteReferences() {
        delete this._data;
        delete this._previousData;
        delete this._modified;
    }
    /**
     * Check validity of data. Throw error if not valid.
     * @param {Object} data JSON serializable object.
     */
    _validate(data) {
        // Abstract
    }
    /**
     * Return default data object for new instance.
     * @param {...} constructorArgs List of arguments passed in constructor.
     * @return {Object} Default data (JSON serializable object) for Model.
     */
    _getDefaults(...constructorArgs) {
        return {
            // Model polymorphic identity
            identity: Model.identity,
            // model uuid
            uuid: uuidV4()
        };
    }
    /**
     * Update data object with defaults.
     * @param {Object} data JSON serializable object.
     * @param {...} constructorArgs List of arguments passed in constructor.
     * @return {Model} The Model object.
     */
    _withDefaults(data, ...constructorArgs) {
        // defaults
        const defaultData = this._getDefaults(...constructorArgs);
        // Update undefined props from defaults
        Object.keys(defaultData).forEach(prop => {
            if (isUndefined(data[prop])) {
                data[prop] = defaultData[prop];
            }
        });
        return this;
    }
    /**
     * Return unique client id.
     * @return {String} Unique string.
     */
    _getUniqueClientId() {
        return uniqueId(this.getModelIdentity());
    }

}
// Polymorphic identity
Model.identity = 'mozy.Model';
// Register Model
identities.set(Model.identity, Model);
<commit_msg>Model. _shouldSetDefaultValue (for changing behaviour of _withDefaults )<commit_after>import EventEmitter from 'events';
import uniqueId from 'lodash.uniqueid';
import isObject from 'lodash.isobject';
import isFunction from 'lodash.isfunction';
import isUndefined from 'lodash.isundefined';
import uuidV4 from 'uuid/v4';

/**
 * Model identities
 */
export const identities = new Map();
/**
 * Flags for controlling mutation.
 * Flag index n must have value 2^n.
 * @example
 * this.set('active', value, UNSET_IF_FALSE);
 * this.set('active', value, UNSET_IF_FALSE + SET_SILENT);
 */
export const SET_SILENT = 1; // Don't dispatch event when setting.
export const UNSET_IF_FALSE = 2; // If value evaluates to Boolean False, unset property.
export const SOFT_UPDATE = 4; // During update, if no setter or model found, use set() silent.
export const RESET_REFERENCE = 8; // Reset this._data or this._items references in reset().
/**
 * Helper for checking flags, e.g. for Model.set().
 * @param {Integer} dec Sum of flags.
 * @param {Integer} flag Flag to check.
 * @return {boolean} True if flag is set.
 */
export function flagIsSet(dec, flag) {
    const binStr = (dec >>> 0).toString(2);
    const flagIndex = binStr.length - (flag >>> 0).toString(2).length;
    return binStr[flagIndex] === '1';
}
/**
 * Model
 */
export default class Model extends EventEmitter {
    /**
     * Model.constructor
     * @param {Object} data JSON serializable object.
     * @param {...} args Arguments passed to _getDefaults().
     */
    constructor(data = {}, ...args) {
        super();
        // Update with defaults
        this._withDefaults(data, ...args);
        // Validate data
        this._validate(data);
        // Valid, set
        this._data = data;
        // Store previous
        this._previousData = {};
        // Store modified
        this._modified = undefined;
        // Client id
        this._cid = this._getUniqueClientId();
    }
    /**
     * Get client id. Not persisted.
     * @return {String}
     */
    get cid() {
        return this._cid;
    }
    /**
     * Get uuid.
     * @return {String}
     */
    get uuid() {
        return this.get('uuid');
    }
    /**
     * Underlying data object for model.
     * @return {String} Model polymorphic identity.
     */
    getModelIdentity() {
        return this.get('identity');
    }
    /**
     * Underlying data object for model.
     * @return {Object} JSON serializable object.
     */
    getModelData() {
        return this._data;
    }
    /**
     * Get value of data.property.
     * @param {String} property Name of property.
     * @param {*} defaultValue Default value to return if property is undefined.
     * @return {*}
     */
    get(property, defaultValue) {
        return this.has(property) ? this._data[property] : defaultValue;
    }
    /**
     * Return previous value of property.
     * @param {String} property Name of property.
     * @return {*}
     */
    getPrevious(property) {
        return this._previousData[property];
    }
    /**
     * Check if property is set in data.
     * @param {String} property Name of property.
     * @return {boolean} True if set.
     */
    has(property) {
        return this._data.hasOwnProperty(property);
    }
    /**
     * Check if previous value of property is same
     * as current.
     * @param {list of strings} properties Names of properties.
     * @return {boolean} True if any of them has changed.
     */
    hasChanged(...properties) {
        for (let prop of properties) {
            if (this._previousData[prop] !== this._data[prop]) {
                return true;
            }
        }
        return false;
    }
    /**
     * Set value of data.property.
     * @param {String} property Name of property.
     * @param {*} value Anything JSON serializable.
     * @param {Integer} flags (@see constants).
     * @return {Model} The Model object.
     */
    set(property, value, flags = 0) {
        // Unset?
        if (flagIsSet(flags, UNSET_IF_FALSE) && Boolean(value) === false) {
            this.unset(property, flags);
            return;
        }
        // Previous value
        this._previousData[property] = this._data[property];
        // If property not set or value different
        if (!this.has(property) || this._data[property] !== value) {
            // Set new value
            this._data[property] = value;
            // Set modified
            this.updateModified();
        }
        // Dispatch change event, if not silent
        if (this.hasChanged(property) && !flagIsSet(flags, SET_SILENT)) {
            this.dispatchChange(property, value, this._previousData[property]);
        }
        // Return
        return this;
    }
    /**
     * Toggle boolean property.
     * @param {String} property Name of property.
     * @param {Integer} flags (@see constants).
     * @return {Model} The Model object.
     */
    toggle(property, flags = 0) {
        const current = this.get(property, false); // False if not set
        return this.set(property, !current, flags); // Set to !current
    }
    /**
     * Unset value of data.property.
     * @param {String} property Name of property.
     * @param {Integer} flags (@see constants).
     * @return {boolean} True if property found and unset.
     */
    unset(property, flags = 0) {
        // Previous value
        this._previousData[property] = this._data[property];
        // Present in _data
        const present = this._data.hasOwnProperty(property);
        // Delete from data
        delete this._data[property];
        // Has changed?
        if (this.hasChanged(property)) {
            // Set modified
            this.updateModified();
            // Dispatch change event, if not silent
            if (!flagIsSet(flags, SET_SILENT)) {
                this.dispatchChange(property, undefined, this._previousData[property]);
            }
        }
        // True if present and deleted.
        return present;
    }
    /**
     * Delete multiple properties from data.
     * @param {list of strings} properties
     * @return {Model} The Model object.
     */
    unsetMultiple(...properties) {
        for (let prop of properties) {
            this._previousData[prop] = this._data[prop];
            delete this._data[prop];
        }
        if (this.hasChanged(...properties)) {
            this.updateModified();
        }
        // Return
        return this;
    }
    /**
     * Reset underlying data object for model.
     * @param {Object}  data JSON serializable object.
     * @param {Integer} flags (@see constants).
     * @return {Model} The Model object.
     */
    reset(data, flags = 0) {
        data = data || {};
        // Keep identity and uuid
        const {uuid, identity} = this._data;
        Object.assign(data, {uuid, identity});
        // Update new data with defaults
        this._withDefaults(data);
        // If reset reference flag
        if (flagIsSet(flags, RESET_REFERENCE)) {
            // Reset data reference
            this._data = data;
            // Dispatch change event, if not silent
            if (!flagIsSet(flags, SET_SILENT)) {
                this.dispatchChange();
            }
        // else, reset properties but keep this reference (not recursive)
        } else {
            // Unset properties not in data
            Object.keys(this._data).forEach(property => {
                if (isUndefined(data[property])) {
                    this.unset(property, flags);
                }
            });
            // Recursive reset or updateProperty
            Object.keys(this._data).forEach(property => {
                // Check recursiveness
                let currentVal = this[property];
                if (currentVal && isFunction(currentVal.reset)) {
                    currentVal.reset(data[property], flags);
                // Just update
                } else {
                    this.updateProperty(property, data[property], flags);
                }
            });
        }
        // Validate
        this._validate(this._data);
        // Return
        return this;
    }
    /**
     * Recursively update model properties.
     * @param {Object} data JSON serializable object.
     * @param {Integer} flags (@see constants).
     * @return {Model} The Model object.
     */
    update(data, flags = 0) {
        // Iterate data dict
        Object.keys(data).forEach(prop => {
            this.updateProperty(prop, data[prop], flags);
        });
        // Set modified
        this.updateModified();
        // Notify if not silent. Dispatch for each property?
        if (!flagIsSet(flags, SET_SILENT)) {
            this.dispatchChange();
        }
        // Return
        return this;
    }
    /**
     * Update single property.
     * @param {String} property Name of property.
     * @param {*} value Anything JSON serializable.
     * @param {Integer} flags (@see constants).
     * @return {Model} The Model object.
     */
    updateProperty(property, value, flags = 0) {
        // Check if setter exists
        if (typeof this.__lookupSetter__(property) !== 'undefined') {
            this[property] = value;
            return this;
        }
        // No setter, check if getter returns model
        const currentVal = this[property];
        if (currentVal && isFunction(currentVal.update)) {
            // If yes, update recursively.
            currentVal.update(value, flags);
            return this;
        }
        // Soft update
        if (flagIsSet(flags, SOFT_UPDATE)) {
            return this.set(property, value, flags);
        }
        // If no setter or sub model, throw error.
        throw new Error('Could not update property "' + property + '" on ' + this.constructor.name + '.');
    }
    /**
     * Update modified timestamp.
     * @param {timestamp} modified Time of modification or undefined if now.
     * @return {Model} The Model object.
     */
    updateModified(modified) {
        this._modified = modified || Date.now();
        // Return
        return this;
    }
    /**
     * Return a copy of this model, with new uuids.
     * FIX: Better way to do this?
     * @return {Model} New instance of Model (or Model subclass).
     */
    copy() {
        // stringify data dict
        const jsonStr = JSON.stringify(this._data);
        // replace all uuids with new one's.
        const uuidRegexp = /"uuid":"........-....-....-....-............"/g;
        const newJsonStr = jsonStr.replace(uuidRegexp, () => {
            return '"uuid":"' + uuidV4() + '"';
        });
        // return instance of this
        const Constructor = this.constructor;
        return new Constructor(JSON.parse(newJsonStr));
    }
    /**
     * Interface for dispatching events.
     * Currently alias for EventEmitter.emit. May change.
     * @param {String} eventType Event type key.
     * @param {...} args Arguments passed to listeners.
     * @return {Model} The Model object.
     */
    dispatchEvent(eventType, ...args) {
        this.emit(eventType, ...[eventType, this].concat(args));
        // Return
        return this;
    }
    /**
     * Dispatch change events.
     * @param {String} property Name of property.
     * @param {*} newValue Anything JSON serializable.
     * @param {*} oldValue Anything JSON serializable.
     * @return {Model} The Model object.
     */
    dispatchChange(property, newValue, oldValue) {
        if (property) {
            this.dispatchEvent('change ' + property, newValue, oldValue);
        }
        return this.dispatchEvent('change');
    }
    /**
     * Alias for EventEmitter.addListener
     */
    addEventListener(event, listener) {
        this.addListener(event, listener);
        // Return
        return this;
    }
    /**
     * Alias for EventEmitter.removeListener
     */
    removeEventListener(event, listener) {
        this.removeListener(event, listener);
        // Return
        return this;
    }
    /**
     * Dispose model and sub models recursively.
     * Remove event listeners and delete references.
     * @return {Model} The Model object.
     */
    dispose() {
        // Remove event listeners
        this.removeAllListeners();
        // Check sub models on this, recursively
        Object.keys(this).forEach(attr => {
            if (isObject(this[attr]) && isFunction(this[attr].dispose)) {
                this[attr].dispose();
            }
        });
        // delete refs
        this._deleteReferences();
        // Return
        return this;
    }
    /**
     * Delete references set on model.
     */
    _deleteReferences() {
        delete this._data;
        delete this._previousData;
        delete this._modified;
    }
    /**
     * Check validity of data. Throw error if not valid.
     * @param {Object} data JSON serializable object.
     */
    _validate(data) {
        // Abstract
    }
    /**
     * Return default data object for new instance.
     * @param {...} constructorArgs List of arguments passed in constructor.
     * @return {Object} Default data (JSON serializable object) for Model.
     */
    _getDefaults(...constructorArgs) {
        return {
            // Model polymorphic identity
            identity: Model.identity,
            // model uuid
            uuid: uuidV4()
        };
    }
    /**
     * Update data object with defaults.
     * @param {Object} data JSON serializable object.
     * @param {...} constructorArgs List of arguments passed in constructor.
     * @return {Model} The Model object.
     */
    _withDefaults(data, ...constructorArgs) {
        // defaults
        const defaultData = this._getDefaults(...constructorArgs);
        // Update undefined props from defaults
        Object.keys(defaultData).forEach(prop => {
            if (this._shouldSetDefaultValue(prop, data[prop])) {
                data[prop] = defaultData[prop];
            }
        });
        return this;
    }
    /**
     * Return true if _withDefaults should set the default
     * value for this property.
     * @param {String} property Name of property.
     * @param {*} value Anything JSON serializable.
     * @return {Boolean}
     */
    _shouldSetDefaultValue(property, value) {
        return isUndefined(value);
    }
    /**
     * Return unique client id.
     * @return {String} Unique string.
     */
    _getUniqueClientId() {
        return uniqueId(this.getModelIdentity());
    }

}
// Polymorphic identity
Model.identity = 'mozy.Model';
// Register Model
identities.set(Model.identity, Model);
<|endoftext|>


<commit_before>Package.describe({
  name:    'constellation:console',
  summary: 'An extensible development console for Meteor',
  version: '1.1.6',
  git:     'https://github.com/JackAdams/constellation.git',
  documentation: 'README.md',
  debugOnly: true
});

Package.onUse(function(api) {

  var clientFiles = [
    "client/lib/utils.js",
    "client/lib/api.js",
    "client/lib/setup.js",
    "client/row_fullscreen/fullscreen.html",
    "client/row_fullscreen/fullscreen.js",
    "client/row_config/config.html",
    "client/row_config/config.js",
    "client/row_account/account.html",
    "client/row_account/account.js",
    "client/row_account/accountViewer.html",
    "client/row_account/accountViewer.js",
    "client/row_collection/collections.html",
    "client/row_collection/collections.js",
    "client/row_collection/search.html",
    "client/row_collection/search.js",
    "client/row_collection/docViewer.html",
    "client/row_collection/docViewer.js",
    "client/row_collection/docInsert.html",
    "client/row_collection/docInsert.js",
    "client/row_collection/docControls.html",
    "client/row_collection/docControls.js",
    "client/row_actions/undoRedo.html",
    "client/row_actions/undoRedo.js",
    "client/row_actions/actions.html",
    "client/row_actions/actions.js",
    "client/Constellation.css",
    "client/Constellation.html",
    "client/Constellation.js"
  ];

  var serverFiles = [
    "server/methods.js"
  ];

  var commonFiles = [
    "common/common.js",
    "common/utility_functions.js",
    "common/mutators.js"
  ];

  api.versionsFrom('1.1');
  api.use(['templating','tracker','mongo','session','underscore','reactive-var','reactive-dict','blaze'], 'client');
  api.use('aldeed:collection2@2.3.3', {weak: true}); // This must go before: api.use('dburles:mongo-collection-instances@0.3.3');
  api.use('dburles:mongo-collection-instances@0.3.4');
  api.use('gwendall:session-json@0.1.7', 'client');
  api.use('babrahams:editable-json@0.5.4');

  api.add_files(commonFiles);
  api.add_files(clientFiles, "client");
  api.add_files(serverFiles, "server");

  if (api.export) {
    api.export('API','client');
    api.export('Constellation');
  }

});<commit_msg>Updated dependencies<commit_after>Package.describe({
  name:    'constellation:console',
  summary: 'An extensible development console for Meteor',
  version: '1.1.7',
  git:     'https://github.com/JackAdams/constellation.git',
  documentation: 'README.md',
  debugOnly: true
});

Package.onUse(function(api) {

  var clientFiles = [
    "client/lib/utils.js",
    "client/lib/api.js",
    "client/lib/setup.js",
    "client/row_fullscreen/fullscreen.html",
    "client/row_fullscreen/fullscreen.js",
    "client/row_config/config.html",
    "client/row_config/config.js",
    "client/row_account/account.html",
    "client/row_account/account.js",
    "client/row_account/accountViewer.html",
    "client/row_account/accountViewer.js",
    "client/row_collection/collections.html",
    "client/row_collection/collections.js",
    "client/row_collection/search.html",
    "client/row_collection/search.js",
    "client/row_collection/docViewer.html",
    "client/row_collection/docViewer.js",
    "client/row_collection/docInsert.html",
    "client/row_collection/docInsert.js",
    "client/row_collection/docControls.html",
    "client/row_collection/docControls.js",
    "client/row_actions/undoRedo.html",
    "client/row_actions/undoRedo.js",
    "client/row_actions/actions.html",
    "client/row_actions/actions.js",
    "client/Constellation.css",
    "client/Constellation.html",
    "client/Constellation.js"
  ];

  var serverFiles = [
    "server/methods.js"
  ];

  var commonFiles = [
    "common/common.js",
    "common/utility_functions.js",
    "common/mutators.js"
  ];

  api.versionsFrom('1.1');
  api.use(['templating','tracker','mongo','session','underscore','reactive-var','reactive-dict','blaze'], 'client');
  api.use('aldeed:collection2@2.3.3', {weak: true}); // This must go before: api.use('dburles:mongo-collection-instances@0.3.3');
  api.use('dburles:mongo-collection-instances@0.3.4');
  api.use('gwendall:session-json@0.1.7', 'client');
  api.use('babrahams:editable-json@0.5.5');

  api.add_files(commonFiles);
  api.add_files(clientFiles, "client");
  api.add_files(serverFiles, "server");

  if (api.export) {
    api.export('API','client');
    api.export('Constellation');
  }

});<|endoftext|>