<commit_before>/*!
  * Simple-Jekyll-Search v1.7.2 (https://github.com/christian-fei/Simple-Jekyll-Search)
  * Copyright 2015-2018, Christian Fei
  * Licensed under the MIT License.
  */
!function(){"use strict";var f={load:function w(t,e){var n=function r(){return window.XMLHttpRequest?new window.XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP")}();n.open("GET",t,!0),n.onreadystatechange=function i(e,n){return function(){if(4===e.readyState&&200===e.status)try{n(null,JSON.parse(e.responseText))}catch(t){n(t,null)}}}(n,e),n.send()}};(function y(t){if(!function e(t){return!!t&&"undefined"!=typeof t.required&&t.required instanceof Array}(t))throw new Error("-- OptionsValidator: required options missing");if(!(this instanceof y))return new y(t);var r=t.required;this.getRequiredOptions=function(){return r},this.validate=function(e){var n=[];return r.forEach(function(t){"undefined"==typeof e[t]&&n.push(t)}),n}});var n=function g(t,e){var n=e.length,r=t.length;if(n<r)return!1;if(r===n)return t===e;t:for(var i=0,o=0;i<r;i++){for(var u=t.charCodeAt(i);o<n;)if(e.charCodeAt(o++)===u)continue t;return!1}return!0},e=new function t(){this.matches=function(t,e){return n(e.toLowerCase(),t.toLowerCase())}};var r=new function O(){this.matches=function(e,t){return!!e&&(e=e.trim().toLowerCase(),(t=t.trim().toLowerCase()).split(" ").filter(function(t){return 0<=e.indexOf(t)}).length===t.split(" ").length)}};var l={put:function z(t){if(c(t))return s(t);if(function e(t){return Boolean(t)&&"[object Array]"===Object.prototype.toString.call(t)}(t))return function i(t){var e=[];a();for(var n=0,r=t.length;n<r;n++)c(t[n])&&e.push(s(t[n]));return e}(t);return undefined},clear:a,search:function S(t){return t?function a(t,e,n,r){for(var i=[],o=0;o<t.length&&i.length<r.limit;o++){var u=d(t[o],e,n,r);u&&i.push(u)}return i}(o,t,u.searchStrategy,u).sort(u.sort):[]},setOptions:function q(t){(u=t||{}).fuzzy=t.fuzzy||!1,u.limit=t.limit||10,u.searchStrategy=t.fuzzy?e:r,u.sort=t.sort||i}};function i(){return 0}var o=[],u={};function a(){return o.length=0,o}function c(t){return Boolean(t)&&"[object Object]"===Object.prototype.toString.call(t)}function s(t){return o.push(t),o}function d(t,e,n,r){for(var i in t)if(!p(t[i],r.exclude)&&n.matches(t[i],e))return t}function p(t,e){for(var n=!1,r=0,i=(e=e||[]).length;r<i;r++){var o=e[r];!n&&new RegExp(t).test(o)&&(n=!0)}return n}u.fuzzy=!1,u.limit=10,u.searchStrategy=u.fuzzy?e:r,u.sort=i;var h={compile:function j(r){return m.template.replace(m.pattern,function(t,e){var n=m.middleware(e,r[e],m.template);return void 0!==n?n:r[e]||t})},setOptions:function C(t){m.pattern=t.pattern||m.pattern,m.template=t.template||m.template,"function"==typeof t.middleware&&(m.middleware=t.middleware)}},m={};m.pattern=/\{(.*?)\}/g,m.template="",m.middleware=function(){};var v={merge:function L(t,e){var n={};for(var r in t)n[r]=t[r],"undefined"!=typeof e[r]&&(n[r]=e[r]);return n},isJSON:function M(t){try{return!!(t instanceof Object&&JSON.parse(JSON.stringify(t)))}catch(e){return!1}}};!function(t){var o={searchInput:null,resultsContainer:null,json:[],success:Function.prototype,searchResultTemplate:'
{title}
',templateMiddleware:Function.prototype,sortMiddleware:function(){return 0},noResultsText:"No results found",limit:10,fuzzy:!1,exclude:[]},n=["searchInput","resultsContainer","json"],r=function y(e){if(!function n(t){return!!t&&"undefined"!=typeof t.required&&t.required instanceof Array}(e))throw new Error("-- OptionsValidator: required options missing");if(!(this instanceof y))return new y(e);var r=e.required;this.getRequiredOptions=function(){return r},this.validate=function(e){var n=[];return r.forEach(function(t){"undefined"==typeof e[t]&&n.push(t)}),n}}({required:n});function i(t){o.success(t),l.put(t),function e(){o.searchInput.addEventListener("keyup",function(t){(function e(t){return-1===[13,16,20,37,38,39,40,91].indexOf(t)})(t.which)&&(u(),c(t.target.value))})}()}function u(){o.resultsContainer.innerHTML=""}function a(t){o.resultsContainer.innerHTML+=t}function c(t){(function e(t){return t&&0<t.length})(t)&&(u(),function i(t,e){var n=t.length;if(0===n)return a(o.noResultsText);for(var r=0;r<n;r++)t[r].query=e,a(h.compile(t[r]))}(l.search(t),t))}function s(t){throw new Error("SimpleJekyllSearch --- "+t)}t.SimpleJekyllSearch=function(t){return 0<r.validate(t).length&&s("You must specify the following required options: "+n),o=v.merge(o,t),h.setOptions({template:o.searchResultTemplate,middleware:o.templateMiddleware}),l.setOptions({fuzzy:o.fuzzy,limit:o.limit,sort:o.sortMiddleware}),v.isJSON(o.json)?i(o.json):function e(n){f.load(n,function(t,e){t&&s("failed to get JSON ("+n+")"),i(e)})}(o.json),{search:c}}}(window)}();
/*! Customizamos Simple Jekyll Search
 */

var sjs = SimpleJekyllSearch({
  searchInput: document.getElementById('search-input'),
  resultsContainer: document.getElementById('results-container'),
  json: 'http://miguelcarvajal.es/search.json',
  searchResultTemplate:'

{name}

{content}

',
  noResultsText: '
Vaya, ese nombre no está registrado, ¿quieres añadirlo?
',
  limit: 10,
  fuzzy: false,
  exclude: ['Welcome']
});<commit_msg>add search<commit_after>/*!
  * Simple-Jekyll-Search v1.7.2 (https://github.com/christian-fei/Simple-Jekyll-Search)
  * Copyright 2015-2018, Christian Fei
  * Licensed under the MIT License.
  */
!function(){"use strict";var f={load:function w(t,e){var n=function r(){return window.XMLHttpRequest?new window.XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP")}();n.open("GET",t,!0),n.onreadystatechange=function i(e,n){return function(){if(4===e.readyState&&200===e.status)try{n(null,JSON.parse(e.responseText))}catch(t){n(t,null)}}}(n,e),n.send()}};(function y(t){if(!function e(t){return!!t&&"undefined"!=typeof t.required&&t.required instanceof Array}(t))throw new Error("-- OptionsValidator: required options missing");if(!(this instanceof y))return new y(t);var r=t.required;this.getRequiredOptions=function(){return r},this.validate=function(e){var n=[];return r.forEach(function(t){"undefined"==typeof e[t]&&n.push(t)}),n}});var n=function g(t,e){var n=e.length,r=t.length;if(n<r)return!1;if(r===n)return t===e;t:for(var i=0,o=0;i<r;i++){for(var u=t.charCodeAt(i);o<n;)if(e.charCodeAt(o++)===u)continue t;return!1}return!0},e=new function t(){this.matches=function(t,e){return n(e.toLowerCase(),t.toLowerCase())}};var r=new function O(){this.matches=function(e,t){return!!e&&(e=e.trim().toLowerCase(),(t=t.trim().toLowerCase()).split(" ").filter(function(t){return 0<=e.indexOf(t)}).length===t.split(" ").length)}};var l={put:function z(t){if(c(t))return s(t);if(function e(t){return Boolean(t)&&"[object Array]"===Object.prototype.toString.call(t)}(t))return function i(t){var e=[];a();for(var n=0,r=t.length;n<r;n++)c(t[n])&&e.push(s(t[n]));return e}(t);return undefined},clear:a,search:function S(t){return t?function a(t,e,n,r){for(var i=[],o=0;o<t.length&&i.length<r.limit;o++){var u=d(t[o],e,n,r);u&&i.push(u)}return i}(o,t,u.searchStrategy,u).sort(u.sort):[]},setOptions:function q(t){(u=t||{}).fuzzy=t.fuzzy||!1,u.limit=t.limit||10,u.searchStrategy=t.fuzzy?e:r,u.sort=t.sort||i}};function i(){return 0}var o=[],u={};function a(){return o.length=0,o}function c(t){return Boolean(t)&&"[object Object]"===Object.prototype.toString.call(t)}function s(t){return o.push(t),o}function d(t,e,n,r){for(var i in t)if(!p(t[i],r.exclude)&&n.matches(t[i],e))return t}function p(t,e){for(var n=!1,r=0,i=(e=e||[]).length;r<i;r++){var o=e[r];!n&&new RegExp(t).test(o)&&(n=!0)}return n}u.fuzzy=!1,u.limit=10,u.searchStrategy=u.fuzzy?e:r,u.sort=i;var h={compile:function j(r){return m.template.replace(m.pattern,function(t,e){var n=m.middleware(e,r[e],m.template);return void 0!==n?n:r[e]||t})},setOptions:function C(t){m.pattern=t.pattern||m.pattern,m.template=t.template||m.template,"function"==typeof t.middleware&&(m.middleware=t.middleware)}},m={};m.pattern=/\{(.*?)\}/g,m.template="",m.middleware=function(){};var v={merge:function L(t,e){var n={};for(var r in t)n[r]=t[r],"undefined"!=typeof e[r]&&(n[r]=e[r]);return n},isJSON:function M(t){try{return!!(t instanceof Object&&JSON.parse(JSON.stringify(t)))}catch(e){return!1}}};!function(t){var o={searchInput:null,resultsContainer:null,json:[],success:Function.prototype,searchResultTemplate:'
{title}
',templateMiddleware:Function.prototype,sortMiddleware:function(){return 0},noResultsText:"No results found",limit:10,fuzzy:!1,exclude:[]},n=["searchInput","resultsContainer","json"],r=function y(e){if(!function n(t){return!!t&&"undefined"!=typeof t.required&&t.required instanceof Array}(e))throw new Error("-- OptionsValidator: required options missing");if(!(this instanceof y))return new y(e);var r=e.required;this.getRequiredOptions=function(){return r},this.validate=function(e){var n=[];return r.forEach(function(t){"undefined"==typeof e[t]&&n.push(t)}),n}}({required:n});function i(t){o.success(t),l.put(t),function e(){o.searchInput.addEventListener("keyup",function(t){(function e(t){return-1===[13,16,20,37,38,39,40,91].indexOf(t)})(t.which)&&(u(),c(t.target.value))})}()}function u(){o.resultsContainer.innerHTML=""}function a(t){o.resultsContainer.innerHTML+=t}function c(t){(function e(t){return t&&0<t.length})(t)&&(u(),function i(t,e){var n=t.length;if(0===n)return a(o.noResultsText);for(var r=0;r<n;r++)t[r].query=e,a(h.compile(t[r]))}(l.search(t),t))}function s(t){throw new Error("SimpleJekyllSearch --- "+t)}t.SimpleJekyllSearch=function(t){return 0<r.validate(t).length&&s("You must specify the following required options: "+n),o=v.merge(o,t),h.setOptions({template:o.searchResultTemplate,middleware:o.templateMiddleware}),l.setOptions({fuzzy:o.fuzzy,limit:o.limit,sort:o.sortMiddleware}),v.isJSON(o.json)?i(o.json):function e(n){f.load(n,function(t,e){t&&s("failed to get JSON ("+n+")"),i(e)})}(o.json),{search:c}}}(window)}();
/*! Customizamos Simple Jekyll Search
 */

var sjs = SimpleJekyllSearch({
  searchInput: document.getElementById('search-input'),
  resultsContainer: document.getElementById('results-container'),
  json: 'http://miguelcarvajal.es/notas/reporterhacks/search.json',
  searchResultTemplate:'

{name}

{content}

',
  noResultsText: '
Vaya, ese nombre no está registrado, ¿quieres añadirlo?
',
  limit: 10,
  fuzzy: false,
  exclude: ['Welcome']
});<|endoftext|>


<commit_before>---
---
/**
 * @name  {{ site.name }}
 * @description  {{ site.description }}
 * @author  {{ site.author }} <{{ site.author_email }}> ({{ site.url }})
 * @version  {{ site.version }}
 * @copyright  {{ site.author }} 2017
 * @license  {{ site.license }}
 */

self.addEventListener('message', function (e) {
    var source = e.data.source;

    if (e.data.beautify) {
        self.importScripts('{{ "/assets/js/lib/js-beautify/beautify.js?v=" | append: site.github.build_revision | relative_url }}');
        source = self.js_beautify(source, {
            unescape_strings: true,
            jslint_happy: true
        });
    }

    if (e.data.highlight) {
        self.importScripts('{{ "/assets/js/lib/highlight-js/highlight.pack.js?v=" | append: site.github.build_revision | relative_url }}');
        source = self.hljs.highlight('javascript', source).value;
    }

    self.postMessage(source);
});<commit_msg>Fix js_beautify not runing in Web Workers<commit_after>---
---
/**
 * @name  {{ site.name }}
 * @description  {{ site.description }}
 * @author  {{ site.author }} <{{ site.author_email }}> ({{ site.url }})
 * @version  {{ site.version }}
 * @copyright  {{ site.author }} 2017
 * @license  {{ site.license }}
 */

self.addEventListener('message', function (e) {
    var source = e.data.source;

    self._window = self.window;
    self.window = {};

    if (e.data.beautify) {
        self.importScripts('{{ "/assets/js/lib/js-beautify/beautify.min.js?v=" | append: site.github.build_revision | relative_url }}');
        source = self.window.js_beautify(source, {
            unescape_strings: true,
            jslint_happy: true
        });
    }

    self.window = self._window;

    if (e.data.highlight) {
        self.importScripts('{{ "/assets/js/lib/highlight-js/highlight.pack.js?v=" | append: site.github.build_revision | relative_url }}');
        source = self.hljs.highlight('javascript', source).value;
    }

    self.postMessage(source);
});
<|endoftext|>


<commit_before>$(function() {
    var categorizationArray = [];

    var updateFilters = function (url){
        var queryArray = url.split("=")[1].split(",");
        var queryObjArray = [];
        if(queryArray.length > 0){
            for(var index in queryArray){
                var obj = queryArray[index];
                var queryObj = {};
                var queryObjValue = [];
                queryObj.queryKey = obj.split(":")[0].split('\"').join('');
                if(obj.indexOf("(") > -1){
                    var newObj = obj.split(":")[1].split('\"').join('').replace("(", "").replace(")", "");
                    queryObjValue = newObj.split("OR");
                } else {
                    if(obj.indexOf(":") > -1){
                        queryObjValue.push(obj.split(":")[1].split('\"').join(''));
                    }
                }
                queryObj.queryValue = queryObjValue;
                queryObjArray.push(queryObj);
            }

            for(var i in queryObjArray){
                $('#categorization :checkbox').each(function() {
                    var $this = $(this);
                    if($this.attr('name') == queryObjArray[i].queryKey){
                        for(var k in queryObjArray[i].queryValue){
                            if($this.attr('value').toLowerCase()
                                == queryObjArray[i].queryValue[k].trim().toLowerCase()){
                                $this.attr('checked', true);
                                $("#"+$this.attr('name')).collapse('show');
                                var icon = $("#"+$this.attr('name')).prev().find('.status').children();
                                icon.removeClass('fw-down');
                                icon.addClass('fw-up');
                            }
                        }
                    }
                });
            }
        }
    };

    var search = function (searchQuery, data, isRemove) {
        var url;

        var encodedQueryString = getEncodedQueryString(searchQuery);
        currentPage = 1;
        if (store.asset) {
            if(window.location.href.indexOf("q=") > -1){
                if(!isRemove){
                    if(window.location.href.split("=")[1] !== ""){
                        if(window.location.href.indexOf(searchQuery.split(":")[0]) > -1){
                            url = removeURLParameter(decodeURIComponent(window.location.href),
                                data, true);
                            if(url.split("q=")[1] !== ""){
                                url = url + "%2C" + encodedQueryString;
                            } else {
                                url = url + encodedQueryString;
                            }
                        } else {
                            url = window.location.href + "%2C" + encodedQueryString;
                        }
                    } else {
                        url = window.location.href + encodedQueryString;
                    }
                } else {
                    url = removeURLParameter(decodeURIComponent(window.location.href), data, false);
                }

            } else {
                url = caramel.tenantedUrl('/assets/' + store.asset.type + '/list?' + buildParams(encodedQueryString));
            }

            if(url.indexOf("mediaType") == -1){
                url = url + encodeURIComponent(",\"mediaType\":\""+store.asset.type+"\"");
            }
            loadAssets(url);
        }

        $('.search-bar h2').find('.page').text(' / Search: "' + searchQuery + '"');
    };

    var buildParams = function (query) {
        return 'q=' + query;
    };

    var getEncodedQueryString = function (searchQuery) {
        var q = {};
        var output = '';
        if(searchQuery !== ''){
            q = parseUsedDefinedQuery(searchQuery);
            q = JSON.stringify(q);
            q = q.replace('{','').replace('}', '');
            q = encodeURIComponent(q);
            output =q;
        }
        return output;
    };

    var triggerEvent = function (data, isRemove){
        var searchQueryString = data.parent + ":" + data.text;

        if((window.location.href.indexOf(data.parent) > -1) && !isRemove){
            searchQueryString = updateORQuery(window.location.href, data);
        }
        search(searchQueryString, data, isRemove);
    };

    var updateORQuery = function (url, data) {
        var value = getParamValue(url, data.parent).trim();
        var updatedQuery = "";
        if(value.indexOf("(") > -1){
            updatedQuery = data.parent + ":(" + value.substring(value.indexOf("\"(")+2, value.indexOf(")\"")) + " OR "
                + data.text + ")";
        } else {
            value = "\"" + value.split("\"").join("").trim() + "\"";
            updatedQuery = data.parent + ":(" + value.replace("\"", "").replace("\"", "") + " OR " + data.text + ")";
        }
        return updatedQuery;
    };

    var removeURLParameter = function(sourceURL, data, removeWhole) {
        var rtn = sourceURL.split("?")[0],
            param,
            params_arr = [],
            queryString = (sourceURL.indexOf("?") !== -1) ? sourceURL.split("?")[1] : "";
        if (queryString !== "") {
            params_arr = queryString.split("&");
            for (var i = params_arr.length - 1; i >= 0; i -= 1) {
                param = params_arr[i].split("=")[1];
                var innerParams = param.split(",");
                for(var j= innerParams.length -1; j >= 0; j -= 1){
                    if(innerParams[j].indexOf(data.parent) > -1){
                        if((innerParams[j].indexOf("OR") > -1) && !removeWhole){
                            var currValues = innerParams[j].substring(innerParams[j].indexOf("\"(")+2,
                                innerParams[j].indexOf(")\"")).split("OR");
                            for(var n in currValues){
                                if(data.text == currValues[n].trim()){
                                    currValues.splice(n, 1);
                                }
                            }
                            if(currValues.length > 1){
                                innerParams[j] = "\"" + data.parent + "\":\"(" +
                                    currValues.map(Function.prototype.call, String.prototype.trim).join(" OR ").trim()
                                    + ")\"";
                            } else {
                                innerParams[j] = "\"" + data.parent + "\":\"" + currValues.join("").trim() + "\"";
                            }

                        } else {
                            innerParams.splice(j, 1);
                        }
                    }
                }
                params_arr[i] = params_arr[i].split("=")[0] + "=" + encodeURIComponent(innerParams.join(","));
            }
            rtn = rtn + "?" + params_arr.join("&");
        }
        return rtn;
    };

    var getParamValue = function(sourceURL, key) {
        var param,
            params_arr = [],
            queryString = (sourceURL.indexOf("?") !== -1) ? sourceURL.split("?")[1] : "";
        if (queryString !== "") {
            params_arr = queryString.split("&");
            for (var i = params_arr.length - 1; i >= 0; i -= 1) {
                param = params_arr[i].split("=")[1];

                var innerParams;
                if(param.indexOf(",") > -1){
                    innerParams = param.split(",");
                } else {
                    innerParams = param.split("%2C");
                }
                for(var j= innerParams.length -1; j >= 0; j -= 1){
                    if(innerParams[j].indexOf(key) > -1){
                        return decodeURIComponent(innerParams[j]).split(":")[1];
                    }
                }
            }
        }
    };

    var formatSearchQuery = function(query){
        var searchQuery = "";
        var qjson = JSON.parse('{' + query + '}');
        var searchKeys = Object.keys(qjson);
        if ((searchKeys.length === 1) && (searchKeys.indexOf("name") >= 0)) {
            searchQuery += qjson[searchKeys.pop()];
        }
        else {
            for (var keyIndex in searchKeys) {
                var key = searchKeys[keyIndex];
                var value = qjson[key];
                searchQuery += key + ":" + value + " ";
            }
        }
        searchQuery = searchQuery.trim();
        return searchQuery;
    };

    var loadAssets = function(url){
        $('.assets-container section .ctrl-wr-asset').remove();
        history.pushState("", "", url);
        resetPageAttributes();
        store.infiniteScroll.addItemsToPage();

        setCategorizationQuery(url);
    };

    var setCategorizationQuery = function(url){
        var searchQuery =  removeUnrelatedKeys(decodeURIComponent(url));
        $('#categorization-query').val(formatSearchQuery(searchQuery));
    };

    var removeUnrelatedKeys = function(url){
        var searchQuery = url.split("q=")[1];
        var keyValues = searchQuery.split(",");
        for(var i in keyValues){
            var data = {};
            var isRemove = true;
            data.parent = keyValues[i].split(":")[0].split("\"").join('').trim();
            data.text = keyValues[i].split(":")[1].split("\"").join('').trim();

            for(var j in categorizationArray){
                if(categorizationArray[j] == data.parent){
                    isRemove = false;
                    break;
                }
            }

            if(isRemove){
                url = removeURLParameter(decodeURIComponent(url), data, true);
            }
        }

        return decodeURIComponent(url.split("q=")[1]);
    };
    var resetPageAttributes = function(){
        store.rows_added = 0;
        store.last_to = 0;
        store.items_per_row = 0;
        store.doPagination = true;
        store.firstRun = false;
        store.infiniteScroll.recalculateRowsAdded();
    };

    $('#categorization :checkbox').click(function() {
        var $this = $(this);
        var data = {};
        data.parent = $this.attr('name');
        data.text = $this.attr('value');
        // $this will contain a reference to the checkbox
        if ($this.is(':checked')) {
            // the checkbox was checked
            triggerEvent(data, false);
        } else {
            // the checkbox was unchecked
            triggerEvent(data, true);
        }
    });

    $('div[data-toggle="collapse"]').on('click',function(){
        var objectID=$(this).attr('href');
        var icon = $(objectID).prev().find('.status').children();

        if($(objectID).hasClass('in'))
        {
            $(objectID).collapse('hide');
            icon.removeClass('fw-up');
            icon.addClass('fw-down');
        }

        else{
            $(objectID).collapse('show');
            icon.removeClass('fw-down');
            icon.addClass('fw-up');
        }
    });

    $('#categorization :checkbox').each(function() {
        var $this = $(this);
        categorizationArray.push($this.attr('name'));
    });

    $.unique(categorizationArray);
    categorizationArray.push("mediaType");
    categorizationArray.push("taxonomy");

    var url = decodeURIComponent(window.location.href);
    if((url.indexOf("q=") > -1) && (url.split("q=")[1] !== "")){
        setCategorizationQuery(url);
    }

    $('#search').val($('#search').val().replace($('#categorization-query').val(),""));

    if(url.indexOf("=") > -1){
        var query = url.split("=");
        if(query[1] !== ""){
            updateFilters(url);
        }
    }

});
<commit_msg>adding a method description<commit_after>$(function() {
    var categorizationArray = [];

    var updateFilters = function (url){
        var queryArray = url.split("=")[1].split(",");
        var queryObjArray = [];
        if(queryArray.length > 0){
            for(var index in queryArray){
                var obj = queryArray[index];
                var queryObj = {};
                var queryObjValue = [];
                queryObj.queryKey = obj.split(":")[0].split('\"').join('');
                if(obj.indexOf("(") > -1){
                    var newObj = obj.split(":")[1].split('\"').join('').replace("(", "").replace(")", "");
                    queryObjValue = newObj.split("OR");
                } else {
                    if(obj.indexOf(":") > -1){
                        queryObjValue.push(obj.split(":")[1].split('\"').join(''));
                    }
                }
                queryObj.queryValue = queryObjValue;
                queryObjArray.push(queryObj);
            }

            for(var i in queryObjArray){
                $('#categorization :checkbox').each(function() {
                    var $this = $(this);
                    if($this.attr('name') == queryObjArray[i].queryKey){
                        for(var k in queryObjArray[i].queryValue){
                            if($this.attr('value').toLowerCase()
                                == queryObjArray[i].queryValue[k].trim().toLowerCase()){
                                $this.attr('checked', true);
                                $("#"+$this.attr('name')).collapse('show');
                                var icon = $("#"+$this.attr('name')).prev().find('.status').children();
                                icon.removeClass('fw-down');
                                icon.addClass('fw-up');
                            }
                        }
                    }
                });
            }
        }
    };

    var search = function (searchQuery, data, isRemove) {
        var url;

        var encodedQueryString = getEncodedQueryString(searchQuery);
        currentPage = 1;
        if (store.asset) {
            if(window.location.href.indexOf("q=") > -1){
                if(!isRemove){
                    if(window.location.href.split("=")[1] !== ""){
                        if(window.location.href.indexOf(searchQuery.split(":")[0]) > -1){
                            url = removeURLParameter(decodeURIComponent(window.location.href),
                                data, true);
                            if(url.split("q=")[1] !== ""){
                                url = url + "%2C" + encodedQueryString;
                            } else {
                                url = url + encodedQueryString;
                            }
                        } else {
                            url = window.location.href + "%2C" + encodedQueryString;
                        }
                    } else {
                        url = window.location.href + encodedQueryString;
                    }
                } else {
                    url = removeURLParameter(decodeURIComponent(window.location.href), data, false);
                }

            } else {
                url = caramel.tenantedUrl('/assets/' + store.asset.type + '/list?' + buildParams(encodedQueryString));
            }

            if(url.indexOf("mediaType") == -1){
                url = url + encodeURIComponent(",\"mediaType\":\""+store.asset.type+"\"");
            }
            loadAssets(url);
        }

        $('.search-bar h2').find('.page').text(' / Search: "' + searchQuery + '"');
    };

    var buildParams = function (query) {
        return 'q=' + query;
    };

    var getEncodedQueryString = function (searchQuery) {
        var q = {};
        var output = '';
        if(searchQuery !== ''){
            q = parseUsedDefinedQuery(searchQuery);
            q = JSON.stringify(q);
            q = q.replace('{','').replace('}', '');
            q = encodeURIComponent(q);
            output =q;
        }
        return output;
    };

    var triggerEvent = function (data, isRemove){
        var searchQueryString = data.parent + ":" + data.text;

        if((window.location.href.indexOf(data.parent) > -1) && !isRemove){
            searchQueryString = updateORQuery(window.location.href, data);
        }
        search(searchQueryString, data, isRemove);
    };

    var updateORQuery = function (url, data) {
        var value = getParamValue(url, data.parent).trim();
        var updatedQuery = "";
        if(value.indexOf("(") > -1){
            updatedQuery = data.parent + ":(" + value.substring(value.indexOf("\"(")+2, value.indexOf(")\"")) + " OR "
                + data.text + ")";
        } else {
            value = "\"" + value.split("\"").join("").trim() + "\"";
            updatedQuery = data.parent + ":(" + value.replace("\"", "").replace("\"", "") + " OR " + data.text + ")";
        }
        return updatedQuery;
    };

    var removeURLParameter = function(sourceURL, data, removeWhole) {
        var rtn = sourceURL.split("?")[0],
            param,
            params_arr = [],
            queryString = (sourceURL.indexOf("?") !== -1) ? sourceURL.split("?")[1] : "";
        if (queryString !== "") {
            params_arr = queryString.split("&");
            for (var i = params_arr.length - 1; i >= 0; i -= 1) {
                param = params_arr[i].split("=")[1];
                var innerParams = param.split(",");
                for(var j= innerParams.length -1; j >= 0; j -= 1){
                    if(innerParams[j].indexOf(data.parent) > -1){
                        if((innerParams[j].indexOf("OR") > -1) && !removeWhole){
                            var currValues = innerParams[j].substring(innerParams[j].indexOf("\"(")+2,
                                innerParams[j].indexOf(")\"")).split("OR");
                            for(var n in currValues){
                                if(data.text == currValues[n].trim()){
                                    currValues.splice(n, 1);
                                }
                            }
                            if(currValues.length > 1){
                                innerParams[j] = "\"" + data.parent + "\":\"(" +
                                    currValues.map(Function.prototype.call, String.prototype.trim).join(" OR ").trim()
                                    + ")\"";
                            } else {
                                innerParams[j] = "\"" + data.parent + "\":\"" + currValues.join("").trim() + "\"";
                            }

                        } else {
                            innerParams.splice(j, 1);
                        }
                    }
                }
                params_arr[i] = params_arr[i].split("=")[0] + "=" + encodeURIComponent(innerParams.join(","));
            }
            rtn = rtn + "?" + params_arr.join("&");
        }
        return rtn;
    };

    var getParamValue = function(sourceURL, key) {
        var param,
            params_arr = [],
            queryString = (sourceURL.indexOf("?") !== -1) ? sourceURL.split("?")[1] : "";
        if (queryString !== "") {
            params_arr = queryString.split("&");
            for (var i = params_arr.length - 1; i >= 0; i -= 1) {
                param = params_arr[i].split("=")[1];

                var innerParams;
                if(param.indexOf(",") > -1){
                    innerParams = param.split(",");
                } else {
                    innerParams = param.split("%2C");
                }
                for(var j= innerParams.length -1; j >= 0; j -= 1){
                    if(innerParams[j].indexOf(key) > -1){
                        return decodeURIComponent(innerParams[j]).split(":")[1];
                    }
                }
            }
        }
    };

    var formatSearchQuery = function(query){
        var searchQuery = "";
        var qjson = JSON.parse('{' + query + '}');
        var searchKeys = Object.keys(qjson);
        if ((searchKeys.length === 1) && (searchKeys.indexOf("name") >= 0)) {
            searchQuery += qjson[searchKeys.pop()];
        }
        else {
            for (var keyIndex in searchKeys) {
                var key = searchKeys[keyIndex];
                var value = qjson[key];
                searchQuery += key + ":" + value + " ";
            }
        }
        searchQuery = searchQuery.trim();
        return searchQuery;
    };

    var loadAssets = function(url){
        $('.assets-container section .ctrl-wr-asset').remove();
        history.pushState("", "", url);
        resetPageAttributes();
        store.infiniteScroll.addItemsToPage();

        setCategorizationQuery(url);
    };

    var setCategorizationQuery = function(url){
        var searchQuery =  removeUnrelatedKeys(decodeURIComponent(url));
        $('#categorization-query').val(formatSearchQuery(searchQuery));
    };

    /**
     * This method removes the keys from the search query which are not related
     * to taxonomy for categorization in order to make generic search independent from taxonomy
     * @param url
     * @returns {string}
     */
    var removeUnrelatedKeys = function(url){
        var searchQuery = url.split("q=")[1];
        var keyValues = searchQuery.split(",");
        for(var i in keyValues){
            var data = {};
            var isRemove = true;
            data.parent = keyValues[i].split(":")[0].split("\"").join('').trim();
            data.text = keyValues[i].split(":")[1].split("\"").join('').trim();

            for(var j in categorizationArray){
                if(categorizationArray[j] == data.parent){
                    isRemove = false;
                    break;
                }
            }

            if(isRemove){
                url = removeURLParameter(decodeURIComponent(url), data, true);
            }
        }

        return decodeURIComponent(url.split("q=")[1]);
    };
    var resetPageAttributes = function(){
        store.rows_added = 0;
        store.last_to = 0;
        store.items_per_row = 0;
        store.doPagination = true;
        store.firstRun = false;
        store.infiniteScroll.recalculateRowsAdded();
    };

    $('#categorization :checkbox').click(function() {
        var $this = $(this);
        var data = {};
        data.parent = $this.attr('name');
        data.text = $this.attr('value');
        // $this will contain a reference to the checkbox
        if ($this.is(':checked')) {
            // the checkbox was checked
            triggerEvent(data, false);
        } else {
            // the checkbox was unchecked
            triggerEvent(data, true);
        }
    });

    $('div[data-toggle="collapse"]').on('click',function(){
        var objectID=$(this).attr('href');
        var icon = $(objectID).prev().find('.status').children();

        if($(objectID).hasClass('in'))
        {
            $(objectID).collapse('hide');
            icon.removeClass('fw-up');
            icon.addClass('fw-down');
        }

        else{
            $(objectID).collapse('show');
            icon.removeClass('fw-down');
            icon.addClass('fw-up');
        }
    });

    $('#categorization :checkbox').each(function() {
        var $this = $(this);
        categorizationArray.push($this.attr('name'));
    });

    $.unique(categorizationArray);
    categorizationArray.push("mediaType");
    categorizationArray.push("taxonomy");

    var url = decodeURIComponent(window.location.href);
    if((url.indexOf("q=") > -1) && (url.split("q=")[1] !== "")){
        setCategorizationQuery(url);
    }

    $('#search').val($('#search').val().replace($('#categorization-query').val(),""));

    if(url.indexOf("=") > -1){
        var query = url.split("=");
        if(query[1] !== ""){
            updateFilters(url);
        }
    }

});
<|endoftext|>


<commit_before>/*
 * grunt-require-gettext
 * https://github.com/open-xchange-frontend/grunt-require-gettext
 *
 * Copyright (c) 2014 Julian Bäume
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function (grunt) {
    var esprima = require('esprima');
    var _ = require('lodash');

    function extractStrings(fileName) {
        function walkTree(node, fn) {
            fn(node);

            for (var key in node) {
                var obj = node[key];
                if (typeof obj === 'object') {
                    walkTree(obj, fn);
                }
            }
        }
        function isBetweenTokens(comment, prevToken, token) {
            return comment.range[0] >= prevToken.range[1] && comment.range[1] <= token.range[0];
        }

        function getComment(ast, node) {
            var tokenIndex;
            var currentIndex, min = 0, max = ast.tokens.length;
            while (tokenIndex === undefined) {
                currentIndex = Math.floor((min + max) / 2);
                if (ast.tokens[currentIndex].loc.start.line < node.loc.start.line) {
                    min = currentIndex;
                    continue;
                } else if (ast.tokens[currentIndex].loc.start.line > node.loc.start.line) {
                    max = currentIndex;
                    continue;
                } else if (ast.tokens[currentIndex].loc.start.column < node.loc.start.column) {
                    min = currentIndex;
                    continue;
                } else if (ast.tokens[currentIndex].loc.start.column > node.loc.start.column) {
                    max = currentIndex;
                    continue;
                }
                tokenIndex = currentIndex;
            }
            while (ast.tokens[currentIndex].loc.start.line === node.loc.start.line) {
                //use currentIndex variable to get the first index in a line
                currentIndex--;
            }

            var commentObj = ast.comments.filter(function (comment) {
                var commentBeforeToken = isBetweenTokens(comment, ast.tokens[tokenIndex - 1], ast.tokens[tokenIndex]);
                var commentInLinesAbove = isBetweenTokens(comment, ast.tokens[currentIndex], ast.tokens[currentIndex + 1]);

                return (commentBeforeToken || commentInLinesAbove);
            }).map(function (commentInRange) {
                return commentInRange.value;
            }).join('\n');

            return commentObj;
        }

        function tryEval(code) {
            var val;
            try {
                val = eval(code);
            } catch (e) {
                grunt.log.warn(e + ' - while statically evaluating code: ' + code);
            }
            return val;
        }

        var code = grunt.file.read(fileName);
        var syntax = esprima.parse(code, {comment: true, loc: true, tokens: true, range: true});
        var items;
        var handleGtCall = function (node, gtName, module) {
            if (node !== null &&
                node.type === 'CallExpression' &&
                node.callee !== null &&
                node.callee.name === gtName &&
                node['arguments'] !== null &&
                node['arguments'].length
            ) {
                var msgId = node['arguments'][0].value || tryEval(code.slice(node['arguments'][0].range[0], node['arguments'][0].range[1]));
                if (!msgId) {
                    if (getComment(syntax, node).indexOf('#, dynamic') >= 0) {
                        grunt.verbose.warn('Ignoring gt.pgettext call with dynamic flag set.');
                        return;
                    }
                    grunt.verbose.warn(JSON.stringify(node['arguments'], null, 4));
                    grunt.fail.warn('Could not read node in file: ' + fileName + ' use --verbose for more info');
                    return;
                }
                items = items || [];
                items.push({
                    msgId: msgId.trim(),
                    module: module,
                    fileName: fileName,
                    line: node.loc.start.line,
                    comment: getComment(syntax, node)
                });
            } else if (
                node !== null &&
                node.type === 'CallExpression' &&
                node.callee !== null &&
                node.callee.type === 'MemberExpression' &&
                node.callee.object.name === gtName &&
                node.callee.property.name === 'pgettext' &&
                node['arguments'] !== null &&
                node['arguments'].length === 2
            ) {
                var msgId = node['arguments'][1].value || tryEval(code.slice(node['arguments'][1].range[0], node['arguments'][1].range[1]));
                var msgContext = node['arguments'][0].value || tryEval(code.slice(node['arguments'][0].range[0], node['arguments'][0].range[1]));
                if (!msgId || !msgContext) {
                    if (getComment(syntax, node).indexOf('#, dynamic') >= 0) {
                        grunt.verbose.warn('Ignoring gt.pgettext call with dynamic flag set.');
                        return;
                    }
                    grunt.verbose.warn(JSON.stringify(node['arguments'], null, 4));
                    grunt.fail.warn('Could not read node in file: ' + fileName + ' use --verbose for more info');
                    return;
                }
                items = items || [];
                items.push({
                    msgId: msgId.trim(),
                    msgContext: msgContext.trim(),
                    module: module,
                    fileName: fileName,
                    line: node.loc.start.line,
                    comment: getComment(syntax, node)
                });
            } else if (
                node !== null &&
                node.type === 'CallExpression' &&
                node.callee !== null &&
                node.callee.type === 'MemberExpression' &&
                node.callee.object.name === gtName &&
                node.callee.property.name === 'ngettext' &&
                node['arguments'] !== null &&
                node['arguments'].length === 3
            ) {
                var msgId = node['arguments'][0].value || tryEval(code.slice(node['arguments'][0].range[0], node['arguments'][0].range[1]));
                var msgIdPlural = node['arguments'][1].value || tryEval(code.slice(node['arguments'][1].range[0], node['arguments'][1].range[1]));
                if (!msgId || !msgIdPlural || !node['arguments'][2]) {
                    if (getComment(syntax, node).indexOf('#, dynamic') >= 0) {
                        grunt.verbose.warn('Ignoring gt.pgettext call with dynamic flag set.');
                        return;
                    }
                    grunt.verbose.warn(JSON.stringify(node['arguments'], null, 4));
                    grunt.fail.warn('Could not read node  in file: ' + fileName + ' use --verbose for more info');
                    return;
                }
                items = items || [];
                items.push({
                    msgId: msgId.trim(),
                    msgIdPlural: msgIdPlural.trim(),
                    module: module,
                    fileName: fileName,
                    line: node.loc.start.line,
                    comment: getComment(syntax, node)
                });
            } else if (
                node !== null &&
                node.type === 'CallExpression' &&
                node.callee !== null &&
                node.callee.type === 'MemberExpression' &&
                node.callee.object.name === gtName &&
                node.callee.property.name === 'npgettext' &&
                node['arguments'] !== null &&
                node['arguments'].length === 4
            ) {
                var msgContext = node['arguments'][0].value || tryEval(code.slice(node['arguments'][0].range[0], node['arguments'][0].range[1]));
                var msgId = node['arguments'][1].value || tryEval(code.slice(node['arguments'][1].range[0], node['arguments'][1].range[1]));
                var msgIdPlural = node['arguments'][2].value || tryEval(code.slice(node['arguments'][2].range[0], node['arguments'][2].range[1]));
                if (!msgContext || !msgId || !msgIdPlural || !node['arguments'][3]) {
                    if (getComment(syntax, node).indexOf('#, dynamic') >= 0) {
                        grunt.verbose.warn('Ignoring gt.pgettext call with dynamic flag set.');
                        return;
                    }
                    grunt.verbose.warn(JSON.stringify(node['arguments'], null, 4));
                    grunt.fail.warn('Could not read node in file: ' + fileName + ' use --verbose for more info');
                    return;
                }
                items = items || [];
                items.push({
                    msgContext: msgContext.trim(),
                    msgId: msgId.trim(),
                    msgIdPlural: msgIdPlural.trim(),
                    module: module,
                    fileName: fileName,
                    line: node.loc.start.line,
                    comment: getComment(syntax, node)
                });
            }
        };

        walkTree(syntax, function (node) {
            if (node !== null &&
                node.type === 'CallExpression' &&
                node.callee !== null &&
                node.callee.name === 'define' &&
                node['arguments'] !== null &&
                node['arguments'].length > 2)
            {
                node['arguments'][1].elements.map(function (el, index) {
                    if (el.value.substr(0, 8) === 'gettext!') {
                        var param = node['arguments'][2].params[index];
                        if (!param) {
                            grunt.log.warn('Unused require-gettext module call in', fileName);
                            return;
                        }
                        return {
                            name: param.name,
                            module: el.value.substr(8)
                        };
                    }
                }).filter(function (arg) {
                    return arg !== undefined;
                }).forEach(function (obj) {
                    var gtName = obj.name;
                    var module = obj.module;

                    if (node['arguments'][2].type === 'FunctionExpression') {
                        walkTree(node['arguments'][2], function (node) {
                            handleGtCall(node, gtName, module);
                        });
                    }
                });
            } else if (node !== null &&
                node.type === 'CallExpression' &&
                node.callee !== null &&
                node.callee.type === 'MemberExpression' &&
                node.callee.object !== null &&
                node.callee.object.name === 'define' &&
                node.callee.property.name === 'async' &&
                node['arguments'] !== null &&
                node['arguments'].length > 2)
            {
                node['arguments'][1].elements.map(function (el, index) {
                    if (el.value.substr(0, 8) === 'gettext!') {
                        var param = node['arguments'][2].params[index];
                        if (!param) {
                            grunt.log.warn('Unused require-gettext module call in', fileName);
                            return;
                        }
                        return {
                            name: param.name,
                            module: el.value.substr(8)
                        };
                    }
                }).filter(function (arg) {
                    return arg !== undefined;
                }).forEach(function (obj) {
                    var gtName = obj.name;
                    var module = obj.module;

                    if (node['arguments'][2].type === 'FunctionExpression') {
                        walkTree(node['arguments'][2], function (node) {
                            handleGtCall(node, gtName, module);
                        });
                    }
                });
            }
        });
        return items;
    }

    grunt.registerMultiTask('create_pot', 'Extract calls to gettext that is used with a requirejs gettext module.', function () {
        var PO = require('pofile');
        var options = this.options();

        this.files.forEach(function (file) {
            var poItems;

            poItems = file.src.filter(function (srcFile) {
                return srcFile.substr(-3) === '.js';
            }).map(function (srcFile) {
                return {srcFile: srcFile, items: extractStrings(srcFile)};
            }).reduce(function (acc, result) {
                if (!acc) {
                    return;
                }
                var items = result.items;
                if (!items) {
                    items = [];
                    grunt.log.debug('No strings extracted from file ' + result.srcFile);
                }
                items.forEach(function (item) {
                    var key = item.msgId;
                    if (item.msgContext) {
                        key += '_' + item.msgContext;
                    }
                    if (!acc[key]) {
                        acc[key] = new PO.Item();
                    }
                    var poItem = acc[key];
                    poItem.msgid = item.msgId;
                    poItem.msgid_plural = item.msgIdPlural;
                    poItem.msgctxt = item.msgContext;
                    if (poItem.references.indexOf(item.fileName + ':' + item.line) < 0) {
                        poItem.references.push(item.fileName + ':' + item.line);
                    }
                    if (poItem.references.indexOf('module:' + item.module) < 0) {
                        poItem.references.push('module:' + item.module);
                    }
                    if (poItem.msgid_plural) {
                        //FIXME: may be, this should be handled by pofile library
                        poItem.msgstr = ['', ''];
                    }
                    if (item.comment) {
                        var commentItem = PO.parse('msgid ""\nmsgstr ""\n\n' + item.comment + '\nmsgid "temp"\nmsgstr""\n').items[0];
                        _(poItem.flags).extend(commentItem.flags);
                        poItem.extractedComments = _.uniq([].concat(poItem.extractedComments, commentItem.extractedComments));
                    }
                });
                return acc;
            }, {});

            if (poItems) {
                var catalog = new PO();
                for (var key in poItems) {
                    catalog.items.push(poItems[key]);
                }
                if (options.headers) {
                    grunt.verbose.writeln('Writing custom headers: ' + JSON.stringify(options.headers, null, 4));
                }
                catalog.headers = options.headers || {
                    'Content-Type': 'text/plain; charset=UTF-8',
                    'Content-Transfer-Encoding': '8bit'
                };
                grunt.file.write(file.dest, catalog.toString());
            }
        });
    });
};
<commit_msg>hide misleading warning when evaluating code fails<commit_after>/*
 * grunt-require-gettext
 * https://github.com/open-xchange-frontend/grunt-require-gettext
 *
 * Copyright (c) 2014 Julian Bäume
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function (grunt) {
    var esprima = require('esprima');
    var _ = require('lodash');

    function extractStrings(fileName) {
        function walkTree(node, fn) {
            fn(node);

            for (var key in node) {
                var obj = node[key];
                if (typeof obj === 'object') {
                    walkTree(obj, fn);
                }
            }
        }
        function isBetweenTokens(comment, prevToken, token) {
            return comment.range[0] >= prevToken.range[1] && comment.range[1] <= token.range[0];
        }

        function getComment(ast, node) {
            var tokenIndex;
            var currentIndex, min = 0, max = ast.tokens.length;
            while (tokenIndex === undefined) {
                currentIndex = Math.floor((min + max) / 2);
                if (ast.tokens[currentIndex].loc.start.line < node.loc.start.line) {
                    min = currentIndex;
                    continue;
                } else if (ast.tokens[currentIndex].loc.start.line > node.loc.start.line) {
                    max = currentIndex;
                    continue;
                } else if (ast.tokens[currentIndex].loc.start.column < node.loc.start.column) {
                    min = currentIndex;
                    continue;
                } else if (ast.tokens[currentIndex].loc.start.column > node.loc.start.column) {
                    max = currentIndex;
                    continue;
                }
                tokenIndex = currentIndex;
            }
            while (ast.tokens[currentIndex].loc.start.line === node.loc.start.line) {
                //use currentIndex variable to get the first index in a line
                currentIndex--;
            }

            var commentObj = ast.comments.filter(function (comment) {
                var commentBeforeToken = isBetweenTokens(comment, ast.tokens[tokenIndex - 1], ast.tokens[tokenIndex]);
                var commentInLinesAbove = isBetweenTokens(comment, ast.tokens[currentIndex], ast.tokens[currentIndex + 1]);

                return (commentBeforeToken || commentInLinesAbove);
            }).map(function (commentInRange) {
                return commentInRange.value;
            }).join('\n');

            return commentObj;
        }

        function tryEval(code) {
            var val;
            try {
                val = eval(code);
            } catch (e) {
                grunt.verbose.warn(e + ' - while statically evaluating code: ' + code);
            }
            return val;
        }

        var code = grunt.file.read(fileName);
        var syntax = esprima.parse(code, {comment: true, loc: true, tokens: true, range: true});
        var items;
        var handleGtCall = function (node, gtName, module) {
            if (node !== null &&
                node.type === 'CallExpression' &&
                node.callee !== null &&
                node.callee.name === gtName &&
                node['arguments'] !== null &&
                node['arguments'].length
            ) {
                var msgId = node['arguments'][0].value || tryEval(code.slice(node['arguments'][0].range[0], node['arguments'][0].range[1]));
                if (!msgId) {
                    if (getComment(syntax, node).indexOf('#, dynamic') >= 0) {
                        grunt.verbose.warn('Ignoring gt.pgettext call with dynamic flag set.');
                        return;
                    }
                    grunt.verbose.warn(JSON.stringify(node['arguments'], null, 4));
                    grunt.fail.warn('Could not read node in file: ' + fileName + ' use --verbose for more info');
                    return;
                }
                items = items || [];
                items.push({
                    msgId: msgId.trim(),
                    module: module,
                    fileName: fileName,
                    line: node.loc.start.line,
                    comment: getComment(syntax, node)
                });
            } else if (
                node !== null &&
                node.type === 'CallExpression' &&
                node.callee !== null &&
                node.callee.type === 'MemberExpression' &&
                node.callee.object.name === gtName &&
                node.callee.property.name === 'pgettext' &&
                node['arguments'] !== null &&
                node['arguments'].length === 2
            ) {
                var msgId = node['arguments'][1].value || tryEval(code.slice(node['arguments'][1].range[0], node['arguments'][1].range[1]));
                var msgContext = node['arguments'][0].value || tryEval(code.slice(node['arguments'][0].range[0], node['arguments'][0].range[1]));
                if (!msgId || !msgContext) {
                    if (getComment(syntax, node).indexOf('#, dynamic') >= 0) {
                        grunt.verbose.warn('Ignoring gt.pgettext call with dynamic flag set.');
                        return;
                    }
                    grunt.verbose.warn(JSON.stringify(node['arguments'], null, 4));
                    grunt.fail.warn('Could not read node in file: ' + fileName + ' use --verbose for more info');
                    return;
                }
                items = items || [];
                items.push({
                    msgId: msgId.trim(),
                    msgContext: msgContext.trim(),
                    module: module,
                    fileName: fileName,
                    line: node.loc.start.line,
                    comment: getComment(syntax, node)
                });
            } else if (
                node !== null &&
                node.type === 'CallExpression' &&
                node.callee !== null &&
                node.callee.type === 'MemberExpression' &&
                node.callee.object.name === gtName &&
                node.callee.property.name === 'ngettext' &&
                node['arguments'] !== null &&
                node['arguments'].length === 3
            ) {
                var msgId = node['arguments'][0].value || tryEval(code.slice(node['arguments'][0].range[0], node['arguments'][0].range[1]));
                var msgIdPlural = node['arguments'][1].value || tryEval(code.slice(node['arguments'][1].range[0], node['arguments'][1].range[1]));
                if (!msgId || !msgIdPlural || !node['arguments'][2]) {
                    if (getComment(syntax, node).indexOf('#, dynamic') >= 0) {
                        grunt.verbose.warn('Ignoring gt.pgettext call with dynamic flag set.');
                        return;
                    }
                    grunt.verbose.warn(JSON.stringify(node['arguments'], null, 4));
                    grunt.fail.warn('Could not read node  in file: ' + fileName + ' use --verbose for more info');
                    return;
                }
                items = items || [];
                items.push({
                    msgId: msgId.trim(),
                    msgIdPlural: msgIdPlural.trim(),
                    module: module,
                    fileName: fileName,
                    line: node.loc.start.line,
                    comment: getComment(syntax, node)
                });
            } else if (
                node !== null &&
                node.type === 'CallExpression' &&
                node.callee !== null &&
                node.callee.type === 'MemberExpression' &&
                node.callee.object.name === gtName &&
                node.callee.property.name === 'npgettext' &&
                node['arguments'] !== null &&
                node['arguments'].length === 4
            ) {
                var msgContext = node['arguments'][0].value || tryEval(code.slice(node['arguments'][0].range[0], node['arguments'][0].range[1]));
                var msgId = node['arguments'][1].value || tryEval(code.slice(node['arguments'][1].range[0], node['arguments'][1].range[1]));
                var msgIdPlural = node['arguments'][2].value || tryEval(code.slice(node['arguments'][2].range[0], node['arguments'][2].range[1]));
                if (!msgContext || !msgId || !msgIdPlural || !node['arguments'][3]) {
                    if (getComment(syntax, node).indexOf('#, dynamic') >= 0) {
                        grunt.verbose.warn('Ignoring gt.pgettext call with dynamic flag set.');
                        return;
                    }
                    grunt.verbose.warn(JSON.stringify(node['arguments'], null, 4));
                    grunt.fail.warn('Could not read node in file: ' + fileName + ' use --verbose for more info');
                    return;
                }
                items = items || [];
                items.push({
                    msgContext: msgContext.trim(),
                    msgId: msgId.trim(),
                    msgIdPlural: msgIdPlural.trim(),
                    module: module,
                    fileName: fileName,
                    line: node.loc.start.line,
                    comment: getComment(syntax, node)
                });
            }
        };

        walkTree(syntax, function (node) {
            if (node !== null &&
                node.type === 'CallExpression' &&
                node.callee !== null &&
                node.callee.name === 'define' &&
                node['arguments'] !== null &&
                node['arguments'].length > 2)
            {
                node['arguments'][1].elements.map(function (el, index) {
                    if (el.value.substr(0, 8) === 'gettext!') {
                        var param = node['arguments'][2].params[index];
                        if (!param) {
                            grunt.log.warn('Unused require-gettext module call in', fileName);
                            return;
                        }
                        return {
                            name: param.name,
                            module: el.value.substr(8)
                        };
                    }
                }).filter(function (arg) {
                    return arg !== undefined;
                }).forEach(function (obj) {
                    var gtName = obj.name;
                    var module = obj.module;

                    if (node['arguments'][2].type === 'FunctionExpression') {
                        walkTree(node['arguments'][2], function (node) {
                            handleGtCall(node, gtName, module);
                        });
                    }
                });
            } else if (node !== null &&
                node.type === 'CallExpression' &&
                node.callee !== null &&
                node.callee.type === 'MemberExpression' &&
                node.callee.object !== null &&
                node.callee.object.name === 'define' &&
                node.callee.property.name === 'async' &&
                node['arguments'] !== null &&
                node['arguments'].length > 2)
            {
                node['arguments'][1].elements.map(function (el, index) {
                    if (el.value.substr(0, 8) === 'gettext!') {
                        var param = node['arguments'][2].params[index];
                        if (!param) {
                            grunt.log.warn('Unused require-gettext module call in', fileName);
                            return;
                        }
                        return {
                            name: param.name,
                            module: el.value.substr(8)
                        };
                    }
                }).filter(function (arg) {
                    return arg !== undefined;
                }).forEach(function (obj) {
                    var gtName = obj.name;
                    var module = obj.module;

                    if (node['arguments'][2].type === 'FunctionExpression') {
                        walkTree(node['arguments'][2], function (node) {
                            handleGtCall(node, gtName, module);
                        });
                    }
                });
            }
        });
        return items;
    }

    grunt.registerMultiTask('create_pot', 'Extract calls to gettext that is used with a requirejs gettext module.', function () {
        var PO = require('pofile');
        var options = this.options();

        this.files.forEach(function (file) {
            var poItems;

            poItems = file.src.filter(function (srcFile) {
                return srcFile.substr(-3) === '.js';
            }).map(function (srcFile) {
                return {srcFile: srcFile, items: extractStrings(srcFile)};
            }).reduce(function (acc, result) {
                if (!acc) {
                    return;
                }
                var items = result.items;
                if (!items) {
                    items = [];
                    grunt.log.debug('No strings extracted from file ' + result.srcFile);
                }
                items.forEach(function (item) {
                    var key = item.msgId;
                    if (item.msgContext) {
                        key += '_' + item.msgContext;
                    }
                    if (!acc[key]) {
                        acc[key] = new PO.Item();
                    }
                    var poItem = acc[key];
                    poItem.msgid = item.msgId;
                    poItem.msgid_plural = item.msgIdPlural;
                    poItem.msgctxt = item.msgContext;
                    if (poItem.references.indexOf(item.fileName + ':' + item.line) < 0) {
                        poItem.references.push(item.fileName + ':' + item.line);
                    }
                    if (poItem.references.indexOf('module:' + item.module) < 0) {
                        poItem.references.push('module:' + item.module);
                    }
                    if (poItem.msgid_plural) {
                        //FIXME: may be, this should be handled by pofile library
                        poItem.msgstr = ['', ''];
                    }
                    if (item.comment) {
                        var commentItem = PO.parse('msgid ""\nmsgstr ""\n\n' + item.comment + '\nmsgid "temp"\nmsgstr""\n').items[0];
                        _(poItem.flags).extend(commentItem.flags);
                        poItem.extractedComments = _.uniq([].concat(poItem.extractedComments, commentItem.extractedComments));
                    }
                });
                return acc;
            }, {});

            if (poItems) {
                var catalog = new PO();
                for (var key in poItems) {
                    catalog.items.push(poItems[key]);
                }
                if (options.headers) {
                    grunt.verbose.writeln('Writing custom headers: ' + JSON.stringify(options.headers, null, 4));
                }
                catalog.headers = options.headers || {
                    'Content-Type': 'text/plain; charset=UTF-8',
                    'Content-Transfer-Encoding': '8bit'
                };
                grunt.file.write(file.dest, catalog.toString());
            }
        });
    });
};
<|endoftext|>


<commit_before>var db = require('../db');
var async = require('async');
var queueReq = require('../operations').queueReq;
module.exports = function(cb) {
    db.matches.distinct('players.account_id', {}, function(err, array) {
        if (err) {
            return cb(err);
        }
        var filtered = [];
        async.map(array, function(id, cb) {
            var player = {
                account_id: id
            };
            db.players.find(player, function(err, docs) {
                if (!docs.length) {
                    filtered.push(player);
                }
                cb(err);
            });
        }, function(err) {
            if (err) {
                return cb(err);
            }
            array = filtered;
            var chunk = 100;
            var chunks = [];
            for (var i = 0; i < array.length; i += chunk) {
                var temp = array.slice(i, i + chunk);
                chunks.push(temp);
            }
            async.mapSeries(chunks, function(chunk, cb) {
                var summaries = {
                    summaries_id: new Date(),
                    players: chunk
                };
                queueReq("api_summaries", summaries, function(err) {
                    cb(err);
                });
            }, function(err) {
                cb(err, array.length);
            });
        });
    });
};<commit_msg>mapseries instead of map to prevent concurrency issues<commit_after>var db = require('../db');
var async = require('async');
var queueReq = require('../operations').queueReq;
module.exports = function(cb) {
    db.matches.distinct('players.account_id', {}, function(err, array) {
        if (err) {
            return cb(err);
        }
        var filtered = [];
        async.mapSeries(array, function(id, cb) {
            var player = {
                account_id: id
            };
            db.players.find(player, function(err, docs) {
                if (!docs.length) {
                    filtered.push(player);
                }
                cb(err);
            });
        }, function(err) {
            if (err) {
                return cb(err);
            }
            array = filtered;
            var chunk = 100;
            var chunks = [];
            for (var i = 0; i < array.length; i += chunk) {
                var temp = array.slice(i, i + chunk);
                chunks.push(temp);
            }
            async.mapSeries(chunks, function(chunk, cb) {
                var summaries = {
                    summaries_id: new Date(),
                    players: chunk
                };
                queueReq("api_summaries", summaries, function(err) {
                    cb(err);
                });
            }, function(err) {
                cb(err, array.length);
            });
        });
    });
};<|endoftext|>


<commit_before>/*
 * grunt-contrib-handlebars
 * http://gruntjs.com/
 *
 * Copyright (c) 2014 Tim Branyen, contributors
 * Licensed under the MIT license.
 */

'use strict';
var chalk = require('chalk');
var nsdeclare = require('nsdeclare');

module.exports = function(grunt) {
  var _ = grunt.util._;

  // content conversion for templates
  var defaultProcessContent = function(content) { return content; };

  // AST processing for templates
  var defaultProcessAST = function(ast) { return ast; };

  // filename conversion for templates
  var defaultProcessName = function(name) { return name; };

  // filename conversion for partials
  var defaultProcessPartialName = function(filepath) {
    var pieces = _.last(filepath.split('/')).split('.');
    var name   = _(pieces).without(_.last(pieces)).join('.'); // strips file extension
    if (name.charAt(0) === '_') {
      name = name.substr(1, name.length); // strips leading _ character
    }
    return name;
  };

  grunt.registerMultiTask('handlebars', 'Compile handlebars templates and partials.', function() {
    var options = this.options({
      namespace: 'JST',
      separator: grunt.util.linefeed + grunt.util.linefeed,
      wrapped: true,
      amd: false,
      commonjs: false,
      knownHelpers: [],
      knownHelpersOnly: false
    });

    // assign regex for partials directory detection
    var partialsPathRegex = options.partialsPathRegex || /./;

    // assign regex for partial detection
    var isPartialRegex = options.partialRegex || /^_/;

    // assign transformation functions
    var processContent = options.processContent || defaultProcessContent;
    var processName = options.processName || defaultProcessName;
    var processPartialName = options.processPartialName || defaultProcessPartialName;
    var processAST = options.processAST || defaultProcessAST;
    var useNamespace = options.namespace !== false;

    // assign compiler options
    var compilerOptions = options.compilerOptions || {};
    var filesCount = 0;

    this.files.forEach(function(f) {
      var partials = [];
      var templates = [];

      // Namespace info for current template
      var nsInfo;

      // Map of already declared namespace parts
      var nsDeclarations = {};

      // nsdeclare options when fetching namespace info
      var nsDeclareOptions = {response: 'details', declared: nsDeclarations};

      // Just get the namespace info for a given template
      var getNamespaceInfo = _.memoize(function(filepath) {
        if (!useNamespace) {return undefined;}
        if (_.isFunction(options.namespace)) {
          return nsdeclare(options.namespace(filepath), nsDeclareOptions);
        } else {
          return nsdeclare(options.namespace, nsDeclareOptions);
        }
      });

      // iterate files, processing partials and templates separately
      f.src.filter(function(filepath) {
        // Warn on and remove invalid source files (if nonull was set).
        if (!grunt.file.exists(filepath)) {
          grunt.log.warn('Source file "' + filepath + '" not found.');
          return false;
        } else {
          return true;
        }
      })
      .forEach(function(filepath) {
        var src = processContent(grunt.file.read(filepath), filepath);

        var Handlebars = require('handlebars');
        var ast, compiled, filename;
        try {
          // parse the handlebars template into it's AST
          ast = processAST(Handlebars.parse(src));
          compiled = Handlebars.precompile(ast, compilerOptions);

          // if configured to, wrap template in Handlebars.template call
          if (options.wrapped === true) {
            compiled = 'Handlebars.template(' + compiled + ')';
          }
        } catch (e) {
          grunt.log.error(e);
          grunt.fail.warn('Handlebars failed to compile ' + filepath + '.');
        }

        // register partial or add template to namespace
        if (partialsPathRegex.test(filepath) && isPartialRegex.test(_.last(filepath.split('/')))) {
          filename = processPartialName(filepath);
          if (options.partialsUseNamespace === true) {
            nsInfo = getNamespaceInfo(filepath);

            partials.push(nsInfo.declaration);
            partials.push('Handlebars.registerPartial(' + JSON.stringify(filename) + ', ' + nsInfo.namespace +
              '[' + JSON.stringify(filename) + '] = ' + compiled + ');');
          } else {
            partials.push('Handlebars.registerPartial(' + JSON.stringify(filename) + ', ' + compiled + ');');
          }
        } else {
          nsInfo = getNamespaceInfo(filepath);

          if (options.amd && !useNamespace) {
            compiled = 'return ' + compiled;
          }
          filename = processName(filepath);
          if (useNamespace) {
            templates.push(nsInfo.declaration);
            templates.push(nsInfo.namespace + '[' + JSON.stringify(filename) + '] = ' + compiled + ';');
          } else if (options.commonjs === true) {
            templates.push('templates[' + JSON.stringify(filename) + '] = ' + compiled + ';');
          } else {
            templates.push(compiled);
          }
        }
      });

      var output = partials.concat(templates);
      if (output.length < 1) {
        grunt.log.warn('Destination not written because compiled files were empty.');
      } else {
        if (useNamespace) {
          if (options.node) {
            output.unshift('Handlebars = glob.Handlebars || require(\'handlebars\');');
            output.unshift('var glob = (\'undefined\' === typeof window) ? global : window,');

            var nodeExport = 'if (typeof exports === \'object\' && exports) {';
            nodeExport += 'module.exports = ' + nsInfo.namespace + ';}';

            output.push(nodeExport);
          }

        }

        if (options.amd) {
          // Wrap the file in an AMD define fn.
          if (typeof options.amd === 'boolean') {
            output.unshift('define([\'handlebars\'], function(Handlebars) {');
          } else if (typeof options.amd === 'string') {
            output.unshift('define([\'' + options.amd + '\'], function(Handlebars) {');
          } else if (Array.isArray(options.amd)) {
            // convert options.amd to a string of dependencies for require([...])
            var amdString = '';
            for (var i = 0; i < options.amd.length; i++) {
              if (i !== 0) {
                amdString += ', ';
              }

              amdString += '\'' + options.amd[i] + '\'';
            }

            // Wrap the file in an AMD define fn.
            output.unshift('define([' + amdString + '], function(Handlebars) {');
          }

          if (useNamespace) {
            // Namespace has not been explicitly set to false; the AMD
            // wrapper will return the object containing the template.
            output.push('return ' + nsInfo.namespace + ';');
          }
          output.push('});');
        }

        if (options.commonjs) {
          if (useNamespace) {
            output.push('return ' + nsInfo.namespace + ';');
          } else {
            output.unshift('var templates = {};');
            output.push('return templates;');
          }
          // Export the templates object for CommonJS environments.
          output.unshift('module.exports = function(Handlebars) {');
          output.push('};');
        }

        filesCount++;
        grunt.file.write(f.dest, output.join(grunt.util.normalizelf(options.separator)));
        grunt.verbose.writeln('File ' + chalk.cyan(f.dest) + ' created.');
      }
    });

    grunt.log.ok(filesCount + ' ' + grunt.util.pluralize(filesCount, 'file/files') + ' created.');

  });

};
<commit_msg>add extractGlobalNamespace to fix #108<commit_after>/*
 * grunt-contrib-handlebars
 * http://gruntjs.com/
 *
 * Copyright (c) 2014 Tim Branyen, contributors
 * Licensed under the MIT license.
 */

'use strict';
var chalk = require('chalk');
var nsdeclare = require('nsdeclare');

module.exports = function(grunt) {
  var _ = grunt.util._;

  // content conversion for templates
  var defaultProcessContent = function(content) { return content; };

  // AST processing for templates
  var defaultProcessAST = function(ast) { return ast; };

  // filename conversion for templates
  var defaultProcessName = function(name) { return name; };

  // filename conversion for partials
  var defaultProcessPartialName = function(filepath) {
    var pieces = _.last(filepath.split('/')).split('.');
    var name   = _(pieces).without(_.last(pieces)).join('.'); // strips file extension
    if (name.charAt(0) === '_') {
      name = name.substr(1, name.length); // strips leading _ character
    }
    return name;
  };

  var extractGlobalNamespace = function(nsDeclarations) {
    // Extract global namespace from any existing namespace declaration.
    // The purpose of this method is too fix an issue with AMD when using namespace as a function where the
    // nsInfo.namespace will contains the last namespace, not the global namespace.

    var declarations = _.keys(nsDeclarations);

    // no declaration found
    if (!declarations.length) {
      return '';
    }

    // In case only one namespace has been declared it will only return it.
    if (declarations.length === 1) {
      return declarations[0];
    }
    else {
      // we only need to take any declaration to extract the global namespace.
      // Another option might be find the shortest declaration which is the global one.
      var matches = declarations[0].match(/(this\[[^\[]+\])/g);
      return matches[0];
    }
  };

  grunt.registerMultiTask('handlebars', 'Compile handlebars templates and partials.', function() {
    var options = this.options({
      namespace: 'JST',
      separator: grunt.util.linefeed + grunt.util.linefeed,
      wrapped: true,
      amd: false,
      commonjs: false,
      knownHelpers: [],
      knownHelpersOnly: false
    });

    // assign regex for partials directory detection
    var partialsPathRegex = options.partialsPathRegex || /./;

    // assign regex for partial detection
    var isPartialRegex = options.partialRegex || /^_/;

    // assign transformation functions
    var processContent = options.processContent || defaultProcessContent;
    var processName = options.processName || defaultProcessName;
    var processPartialName = options.processPartialName || defaultProcessPartialName;
    var processAST = options.processAST || defaultProcessAST;
    var useNamespace = options.namespace !== false;

    // assign compiler options
    var compilerOptions = options.compilerOptions || {};
    var filesCount = 0;

    this.files.forEach(function(f) {
      var partials = [];
      var templates = [];

      // Namespace info for current template
      var nsInfo;

      // Map of already declared namespace parts
      var nsDeclarations = {};

      // nsdeclare options when fetching namespace info
      var nsDeclareOptions = {response: 'details', declared: nsDeclarations};

      // Just get the namespace info for a given template
      var getNamespaceInfo = _.memoize(function(filepath) {
        if (!useNamespace) {return undefined;}
        if (_.isFunction(options.namespace)) {
          return nsdeclare(options.namespace(filepath), nsDeclareOptions);
        } else {
          return nsdeclare(options.namespace, nsDeclareOptions);
        }
      });

      // iterate files, processing partials and templates separately
      f.src.filter(function(filepath) {
        // Warn on and remove invalid source files (if nonull was set).
        if (!grunt.file.exists(filepath)) {
          grunt.log.warn('Source file "' + filepath + '" not found.');
          return false;
        } else {
          return true;
        }
      })
      .forEach(function(filepath) {
        var src = processContent(grunt.file.read(filepath), filepath);

        var Handlebars = require('handlebars');
        var ast, compiled, filename;
        try {
          // parse the handlebars template into it's AST
          ast = processAST(Handlebars.parse(src));
          compiled = Handlebars.precompile(ast, compilerOptions);

          // if configured to, wrap template in Handlebars.template call
          if (options.wrapped === true) {
            compiled = 'Handlebars.template(' + compiled + ')';
          }
        } catch (e) {
          grunt.log.error(e);
          grunt.fail.warn('Handlebars failed to compile ' + filepath + '.');
        }

        // register partial or add template to namespace
        if (partialsPathRegex.test(filepath) && isPartialRegex.test(_.last(filepath.split('/')))) {
          filename = processPartialName(filepath);
          if (options.partialsUseNamespace === true) {
            nsInfo = getNamespaceInfo(filepath);

            partials.push(nsInfo.declaration);
            partials.push('Handlebars.registerPartial(' + JSON.stringify(filename) + ', ' + nsInfo.namespace +
              '[' + JSON.stringify(filename) + '] = ' + compiled + ');');
          } else {
            partials.push('Handlebars.registerPartial(' + JSON.stringify(filename) + ', ' + compiled + ');');
          }
        } else {
          nsInfo = getNamespaceInfo(filepath);

          if (options.amd && !useNamespace) {
            compiled = 'return ' + compiled;
          }
          filename = processName(filepath);
          if (useNamespace) {
            templates.push(nsInfo.declaration);
            templates.push(nsInfo.namespace + '[' + JSON.stringify(filename) + '] = ' + compiled + ';');
          } else if (options.commonjs === true) {
            templates.push('templates[' + JSON.stringify(filename) + '] = ' + compiled + ';');
          } else {
            templates.push(compiled);
          }
        }
      });

      var output = partials.concat(templates);
      if (output.length < 1) {
        grunt.log.warn('Destination not written because compiled files were empty.');
      } else {
        if (useNamespace) {
          if (options.node) {
            output.unshift('Handlebars = glob.Handlebars || require(\'handlebars\');');
            output.unshift('var glob = (\'undefined\' === typeof window) ? global : window,');

            var nodeExport = 'if (typeof exports === \'object\' && exports) {';
            nodeExport += 'module.exports = ' + nsInfo.namespace + ';}';

            output.push(nodeExport);
          }

        }

        if (options.amd) {
          // Wrap the file in an AMD define fn.
          if (typeof options.amd === 'boolean') {
            output.unshift('define([\'handlebars\'], function(Handlebars) {');
          } else if (typeof options.amd === 'string') {
            output.unshift('define([\'' + options.amd + '\'], function(Handlebars) {');
          } else if (Array.isArray(options.amd)) {
            // convert options.amd to a string of dependencies for require([...])
            var amdString = '';
            for (var i = 0; i < options.amd.length; i++) {
              if (i !== 0) {
                amdString += ', ';
              }

              amdString += '\'' + options.amd[i] + '\'';
            }

            // Wrap the file in an AMD define fn.
            output.unshift('define([' + amdString + '], function(Handlebars) {');
          }

          if (useNamespace) {
            // Namespace has not been explicitly set to false; the AMD
            // wrapper will return the object containing the template.
            output.push('return ' + extractGlobalNamespace(nsDeclarations) + ';');
          }
          output.push('});');
        }

        if (options.commonjs) {
          if (useNamespace) {
            output.push('return ' + nsInfo.namespace + ';');
          } else {
            output.unshift('var templates = {};');
            output.push('return templates;');
          }
          // Export the templates object for CommonJS environments.
          output.unshift('module.exports = function(Handlebars) {');
          output.push('};');
        }

        filesCount++;
        grunt.file.write(f.dest, output.join(grunt.util.normalizelf(options.separator)));
        grunt.verbose.writeln('File ' + chalk.cyan(f.dest) + ' created.');
      }
    });

    grunt.log.ok(filesCount + ' ' + grunt.util.pluralize(filesCount, 'file/files') + ' created.');

  });

};
<|endoftext|>


<commit_before>// @flow

import type { Config } from './Config';

import Telegraf from 'telegraf';

import appConfig from '../../../app-config';
import bus from '../../bus';
import botNetwork from './network';

const config: Config = appConfig.telegram;

const chat = config[process.env.NODE_ENV === 'prod' ? 'prod' : 'dev'];

const { BOT_TOKEN } = config;

const client: Telegraf = new Telegraf(BOT_TOKEN);

class Name {
  static from(msg) {
    if (msg.username) {
      return msg.username;
    }

    if (msg.last_name) {
      return `${msg.first_name} ${msg.last_name}`;
    }

    return msg.first_name;
  }
}

class Message {
  constructor(msg) {
    this.msg = msg;
  }

  toString() {
    return this.msg.text;
  }
}

class ReplyToMessage extends Message {
  static test(msg) {
    const replyToMessage = msg.reply_to_message;
    const isReplyWithText = replyToMessage && replyToMessage.text;
    return isReplyWithText;
  }

  getDetails() {
    const msg = this.msg;
    const replyToMessage = msg.reply_to_message;
    const nick = Name.from(replyToMessage.from);
    const message = replyToMessage.text;

    return [nick, message];
  }

  toString() {
    const msg = this.msg;
    let [nick, message] = this.getDetails();

    // adds quoting brackets
    message = message.replace(/\n/g, '\n>> ');

    return `>> <${nick}> ${message}\n${msg.text}`;
  }
}

class ForwardedMessage extends Message {
  static test(msg) {
    return msg.forward_from;
  }

  toString() {
    const msg = this.msg;
    const nick = Name.from(msg.forward_from);

    // adds quoting brackets
    const message = msg.text.replace(/\n/g, '\n>> ');

    return `>> <${nick}> ${message}`;
  }
}

class BotMessage extends ReplyToMessage {
  static test(msg) {
    const replyToMessage = msg.reply_to_message;

    const isReplyWithText = replyToMessage && replyToMessage.text;
    if (!isReplyWithText) {
      return false;
    }

    const isReplyFromOurBot = BOT_TOKEN.indexOf(replyToMessage.from.id) > -1;

    return isReplyFromOurBot;
  }

  getDetails() {
    const msg = this.msg;
    const replyToMessage = msg.reply_to_message;
    const text = replyToMessage.text;
    const lineEndPos = text.indexOf('\n');
    const _nick = text.slice(0, lineEndPos);
    const _message = text.slice(lineEndPos + 1);
    return [_nick, _message];
  }
}

function messageFactory(msg) {
  if (ForwardedMessage.test(msg)) {
    return new ForwardedMessage(msg);
  }

  if (!ReplyToMessage.test(msg)) {
    return new Message(msg);
  }

  if (BotMessage.test(msg)) {
    return new BotMessage(msg);
  }

  return new ReplyToMessage(msg);
}

function prepareMessage(msg) {
  const message = messageFactory(msg);
  const stringMessage = message.toString();

  return stringMessage;
}

function prepareEmittingMessageDetails(message) {
  const room = message.chat.title;
  if (room !== chat.title) {
    return null;
  }

  const name = Name.from(message.from);
  const msg = prepareMessage(message);

  return {network: botNetwork, room, name, message: msg};
}

client.on('text', (ctx, next) => {
  const msg = prepareEmittingMessageDetails(ctx.message);
  if (msg) {
    bus.emit('message', msg);
    next();
  }
});

client.on('sticker', (ctx, next) => {
  const msg = prepareEmittingMessageDetails(ctx.message);
  if (msg) {
    const sticker = ctx.message.sticker;
    const emoji = sticker.emoji;
    msg.message = emoji || msg.message;
    bus.emit('message', msg);
    next();
  }
});

client.startPolling();

export default client;
<commit_msg>Add User type<commit_after>// @flow

import type { Config } from './Config';

import Telegraf from 'telegraf';

import appConfig from '../../../app-config';
import bus from '../../bus';
import botNetwork from './network';

const config: Config = appConfig.telegram;

const chat = config[process.env.NODE_ENV === 'prod' ? 'prod' : 'dev'];

const { BOT_TOKEN } = config;

const client: Telegraf = new Telegraf(BOT_TOKEN);

type User = {
  id: number,
  is_bot: boolean,
  first_name: string,
  last_name?: string,
  username?: string,
  language_code?: string
}

class Name {
  static from(user: User) {
    if (user.username) {
      return user.username;
    }

    if (user.last_name) {
      return `${user.first_name} ${user.last_name}`;
    }

    return user.first_name;
  }
}

class Message {
  msg: Object;

  constructor(msg: Object) {
    this.msg = msg;
  }

  toString() {
    return this.msg.text || '';
  }
}

class ReplyToMessage extends Message {
  static test(msg) {
    const replyToMessage = msg.reply_to_message;
    const isReplyWithText = replyToMessage && replyToMessage.text;
    return isReplyWithText;
  }

  getDetails() {
    const msg = this.msg;
    const replyToMessage = msg.reply_to_message;
    const nick = Name.from(replyToMessage.from);
    const message = replyToMessage.text;

    return [nick, message];
  }

  toString() {
    const msg = this.msg;
    let [nick, message] = this.getDetails();

    // adds quoting brackets
    message = message.replace(/\n/g, '\n>> ');

    return `>> <${nick}> ${message}\n${msg.text}`;
  }
}

class ForwardedMessage extends Message {
  static test(msg) {
    return msg.forward_from;
  }

  toString() {
    const msg = this.msg;
    const nick = Name.from(msg.forward_from);

    // adds quoting brackets
    const message = msg.text.replace(/\n/g, '\n>> ');

    return `>> <${nick}> ${message}`;
  }
}

class BotMessage extends ReplyToMessage {
  static test(msg) {
    const replyToMessage = msg.reply_to_message;

    const isReplyWithText = replyToMessage && replyToMessage.text;
    if (!isReplyWithText) {
      return false;
    }

    const isReplyFromOurBot = BOT_TOKEN.indexOf(replyToMessage.from.id) > -1;

    return isReplyFromOurBot;
  }

  getDetails() {
    const msg = this.msg;
    const replyToMessage = msg.reply_to_message;
    const text = replyToMessage.text;
    const lineEndPos = text.indexOf('\n');
    const _nick = text.slice(0, lineEndPos);
    const _message = text.slice(lineEndPos + 1);
    return [_nick, _message];
  }
}

function messageFactory(msg) {
  if (ForwardedMessage.test(msg)) {
    return new ForwardedMessage(msg);
  }

  if (!ReplyToMessage.test(msg)) {
    return new Message(msg);
  }

  if (BotMessage.test(msg)) {
    return new BotMessage(msg);
  }

  return new ReplyToMessage(msg);
}

function prepareMessage(msg) {
  const message = messageFactory(msg);
  const stringMessage = message.toString();

  return stringMessage;
}

function prepareEmittingMessageDetails(message) {
  const room = message.chat.title;
  if (room !== chat.title) {
    return null;
  }

  const name = Name.from(message.from);
  const msg = prepareMessage(message);

  return {network: botNetwork, room, name, message: msg};
}

client.on('text', (ctx, next) => {
  const msg = prepareEmittingMessageDetails(ctx.message);
  if (msg) {
    bus.emit('message', msg);
    next();
  }
});

client.on('sticker', (ctx, next) => {
  const msg = prepareEmittingMessageDetails(ctx.message);
  if (msg) {
    const sticker = ctx.message.sticker;
    const emoji = sticker.emoji;
    msg.message = emoji || msg.message;
    bus.emit('message', msg);
    next();
  }
});

client.startPolling();

export default client;
<|endoftext|>