<commit_before>/**
 * @file customStorage Function. Support publiser management and localstorage
 * @author wupeng10@baidu.com
 */
define(function (require) {
    'use strict';

    var fn = require('./fn');

    /**
     * Type of storage
     * @const
     * @inner
     * @type {Object}
     */
    var storageType = {
        LOCALSTORAGE: 0,
        ASYNCSTORAGE: 1,
        COOKIESTORAGE: 2
    };

    /**
     * Error code
     * @const
     * @inner
     * @type {Object}
     */
    var eCode = {
        siteExceed: 21,
        lsExceed: 22
    };

    /**
     * When no support local storage, store data temporary
     * @const
     * @inner
     * @type {Object}
     */
    var lsCache = {};

    /**
     * Whether page in cache
     * @const
     * @inner
     * @type {boolean}
     */
    var href = window.location.href;
    var isCachePage = /mipcache.bdstatic.com/.test(href)
                     || /c.mipcdn.com/.test(href);

    /**
     * Domain of website
     * @const
     * @inner
     * @type {string}
     */
    var reg = /[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+\.?/g;
    var matchArr = href.match(reg);
    var HOST = matchArr && matchArr.length > 1 ? matchArr[1] : '';

    /**
     * Current domain storage size, max is 4k
     * @const
     * @inner
     * @type {number}
     */
    var STORAGESIZE = 4 * 1024;

    /**
     * Update local storage operation time
     *
     * @param {Object} storage it's local storage
     */
    function updateTime(storage) {
        if (!storage) {
            return;
        }
        storage.u = new Date().getTime();
    }

    /**
     * Parse json link JSON.parse
     *
     * @param {string} str parse string
     * @return {string} parsed string
     */
    function parseJson(str) {
        try {
            str = JSON.parse(str);
        } catch (e) {
            str = JSON.stringify(str);
            str = JSON.parse(str);
        }
        return str;
    }

    /**
     * Get error message with error code
     *
     * @param {string} code error code
     * @param {string} name error name
     * @return {string} error message
     */
    function getErrorMess(code, name) {
        var mess;
        switch (code) {
            case eCode.siteExceed:
                mess = 'storage space need less than 4k';
            case eCode.lsExceed:
                mess = 'Uncaught DOMException: Failed to execute setItem on Storage: Setting the value of '
                        + name + ' exceeded the quota at ' + window.location.href;
        }
        return mess;
    }

    /**
     * Generate error object
     *
     * @param {string} code error code
     * @param {string} mess error name
     * @return {string} error object
     */
    function getError(code, mess) {
        return {
            errCode: code,
            errMess: mess
        };
    }

    /**
     * Get local storage
     *
     * @return {Object} value of local storage
     */
    function getLocalStorage() {
        var ls = supportLs() ? localStorage.getItem(HOST) : lsCache[HOST];
        ls = ls ? parseJson(ls) : {};
        updateTime(ls);
        return ls;
    }

    /**
     * Delete local storage
     *
     * @param {string} key the key of local storage
     */
    function rmLocalStorage(key) {
        if (!key) {
            key = HOST;
        }
        supportLs() ? localStorage.removeItem(key) : fn.del(lsCache, key);
    }

    /**
     * Whether support Local Storage
     *
     * @return {boolean} Whether support ls
     */
    function supportLs() {
        var support = false;
        if (window.localStorage && window.localStorage.setItem) {
            try {
                window.localStorage.setItem('lsExisted', '1');
                window.localStorage.removeItem('lsExisted');
                support = true;
            } catch (e) {
                support = false;
            }
        }
        return support;
    }

    /**
     * Storage Class
     *
     * @param {number} type type of storage
     * @class
     */
    function customStorage(type) {
        switch (type) {
            case storageType.ASYNCSTORAGE:
                this.storage = new AsyncStorage();
                break;
            case storageType.LOCALSTORAGE:
                this.storage = new LocalStorage();
                break;
            case storageType.COOKIESTORAGE:
                this.storage = new CookieStorage();
                break;
        }
        return this.storage;
    }

    /**
     * Local Storage class
     *
     * @class
     */
    function LocalStorage() {
    }

    /**
     * Set current site data in local storage
     *
     * @param {string} name name of storage
     * @param {string} value value of storage
     * @param {string} expire optional
     * @param {string} callback if error callback to publisher
     */
    LocalStorage.prototype.set = function (name, value, expire, callback) {
        if (!name || !value) {
            return;
        }
        callback = typeof expire === 'function' ? expire : callback;
        if (isCachePage) {
            var ls = getLocalStorage();
            ls[name] = value;
            expire = parseInt(expire, 10);
            if (!isNaN(expire) && expire > 0) {
                ls.e = new Date().getTime() + expire * 1000;
            } else {
                fn.del(ls, 'e');
            }
            ls = JSON.stringify(ls);
            if (ls.length > STORAGESIZE) {
                callback && callback(getError(eCode.siteExceed, getErrorMess(eCode.siteExceed)));
                throw getErrorMess(eCode.siteExceed);
            }
            this._setLocalStorage(HOST, ls, expire, callback);
        } else {
            this._setLocalStorage(name, value, expire, callback);
        }
    };

    /**
     * Set local storage
     *
     * @param {string} key the key of local storage
     * @param {string} value the key of local storage
     * @param {string} expire the expire of local storage
     * @param {string} callback if error callback to publisher
     */
    LocalStorage.prototype._setLocalStorage = function (key, value, expire, callback) {
        var mess = getErrorMess(eCode.lsExceed, key);
        callback = typeof expire === 'function' ? expire : callback;
        if (supportLs()) {
            try {
                localStorage.setItem(key, value);
            } catch (e) {
                if (this._isExceed(e) && isCachePage) {
                    this._exceedHandler(key, value, expire);
                } else if (this._isExceed(e) && !isCachePage) {
                    callback && callback(getError(eCode.lsExceed, mess));
                    throw mess;
                }
            }
        } else {
            var size = value.length / 1024.0 / 1024.0;
            for (var k in lsCache) {
                if (lsCache[k]) {
                    size += lsCache[k].length / 1024.0 / 1024.0;
                }
            }
            if (size > 5.0) {
                callback && callback(eCode.lsExceed, mess);
                throw mess;
            }
            lsCache[key] = value;
        }
    };

    /**
     * Get current site data in local storage
     *
     * @param {string} name name of storage
     * @return {string} get data with key
     */
    LocalStorage.prototype.get = function (name) {
        if (!fn.isString(name)) {
            return;
        }

        var result;
        if (isCachePage) {
            var ls = getLocalStorage();
            if (ls && ls[name]) {
                result = ls[name];
            }
        } else {
            result = supportLs() ? localStorage.getItem(name) : lsCache[name];
        }
        return result;
    };

    /**
     * Delete current site data in local storage with key
     *
     * @param {string} name name of storage
     */
    LocalStorage.prototype.rm = function (name) {
        if (!fn.isString(name)) {
            return;
        }

        if (isCachePage) {
            var ls = getLocalStorage();
            if (ls && ls[name]) {
                fn.del(ls, name);
                this._setLocalStorage(HOST, JSON.stringify(ls));
            }
        } else {
            supportLs() ? localStorage.removeItem(name) : fn.del(lsCache, name);
        }
    };

    /**
     * Clear current site local storage
     *
     */
    LocalStorage.prototype.clear = function () {
        if (isCachePage) {
            rmLocalStorage();
        } else {
            supportLs() ? localStorage.clear() : lsCache = {};
        }
    };

    /**
     * Delete all expire storage, scope is all sites
     *
     * @return {boolean} whether storage has expired
     */
    LocalStorage.prototype.rmExpires = function () {
        var hasExpires = false;
        if (isCachePage) {
            var ls = supportLs() ? localStorage : lsCache;
            for (var k in ls) {
                var val;
                if (typeof ls[k] === 'string') {
                    val = parseJson(ls[k]);
                }
                if (val && val.e) {
                    var expire = parseInt(parseJson(ls[k]).e, 10);
                    if (expire && new Date().getTime() >= expire) {
                        hasExpires = true;
                        rmLocalStorage(k);
                    }
                }
            }
        }
        return hasExpires;
    };

    /**
     * Whether local storage is exceed, http://crocodillon.com/blog/always-catch-localstorage-security-and-quota-exceeded-errors
     *
     * @param {Object} e set local storage error
     * @return {boolean} whether storage exceed
     */
    LocalStorage.prototype._isExceed = function (e) {
        var quotaExceeded = false;
        if (e) {
            if (e.code) {
                switch (e.code) {
                    case 22: {
                        quotaExceeded = true;
                        break;
                    }
                    case 1014: { // Firefox
                        if (e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
                            quotaExceeded = true;
                        }
                        break;
                    }
                }
            } else if (e.number === -2147024882) { // Internet Explorer 8
                quotaExceeded = true;
            }
        }
        return quotaExceeded;
    };

    /**
     * Handle when storage exceed
     *
     * @param {string} name the key of local storage
     * @param {string} value the key of local storage
     * @param {string} expire the expire of local storage
     */
    LocalStorage.prototype._exceedHandler = function (name, value, expire) {
        var minTimeStamp;
        var key;
        if (!this.rmExpires()) {
            var ls = localStorage;
            for (var k in ls) {
                if (ls[k]) {
                    var item = parseJson(ls[k]).u;
                    if (!key || parseInt(item, 10) < minTimeStamp) {
                        key = k;
                        minTimeStamp = item ? parseInt(item, 10) : 0;
                    }
                }
            }
            rmLocalStorage(key);
        }
        this.set(name, value, expire);
    };

    /**
     * Publisher manage storage, via request
     *
     * @class
     */
    function AsyncStorage() {
    }

    /**
     * Send request to server with params
     *
     * @param {Object} opt request params
     */
    AsyncStorage.prototype.request = function (opt) {
        if (!opt || !opt.url) {
            return;
        }
        var myInit = {};
        myInit.mode = opt.mode ? opt.mode : null;
        myInit.method = opt.method ? opt.method : 'GET';
        myInit.credentials = opt.credentials ? opt.credentials : 'omit';
        myInit.cache = opt.cache ? opt.cache : 'default';
        if (opt.headers) {
            myInit.headers = opt.headers;
        }
        if (opt.body) {
            myInit.body = opt.body;
        }
        fetch(opt.url, myInit).then(function (res) {
            if (res.ok) {
                res.text().then(function (data) {
                    opt.success && opt.success(JSON.parse(data));
                });
            } else {
                opt.error && opt.error(res);
            }
        }).catch(function (err) {
            opt.error && opt.error(err);
        });
    };

    /**
     * Cookie storage
     *
     * @class
     */
    function CookieStorage() {
    }

    /**
     * Delete exceed cookie storage
     *
     * @param {Object} opt request params
     */
    CookieStorage.prototype.dealExceedCookie = function () {
        var cks = document.cookie;
        var cksLen = cks.length;
        var MINSIZE = 3 * 1024;
        var MAXSIZE = 5 * 1024;
        if (cksLen >= MAXSIZE) {
            var items = cks.split(';');
            for (var i = 0; i < items.length; i++) {
                var item = items[i].split('=');
                if (item && item.length > 1) {
                    cksLen -= items[i].length;
                    var exp = new Date();
                    exp.setTime(exp.getTime() - 1);
                    document.cookie = item[0] + '=' + item[1] + ';expires=' + exp.toGMTString();
                }
                if (cksLen <= MINSIZE) {
                    break;
                }
            }
        }
    };

    return customStorage;
});
<commit_msg>add annotations<commit_after>/**
 * @file customStorage Function. Support publiser management and localstorage
 * @author wupeng10@baidu.com
 * @modify wupeng10@baidu.com 2017-03-02 Add cookieStorage module, In order to reduce http header
 * size, otherwise page will be a bad request with 40*,Need to be deleted after long-term solution
 */
define(function (require) {
    'use strict';

    var fn = require('./fn');

    /**
     * Type of storage
     * @const
     * @inner
     * @type {Object}
     */
    var storageType = {
        LOCALSTORAGE: 0,
        ASYNCSTORAGE: 1,
        COOKIESTORAGE: 2
    };

    /**
     * Error code
     * @const
     * @inner
     * @type {Object}
     */
    var eCode = {
        siteExceed: 21,
        lsExceed: 22
    };

    /**
     * When no support local storage, store data temporary
     * @const
     * @inner
     * @type {Object}
     */
    var lsCache = {};

    /**
     * Whether page in cache
     * @const
     * @inner
     * @type {boolean}
     */
    var href = window.location.href;
    var isCachePage = /mipcache.bdstatic.com/.test(href)
                     || /c.mipcdn.com/.test(href);

    /**
     * Domain of website
     * @const
     * @inner
     * @type {string}
     */
    var reg = /[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+\.?/g;
    var matchArr = href.match(reg);
    var HOST = matchArr && matchArr.length > 1 ? matchArr[1] : '';

    /**
     * Current domain storage size, max is 4k
     * @const
     * @inner
     * @type {number}
     */
    var STORAGESIZE = 4 * 1024;

    /**
     * Update local storage operation time
     *
     * @param {Object} storage it's local storage
     */
    function updateTime(storage) {
        if (!storage) {
            return;
        }
        storage.u = new Date().getTime();
    }

    /**
     * Parse json link JSON.parse
     *
     * @param {string} str parse string
     * @return {string} parsed string
     */
    function parseJson(str) {
        try {
            str = JSON.parse(str);
        } catch (e) {
            str = JSON.stringify(str);
            str = JSON.parse(str);
        }
        return str;
    }

    /**
     * Get error message with error code
     *
     * @param {string} code error code
     * @param {string} name error name
     * @return {string} error message
     */
    function getErrorMess(code, name) {
        var mess;
        switch (code) {
            case eCode.siteExceed:
                mess = 'storage space need less than 4k';
            case eCode.lsExceed:
                mess = 'Uncaught DOMException: Failed to execute setItem on Storage: Setting the value of '
                        + name + ' exceeded the quota at ' + window.location.href;
        }
        return mess;
    }

    /**
     * Generate error object
     *
     * @param {string} code error code
     * @param {string} mess error name
     * @return {string} error object
     */
    function getError(code, mess) {
        return {
            errCode: code,
            errMess: mess
        };
    }

    /**
     * Get local storage
     *
     * @return {Object} value of local storage
     */
    function getLocalStorage() {
        var ls = supportLs() ? localStorage.getItem(HOST) : lsCache[HOST];
        ls = ls ? parseJson(ls) : {};
        updateTime(ls);
        return ls;
    }

    /**
     * Delete local storage
     *
     * @param {string} key the key of local storage
     */
    function rmLocalStorage(key) {
        if (!key) {
            key = HOST;
        }
        supportLs() ? localStorage.removeItem(key) : fn.del(lsCache, key);
    }

    /**
     * Whether support Local Storage
     *
     * @return {boolean} Whether support ls
     */
    function supportLs() {
        var support = false;
        if (window.localStorage && window.localStorage.setItem) {
            try {
                window.localStorage.setItem('lsExisted', '1');
                window.localStorage.removeItem('lsExisted');
                support = true;
            } catch (e) {
                support = false;
            }
        }
        return support;
    }

    /**
     * Storage Class
     *
     * @param {number} type type of storage
     * @class
     */
    function customStorage(type) {
        switch (type) {
            case storageType.ASYNCSTORAGE:
                this.storage = new AsyncStorage();
                break;
            case storageType.LOCALSTORAGE:
                this.storage = new LocalStorage();
                break;
            case storageType.COOKIESTORAGE:
                this.storage = new CookieStorage();
                break;
        }
        return this.storage;
    }

    /**
     * Local Storage class
     *
     * @class
     */
    function LocalStorage() {
    }

    /**
     * Set current site data in local storage
     *
     * @param {string} name name of storage
     * @param {string} value value of storage
     * @param {string} expire optional
     * @param {string} callback if error callback to publisher
     */
    LocalStorage.prototype.set = function (name, value, expire, callback) {
        if (!name || !value) {
            return;
        }
        callback = typeof expire === 'function' ? expire : callback;
        if (isCachePage) {
            var ls = getLocalStorage();
            ls[name] = value;
            expire = parseInt(expire, 10);
            if (!isNaN(expire) && expire > 0) {
                ls.e = new Date().getTime() + expire * 1000;
            } else {
                fn.del(ls, 'e');
            }
            ls = JSON.stringify(ls);
            if (ls.length > STORAGESIZE) {
                callback && callback(getError(eCode.siteExceed, getErrorMess(eCode.siteExceed)));
                throw getErrorMess(eCode.siteExceed);
            }
            this._setLocalStorage(HOST, ls, expire, callback);
        } else {
            this._setLocalStorage(name, value, expire, callback);
        }
    };

    /**
     * Set local storage
     *
     * @param {string} key the key of local storage
     * @param {string} value the key of local storage
     * @param {string} expire the expire of local storage
     * @param {string} callback if error callback to publisher
     */
    LocalStorage.prototype._setLocalStorage = function (key, value, expire, callback) {
        var mess = getErrorMess(eCode.lsExceed, key);
        callback = typeof expire === 'function' ? expire : callback;
        if (supportLs()) {
            try {
                localStorage.setItem(key, value);
            } catch (e) {
                if (this._isExceed(e) && isCachePage) {
                    this._exceedHandler(key, value, expire);
                } else if (this._isExceed(e) && !isCachePage) {
                    callback && callback(getError(eCode.lsExceed, mess));
                    throw mess;
                }
            }
        } else {
            var size = value.length / 1024.0 / 1024.0;
            for (var k in lsCache) {
                if (lsCache[k]) {
                    size += lsCache[k].length / 1024.0 / 1024.0;
                }
            }
            if (size > 5.0) {
                callback && callback(eCode.lsExceed, mess);
                throw mess;
            }
            lsCache[key] = value;
        }
    };

    /**
     * Get current site data in local storage
     *
     * @param {string} name name of storage
     * @return {string} get data with key
     */
    LocalStorage.prototype.get = function (name) {
        if (!fn.isString(name)) {
            return;
        }

        var result;
        if (isCachePage) {
            var ls = getLocalStorage();
            if (ls && ls[name]) {
                result = ls[name];
            }
        } else {
            result = supportLs() ? localStorage.getItem(name) : lsCache[name];
        }
        return result;
    };

    /**
     * Delete current site data in local storage with key
     *
     * @param {string} name name of storage
     */
    LocalStorage.prototype.rm = function (name) {
        if (!fn.isString(name)) {
            return;
        }

        if (isCachePage) {
            var ls = getLocalStorage();
            if (ls && ls[name]) {
                fn.del(ls, name);
                this._setLocalStorage(HOST, JSON.stringify(ls));
            }
        } else {
            supportLs() ? localStorage.removeItem(name) : fn.del(lsCache, name);
        }
    };

    /**
     * Clear current site local storage
     *
     */
    LocalStorage.prototype.clear = function () {
        if (isCachePage) {
            rmLocalStorage();
        } else {
            supportLs() ? localStorage.clear() : lsCache = {};
        }
    };

    /**
     * Delete all expire storage, scope is all sites
     *
     * @return {boolean} whether storage has expired
     */
    LocalStorage.prototype.rmExpires = function () {
        var hasExpires = false;
        if (isCachePage) {
            var ls = supportLs() ? localStorage : lsCache;
            for (var k in ls) {
                var val;
                if (typeof ls[k] === 'string') {
                    val = parseJson(ls[k]);
                }
                if (val && val.e) {
                    var expire = parseInt(parseJson(ls[k]).e, 10);
                    if (expire && new Date().getTime() >= expire) {
                        hasExpires = true;
                        rmLocalStorage(k);
                    }
                }
            }
        }
        return hasExpires;
    };

    /**
     * Whether local storage is exceed, http://crocodillon.com/blog/always-catch-localstorage-security-and-quota-exceeded-errors
     *
     * @param {Object} e set local storage error
     * @return {boolean} whether storage exceed
     */
    LocalStorage.prototype._isExceed = function (e) {
        var quotaExceeded = false;
        if (e) {
            if (e.code) {
                switch (e.code) {
                    case 22: {
                        quotaExceeded = true;
                        break;
                    }
                    case 1014: { // Firefox
                        if (e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
                            quotaExceeded = true;
                        }
                        break;
                    }
                }
            } else if (e.number === -2147024882) { // Internet Explorer 8
                quotaExceeded = true;
            }
        }
        return quotaExceeded;
    };

    /**
     * Handle when storage exceed
     *
     * @param {string} name the key of local storage
     * @param {string} value the key of local storage
     * @param {string} expire the expire of local storage
     */
    LocalStorage.prototype._exceedHandler = function (name, value, expire) {
        var minTimeStamp;
        var key;
        if (!this.rmExpires()) {
            var ls = localStorage;
            for (var k in ls) {
                if (ls[k]) {
                    var item = parseJson(ls[k]).u;
                    if (!key || parseInt(item, 10) < minTimeStamp) {
                        key = k;
                        minTimeStamp = item ? parseInt(item, 10) : 0;
                    }
                }
            }
            rmLocalStorage(key);
        }
        this.set(name, value, expire);
    };

    /**
     * Publisher manage storage, via request
     *
     * @class
     */
    function AsyncStorage() {
    }

    /**
     * Send request to server with params
     *
     * @param {Object} opt request params
     */
    AsyncStorage.prototype.request = function (opt) {
        if (!opt || !opt.url) {
            return;
        }
        var myInit = {};
        myInit.mode = opt.mode ? opt.mode : null;
        myInit.method = opt.method ? opt.method : 'GET';
        myInit.credentials = opt.credentials ? opt.credentials : 'omit';
        myInit.cache = opt.cache ? opt.cache : 'default';
        if (opt.headers) {
            myInit.headers = opt.headers;
        }
        if (opt.body) {
            myInit.body = opt.body;
        }
        fetch(opt.url, myInit).then(function (res) {
            if (res.ok) {
                res.text().then(function (data) {
                    opt.success && opt.success(JSON.parse(data));
                });
            } else {
                opt.error && opt.error(res);
            }
        }).catch(function (err) {
            opt.error && opt.error(err);
        });
    };

    /**
     * Cookie storage
     *
     * @class
     */
    function CookieStorage() {
    }

    /**
     * Delete exceed cookie storage
     *
     * @param {Object} opt request params
     */
    CookieStorage.prototype.dealExceedCookie = function () {
        var cks = document.cookie;
        var cksLen = cks.length;
        var MINSIZE = 3 * 1024;
        var MAXSIZE = 5 * 1024;
        if (cksLen >= MAXSIZE) {
            var items = cks.split(';');
            for (var i = 0; i < items.length; i++) {
                var item = items[i].split('=');
                if (item && item.length > 1) {
                    cksLen -= items[i].length;
                    var exp = new Date();
                    exp.setTime(exp.getTime() - 1);
                    document.cookie = item[0] + '=' + item[1] + ';expires=' + exp.toGMTString();
                }
                if (cksLen <= MINSIZE) {
                    break;
                }
            }
        }
    };

    return customStorage;
});
<|endoftext|>


<commit_before>// import { baseURL } from './constants.js'
// import * as types from '../../core/types.js'
import ENDPOINTS from '../../config.js'

import request from 'superagent'
require('dotenv').config()

/***
 * !This is an internal function that should not be called by the end user!

 * Builds a URL for HTTP request
 * @param {object} anonymous: anonyous object with arguments:
 * @param {string} type: type of HTTP request (GET, POST, etc). Used for validation of parameters
 * @param {string} AMaaSClass: class being requested/sent (e.g. Transaction) (required)
 * @param {string} AMId: Asset Manager Id (required)
 * @param {string} resourceId: Id of the resource being requested (e.g. book_id)
*/
export function buildURL({ AMaaSClass, AMId, resourceId }) {
  let baseURL;
  switch (AMaaSClass) {
    case 'book':
      // baseURL = process.env.booksURL
      baseURL = `${ENDPOINTS.books}/books`
      break
    case 'parties':
      // baseURL = process.env.partiesURL
      baseURL = `${ENDPOINTS.parties}/parties`
      break
    case 'assetManagers':
      baseURL = `${ENDPOINTS.assetManagers}/asset-managers`
      break
    case 'assets':
      baseURL = `${ENDPOINTS.assets}/assets`
      break
    case 'positions':
      baseURL = `${ENDPOINTS.transactions}/positions`
      break
    default:
      // baseURL = process.env.booksURL
      baseURL = `${ENDPOINTS.books}/books`
  }
  if (!AMaaSClass) {
    throw new Error('Class is required to build URL')
  } else if (!AMId) {
    return `${baseURL}/`
  } else if (!resourceId) {
    return `${baseURL}/${AMId}`
  } else {
    return `${baseURL}/${AMId}/${resourceId}`
  }
}

/***
 * !This is an internal function that should not be called by the end user!
 * !Wrapper functions are exposed for the individual asset classes for consumption!

 * Base function for retrieval of data from the database (GET request)
 * @param {object} anonymous: anonymous object with arguments:
 * @param {string} AMaaSClass: class being requested/sent (e.g. Transaction) (required)
 * @param {string} AMId: Asset Manager Id (required)
 * @param {string} resourceId: Id of the resource being requested (e.g. book_id)
*/
export function retrieveData({ AMaaSClass, AMId, resourceId, token }, callback) {
  // callback(err, result)
  // Class and AMId needed to build the Url and for authorization
  if (!AMaaSClass || !AMId) {
    if (typeof callback !== 'function') {
      return Promise.reject('Both class and AMId are required')
    }
    callback('Both class and AMId are required')
    return
    // throw new Error('Both class and AMId are required')
  }
  if (!token) {
    if (typeof callback !== 'function') {
      return Promise.reject('Missing Authorization')
    }
    callback('Missing Authorization')
    return
    // throw new Error('Missing Authorization')
  }
  let url
  // If resourceId is supplied, append to url. Otherwise, return all data for AMId
  try {
    url = buildURL({ AMaaSClass, AMId, resourceId })
  } catch (e) {
    if (typeof callback !== 'function') {
      return Promise.reject(e)
    }
    callback(e)
    return
  }
  let promise = request.get(url).set('Authorization', token).query({ camelcase: true })
  if (typeof callback !== 'function') {
    // return promise if callback is not provided
    return promise.then(response => response.body)
  }
  promise.end((error, response) => {
    if (!error && response.status == 200) {
      callback(null, response.body)
    } else {
      const statusCode = response ? response.status : ''
      const requestError = {statusCode, error}
      if (typeof callback === 'function') {
        callback(requestError)
      }
    }
  })
}

/***
 * !This is an internal function that should not be called by the end user!
 * !Wrapper functions are exposed for the individual asset classes for consumption!

 * Base function for insertion of data to the database (POST request)
 * @param {object} anonymous: anonymous object with arguments:
 * @param {string} AMaaSClass: class being requested/sent (e.g. Transaction) (required)
 * @param {string} AMId: Asset Manager Id (required)
 * @param {string} data: data to insert into database
*/
export function insertData({ AMaaSClass, AMId, data, token }, callback) {
  // if (!AMaaSClass || !AMId || !data) {
  //   throw new Error('Class, AMId and data to insert are required')
  // }
  if (!token) {
    if (typeof callback !== 'function') {
      return Promise.reject('Missing Authorization')
    }
    callback('Missing Authorization')
    return
  }
  let url
  try {
    url = buildURL({
      AMaaSClass,
      AMId
    })
  } catch (e) {
    if (typeof callback !== 'function') {
      return Promise.reject(e)
    }
    callback(e)
    return
  }
  // Data is object with required key value pairs for that class
  // const am = 'asset_manager_id'
  // data[am] = AMId
  const params = {
    url,
    json: data
  }
  let promise = request.post(url).send(data).set('Authorization', token).query({ camelcase: true })
  if (typeof callback !== 'function') {
    // return promise if callback is not provided
    return promise.then(response => response.body)
  }
  promise.end((error, response) => {
    let body
    if (response) body = response.body
    _networkCallback(error, response, body, callback)
  })
}

export function putData({ AMaaSClass, AMId, resourceId, data, token }, callback) {
  if (!token) {
    if (typeof callback !== 'function') {
      return Promise.reject('Missing Authorization')
    }
    callback('Missing Authorization')
    return
  }
  let url
  try {
    url = buildURL({
      AMaaSClass,
      AMId,
      resourceId
    })
  } catch (e) {
    if (typeof callback !== 'function') {
      return Promise.reject(e)
    }
    callback(e)
    return
  }
  const params = {
    url,
    json: data
  }
  let promise = request.put(url).send(data).set('Authorization', token).query({ camelcase: true })
  if (typeof callback !== 'function') {
    // return promise if callback is not provided
    return promise.then(response => response.body)
  }
  promise.end((error, response) => {
    let body
    if (response) body = response.body
    _networkCallback(error, response, body, callback)
  })
}

export function patchData({ AMaaSClass, AMId, resourceId, data, token }, callback) {
  if (!token) {
    if (typeof callback !== 'function') {
      return Promise.reject('Missing Authorization')
    }
    callback('Missing Authorization')
    return
  }
  let url
  try {
    url = buildURL({
      AMaaSClass,
      AMId,
      resourceId
    })
  } catch (e) {
    if (typeof callback !== 'function') {
      return Promise.reject(e)
    }
    callback(e)
    return
  }
  const params = {
    url,
    json: data
  }
  let promise = request.patch(url).send(data).set('Authorization', token).query({ camelcase: true })
  if (typeof callback !== 'function') {
    // return promise if callback is not provided
    return promise.then(response => response.body)
  }
  promise.end((error, response) => {
    let body
    if (response) body = response.body
    _networkCallback(error, response, body, callback)
  })
}

export function deleteData({ AMaaSClass, AMId, resourceId, token }, callback) {
  if (!token) {
    if (typeof callback !== 'function') {
      return Promise.reject('Missing Authorization')
    }
    callback('Missing Authorization')
    return
  }
  let url
  try {
    url = buildURL({
      AMaaSClass,
      AMId,
      resourceId
    })
  } catch (e) {
    if (typeof callback !== 'function') {
      return Promise.reject(e)
    }
    callback(e)
    return
  }
  let promise = request.delete(url).set('Authorization', token).query({ camelcase: true })
  if (typeof callback !== 'function') {
    // return promise if callback is not provided
    return promise.then(response => response.body)
  }
  promise.end((error, response) => {
    let body
    if (response) body = response.body
    _networkCallback(error, response, body, callback)
  })
}

export function searchData({ AMaaSClass, queryKey, queryValue, token }, callback) {
  if (!token) {
    if (typeof callback !== 'function') {
      return Promise.reject('Missing Authorization')
    }
    callback('Missing Authorization')
    return
  }
  let url
  try {
    url = buildURL({
      AMaaSClass
    })
  } catch (e) {
    if (typeof callback !== 'function') {
      return Promise.reject(e)
    }
    callback(e)
    return
  }
  let qString = {}
  const qValueString = queryValue.join()
  qString[queryKey] = qValueString
  qString.camelcase = true
  const params = {
    url,
    qs: qString
  }
  let promise = request.get(url).set('Authorization', token).query(qString)
  if (typeof callback !== 'function') {
    // return promise if callback is not provided
    return promise.then(response => response.body)
  }
  promise.end((error, response) => {
    let body
    if (response) body = response.body
    _networkCallback(error, response, body, callback)
  })
}

function _networkCallback(error, response, body, callback) {
  if (typeof callback !== 'function') {
    return false
  }
  if (!error && response.status === 200) {
    callback(null, body)
  } else if (error) {
    callback(error)
  } else {
    callback({ response, body })
  }
}
<commit_msg>Add allocations and nettings endpoints. Throw if an unrecognised Service type is passed.<commit_after>// import { baseURL } from './constants.js'
// import * as types from '../../core/types.js'
import ENDPOINTS from '../../config.js'

import request from 'superagent'
require('dotenv').config()

/***
 * !This is an internal function that should not be called by the end user!

 * Builds a URL for HTTP request
 * @param {object} anonymous: anonyous object with arguments:
 * @param {string} type: type of HTTP request (GET, POST, etc). Used for validation of parameters
 * @param {string} AMaaSClass: class being requested/sent (e.g. Transaction) (required)
 * @param {string} AMId: Asset Manager Id (required)
 * @param {string} resourceId: Id of the resource being requested (e.g. book_id)
*/
export function buildURL({ AMaaSClass, AMId, resourceId }) {
  let baseURL = ''
  switch (AMaaSClass) {
    case 'book':
      baseURL = `${ENDPOINTS.books}/books`
      break
    case 'parties':
      baseURL = `${ENDPOINTS.parties}/parties`
      break
    case 'assetManagers':
      baseURL = `${ENDPOINTS.assetManagers}/asset-managers`
      break
    case 'assets':
      baseURL = `${ENDPOINTS.assets}/assets`
      break
    case 'positions':
      baseURL = `${ENDPOINTS.transactions}/positions`
      break
    case 'allocations':
      baseURL = `${ENDPOINTS.transactions}/allocations`
      break
    case 'netting':
      baseURL = `${ENDPOINTS.transactions}/netting`
      break
    default:
      throw new Error(`Invalid class type: ${AMaaSClass}`)
  }
  if (!AMaaSClass) {
    throw new Error('Class is required to build URL')
  } else if (!AMId) {
    return `${baseURL}/`
  } else if (!resourceId) {
    return `${baseURL}/${AMId}`
  } else {
    return `${baseURL}/${AMId}/${resourceId}`
  }
}

/***
 * !This is an internal function that should not be called by the end user!
 * !Wrapper functions are exposed for the individual asset classes for consumption!

 * Base function for retrieval of data from the database (GET request)
 * @param {object} anonymous: anonymous object with arguments:
 * @param {string} AMaaSClass: class being requested/sent (e.g. Transaction) (required)
 * @param {string} AMId: Asset Manager Id (required)
 * @param {string} resourceId: Id of the resource being requested (e.g. book_id)
*/
export function retrieveData({ AMaaSClass, AMId, resourceId, token }, callback) {
  // callback(err, result)
  // Class and AMId needed to build the Url and for authorization
  if (!AMaaSClass || !AMId) {
    if (typeof callback !== 'function') {
      return Promise.reject('Both class and AMId are required')
    }
    callback('Both class and AMId are required')
    return
    // throw new Error('Both class and AMId are required')
  }
  if (!token) {
    if (typeof callback !== 'function') {
      return Promise.reject('Missing Authorization')
    }
    callback('Missing Authorization')
    return
    // throw new Error('Missing Authorization')
  }
  let url
  // If resourceId is supplied, append to url. Otherwise, return all data for AMId
  try {
    url = buildURL({ AMaaSClass, AMId, resourceId })
  } catch (e) {
    if (typeof callback !== 'function') {
      return Promise.reject(e)
    }
    callback(e)
    return
  }
  let promise = request.get(url).set('Authorization', token).query({ camelcase: true })
  if (typeof callback !== 'function') {
    // return promise if callback is not provided
    return promise.then(response => response.body)
  }
  promise.end((error, response) => {
    if (!error && response.status == 200) {
      callback(null, response.body)
    } else {
      const statusCode = response ? response.status : ''
      const requestError = {statusCode, error}
      if (typeof callback === 'function') {
        callback(requestError)
      }
    }
  })
}

/***
 * !This is an internal function that should not be called by the end user!
 * !Wrapper functions are exposed for the individual asset classes for consumption!

 * Base function for insertion of data to the database (POST request)
 * @param {object} anonymous: anonymous object with arguments:
 * @param {string} AMaaSClass: class being requested/sent (e.g. Transaction) (required)
 * @param {string} AMId: Asset Manager Id (required)
 * @param {string} data: data to insert into database
*/
export function insertData({ AMaaSClass, AMId, data, token }, callback) {
  // if (!AMaaSClass || !AMId || !data) {
  //   throw new Error('Class, AMId and data to insert are required')
  // }
  if (!token) {
    if (typeof callback !== 'function') {
      return Promise.reject('Missing Authorization')
    }
    callback('Missing Authorization')
    return
  }
  let url
  try {
    url = buildURL({
      AMaaSClass,
      AMId
    })
  } catch (e) {
    if (typeof callback !== 'function') {
      return Promise.reject(e)
    }
    callback(e)
    return
  }
  // Data is object with required key value pairs for that class
  // const am = 'asset_manager_id'
  // data[am] = AMId
  const params = {
    url,
    json: data
  }
  let promise = request.post(url).send(data).set('Authorization', token).query({ camelcase: true })
  if (typeof callback !== 'function') {
    // return promise if callback is not provided
    return promise.then(response => response.body)
  }
  promise.end((error, response) => {
    let body
    if (response) body = response.body
    _networkCallback(error, response, body, callback)
  })
}

export function putData({ AMaaSClass, AMId, resourceId, data, token }, callback) {
  if (!token) {
    if (typeof callback !== 'function') {
      return Promise.reject('Missing Authorization')
    }
    callback('Missing Authorization')
    return
  }
  let url
  try {
    url = buildURL({
      AMaaSClass,
      AMId,
      resourceId
    })
  } catch (e) {
    if (typeof callback !== 'function') {
      return Promise.reject(e)
    }
    callback(e)
    return
  }
  const params = {
    url,
    json: data
  }
  let promise = request.put(url).send(data).set('Authorization', token).query({ camelcase: true })
  if (typeof callback !== 'function') {
    // return promise if callback is not provided
    return promise.then(response => response.body)
  }
  promise.end((error, response) => {
    let body
    if (response) body = response.body
    _networkCallback(error, response, body, callback)
  })
}

export function patchData({ AMaaSClass, AMId, resourceId, data, token }, callback) {
  if (!token) {
    if (typeof callback !== 'function') {
      return Promise.reject('Missing Authorization')
    }
    callback('Missing Authorization')
    return
  }
  let url
  try {
    url = buildURL({
      AMaaSClass,
      AMId,
      resourceId
    })
  } catch (e) {
    if (typeof callback !== 'function') {
      return Promise.reject(e)
    }
    callback(e)
    return
  }
  const params = {
    url,
    json: data
  }
  let promise = request.patch(url).send(data).set('Authorization', token).query({ camelcase: true })
  if (typeof callback !== 'function') {
    // return promise if callback is not provided
    return promise.then(response => response.body)
  }
  promise.end((error, response) => {
    let body
    if (response) body = response.body
    _networkCallback(error, response, body, callback)
  })
}

export function deleteData({ AMaaSClass, AMId, resourceId, token }, callback) {
  if (!token) {
    if (typeof callback !== 'function') {
      return Promise.reject('Missing Authorization')
    }
    callback('Missing Authorization')
    return
  }
  let url
  try {
    url = buildURL({
      AMaaSClass,
      AMId,
      resourceId
    })
  } catch (e) {
    if (typeof callback !== 'function') {
      return Promise.reject(e)
    }
    callback(e)
    return
  }
  let promise = request.delete(url).set('Authorization', token).query({ camelcase: true })
  if (typeof callback !== 'function') {
    // return promise if callback is not provided
    return promise.then(response => response.body)
  }
  promise.end((error, response) => {
    let body
    if (response) body = response.body
    _networkCallback(error, response, body, callback)
  })
}

export function searchData({ AMaaSClass, queryKey, queryValue, token }, callback) {
  if (!token) {
    if (typeof callback !== 'function') {
      return Promise.reject('Missing Authorization')
    }
    callback('Missing Authorization')
    return
  }
  let url
  try {
    url = buildURL({
      AMaaSClass
    })
  } catch (e) {
    if (typeof callback !== 'function') {
      return Promise.reject(e)
    }
    callback(e)
    return
  }
  let qString = {}
  const qValueString = queryValue.join()
  qString[queryKey] = qValueString
  qString.camelcase = true
  const params = {
    url,
    qs: qString
  }
  let promise = request.get(url).set('Authorization', token).query(qString)
  if (typeof callback !== 'function') {
    // return promise if callback is not provided
    return promise.then(response => response.body)
  }
  promise.end((error, response) => {
    let body
    if (response) body = response.body
    _networkCallback(error, response, body, callback)
  })
}

function _networkCallback(error, response, body, callback) {
  if (typeof callback !== 'function') {
    return false
  }
  if (!error && response.status === 200) {
    callback(null, body)
  } else if (error) {
    callback(error)
  } else {
    callback({ response, body })
  }
}
<|endoftext|>


<commit_before>// Universal Subtitles, universalsubtitles.org
//
// Copyright (C) 2010 Participatory Culture Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see
// http://www.gnu.org/licenses/agpl-3.0.html.

goog.provide('mirosubs.Widgetizer');

/**
 * @constructor
 * This is a singleton, so don't call this method directly.
 */
mirosubs.Widgetizer = function() {
    this.widgetizeBound_ = false;
    this.widgetized_ = false;
};
goog.addSingletonGetter(mirosubs.Widgetizer);

/**
 * Converts all videos in the page to Mirosubs widgets.
 *
 */
mirosubs.Widgetizer.prototype.widgetize = function() {
    if (this.widgetizeBound_)
        return;
    this.widgetizeBound_ = true;
    if (document.readyState == "complete")
        this.onLoaded_();
    else
        this.addReadyEventListener_();
};

mirosubs.Widgetizer.prototype.addReadyEventListener_ = function() {
    var that = this;
    if (document.addEventListener) {
        var EVENT = "DOMContentLoaded";
        document.addEventListener(
            EVENT,
            function() {
                document.removeEventListener(EVENT, arguments.callee, false);
                that.onLoaded_();
            }, false);
    }
    else if (document.attachEvent) {
        var EVENT = "onreadystatechange";
        // TODO: this code is copied from templates/widget/embed.js.
        // Possilby remove duplication in the future.
        document.attachEvent(EVENT, function() {
            if (document.readyState == "complete") {
                document.detachEvent(EVENT, arguments.callee);
                that.onLoaded_();
            }
        });
        if (document.documentElement.doScroll && window == window.top)
            (function() {
                if (that.widgetized_)
                    return;
                try {
                    // Thanks to Diego Perini: http://javascript.nwbox.com/IEContentLoaded/
                    document.documentElement.doScroll('left');
                }
                catch (error) {
                    setTimeout(arguments.callee, 0);
                    return;
                }
                that.onLoaded_();
            })();
    }
    // in case nothing else works: load event
    goog.events.listen(window, goog.events.EventType.LOAD,
                       this.onLoaded_, false, this);
};

mirosubs.Widgetizer.prototype.onLoaded_ = function() {
    if (this.widgetized_)
        return;
    this.widgetized_ = true;
    this.addHeadCss_();
    this.widgetizeVideoElements_(document.getElementsByTagName('video'));
    this.widgetizeObjectElements_(document.getElementsByTagName('object'));
};

mirosubs.Widgetizer.prototype.addHeadCss_ = function() {
    if (!window.MiroCSSLoading) {
        window.MiroCSSLoading = true;
        var head = document.getElementsByTagName('head')[0];
        var css = document.createElement('link');
        css.type = 'text/css';
        css.rel = 'stylesheet';
        css.href = mirosubs.WidgetizerConfig.siteConfig['mediaURL'] +
            'css/mirosubs-widget.css';
        css.media = 'screen';
        head.appendChild(css);
    }
};

mirosubs.Widgetizer.prototype.widgetizeVideoElements_ = function(videoElems) {
    for (var i = 0; i < videoElems.length; i++)
        this.widgetizeElem_(videoElems[i], this.findHtml5URL_(videoElems[i]));
};

mirosubs.Widgetizer.prototype.widgetizeObjectElements_ = function(objectElems) {
    for (var i = 0; i < objectElems.length; i++) {
        var youtubeURL = this.findYoutubeURL_(objectElems[i]);
        if (youtubeURL != null)
            this.widgetizeElem_(objectElems[i], youtubeURL);
    }
};

mirosubs.Widgetizer.prototype.findHtml5URL_ = function(videoElem) {
    return videoElem.getElementsByTagName('source')[0].src;
};

mirosubs.Widgetizer.prototype.findYoutubeURL_ = function(objectElem) {
    var paramElems = objectElem.getElementsByTagName('param');
    for (var i = 0; i < paramElems.length; i++) {
        if (paramElems[i]["name"] == "movie" &&
            paramElems[i]["value"] != null &&
            mirosubs.video.VideoSource.isYoutube(paramElems[i]["value"]))
            return paramElems[i]["value"];
    }
    return null;
};

mirosubs.Widgetizer.prototype.widgetizeElem_ = function(elem, videoURL) {
    var containingElement = document.createElement('div');
    var styleElement = document.createElement('style');
    var innerStyle = mirosubs.WidgetizerConfig.innerStyle;
    if ('textContent' in styleElement)
        styleElement.textContent = innerStyle;
    else {
        // IE
        styleElement.setAttribute("type", "text/css")
        styleElement.styleSheet.cssText = innerStyle;
    }
    containingElement.appendChild(styleElement);
    var widgetDiv = document.createElement('div');
    containingElement.appendChild(widgetDiv);

    var parentElem = elem.parentNode;
    parentElem.insertBefore(containingElement, elem);
    parentElem.removeChild(elem);
    mirosubs.widget.CrossDomainEmbed.embed(
        widgetDiv, { 'video_url': videoURL }, mirosubs.WidgetizerConfig.siteConfig);
};

mirosubs.Widgetizer.getInstance().widgetize();<commit_msg>Altered widgetizer to correctly process youtube.<commit_after>// Universal Subtitles, universalsubtitles.org
//
// Copyright (C) 2010 Participatory Culture Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see
// http://www.gnu.org/licenses/agpl-3.0.html.

goog.provide('mirosubs.Widgetizer');

/**
 * @constructor
 * This is a singleton, so don't call this method directly.
 */
mirosubs.Widgetizer = function() {
    this.widgetizeBound_ = false;
    this.widgetized_ = false;
};
goog.addSingletonGetter(mirosubs.Widgetizer);

/**
 * Converts all videos in the page to Mirosubs widgets.
 *
 */
mirosubs.Widgetizer.prototype.widgetize = function() {
    if (this.widgetizeBound_)
        return;
    this.widgetizeBound_ = true;
    if (document.readyState == "complete")
        this.onLoaded_();
    else
        this.addReadyEventListener_();
};

mirosubs.Widgetizer.prototype.addReadyEventListener_ = function() {
    var that = this;
    if (document.addEventListener) {
        var EVENT = "DOMContentLoaded";
        document.addEventListener(
            EVENT,
            function() {
                document.removeEventListener(EVENT, arguments.callee, false);
                that.onLoaded_();
            }, false);
    }
    else if (document.attachEvent) {
        var EVENT = "onreadystatechange";
        // TODO: this code is copied from templates/widget/embed.js.
        // Possilby remove duplication in the future.
        document.attachEvent(EVENT, function() {
            if (document.readyState == "complete") {
                document.detachEvent(EVENT, arguments.callee);
                that.onLoaded_();
            }
        });
        if (document.documentElement.doScroll && window == window.top)
            (function() {
                if (that.widgetized_)
                    return;
                try {
                    // Thanks to Diego Perini: http://javascript.nwbox.com/IEContentLoaded/
                    document.documentElement.doScroll('left');
                }
                catch (error) {
                    setTimeout(arguments.callee, 0);
                    return;
                }
                that.onLoaded_();
            })();
    }
    // in case nothing else works: load event
    goog.events.listen(window, goog.events.EventType.LOAD,
                       this.onLoaded_, false, this);
};

mirosubs.Widgetizer.prototype.onLoaded_ = function() {
    if (this.widgetized_)
        return;
    this.widgetized_ = true;
    this.addHeadCss_();
    this.findAndWidgetizeElements_();
};

mirosubs.Widgetizer.prototype.findAndWidgetizeElements_ = function() {
    // including some heuristics here for some of the bigger sites.
    if (this.location.hostname.match(/youtube\.com$/) != null) {
        this.widgetizeElem_(
            goog.dom.getElement('movie_player'),
            this.location.href);
    }
    else {
        this.widgetizeVideoElements_(
            this.filterWidgetized_(
                document.getElementsByTagName('video')));
        this.widgetizeObjectElements_(
            this.filterWidgetized_(
                document.getElementsByTagName('object')));
    }
};

mirosubs.Widgetizer.prototype.addHeadCss_ = function() {
    if (!window.MiroCSSLoading) {
        window.MiroCSSLoading = true;
        var head = document.getElementsByTagName('head')[0];
        var css = document.createElement('link');
        css.type = 'text/css';
        css.rel = 'stylesheet';
        css.href = mirosubs.WidgetizerConfig.siteConfig['mediaURL'] +
            'css/mirosubs-widget.css';
        css.media = 'screen';
        head.appendChild(css);
    }
};

mirosubs.Widgetizer.prototype.filterWidgetized_ = function(elementArray) {
    var that = this;
    return goog.array.filter(
        elementArray,
        function(elem) {
            return !that.alreadyWidgetized_(elem);
        });
};

mirosubs.Widgetizer.prototype.alreadyWidgetized_ = function(elem) {
    // we consider it to be widgetized if it's contained in a widget div or
    // it's contained in the subtitling dialog.
    return goog.dom.getAncestorByTagNameAndClass(
        elem, 'div', 'mirosubs-widget') != null ||
        goog.dom.getAncestorByTagNameAndClass(
            elem, 'div', 'mirosubs-modal-widget') != null;
};

mirosubs.Widgetizer.prototype.widgetizeVideoElements_ = function(videoElems) {
    for (var i = 0; i < videoElems.length; i++)
        this.widgetizeElem_(videoElems[i], this.findHtml5URL_(videoElems[i]));
};

mirosubs.Widgetizer.prototype.widgetizeObjectElements_ = function(objectElems) {
    for (var i = 0; i < objectElems.length; i++) {
        var youtubeURL = this.findYoutubeURL_(objectElems[i]);
        if (youtubeURL != null)
            this.widgetizeElem_(objectElems[i], youtubeURL);
    }
};

mirosubs.Widgetizer.prototype.findHtml5URL_ = function(videoElem) {
    return videoElem.getElementsByTagName('source')[0].src;
};

mirosubs.Widgetizer.prototype.findYoutubeURL_ = function(objectElem) {
    var paramElems = objectElem.getElementsByTagName('param');
    for (var i = 0; i < paramElems.length; i++) {
        if (paramElems[i]["name"] == "movie" &&
            paramElems[i]["value"] != null &&
            mirosubs.video.VideoSource.isYoutube(paramElems[i]["value"]))
            return paramElems[i]["value"];
    }
    return null;
};

mirosubs.Widgetizer.prototype.widgetizeElem_ = function(elem, videoURL) {
    var containingElement = document.createElement('div');
    var styleElement = document.createElement('style');
    var innerStyle = mirosubs.WidgetizerConfig.innerStyle;
    if ('textContent' in styleElement)
        styleElement.textContent = innerStyle;
    else {
        // IE
        styleElement.setAttribute("type", "text/css")
        styleElement.styleSheet.cssText = innerStyle;
    }
    containingElement.appendChild(styleElement);
    var widgetDiv = document.createElement('div');
    widgetDiv.className = 'mirosubs-widget';
    containingElement.appendChild(widgetDiv);

    var parentElem = elem.parentNode;
    parentElem.insertBefore(containingElement, elem);
    parentElem.removeChild(elem);
    mirosubs.widget.CrossDomainEmbed.embed(
        widgetDiv, { 'video_url': videoURL }, mirosubs.WidgetizerConfig.siteConfig);
};

mirosubs.Widgetizer.getInstance().widgetize();<|endoftext|>


<commit_before>/**
 * Validates space separated string against an array of accepted values.
 * @param {String} propValue -- Space separated string (provided by the user)
 * @param {Array} validArr -- Array of values that are considered "valid"
 * @param {Boolean} responsive -- Enables validation of validArr values with '@sm', '', '@lg' added to them
 */
function validateProp(propValue, validArr, responsive = true) {
  const strArr = propValue.split(' ');
  return strArr.every((mod) => {
    const modValid = validArr.some((validStr) => {
      if (responsive) {
        return (
          mod === validStr
          || mod === `${validStr}@xs`
          || mod === `${validStr}@sm`
          || mod === `${validStr}@md`
          || mod === `${validStr}@lg`
        );
      }

      return (mod === validStr);
    });
    if (!modValid) {
      console.error(`Invalid prop value: ${mod}`); // eslint-disable-line no-console
    }
    return modValid;
  });
}

export default validateProp;
<commit_msg>docs(comment): adding in prop options comments<commit_after>/**
 * Validates space separated string against an array of accepted values.
 * @param {String} propValue -- Space separated string (provided by the user)
 * @param {Array} validArr -- Array of values that are considered "valid"
 * @param {Boolean} responsive -- Enables validation of validArr values with '@sm', '@md', '@lg' added to them
 */
function validateProp(propValue, validArr, responsive = true) {
  const strArr = propValue.split(' ');
  return strArr.every((mod) => {
    const modValid = validArr.some((validStr) => {
      if (responsive) {
        return (
          mod === validStr
          || mod === `${validStr}@xs`
          || mod === `${validStr}@sm`
          || mod === `${validStr}@md`
          || mod === `${validStr}@lg`
        );
      }

      return (mod === validStr);
    });
    if (!modValid) {
      console.error(`Invalid prop value: ${mod}`); // eslint-disable-line no-console
    }
    return modValid;
  });
}

export default validateProp;
<|endoftext|>


<commit_before>var colorSet = ["#373854","#493267","#7bb3ff","#e86af0","#7bb3ff","#9e379f"];
var graph;
var tx_unconfirmed_timer;
var tx_unconfirmed_timer_last_block;
var txid;

function checkConfirmed() {
    $.ajax({url: "/api/confirmed/"+$("#input_txid").val(), success: function(result){
        if(result.statusCode=="200"){
            if(tx_unconfirmed_timer_last_block == null && result.data.tx_confirmed_in_block > 1){ // tx is confirmed
                new Audio('mp3/attention-seeker.mp3').play();
                tx_unconfirmed_timer_last_block = result.data.tx_confirmed_in_block;
                $('#card_info_tx_confirmed_sound_checkbox').prop("checked", false );
                $("#card_info_tx_confirmed_block").text(result.data.tx_confirmed_in_block);
                $("#card_info_tx_confirmed_sound").css("display", "none");
                $("#card_info_tx_confirmed").css("display", "block");
                window.clearInterval(tx_unconfirmed_timer) // disables the timer
            }
        }else{
            alert(result.statusCode+" - "+result.message);
        }
    }});
}

function changeGraphColor(index) {
    graph.setSelection(false, ''+index,false);
}

function setCursorTextFeelevel(date,key,value) {
    date = new Date(date*1000);
    var time = ("0" + date.getHours()).slice(-2) + ":" + ("0" + date.getMinutes()).slice(-2);
    if(value>0){
        $("#cursortext_detailed").css("visibility","visible");
        $("#cursortext_tally_detailed").text(value);
        $("#cursortext_SpB_detailed").text(key);
        $("#cursortext_date_detailed").text(time);
    }else{
        $("#cursortext_detailed").css("visibility","hidden");
    }
}
function setCursorTextBucketlevel(date,key,value) {
    date = new Date(date*1000);
    var time = ("0" + date.getHours()).slice(-2) + ":" + ("0" + date.getMinutes()).slice(-2);
    if(value>0){
        $("#cursortext_bucket").css("visibility","visible");
        $("#cursortext_tally_bucket").text(value);
        $("#cursortext_buckets_bucket").text(key);
        $("#cursortext_date_bucket").text(time);
    }else{
        $("#cursortext_bucket").css("visibility","hidden");
    }
}

function loadTXinfo(){
    if($("#input_txid").val().length==64){
        $.ajax({url: "/api/tx/"+$("#input_txid").val(), success: function(result){
            if(result.statusCode=="200"){
                txid = result.data.hash;
                tx_unconfirmed_timer_last_block = result.data.block;
                $("#card_info_tx_id").text(result.data.hash);
                $("#card_info_tx_permalink").attr("href", "https://mempool.observer/"+result.data.hash);
                if(result.data.block!=null){ // transaction confirmed
                    $("#card_info_tx_confirmed_block").text(result.data.block);
                    $("#card_info_tx_confirmed").css("display", "block");
                    $("#card_info_tx_confirmed_sound").css("display", "none");
                }else { // transaction unconfirmed (block = null -> not inclued in a block)
                    $("#card_info_tx_confirmed").css("display", "none");
                    $("#card_info_tx_confirmed_sound").css("display", "block");
                    changeGraphColor(result.data.rate.toFixed(0));
                }
                $("#card_info_tx_input").text("");
                $("#card_info_tx_output").text("");
                result.data.inputs.forEach(function(input) {
                    $("#card_info_tx_input").append("
"+input.address[0]+"
"+(input.amount*0.00000001).toFixed(8)+" BTC
" );
                });

                $("#card_info_tx_middle_SpB").text(result.data.rate.toFixed(0)+" sat/byte");
                $("#card_info_tx_middle_fee").text(result.data.fee +" sat");
                $("#card_info_tx_middle_size").text(result.data.size+" byte");
                $("#card_info_tx_middle_timestamp").text((new Date(result.data.timestamp * 1000)).toUTCString());

                result.data.outputs.forEach(function(output) {
                    $("#card_info_tx_output").append( "
"+output.address[0]+"
"+(output.amount*0.00000001).toFixed(8)+" BTC
" );
                });

                $("#card_info_tx").css("display", "block");

            }else{
                alert(result.statusCode+" - "+result.message);
            }
        }});
    }else {
        alert("invalid input: '" + $("#input_txid").val() + "' - length: [" +  $("#input_txid").val().length + "]");
    }
}

var buildGraph = function(data,options) {
    var chart = document.getElementById("graphdiv");
    var div = document.createElement('div');
    div.className = "chartclass";
    div.style.display = 'inline-block';
    chart.appendChild(div);
    var labels = data[1];
    graph = new Dygraph(div, data, options)
}

var options_detailed = {
    width: 1000,
    height: 650,
    colors: colorSet,
    fillAlpha: 1,
    strokeWidth: 4,
    strokeBorderWidth: 0,
    highlightCircleSize: 0,
    stackedGraph: true,
    stackedGraphNaNFill:"none",
    rightGap: 0,

    legend: "never",
    ylabel: "transactions in mempool",
    xlabel: "time",

    highlightSeriesOpts: {
        strokeWidth: 5,
        strokeBorderWidth: 2,
        strokeBorderColor: "#FDD",
        highlightCircleSize: 1
    },
    interactionModel:  {},
    highlightSeriesBackgroundAlpha: 0.5,
    highlightSeriesBackgroundColor: "#000",
    highlightCallback: function(e, x, pts, row) {
        setCursorTextFeelevel(x,graph.getHighlightSeries(),graph.rolledSeries_[graph.rolledSeries_.length-graph.getHighlightSeries()-1][row][1]);
    },
    unhighlightCallback: function(e) {
        $("#cursortext").css("visibility","hidden");
    },
    axes: {
        x: {
            axisLabelFormatter: function(d, gran, opts) {
                return Dygraph.dateAxisLabelFormatter(new Date((d/60).toFixed(0)*60000), gran, opts);
            }
        },
        y: {
            axisLabelFormatter: function(y) {
                if(y>999){
                    return + y/1000 + 'k';
                }else{
                    return y;
                }
            },
            axisLabelWidth: 50,
            includeZero:true
        }
    }
}

var options_bucket = {
    width: 1000,
    height: 650,
    colors: colorSet,
    fillAlpha: 1,
    strokeWidth: 4,
    strokeBorderWidth: 0,
    highlightCircleSize: 0,
    stackedGraph: true,
    stackedGraphNaNFill:"none",
    rightGap: 0,

    legend: "never",
    ylabel: "transactions in mempool",
    xlabel: "time",

    highlightSeriesOpts: {
        strokeWidth: 5,
        strokeBorderWidth: 2,
        strokeBorderColor: "#FDD",
        highlightCircleSize: 1
    },
    interactionModel:  {},
    highlightSeriesBackgroundAlpha: 0.5,
    highlightSeriesBackgroundColor: "#000",
    highlightCallback: function(e, x, pts, row) {
        setCursorTextBucketlevel(x,graph.getHighlightSeries(),graph.rolledSeries_[graph.rolledSeries_.length-graph.getHighlightSeries()-1][row][1]);
    },
    unhighlightCallback: function(e) {
        $("#cursortext").css("visibility","hidden");
    },
    axes: {
        x: {
            axisLabelFormatter: function(d, gran, opts) {
                return Dygraph.dateAxisLabelFormatter(new Date((d/60).toFixed(0)*60000), gran, opts);
            }
        },
        y: {
            axisLabelFormatter: function(y) {
                if(y>999){
                    return + y/1000 + 'k';
                }else{
                    return y;
                }
            },
            axisLabelWidth: 50,
            includeZero:true
        }
    }
}

window.onload = function () {

    // register onClickListener for the 'load tx id'-button
    $("#button_load_tx_info").click(function(){
        loadTXinfo();
    });

    buildGraph('/dyn/feelevel.csv', options_detailed);

    // if 'load_txid' was defined by the ejs renderer load the tx
    // 'load_txid' is the permalink txid
    if (typeof load_txid !== 'undefined') {
        $("#input_txid").val(load_txid)
        loadTXinfo();
    }

    // onChangeListener for the confirm sound checkbox
    $('#card_info_tx_confirmed_sound_checkbox').change(function(){
        if($(this).is(':checked')) {
            new Audio('mp3/attention-seeker.mp3').play(); // plays audio once
            tx_unconfirmed_timer = setInterval(checkConfirmed, 60000); // checks with the backend (over ajax) every 60 seconds if the transaction is confirmed
        } else {
            window.clearInterval(tx_unconfirmed_timer) // disables the timer
        }
    });

    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
        switch (e.target.id) {
            case "nav-detailed-tab":
                graph.updateOptions($.extend(options_detailed, {file: "/dyn/feelevel.csv"}),false);
                break;
            case "nav-bucket-tab":
                graph.updateOptions($.extend(options_bucket, {file: "/dyn/bucketlevel-orig.csv"}),false);
                break;
        }
    })

}
<commit_msg>buckets: fixed dev resource<commit_after>var colorSet = ["#373854","#493267","#7bb3ff","#e86af0","#7bb3ff","#9e379f"];
var graph;
var tx_unconfirmed_timer;
var tx_unconfirmed_timer_last_block;
var txid;

function checkConfirmed() {
    $.ajax({url: "/api/confirmed/"+$("#input_txid").val(), success: function(result){
        if(result.statusCode=="200"){
            if(tx_unconfirmed_timer_last_block == null && result.data.tx_confirmed_in_block > 1){ // tx is confirmed
                new Audio('mp3/attention-seeker.mp3').play();
                tx_unconfirmed_timer_last_block = result.data.tx_confirmed_in_block;
                $('#card_info_tx_confirmed_sound_checkbox').prop("checked", false );
                $("#card_info_tx_confirmed_block").text(result.data.tx_confirmed_in_block);
                $("#card_info_tx_confirmed_sound").css("display", "none");
                $("#card_info_tx_confirmed").css("display", "block");
                window.clearInterval(tx_unconfirmed_timer) // disables the timer
            }
        }else{
            alert(result.statusCode+" - "+result.message);
        }
    }});
}

function changeGraphColor(index) {
    graph.setSelection(false, ''+index,false);
}

function setCursorTextFeelevel(date,key,value) {
    date = new Date(date*1000);
    var time = ("0" + date.getHours()).slice(-2) + ":" + ("0" + date.getMinutes()).slice(-2);
    if(value>0){
        $("#cursortext_detailed").css("visibility","visible");
        $("#cursortext_tally_detailed").text(value);
        $("#cursortext_SpB_detailed").text(key);
        $("#cursortext_date_detailed").text(time);
    }else{
        $("#cursortext_detailed").css("visibility","hidden");
    }
}
function setCursorTextBucketlevel(date,key,value) {
    date = new Date(date*1000);
    var time = ("0" + date.getHours()).slice(-2) + ":" + ("0" + date.getMinutes()).slice(-2);
    if(value>0){
        $("#cursortext_bucket").css("visibility","visible");
        $("#cursortext_tally_bucket").text(value);
        $("#cursortext_buckets_bucket").text(key);
        $("#cursortext_date_bucket").text(time);
    }else{
        $("#cursortext_bucket").css("visibility","hidden");
    }
}

function loadTXinfo(){
    if($("#input_txid").val().length==64){
        $.ajax({url: "/api/tx/"+$("#input_txid").val(), success: function(result){
            if(result.statusCode=="200"){
                txid = result.data.hash;
                tx_unconfirmed_timer_last_block = result.data.block;
                $("#card_info_tx_id").text(result.data.hash);
                $("#card_info_tx_permalink").attr("href", "https://mempool.observer/"+result.data.hash);
                if(result.data.block!=null){ // transaction confirmed
                    $("#card_info_tx_confirmed_block").text(result.data.block);
                    $("#card_info_tx_confirmed").css("display", "block");
                    $("#card_info_tx_confirmed_sound").css("display", "none");
                }else { // transaction unconfirmed (block = null -> not inclued in a block)
                    $("#card_info_tx_confirmed").css("display", "none");
                    $("#card_info_tx_confirmed_sound").css("display", "block");
                    changeGraphColor(result.data.rate.toFixed(0));
                }
                $("#card_info_tx_input").text("");
                $("#card_info_tx_output").text("");
                result.data.inputs.forEach(function(input) {
                    $("#card_info_tx_input").append("
"+input.address[0]+"
"+(input.amount*0.00000001).toFixed(8)+" BTC
" );
                });

                $("#card_info_tx_middle_SpB").text(result.data.rate.toFixed(0)+" sat/byte");
                $("#card_info_tx_middle_fee").text(result.data.fee +" sat");
                $("#card_info_tx_middle_size").text(result.data.size+" byte");
                $("#card_info_tx_middle_timestamp").text((new Date(result.data.timestamp * 1000)).toUTCString());

                result.data.outputs.forEach(function(output) {
                    $("#card_info_tx_output").append( "
"+output.address[0]+"
"+(output.amount*0.00000001).toFixed(8)+" BTC
" );
                });

                $("#card_info_tx").css("display", "block");

            }else{
                alert(result.statusCode+" - "+result.message);
            }
        }});
    }else {
        alert("invalid input: '" + $("#input_txid").val() + "' - length: [" +  $("#input_txid").val().length + "]");
    }
}

var buildGraph = function(data,options) {
    var chart = document.getElementById("graphdiv");
    var div = document.createElement('div');
    div.className = "chartclass";
    div.style.display = 'inline-block';
    chart.appendChild(div);
    var labels = data[1];
    graph = new Dygraph(div, data, options)
}

var options_detailed = {
    width: 1000,
    height: 650,
    colors: colorSet,
    fillAlpha: 1,
    strokeWidth: 4,
    strokeBorderWidth: 0,
    highlightCircleSize: 0,
    stackedGraph: true,
    stackedGraphNaNFill:"none",
    rightGap: 0,

    legend: "never",
    ylabel: "transactions in mempool",
    xlabel: "time",

    highlightSeriesOpts: {
        strokeWidth: 5,
        strokeBorderWidth: 2,
        strokeBorderColor: "#FDD",
        highlightCircleSize: 1
    },
    interactionModel:  {},
    highlightSeriesBackgroundAlpha: 0.5,
    highlightSeriesBackgroundColor: "#000",
    highlightCallback: function(e, x, pts, row) {
        setCursorTextFeelevel(x,graph.getHighlightSeries(),graph.rolledSeries_[graph.rolledSeries_.length-graph.getHighlightSeries()-1][row][1]);
    },
    unhighlightCallback: function(e) {
        $("#cursortext").css("visibility","hidden");
    },
    axes: {
        x: {
            axisLabelFormatter: function(d, gran, opts) {
                return Dygraph.dateAxisLabelFormatter(new Date((d/60).toFixed(0)*60000), gran, opts);
            }
        },
        y: {
            axisLabelFormatter: function(y) {
                if(y>999){
                    return + y/1000 + 'k';
                }else{
                    return y;
                }
            },
            axisLabelWidth: 50,
            includeZero:true
        }
    }
}

var options_bucket = {
    width: 1000,
    height: 650,
    colors: colorSet,
    fillAlpha: 1,
    strokeWidth: 4,
    strokeBorderWidth: 0,
    highlightCircleSize: 0,
    stackedGraph: true,
    stackedGraphNaNFill:"none",
    rightGap: 0,

    legend: "never",
    ylabel: "transactions in mempool",
    xlabel: "time",

    highlightSeriesOpts: {
        strokeWidth: 5,
        strokeBorderWidth: 2,
        strokeBorderColor: "#FDD",
        highlightCircleSize: 1
    },
    interactionModel:  {},
    highlightSeriesBackgroundAlpha: 0.5,
    highlightSeriesBackgroundColor: "#000",
    highlightCallback: function(e, x, pts, row) {
        setCursorTextBucketlevel(x,graph.getHighlightSeries(),graph.rolledSeries_[graph.rolledSeries_.length-graph.getHighlightSeries()-1][row][1]);
    },
    unhighlightCallback: function(e) {
        $("#cursortext").css("visibility","hidden");
    },
    axes: {
        x: {
            axisLabelFormatter: function(d, gran, opts) {
                return Dygraph.dateAxisLabelFormatter(new Date((d/60).toFixed(0)*60000), gran, opts);
            }
        },
        y: {
            axisLabelFormatter: function(y) {
                if(y>999){
                    return + y/1000 + 'k';
                }else{
                    return y;
                }
            },
            axisLabelWidth: 50,
            includeZero:true
        }
    }
}

window.onload = function () {

    // register onClickListener for the 'load tx id'-button
    $("#button_load_tx_info").click(function(){
        loadTXinfo();
    });

    buildGraph('/dyn/feelevel.csv', options_detailed);

    // if 'load_txid' was defined by the ejs renderer load the tx
    // 'load_txid' is the permalink txid
    if (typeof load_txid !== 'undefined') {
        $("#input_txid").val(load_txid)
        loadTXinfo();
    }

    // onChangeListener for the confirm sound checkbox
    $('#card_info_tx_confirmed_sound_checkbox').change(function(){
        if($(this).is(':checked')) {
            new Audio('mp3/attention-seeker.mp3').play(); // plays audio once
            tx_unconfirmed_timer = setInterval(checkConfirmed, 60000); // checks with the backend (over ajax) every 60 seconds if the transaction is confirmed
        } else {
            window.clearInterval(tx_unconfirmed_timer) // disables the timer
        }
    });

    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
        switch (e.target.id) {
            case "nav-detailed-tab":
                graph.updateOptions($.extend(options_detailed, {file: "/dyn/feelevel.csv"}),false);
                break;
            case "nav-bucket-tab":
                graph.updateOptions($.extend(options_bucket, {file: "/dyn/bucketlevel.csv"}),false);
                break;
        }
    })

}
<|endoftext|>


<commit_before>require({
    cacheBust: true,
    packages: [
        { name: 'bootstrap', location: '../../../' }
    ]
},[
    'bootstrap/tests/support',
    'bootstrap/tests/alert',
    'bootstrap/tests/button',
    'bootstrap/tests/dropdown',
    'bootstrap/tests/modal',
    // 'bootstrap/tests/popover',
    // 'bootstrap/tests/tab',
    'bootstrap/tests/tooltip',
    'bootstrap/tests/scrollspy',
    // 'bootstrap/tests/collapse',
    'bootstrap/tests/carousel'
], {});
<commit_msg>fix path to Dojo-Bootstrap for doh tests<commit_after>require({
    cacheBust: true,
    packages: [
        { name: 'bootstrap', location: '../../' }
    ]
},[
    'bootstrap/tests/support',
    'bootstrap/tests/alert',
    'bootstrap/tests/button',
    'bootstrap/tests/dropdown',
    'bootstrap/tests/modal',
    // 'bootstrap/tests/popover',
    // 'bootstrap/tests/tab',
    'bootstrap/tests/tooltip',
    'bootstrap/tests/scrollspy',
    // 'bootstrap/tests/collapse',
    'bootstrap/tests/carousel'
], {});
<|endoftext|>


<commit_before>var test = require('tape')
var Hoodie = require('../../index')

test('has "on" method', function (t) {
  t.plan(1)

  var hoodie = new Hoodie()
  t.is(typeof hoodie.on, 'function', 'has method')
})

test('"on" without listener', function (t) {
  t.plan(1)

  var hoodie = new Hoodie()
  t.throws(function () {
    hoodie.on('account:signin')
  }, /listener must be a function/, 'throws exception when listener is not a function')
})

test('"on" returns an object', function (t) {
  t.plan(1)

  var hoodie = new Hoodie()
  t.is(typeof hoodie.on('account:signin', function () {}), 'object', 'returns an object')
})

test('has "one" method', function (t) {
  t.plan(1)

  var hoodie = new Hoodie()
  t.is(typeof hoodie.one, 'function', 'has method')
})

test('"one" returns an object', function (t) {
  t.plan(1)

  var hoodie = new Hoodie()
  t.is(typeof hoodie.one('account:signin', function () {}), 'object', 'returns an object')
})

test('"one" without listener', function (t) {
  t.plan(1)

  var hoodie = new Hoodie()
  t.throws(function () {
    hoodie.one('account:signin')
  }, /listener must be a function/, 'throws exception when listener is not a function')
})

test('has "off" method', function (t) {
  t.plan(1)

  var hoodie = new Hoodie()
  t.is(typeof hoodie.off, 'function', 'has method')
})

test('"off" returns an object', function (t) {
  t.plan(1)

  var hoodie = new Hoodie()
  t.is(typeof hoodie.off('account:signin', function () {}), 'object', 'returns an object')
})

test('"off" without listener', function (t) {
  t.plan(1)

  var hoodie = new Hoodie()
  t.throws(function () {
    hoodie.off('account:signin')
  }, /listener must be a function/, 'throws exception when listener is not a function')
})

test('has "trigger" method', function (t) {
  t.plan(1)

  var hoodie = new Hoodie()
  t.is(typeof hoodie.trigger, 'function', 'has method')
})

test('"trigger" returns an object', function (t) {
  t.plan(1)

  var hoodie = new Hoodie()
  t.is(typeof hoodie.trigger('account:signin'), 'object', 'returns an object')
})
<commit_msg>test: updates for node@6<commit_after>var test = require('tape')
var Hoodie = require('../../index')

test('has "on" method', function (t) {
  t.plan(1)

  var hoodie = new Hoodie()
  t.is(typeof hoodie.on, 'function', 'has method')
})

test('"on" without listener', function (t) {
  t.plan(1)

  var hoodie = new Hoodie()
  t.throws(function () {
    hoodie.on('account:signin')
  }, /must be a function/, 'throws exception when listener is not a function')
})

test('"on" returns an object', function (t) {
  t.plan(1)

  var hoodie = new Hoodie()
  t.is(typeof hoodie.on('account:signin', function () {}), 'object', 'returns an object')
})

test('has "one" method', function (t) {
  t.plan(1)

  var hoodie = new Hoodie()
  t.is(typeof hoodie.one, 'function', 'has method')
})

test('"one" returns an object', function (t) {
  t.plan(1)

  var hoodie = new Hoodie()
  t.is(typeof hoodie.one('account:signin', function () {}), 'object', 'returns an object')
})

test('"one" without listener', function (t) {
  t.plan(1)

  var hoodie = new Hoodie()
  t.throws(function () {
    hoodie.one('account:signin')
  }, /must be a function/, 'throws exception when listener is not a function')
})

test('has "off" method', function (t) {
  t.plan(1)

  var hoodie = new Hoodie()
  t.is(typeof hoodie.off, 'function', 'has method')
})

test('"off" returns an object', function (t) {
  t.plan(1)

  var hoodie = new Hoodie()
  t.is(typeof hoodie.off('account:signin', function () {}), 'object', 'returns an object')
})

test('"off" without listener', function (t) {
  t.plan(1)

  var hoodie = new Hoodie()
  t.throws(function () {
    hoodie.off('account:signin')
  }, /must be a function/, 'throws exception when listener is not a function')
})

test('has "trigger" method', function (t) {
  t.plan(1)

  var hoodie = new Hoodie()
  t.is(typeof hoodie.trigger, 'function', 'has method')
})

test('"trigger" returns an object', function (t) {
  t.plan(1)

  var hoodie = new Hoodie()
  t.is(typeof hoodie.trigger('account:signin'), 'object', 'returns an object')
})
<|endoftext|>


<commit_before>'use strict';

const isLambda = !!module.parent;
const AWS = require('aws-sdk');
const gm = require('gm').subClass({
  imageMagick: true,
  appPath: isLambda ? '/var/task/opt/bin/' : ''
});
const imgConfig = {
  thumbnailWidth: '1000',
  dstBucket: 'mirakui-img-deliver'
};

function s3Get(bucket, key) {
  console.log('s3Get: bucket=%s, key=%s', bucket, key);

  const s3 = new AWS.S3();
  const params = {
    Bucket: bucket,
    Key: key
  };
  return new Promise((resolve, reject) => {
    s3.getObject(params, (err, data) => {
      if (err) {
        reject(err);
      }
      else {
        resolve(data);
      }
    });
  });
}

function s3Put(bucket, key, data) {
  console.log('s3Put: bucket=%s, key=%s', bucket, key);

  const s3 = new AWS.S3();
  const params = {
    Bucket: bucket,
    Key: key,
    Body: data
  };
  return new Promise((resolve, reject) => {
    s3.putObject(params, (err, data) => {
      if (err) {
        reject(err);
      }
      else {
        resolve(data);
      }
    });
  });
}

function makeThumbnail(data) {
  console.log('makeThumbnail: size=%d', data.length);

  return new Promise((resolve, reject) => {
    gm(data).
      resize(`${imgConfig.thumbnailWidth}>`).
      define(`jpeg:size=${imgConfig.thumbnailWidth}`).
      limit('map', '0MiB').
      limit('disk', '0MiB').
      repage('+').
      out('-auto-orient').
      quality(90).
      colorspace('sRGB').
      strip().
      toBuffer('JPG', (err, buffer) => {
        if (err) {
          reject(err);
        }
        else {
          resolve(buffer);
        }
      });
  });
}

function processObject(srcBucket, key) {
  return s3Get(srcBucket, key).then(
    (resp) => makeThumbnail(resp.Body)
  ).then(
    (buffer) => s3Put(imgConfig.dstBucket, key, buffer)
  ).then(
    () => Promise.resolve({ key: key, status: 'success' })
  ).catch(
    (e) => Promise.reject({ key: key, status: 'error', error: e })
  );
}

exports.handle = function(e, ctx, cb) {
  console.log('processing event: %j', e);

  const promises = e.Records.map((record) => {
    if (!record.s3) { return null; }
    const srcBucket = record.s3.bucket.name;
    const key = record.s3.object.key;
    return processObject(srcBucket, key);
  });

  Promise.all(promises).then(
    (results) => cb(null, { results: results })
  );
};

function loadJsonFromStdin() {
  return new Promise((resolve, reject) => {
    const stdin = process.stdin;
    let buf = '';
    stdin.resume();
    stdin.setEncoding('utf8');
    stdin.on('data', (chunk) => { buf += chunk; });
    stdin.on('end', () => resolve(JSON.parse(buf)));
  });
}

if (!isLambda) {
  loadJsonFromStdin().
    then((e) => exports.handle(e, {}, (_, results) => {
      console.log('results: %j', results);
    }));
}
<commit_msg>Update<commit_after>'use strict';

const isLambda = !!module.parent;
const AWS = require('aws-sdk');
const gm = require('gm').subClass({
  imageMagick: true,
  appPath: isLambda ? '/var/task/opt/bin/' : ''
});
const imgConfig = {
  thumbnailWidth: '1000',
  dstBucket: 'mirakui-img-deliver'
};

function s3Get(bucket, key) {
  console.log('s3Get: bucket=%s, key=%s', bucket, key);

  const s3 = new AWS.S3();
  const params = {
    Bucket: bucket,
    Key: key
  };
  return new Promise((resolve, reject) => {
    s3.getObject(params, (err, data) => {
      if (err) {
        console.log('s3Get: [reject] %j', err);
        reject(err);
      }
      else {
        console.log('s3Get: [resolve]');
        resolve(data);
      }
    });
  });
}

function s3Put(bucket, key, data, meta) {
  console.log('s3Put: bucket=%s, key=%s, meta=%j', bucket, key, meta);

  const s3 = new AWS.S3();
  let params = {
    Bucket: bucket,
    Key: key,
    Body: data
  };
  console.log('s3Put: meta=%j', meta);
  for (const k in meta) {
    console.log('s3Put: k=%j', k);
  }
  console.log('s3Put: params=%j', meta);

  return new Promise((resolve, reject) => {
    s3.putObject(params, (err, data) => {
      if (err) {
        console.log('s3Put: [reject] %j', err);
        reject(err);
      }
      else {
        console.log('s3Put: [resolve]');
        resolve(data);
      }
    });
  });
}

function makeThumbnail(data) {
  console.log('makeThumbnail: size=%d', data.length);

  return new Promise((resolve, reject) => {
    gm(data).
      resize(`${imgConfig.thumbnailWidth}>`).
      define(`jpeg:size=${imgConfig.thumbnailWidth}`).
      limit('map', '0MiB').
      limit('disk', '0MiB').
      repage('+').
      out('-auto-orient').
      quality(90).
      colorspace('sRGB').
      strip().
      toBuffer('JPG', (err, buffer) => {
        if (err) {
          console.log('makeThumbnail: [reject] %j', err);
          reject(err);
        }
        else {
          console.log('makeThumbnail: [resolve]');
          resolve(buffer);
        }
      });
  });
}

function getGeometry(data) {
  console.log('getGeometry: size=%d', data.length);

  return new Promise((resolve, reject) => {
    gm(data).
      size((err, size) => {
        if (err) {
          console.log('getGeometry: [reject] %j', err);
          reject(err);
        }
        else {
          console.log('getGeometry: [resolve] %j', size);
          resolve([data, size]);
        }
      });
  });
}

function processObject(srcBucket, key) {
  return s3Get(srcBucket, key).then(
    (resp) => makeThumbnail(resp.Body)
  ).then(
    (buffer) => getGeometry(buffer)
  ).then(
    (arr) => {
      const buffer = arr[0], geom = arr[1];
      return s3Put(
        imgConfig.dstBucket, key, buffer,
        { 'X-ThumbnailWidth': geom.width, 'X-ThumbnailHeight': geom.height }
      );
    }
  ).then(
    () => Promise.resolve({ key: key, status: 'success' })
  ).catch(
    (e) => Promise.resolve({ key: key, status: 'error', error: e })
  );
}

exports.handle = function(e, ctx, cb) {
  console.log('processing event: %j', e);

  const promises = e.Records.map((record) => {
    if (!record.s3) { return null; }
    const srcBucket = record.s3.bucket.name;
    const key = record.s3.object.key;
    return processObject(srcBucket, key);
  });

  Promise.all(promises).then(
    (results) => cb(null, { results: results })
  );
};

function loadJsonFromStdin() {
  return new Promise((resolve, reject) => {
    const stdin = process.stdin;
    let buf = '';
    stdin.resume();
    stdin.setEncoding('utf8');
    stdin.on('data', (chunk) => { buf += chunk; });
    stdin.on('end', () => resolve(JSON.parse(buf)));
  });
}

if (!isLambda) {
  loadJsonFromStdin().
    then((e) => exports.handle(e, {}, (_, results) => {
      console.log('results: %j', results);
    }));
}
<|endoftext|>


<commit_before>Ext.namespace('Vps.Auto.Form');

Vps.Auto.Form.Window = Ext.extend(Ext.Window, {
    initComponent : function()
    {
        this.actions = {};

        if (!this.formConfig) this.formConfig = {};

        Ext.applyIf(this.formConfig, {
            baseCls: 'x-plain',
            controllerUrl: this.controllerUrl
        });
        this.autoForm = new Vps.Auto.FormPanel(this.formConfig);
        this.on('render', function() {
            this.getForm().waitMsgTarget = this.el;
        }, this);

        Ext.applyIf(this, {
            width: 300,
            height: 200,
            layout: 'fit',
            bodyStyle:'padding:5px;',
            plain: true,
            modal: true,
            buttons: [this.getAction('cancel'), this.getAction('save')]
        });

        this.items = [this.autoForm];

        this.relayEvents(this.autoForm, ['renderform']);
        this.addEvents({
            datachange: true
        });

        Vps.Auto.Form.Window.superclass.initComponent.call(this);
    },

    getAction : function(type)
    {
        if (this.actions[type]) return this.actions[type];

        if (type == 'save') {
            var action = this.getAutoForm().getAction('save');
            action.handler = function() {
                this.getForm().onSubmit(null, {
                    callback: function() {
                        this.hide();
                    },
                    scope: this
                });
            };
            this.actions[type] = action;
        } else if (type == 'cancel') {
            this.actions[type] = new Ext.Action({
                text    : 'Cancel',
                handler : function() {
                    this.hide();
                },
                scope   : this
            });
        } else {
            throw "unknown action-type: "+type;
        }
        return this.actions[type];
    },

    showAdd : function()
    {
        this.getAutoForm().onAdd();
        this.setTitle('add');
        this.show();
    },

    showEdit : function(id, options)
    {
        this.setTitle('edit');
        this.show();
        this.getAutoForm().load(id, options);
    },

    getAutoForm : function()
    {
        return this.autoForm;
    },

    getForm : function()
    {
        return this.getAutoForm().getForm();
    }
});
<commit_msg>bugfix speichern-action von window<commit_after>Ext.namespace('Vps.Auto.Form');

Vps.Auto.Form.Window = Ext.extend(Ext.Window, {
    initComponent : function()
    {
        this.actions = {};

        if (!this.formConfig) this.formConfig = {};

        Ext.applyIf(this.formConfig, {
            baseCls: 'x-plain',
            controllerUrl: this.controllerUrl
        });
        this.autoForm = new Vps.Auto.FormPanel(this.formConfig);
        this.on('renderform', function() {
            this.getForm().waitMsgTarget = this.el;
        }, this);

        Ext.applyIf(this, {
            width: 300,
            height: 200,
            layout: 'fit',
            bodyStyle:'padding:5px;',
            plain: true,
            modal: true,
            buttons: [this.getAction('cancel'), this.getAction('save')]
        });
        this.closeAction = 'hide';

        this.items = [this.autoForm];

        this.relayEvents(this.autoForm, ['renderform']);
        this.addEvents({
            datachange: true
        });

        Vps.Auto.Form.Window.superclass.initComponent.call(this);
    },

    getAction : function(type)
    {
        if (this.actions[type]) return this.actions[type];

        if (type == 'save') {
            var action = this.getAutoForm().getAction('save');
            action.setHandler(function() {
                this.getAutoForm().onSubmit({}, {
                    callback: function() {
                        this.hide();
                    },
                    scope: this
                });
            }, this);
            this.actions[type] = action;
        } else if (type == 'cancel') {
            this.actions[type] = new Ext.Action({
                text    : 'Cancel',
                handler : function() {
                    this.hide();
                },
                scope   : this
            });
        } else {
            throw "unknown action-type: "+type;
        }
        return this.actions[type];
    },

    showAdd : function()
    {
        this.getAutoForm().onAdd();
        this.setTitle('add');
        this.show();
    },

    showEdit : function(id, options)
    {
        this.setTitle('edit');
        this.show();
        this.getAutoForm().load(id, options);
    },

    getAutoForm : function()
    {
        return this.autoForm;
    },

    getForm : function()
    {
        return this.getAutoForm().getForm();
    }
});
<|endoftext|>