<commit_before>/*

    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
      This file is part of the Smart Developer Hub Project:
        http://www.smartdeveloperhub.org/
      Center for Open Middleware
            http://www.centeropenmiddleware.com/
    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
      Copyright (C) 2015 Center for Open Middleware.
    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
      Licensed under the Apache License, Version 2.0 (the "License");
      you may not use this file except in compliance with the License.
      You may obtain a copy of the License at
                http://www.apache.org/licenses/LICENSE-2.0
      Unless required by applicable law or agreed to in writing, software
      distributed under the License is distributed on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      See the License for the specific language governing permissions and
     limitations under the License.
    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
*/

'use strict';

/* PRIVATE */
    var helpme = function helpme(clientId, msg, callback) {
        var data = [];
        for (var pat in corePatterns) {
            data.push(
                {
                    title: pat,
                    text: corePatterns[pat].description,
                    'thumb': "https://pixabay.com/static/uploads/photo/2013/07/12/18/09/help-153094_960_720.png",
                    'link': "http://botEndpointOrSomethingSimilar/api/resource/elelele"
                }
            );
        }
        callback ({
            'title': "Help Information",
            'description': "This is the core bot basic methods help information",
            'data': data
        });
    };
    var metric = function metric(clientId, msg, callback) {
        // TODO extract metric id, subjects and range information from msg to generate metric options
        callback ("metric data");
    };
    var getMetricsAbout = function getMetricsAbout(clientId, msg, callback) {
        log.info("metric abut query ---> " + msg.text);
        var tags = msg.text.toLowerCase().split(' ');
        var auxTags = [];
        for (var d = 0; d < tags.length; d ++) {
            if (tags[d] !== "" && tags[d] !== "metrics" && tags[d] !== "give" && tags[d] !== "me" && tags[d] !== "about") {
                auxTags.push(tags[d]);
            }
        }
        tags = auxTags;
        var parsedElements = [];
        internalSDHtools.getSDHMetrics(function(allmet) {
            for (var i = 0; i < allmet.length; i++) {
                var metric = allmet[i];
                var refAtt = metric.title.toLowerCase(); // Views have not titles
                if (tags.length == 0) {
                    // All
                    parsedElements.push(refAtt);
                } else {
                    // Tag filter
                    var match = false;
                    for (var j = 0; j < tags.length; j++) {
                        if (refAtt.indexOf(tags[j]) == -1) {
                            match = false;
                            break;
                        } else {
                            match = true;
                        }
                    }
                    if (match) {
                        parsedElements.push(metric);
                    }
                }

            };
            callback(parsedElements);
        });
    };

    var view = function view(clientId, msg, callback) {
        // TODO extract metric id, subjects and range information from msg to generate view options
        callback ("view data");
    };
    var org = function org(clientId, msg, callback) {
        // Not implemented in sdh-api, only 1 organization
        internalSDHtools.getSDHOrganizations(callback);
    };
    var product = function product(clientId, msg, callback) {
        log.info("product info ---> " + msg.text);
        var prodList = getProductFromMsg(msg);
        log.debug(prodList);
        var pj = [];
        for (var i = 0; i < prodList.length; i++) {
            pj.push(sdhProductsByID[prodList[i]]);
        }
        var data = {
            'title': "Product Information",
            'description': "This is the core bot get product/s information",
            'data': pj
        }
        callback (data);
    };

// Product Aux methods
    var getProductFromMsg = function getProductFromMsg(msg) {
        var tags = msg.text.toLowerCase().split(' ');
        var origTagsAux = msg.text.split(' ');
        var origTags = [];
        var auxTags = [];
        var customTag = "";
        for (var d = 0; d < tags.length; d++) {
            if (tags[d] !== "" && tags[d] !== "product" && tags[d] !== "producto" && tags[d].indexOf(botId.toLowerCase()) == -1) {
                auxTags.push(tags[d]);
                origTags.push(origTagsAux[d]);
                if (customTag.length > 0) {customTag += " ";}
                customTag += tags[d];
            } else {
                if (customTag.length > 0) {
                    auxTags.push(customTag);
                }
                customTag = "";
            }
        }
        if (customTag.length > 0) {
            auxTags.push(customTag);
        }
        tags = auxTags;
        log.debug(tags);
        var data = [];
        for (var d = 0; d < tags.length; d++) {
            if (origTags[d] in sdhProductsByID) {
                data.push(origTags[d]);
            } else if (origTags[d] in sdhProductsByName){
                data.push(sdhProductsByName[origTags[d]].productid);
            }
        }
        return data;
    };

    var project = function project(clientId, msg, callback) {
        log.info("project info ---> " + msg.text);
        var projList = getProjectFromMsg(msg);
        log.debug(projList);
        var pj = [];
        for (var i = 0; i < projList.length; i++) {
            pj.push(sdhProjectsByID[projList[i]]);
        }
        var data = {
            'title': "Project Information",
            'description': "This is the core bot get project/s information",
            'data': pj
        }
        callback (data);
    };

// Project Aux methods
    var getProjectFromMsg = function getProjectFromMsg(msg) {
        var tags = msg.text.toLowerCase().split(' ');
        var origTagsAux = msg.text.split(' ');
        var origTags = [];
        var auxTags = [];
        var customTag = "";
        for (var d = 0; d < tags.length; d++) {
            if (tags[d] !== "" && tags[d] !== "project" && tags[d] !== "proyecto" && tags[d].indexOf(botId.toLowerCase()) == -1) {
                auxTags.push(tags[d]);
                origTags.push(origTagsAux[d]);
                if (customTag.length > 0) {customTag += " ";}
                customTag += tags[d];
            } else {
                if (customTag.length > 0) {
                    auxTags.push(customTag);
                }
                customTag = "";
            }
        }
        if (customTag.length > 0) {
            auxTags.push(customTag);
        }
        tags = auxTags;
        log.debug(tags);
        var data = [];
        for (var d = 0; d < tags.length; d++) {
            if (origTags[d] in sdhProjectsByID) {
                data.push(origTags[d]);
            } else if (origTags[d] in sdhProjectsByName){
                data.push(sdhProjectsByName[origTags[d]].projectid);
            }
        }
        return data;
    };

    var repo = function repo(clientId, msg, callback) {
        log.info("repo info ---> " + msg.text);
        var repoList = getRepoFromMsg(msg);
        log.debug(repoList);
        var rp = [];
        for (var i = 0; i < repoList.length; i++) {
            rp.push(sdhReposByID[repoList[i]]);
        }
        var data = {
            'title': "Repository Information",
            'description': "This is the core bot get rpository/ies information",
            'data': rp
        }
        callback (data);
    };

// Repos Aux methods
    var getRepoFromMsg = function getRepoFromMsg(msg) {
        var tags = msg.text.toLowerCase().split(' ');
        var origTagsAux = msg.text.split(' ');
        var origTags = [];
        var auxTags = [];
        var customTag = "";
        for (var d = 0; d < tags.length; d++) {
            if (tags[d] !== "" && tags[d] !== "repository" && tags[d] !== "repositorio" && tags[d] !== "repo" && tags[d].indexOf(botId.toLowerCase()) == -1) {
                auxTags.push(tags[d]);
                origTags.push(origTagsAux[d]);
                if (customTag.length > 0) {customTag += " ";}
                customTag += tags[d];
            } else {
                if (customTag.length > 0) {
                    auxTags.push(customTag);
                }
                customTag = "";
            }
        }
        if (customTag.length > 0) {
            auxTags.push(customTag);
        }
        tags = auxTags;
        log.debug(tags);
        var repo = [];
        for (var d = 0; d < tags.length; d++) {
            if (origTags[d] in sdhReposByID) {
                repo.push(origTags[d]);
            } else if (origTags[d] in sdhReposByName){
                repo.push(sdhReposByName[origTags[d]].repositoryid);
            }
        }
        return repo;
    };

// Members aux methods
    var getUsersFromMsg = function getUsersFromMsg(msg) {
        var tags = msg.text.toLowerCase().split(' ');
        var origTagsAux = msg.text.split(' ');
        var origTags = [];
        var auxTags = [];
        var customTag = "";
        for (var d = 0; d < tags.length; d++) {
            if (tags[d] !== "" && tags[d] !== "user" && tags[d] !== "miembro" && tags[d] !== "member" && tags[d] !== "usuario" && tags[d].indexOf(botId.toLowerCase()) == -1) {
                auxTags.push(tags[d]);
                origTags.push(origTagsAux[d]);
                if (customTag.length > 0) {customTag += " ";}
                customTag += tags[d];
            } else {
                if (customTag.length > 0) {
                    auxTags.push(customTag);
                }
                customTag = "";
            }
        }
        if (customTag.length > 0) {
            auxTags.push(customTag);
        }
        tags = auxTags;
        log.debug(tags);
        var userList = [];
        for (var d = 0; d < tags.length; d++) {
            if (origTags[d] in clientUserInfo) {
                userList.push(clientUserInfo[origTags[d]]);
            } else {
                for (var key in clientUserInfo) {
                    if (key.indexOf("<@") > -1 && key.indexOf(">") > -1 && key.indexOf(origTags[d]) > -1) {
                        userList.push(clientUserInfo[key]);
                    }
                }
            }
        }
        return userList;
    };

    var member = function member(clientId, msg, callback) {
        log.info("member info ---> " + msg.text);
        var userList = getUsersFromMsg(msg);
        log.debug(userList);
        var us = [];
        for (var i = 0; i < userList.length; i++) {
            us.push(sdhUsersByID[userList[i]]);
        }
        var data = {
            'title': "User Information",
            'description': "This is the core bot get member/s information",
            'data': us
        }
        callback (data);
    };
    var allMetrics = function allMetrics(clientId, msg, callback) {
        internalSDHtools.getSDHMetrics(callback);
    };
    var allViews = function allViews(clientId, msg, callback) {
        internalSDHtools.getSDHViews(callback);
    };
    var allOrgs = function allOrgs(clientId, msg, callback) {
        internalSDHtools.getSDHOrganizations(callback);
    };
    var allProducts = function allProducts(clientId, msg, callback) {
        internalSDHtools.getSDHProducts(callback);
    };
    var allProjects = function allProjects(clientId, msg, callback) {
        internalSDHtools.getSDHProjects(callback);
    };
    var allRepos = function allRepos(clientId, msg, callback) {
        internalSDHtools.getSDHRepositories(callback);
    };
    var allMembers = function allMembers(clientId, msg, callback) {
        internalSDHtools.getSDHMembers(callback);
    };

/* PUBLIC */
    var corePatterns = {
        '/help|ayuda/':{
            'callback': helpme,
            'description': "Return core bot help information"
        },
        '/all metrics|todas las metricas/':{
            'callback': allMetrics,
            'description': "Return complete SDH metrics list"
        },
        '/all views|all tbds|all time based data|todas las vistas/':{
            'callback': allViews,
            'description': "Return complete SDH views list"
        },
        '/all organizations|todas las organizaciones/':{
            'callback': allOrgs,
            'description': "Return complete SDH organizations list"
        },
        '/all products|todos los productos/':{
            'callback': allProducts,
            'description': "Return complete SDH projects list"
        },
        '/all projects|todos los proyectos/':{
            'callback': allProjects,
            'description': "Return complete SDH projects list"
        },
        '/all users|todos los usuarios|all members|todos los miembros/':{
            'callback': allMembers,
            'description': "Return complete SDH products list"
        },
        '/all repositories|todos los repositorios/':{
            'callback': allRepos,
            'description': "Return complete SDH products list"
        },
        '/organization|organizacion/':{
            'callback': org,
            'description': "Return a SDH organization"
        },
        '/product|producto/':{
            'callback': product,
            'description': "Return a SDH product"
        },
        '/project|proyecto/':{
            'callback': project,
            'description': "Return a SDH project"
        },
        '/user|usuario|member|miembro/':{
            'callback': member,
            'description': "Return a SDH member"
        },
        '/repository|repositorio/repo':{
            'callback': repo,
            'description': "Return a SDH repository"
        },
        '/metric|metrica|métrica/':{
            'callback': metric,
            'description': "Return SDH metric data"
        },
        '/view|tbd|time based data':{
            'callback': view,
            'description': "Return SDH view data"
        }
    };
    module.exports.phInfo = corePatterns;<commit_msg>Add new patterns<commit_after>/*

    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
      This file is part of the Smart Developer Hub Project:
        http://www.smartdeveloperhub.org/
      Center for Open Middleware
            http://www.centeropenmiddleware.com/
    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
      Copyright (C) 2015 Center for Open Middleware.
    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
      Licensed under the Apache License, Version 2.0 (the "License");
      you may not use this file except in compliance with the License.
      You may obtain a copy of the License at
                http://www.apache.org/licenses/LICENSE-2.0
      Unless required by applicable law or agreed to in writing, software
      distributed under the License is distributed on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      See the License for the specific language governing permissions and
     limitations under the License.
    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
*/

'use strict';

/* PRIVATE */
    var helpme = function helpme(clientId, msg, callback) {
        var data = [];
        for (var pat in corePatterns) {
            data.push(
                {
                    title: pat,
                    text: corePatterns[pat].description,
                    'thumb': "https://pixabay.com/static/uploads/photo/2013/07/12/18/09/help-153094_960_720.png",
                    'link': "http://botEndpointOrSomethingSimilar/api/resource/elelele"
                }
            );
        }
        callback ({
            'title': "Help Information",
            'description': "This is the core bot basic methods help information",
            'data': data
        });
    };
    var metric = function metric(clientId, msg, callback) {
        // TODO extract metric id, subjects and range information from msg to generate metric options
        callback ("metric data");
    };
    var getMetricsAbout = function getMetricsAbout(clientId, msg, callback) {
        log.info("metric abut query ---> " + msg.text);
        var tags = msg.text.toLowerCase().split(' ');
        var auxTags = [];
        for (var d = 0; d < tags.length; d ++) {
            if (tags[d] !== "" && tags[d] !== "metrics" && tags[d] !== "give" && tags[d] !== "me" && tags[d] !== "about") {
                auxTags.push(tags[d]);
            }
        }
        tags = auxTags;
        var parsedElements = [];
        internalSDHtools.getSDHMetrics(function(allmet) {
            for (var i = 0; i < allmet.length; i++) {
                var metric = allmet[i];
                var refAtt = metric.title.toLowerCase(); // Views have not titles
                if (tags.length == 0) {
                    // All
                    parsedElements.push(refAtt);
                } else {
                    // Tag filter
                    var match = false;
                    for (var j = 0; j < tags.length; j++) {
                        if (refAtt.indexOf(tags[j]) == -1) {
                            match = false;
                            break;
                        } else {
                            match = true;
                        }
                    }
                    if (match) {
                        parsedElements.push(metric);
                    }
                }

            };
            callback(parsedElements);
        });
    };

    var view = function view(clientId, msg, callback) {
        // TODO extract metric id, subjects and range information from msg to generate view options
        callback ("view data");
    };
    var org = function org(clientId, msg, callback) {
        // Not implemented in sdh-api, only 1 organization
        internalSDHtools.getSDHOrganizations(callback);
    };
    var product = function product(clientId, msg, callback) {
        log.info("product info ---> " + msg.text);
        var prodList = getProductFromMsg(msg);
        log.debug(prodList);
        var pj = [];
        for (var i = 0; i < prodList.length; i++) {
            pj.push(sdhProductsByID[prodList[i]]);
        }
        var data = {
            'title': "Product Information",
            'description': "This is the core bot get product/s information",
            'data': pj
        }
        callback (data);
    };

// Product Aux methods
    var getProductFromMsg = function getProductFromMsg(msg) {
        var tags = msg.text.toLowerCase().split(' ');
        var origTagsAux = msg.text.split(' ');
        var origTags = [];
        var auxTags = [];
        var customTag = "";
        for (var d = 0; d < tags.length; d++) {
            if (tags[d] !== "" && tags[d] !== "product" && tags[d] !== "producto" && tags[d].indexOf(botId.toLowerCase()) == -1) {
                auxTags.push(tags[d]);
                origTags.push(origTagsAux[d]);
                if (customTag.length > 0) {customTag += " ";}
                customTag += tags[d];
            } else {
                if (customTag.length > 0) {
                    auxTags.push(customTag);
                }
                customTag = "";
            }
        }
        if (customTag.length > 0) {
            auxTags.push(customTag);
        }
        tags = auxTags;
        log.debug(tags);
        var data = [];
        for (var d = 0; d < tags.length; d++) {
            if (origTags[d] in sdhProductsByID) {
                data.push(origTags[d]);
            } else if (origTags[d] in sdhProductsByName){
                data.push(sdhProductsByName[origTags[d]].productid);
            }
        }
        return data;
    };

    var project = function project(clientId, msg, callback) {
        log.info("project info ---> " + msg.text);
        var projList = getProjectFromMsg(msg);
        log.debug(projList);
        var pj = [];
        for (var i = 0; i < projList.length; i++) {
            pj.push(sdhProjectsByID[projList[i]]);
        }
        var data = {
            'title': "Project Information",
            'description': "This is the core bot get project/s information",
            'data': pj
        }
        callback (data);
    };

// Project Aux methods
    var getProjectFromMsg = function getProjectFromMsg(msg) {
        var tags = msg.text.toLowerCase().split(' ');
        var origTagsAux = msg.text.split(' ');
        var origTags = [];
        var auxTags = [];
        var customTag = "";
        for (var d = 0; d < tags.length; d++) {
            if (tags[d] !== "" && tags[d] !== "project" && tags[d] !== "proyecto" && tags[d].indexOf(botId.toLowerCase()) == -1) {
                auxTags.push(tags[d]);
                origTags.push(origTagsAux[d]);
                if (customTag.length > 0) {customTag += " ";}
                customTag += tags[d];
            } else {
                if (customTag.length > 0) {
                    auxTags.push(customTag);
                }
                customTag = "";
            }
        }
        if (customTag.length > 0) {
            auxTags.push(customTag);
        }
        tags = auxTags;
        log.debug(tags);
        var data = [];
        for (var d = 0; d < tags.length; d++) {
            if (origTags[d] in sdhProjectsByID) {
                data.push(origTags[d]);
            } else if (origTags[d] in sdhProjectsByName){
                data.push(sdhProjectsByName[origTags[d]].projectid);
            }
        }
        return data;
    };

    var repo = function repo(clientId, msg, callback) {
        log.info("repo info ---> " + msg.text);
        var repoList = getRepoFromMsg(msg);
        log.debug(repoList);
        var rp = [];
        for (var i = 0; i < repoList.length; i++) {
            rp.push(sdhReposByID[repoList[i]]);
        }
        var data = {
            'title': "Repository Information",
            'description': "This is the core bot get rpository/ies information",
            'data': rp
        }
        callback (data);
    };

// Repos Aux methods
    var getRepoFromMsg = function getRepoFromMsg(msg) {
        var tags = msg.text.toLowerCase().split(' ');
        var origTagsAux = msg.text.split(' ');
        var origTags = [];
        var auxTags = [];
        var customTag = "";
        for (var d = 0; d < tags.length; d++) {
            if (tags[d] !== "" && tags[d] !== "repository" && tags[d] !== "repositorio" && tags[d] !== "repo" && tags[d].indexOf(botId.toLowerCase()) == -1) {
                auxTags.push(tags[d]);
                origTags.push(origTagsAux[d]);
                if (customTag.length > 0) {customTag += " ";}
                customTag += tags[d];
            } else {
                if (customTag.length > 0) {
                    auxTags.push(customTag);
                }
                customTag = "";
            }
        }
        if (customTag.length > 0) {
            auxTags.push(customTag);
        }
        tags = auxTags;
        log.debug(tags);
        var repo = [];
        for (var d = 0; d < tags.length; d++) {
            if (origTags[d] in sdhReposByID) {
                repo.push(origTags[d]);
            } else if (origTags[d] in sdhReposByName){
                repo.push(sdhReposByName[origTags[d]].repositoryid);
            }
        }
        return repo;
    };

// Members aux methods
    var getUsersFromMsg = function getUsersFromMsg(msg) {
        var tags = msg.text.toLowerCase().split(' ');
        var origTagsAux = msg.text.split(' ');
        var origTags = [];
        var auxTags = [];
        var customTag = "";
        for (var d = 0; d < tags.length; d++) {
            if (tags[d] !== "" && tags[d] !== "user" && tags[d] !== "miembro" && tags[d] !== "member" && tags[d] !== "usuario" && tags[d].indexOf(botId.toLowerCase()) == -1) {
                auxTags.push(tags[d]);
                origTags.push(origTagsAux[d]);
                if (customTag.length > 0) {customTag += " ";}
                customTag += tags[d];
            } else {
                if (customTag.length > 0) {
                    auxTags.push(customTag);
                }
                customTag = "";
            }
        }
        if (customTag.length > 0) {
            auxTags.push(customTag);
        }
        tags = auxTags;
        log.debug(tags);
        var userList = [];
        for (var d = 0; d < tags.length; d++) {
            if (origTags[d] in clientUserInfo) {
                userList.push(clientUserInfo[origTags[d]]);
            } else {
                for (var key in clientUserInfo) {
                    if (key.indexOf("<@") > -1 && key.indexOf(">") > -1 && key.indexOf(origTags[d]) > -1) {
                        userList.push(clientUserInfo[key]);
                    }
                }
            }
        }
        return userList;
    };

    var member = function member(clientId, msg, callback) {
        log.info("member info ---> " + msg.text);
        var userList = getUsersFromMsg(msg);
        log.debug(userList);
        var us = [];
        for (var i = 0; i < userList.length; i++) {
            us.push(sdhUsersByID[userList[i]]);
        }
        var data = {
            'title': "User Information",
            'description': "This is the core bot get member/s information",
            'data': us
        }
        callback (data);
    };
    var allMetrics = function allMetrics(clientId, msg, callback) {
        internalSDHtools.getSDHMetrics(callback);
    };
    var allViews = function allViews(clientId, msg, callback) {
        internalSDHtools.getSDHViews(callback);
    };
    var allOrgs = function allOrgs(clientId, msg, callback) {
        internalSDHtools.getSDHOrganizations(callback);
    };
    var allProducts = function allProducts(clientId, msg, callback) {
        internalSDHtools.getSDHProducts(callback);
    };
    var allProjects = function allProjects(clientId, msg, callback) {
        internalSDHtools.getSDHProjects(callback);
    };
    var allRepos = function allRepos(clientId, msg, callback) {
        internalSDHtools.getSDHRepositories(callback);
    };
    var allMembers = function allMembers(clientId, msg, callback) {
        internalSDHtools.getSDHMembers(callback);
    };
    var sdhParser = function sdhParser(clientId, msg, callback) {

        var origTagsAux = msg.text.split(' ');
        var origTags = [];
        for (var d = 0; d < origTagsAux.length; d++) {
            //TODO
            if (origTagsAux[d] !== "" && origTagsAux[d] !== "elastic" && origTagsAux[d].indexOf(botId.toLowerCase()) == -1) {
                origTags.push(origTagsAux[d]);
            }
        }
        /*elastic.getSuggestions(origTags).then(function (result) {
            log.info("--Result for: " + origTags);
            for (var i = 0; i < result.docsuggest[0].options.length; i++) {
                log.info("elasticSearch: '" + result.docsuggest[0].options[i].text + "' --score:" + result.docsuggest[0].options[i].score);
            }
        });*/
        elastic.search(msg.text, indexName).then(function (result) {
            log.info("-Simple E.S search for: " + msg.text);
            for (var i = 0; i < result.hits.hits.length; i++) {
                log.debug("hit " + i + ": '" + result.hits.hits[i]._source.title + "' ;score: " + result.hits.hits[i]._score);
            }
        });
    };

    var parseTags = function parseTags(msg) {
        var origTagsAux = msg.split(' ');
        var origTags = [];
        for (var d = 0; d < origTagsAux.length; d++) {
            //TODO
            if (origTagsAux[d] !== "") {
                origTags.push(origTagsAux[d]);
            }
        }
        return origTags;
    };

/* PUBLIC */
    var corePatterns = {
        '/help/':{
            'callback': helpme,
            'description': "Return core bot help information"
        },
        '/give me all metrics/':{
            'callback': allMetrics,
            'description': "Return complete SDH metrics list"
        },
        '/give me metrics about [\\s\\S]+/':{
            'callback': allMetrics,
            'description': "Return complete SDH metrics list"
        },
        '/give me [\\s\\S]+ metrics/':{
            'callback': getMetricsAbout,
            'description': "Return complete SDH metrics list"
        },
        '/give me all views/':{
            'callback': allViews,
            'description': "Return complete SDH views list"
        },
        '/give me all organizations/':{
            'callback': allOrgs,
            'description': "Return complete SDH organizations list"
        },
        '/give me all products/':{
            'callback': allProducts,
            'description': "Return complete SDH projects list"
        },
        '/give me all projects/':{
            'callback': allProjects,
            'description': "Return complete SDH projects list"
        },
        '/give me all users|give me all members/':{
            'callback': allMembers,
            'description': "Return complete SDH products list"
        },
        '/give me all repositories/':{
            'callback': allRepos,
            'description': "Return complete SDH products list"
        },
        /*'/give me [\\s\\S]+ information/':{
            'callback': allRepos,
            'description': "Return complete SDH products list"
        },*/
        '/give me [\\s\\S]+ product':{
            'callback': product,
            'description': "Return a SDH product"
        },
        '/give me [\\s\\S]+ project/':{
            'callback': project,
            'description': "Return a SDH project"
        },
        '/give me [\\s\\S]+ user|give me [\\s\\S]+ member/':{
            'callback': member,
            'description': "Return a SDH member"
        },
        '/give me [\\s\\S]+ repository|give me [\\s\\S]+ repo/':{
            'callback': repo,
            'description': "Return a SDH repository"
        },
        '/give me [\\s\\S]+ metric/':{
            'callback': metric,
            'description': "Return SDH metric data"
        },
        '/give me [\\s\\S]+ view/':{
            'callback': view,
            'description': "Return SDH view data"
        },
        //'/[a-zA-Z]+/':{
        /*'/[\\s\\S]/':{
            'callback': sdhParser,
            'description': "Return elastic matching info"
        }*/
    };
    module.exports.phInfo = corePatterns;<|endoftext|>


<commit_before>angular.module('events.timeline.controller', [
    'api.service',
    'events.events.filter',
    'events.topics.filter',
    'ui.router',
    'ngSanitize'
  ])
  .controller('TimelineController', [
    '$scope',
    '$http',
    '$location',
    '$state',
    '$stateParams',
    'lodash',
    'ApiService',
  function ($scope, $http, $location, $state, $stateParams, lodash, ApiService) {
    $scope.events = [];
    $scope.config = {};

    $scope.filter = { topics: [], searchText: '' };

    $scope.countries = [
      { name: 'Deutschland', slug: 'deutschland' },
      { name: 'United States', slug: 'united-states' }
    ];

    $scope.timeline = lodash.findWhere($scope.countries, {
      slug: $stateParams.timeline
    });

    $scope.loadConfig = function () {
      ApiService
        .getConfig()
        .then(function(response) {
          $scope.siteConfig = response;
          if ($stateParams.timeline === '') {
            $state.go('timeline', {
              timeline: $scope.siteConfig.default_timeline.slug
            });
          } else {
            $scope.loadEvents();
          }
        });
    };

    $scope.loadEvents = function () {
      ApiService
        .get($stateParams.timeline)
        .then(function(response){
          $scope.events = response;
        });
    };

    $scope.toggleTopicInFilter = function (topic) {
      var i = $scope.filter.topics.indexOf(topic);

      if (i > -1) {
          $scope.filter.topics.splice(i,1);
      } else {
        $scope.filter.topics.push(topic);
      }
    };

    $scope.resetTopicsFilter = function () {
      $scope.filter.topics = [];
    };

    $scope.switchCountry = function (slug) {
      $state.go('timeline', { timeline: slug });
    };

    $scope.openEvent = function (slug) {
      $state.go('timeline.event', { event: slug });
    };

    $scope.$watch('filter.topics', function () {
      if ($scope.filter.topics.length === 0) {
        $location.search('topics', null);
      } else {
        $location.search('topics', $scope.filter.topics.join(','));
      }
    }, true);

    $scope.$watch('filter.searchText', function () {
      if ($scope.filter.searchText === '') {
        $location.search('search', null);
      } else {
        $location.search('search', $scope.filter.searchText);
      }
    }, true);

    $scope.loadConfig();

  }]);
<commit_msg>Switch for the better function name<commit_after>angular.module('events.timeline.controller', [
    'api.service',
    'events.events.filter',
    'events.topics.filter',
    'ui.router',
    'ngSanitize'
  ])
  .controller('TimelineController', [
    '$scope',
    '$http',
    '$location',
    '$state',
    '$stateParams',
    'lodash',
    'ApiService',
  function ($scope, $http, $location, $state, $stateParams, lodash, ApiService) {
    $scope.events = [];
    $scope.config = {};

    $scope.filter = { topics: [], searchText: '' };

    $scope.countries = [
      { name: 'Deutschland', slug: 'deutschland' },
      { name: 'United States', slug: 'united-states' }
    ];

    $scope.timeline = lodash.findWhere($scope.countries, {
      slug: $stateParams.timeline
    });

    $scope.loadConfig = function () {
      ApiService
        .getConfig()
        .then(function(response) {
          $scope.siteConfig = response;
          if ($stateParams.timeline === '') {
            $state.go('timeline', {
              timeline: $scope.siteConfig.default_timeline.slug
            });
          } else {
            $scope.loadEvents();
          }
        });
    };

    $scope.loadEvents = function () {
      ApiService
        .getEvents($stateParams.timeline)
        .then(function(response){
          $scope.events = response;
        });
    };

    $scope.toggleTopicInFilter = function (topic) {
      var i = $scope.filter.topics.indexOf(topic);

      if (i > -1) {
          $scope.filter.topics.splice(i,1);
      } else {
        $scope.filter.topics.push(topic);
      }
    };

    $scope.resetTopicsFilter = function () {
      $scope.filter.topics = [];
    };

    $scope.switchCountry = function (slug) {
      $state.go('timeline', { timeline: slug });
    };

    $scope.openEvent = function (slug) {
      $state.go('timeline.event', { event: slug });
    };

    $scope.$watch('filter.topics', function () {
      if ($scope.filter.topics.length === 0) {
        $location.search('topics', null);
      } else {
        $location.search('topics', $scope.filter.topics.join(','));
      }
    }, true);

    $scope.$watch('filter.searchText', function () {
      if ($scope.filter.searchText === '') {
        $location.search('search', null);
      } else {
        $location.search('search', $scope.filter.searchText);
      }
    }, true);

    $scope.loadConfig();

  }]);
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { playEpisode } from 'app/actions/player';
import { Link } from 'react-router-dom'

import feedcastApi from 'feedcast-client'
import helpers from 'app/scripts/helpers'
import ReactDisqusComments from 'react-disqus-comments';

import 'app/styles/episode.sass'

const DISQUS_SHORTNAME = process.env.REACT_APP_DISQUS_SHORTNAME || 'default';

class Episode extends Component {
  constructor(props) {
    super(props);
    this.state = {
      published_at: '',
      description: '',
      summary: '',
      channel: {},
      audio : {},
      title: '',
      slug: '',
      uuid: '',
    }
  }

  componentDidMount() {
    const { slug, episode_slug} = this.props.match.params
    feedcastApi
      .getEpisode({slug, episode_slug})
      .then( data => {
        this.setState(data)
      })
      .catch( e => {
        console.log(e.message)
      })
  }

  handleNewComment(comment) {
    console.log(comment.text);
  }

  playEpisode(){
    this.props.dispatch(
      playEpisode(this.state, [])
    );
  }

  render() {
    const { slug, episode_slug} = this.props.match.params

    const {
      title,
      summary,
      description,
      channel,
    } = this.state

    const html = description && description.length > 0 ? description : (
      summary && summary.length > 0 ? summary : ''
    );
    console.log(description, summary)

    return (

          <div className="feedcast__episode-bg" style={{backgroundImage:`url(${channel.image_url})`}}>

          <div
            className="feedcast__episode-channel"
            style={{backgroundImage:`url(${channel.image_url})`}}>
            <button
              onClick={() => this.playEpisode()}
              className="feedcast__episode-button">

            </button>

{title}

              <Link to={`/${channel.slug}`} >{channel.title}</Link>

          <ReactDisqusComments
            shortname={DISQUS_SHORTNAME}
            identifier={`${slug}/${episode_slug}`}
            title={title}
            url={window.location.href}
            category_id={ channel.slug }
            onNewComment={this.handleNewComment}/>

    )
  }
}

export default connect()(Episode)
<commit_msg>fix: remove remaining console.log's #16<commit_after>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { playEpisode } from 'app/actions/player';
import { Link } from 'react-router-dom'

import feedcastApi from 'feedcast-client'
import helpers from 'app/scripts/helpers'
import ReactDisqusComments from 'react-disqus-comments';

import 'app/styles/episode.sass'

const DISQUS_SHORTNAME = process.env.REACT_APP_DISQUS_SHORTNAME || 'default';

class Episode extends Component {
  constructor(props) {
    super(props);
    this.state = {
      published_at: '',
      description: '',
      summary: '',
      channel: {},
      audio : {},
      title: '',
      slug: '',
      uuid: '',
    }
  }

  componentDidMount() {
    const { slug, episode_slug} = this.props.match.params
    feedcastApi
      .getEpisode({slug, episode_slug})
      .then( data => {
        this.setState(data)
      })
      .catch( e => {
        console.log(e.message)
      })
  }

  handleNewComment(comment) {
    console.log(comment.text);
  }

  playEpisode(){
    this.props.dispatch(
      playEpisode(this.state, [])
    );
  }

  render() {
    const { slug, episode_slug} = this.props.match.params

    const {
      title,
      summary,
      description,
      channel,
    } = this.state

    const html = description && description.length > 0 ? description : (
      summary && summary.length > 0 ? summary : ''
    );

    return (

          <div className="feedcast__episode-bg" style={{backgroundImage:`url(${channel.image_url})`}}>

          <div
            className="feedcast__episode-channel"
            style={{backgroundImage:`url(${channel.image_url})`}}>
            <button
              onClick={() => this.playEpisode()}
              className="feedcast__episode-button">

            </button>

{title}

              <Link to={`/${channel.slug}`} >{channel.title}</Link>

          <ReactDisqusComments
            shortname={DISQUS_SHORTNAME}
            identifier={`${slug}/${episode_slug}`}
            title={title}
            url={window.location.href}
            category_id={ channel.slug }
            onNewComment={this.handleNewComment}/>

    )
  }
}

export default connect()(Episode)
<|endoftext|>


<commit_before>import { translate } from '../../../common/i18n';

const steps = [
    {
        title: translate('Take a quick tour'),
        text : `

            ${translate('Ready to learn how to use Binary Bot?')}

            ${translate('No Thanks')}
            ${translate('Yes')}

            <input type="checkbox" id="do-not-ask-me-again"></input>

                ${translate('Do not ask me again.')}

          `,
        selector: '#center',
        position: 'top',
        style   : {
            textAlign: 'center',
            arrow    : {
                display: 'none',
            },
            button: {
                display: 'none',
            },
            close: {
                display: 'none',
            },
        },
    },
    {
        title: translate('Workspace'),
        text : `

      ${translate('Drag and drop block files.')}
      ${translate('or')} ${translate('make your own strategies.')}

`,
        selector: '#workspace_center',
        position: 'top',
    },
    {
        title: translate('Blocks toolbox'),
        text : `

      ${translate('Add more blocks from here to your bot.')}

`,
        selector: '.blocklyToolboxDiv',
        position: 'right',
    },
    {
        title: translate('Accounts'),
        text : `

      ${translate('Login before starting your bot. Always test your strategies with the virtual account.')}

`,
        selector: '.intro-login-logout',
        position: 'left',
    },
    {
        title: translate('Bot controls'),
        text : `

      ${translate('Control your blocks. Hold the cursor on each button for more info.')}

`,
        selector: '#zoomIn',
        position: 'left',
    },
    {
        title: translate('Enjoy!'),
        text : `

      ${translate('Want to report an issue or ask for help?')}

        ${translate('Click here')}

`,
        selector: '#center',
        position: 'top',
        style   : {
            arrow: {
                display: 'none',
            },
        },
    },
];

export default steps;
<commit_msg>fix: remove dot<commit_after>import { translate } from '../../../common/i18n';

const steps = [
    {
        title: translate('Take a quick tour'),
        text : `

            ${translate('Ready to learn how to use Binary Bot?')}

            ${translate('No Thanks')}
            ${translate('Yes')}

            <input type="checkbox" id="do-not-ask-me-again"></input>

                ${translate('Do not ask me again.')}

          `,
        selector: '#center',
        position: 'top',
        style   : {
            textAlign: 'center',
            arrow    : {
                display: 'none',
            },
            button: {
                display: 'none',
            },
            close: {
                display: 'none',
            },
        },
    },
    {
        title   : translate('Workspace'),
        text    : `<p>${translate('Drag and drop block files or make your own strategies.')}</p>`,
        selector: '#workspace_center',
        position: 'top',
    },
    {
        title: translate('Blocks toolbox'),
        text : `

      ${translate('Add more blocks from here to your bot.')}

`,
        selector: '.blocklyToolboxDiv',
        position: 'right',
    },
    {
        title: translate('Accounts'),
        text : `

      ${translate('Login before starting your bot. Always test your strategies with the virtual account.')}

`,
        selector: '.intro-login-logout',
        position: 'left',
    },
    {
        title: translate('Bot controls'),
        text : `

      ${translate('Control your blocks. Hold the cursor on each button for more info.')}

`,
        selector: '#zoomIn',
        position: 'left',
    },
    {
        title: translate('Enjoy!'),
        text : `

      ${translate('Want to report an issue or ask for help?')}

        ${translate('Click here')}

`,
        selector: '#center',
        position: 'top',
        style   : {
            arrow: {
                display: 'none',
            },
        },
    },
];

export default steps;
<|endoftext|>


<commit_before>var path = require('path');
var AssetsPlugin = require('assets-webpack-plugin')
var CompressionPlugin = require('compression-webpack-plugin')
var assetsPluginInstance = new AssetsPlugin({
  filename: 'static/prd/assets.js',
  processOutput: function (assets) {
    return 'window.WEBPACK_ASSETS = ' + JSON.stringify(assets);
  }
})
var config = require('../config.json');

var compressPlugin = new CompressionPlugin({
  asset: "[path].gz[query]",
  algorithm: "gzip",
  test: /\.(js|css)$/,
  threshold: 10240,
  minRatio: 0.8
});

function fileExist (filePath){
  try {
      return fs.statSync(filePath).isFile();
  } catch (err) {
      return false;
  }
};

function initPlugins(){
  if(config.plugins && Array.isArray(config.plugins)){
    config.plugins = config.plugins.filter(item=>{
      return fileExist(path.resolve(__dirname, 'plugins/yapi-plugin-' + item + '/client.js'))
    })
  }
}

initPlugins();

function handleCommonsChunk(webpackConfig) {
  var commonsChunk = {
    vendors: {
      lib: ['react', 'redux',
        'redux-thunk',
        'react-dom',
        'redux-promise',
        'react-router',
        'react-router-dom',
        'prop-types',
        'axios',
        'moment'

      ],
      lib2: [
        'brace',
        'mockjs',
        'json5'
      ]
    }
  },
    chunks = [],
    filenameTpl = webpackConfig.output[this.env],
    vendors;

  if (typeof commonsChunk === 'object' && commonsChunk !== undefined) {
    if (typeof commonsChunk.name === 'string' && commonsChunk) {
      chunks.push(commonsChunk.name);
    }
    vendors = commonsChunk.vendors;
    if (typeof vendors === 'object' && vendors !== undefined) {
      var i = 0;
      for (var name in vendors) {
        if (vendors.hasOwnProperty(name) && vendors[name]) {
          i++;
          chunks.push(name);
          webpackConfig.entry[name] = Array.isArray(vendors[name]) ? vendors[name] : [vendors[name]];
        }
      }
      if (i > 0) {
        chunks.push('manifest');
      }

    }

    if (chunks.length > 0) {
      let chunkFilename = filenameTpl.filename
      chunkFilename = chunkFilename.replace("[ext]", '.js')
      webpackConfig.plugins.push(
        new this.webpack.optimize.CommonsChunkPlugin({
          name: chunks,
          filename: chunkFilename,
          minChunks: commonsChunk.minChunks ? commonsChunk.minChunks : 2
        })
      );

    }
  }
}

module.exports = {
  plugins: [{
    name: 'antd',
    options: {
      modifyQuery: function (defaultQuery) { // 可查看和编辑 defaultQuery
        defaultQuery.plugins = [];
        defaultQuery.plugins.push(["transform-runtime", {
          "polyfill": false,
          "regenerator": true
        }]);
        defaultQuery.plugins.push('transform-decorators-legacy');
        defaultQuery.plugins.push(["import", { libraryName: "antd"}])
        return defaultQuery;
      },
      exclude: /node_modules/
    }
  }],
  // devtool:  'cheap-source-map',
  config: function (ykit) {
    return {
      exports: [
        './index.js'
      ],
      modifyWebpackConfig: function (baseConfig) {

        var ENV_PARAMS = {};
        switch (this.env) {
          case 'local':
            ENV_PARAMS = 'dev';
            break;
          case 'dev':
            ENV_PARAMS = 'dev';
            break;
          case 'prd':
            ENV_PARAMS = 'production';
            break;
          default:
        }

        baseConfig.plugins.push(new this.webpack.DefinePlugin({
          'process.env.NODE_ENV': JSON.stringify(ENV_PARAMS),
          'process.env.config': JSON.stringify(config)
        }))

        //初始化配置
        baseConfig.devtool = 'cheap-module-eval-source-map'
        baseConfig.context = path.resolve(__dirname, './client');
        baseConfig.resolve.alias.common = '/common';
        baseConfig.resolve.alias.plugins = '/plugins';
        baseConfig.output.prd.path = 'static/prd';
        baseConfig.output.prd.publicPath = '';
        baseConfig.output.prd.filename = '[name]@[chunkhash][ext]'

        //commonsChunk
        handleCommonsChunk.call(this, baseConfig)
        baseConfig.module.loaders.push({
          test: /\.less$/,
          loader: ykit.ExtractTextPlugin.extract(
            require.resolve('style-loader'),
            require.resolve('css-loader')
            + '?sourceMap!'
            + require.resolve('less-loader') + '?sourceMap'
          )
        })
        baseConfig.module.loaders.push({
          test: /\.(sass|scss)$/,
          loader: ykit.ExtractTextPlugin.extract(
            require.resolve('css-loader')
            + '?sourceMap!'
            + require.resolve('fast-sass-loader-china') + '?sourceMap'
          )
        })
        baseConfig.module.preLoaders.push({
          test: /\.(js|jsx)$/,
          exclude: /node_modules/,
          loader: "eslint-loader"
        });

        if (this.env == 'prd') {
          baseConfig.plugins.push(assetsPluginInstance)
          baseConfig.plugins.push(compressPlugin)

        }
        return baseConfig;
      }
    }
  },
  server: {
    // true/false，默认 false，效果相当于 ykit server --hot
    hot: true,
    // true/false，默认 false，开启后可在当前打开的页面提示打包错误
    overlay: false
  },
  hooks: {},
  commands: []
};
<commit_msg>chore: 修改ykit 构建<commit_after>var path = require('path');
var AssetsPlugin = require('assets-webpack-plugin')
var CompressionPlugin = require('compression-webpack-plugin')
var assetsPluginInstance = new AssetsPlugin({
  filename: 'static/prd/assets.js',
  processOutput: function (assets) {
    return 'window.WEBPACK_ASSETS = ' + JSON.stringify(assets);
  }
})
var config = require('../config.json');

var compressPlugin = new CompressionPlugin({
  asset: "[path].gz[query]",
  algorithm: "gzip",
  test: /\.(js|css)$/,
  threshold: 10240,
  minRatio: 0.8
});

function fileExist (filePath){
  try {
      return fs.statSync(filePath).isFile();
  } catch (err) {
      return false;
  }
};

function initPlugins(){
  if(config.plugins && Array.isArray(config.plugins)){
    config.plugins = config.plugins.filter(item=>{
      return fileExist(path.resolve(__dirname, 'plugins/yapi-plugin-' + item + '/client.js'))
    })
  }
}

initPlugins();

module.exports = {
  plugins: [{
    name: 'antd',
    options: {
      modifyQuery: function (defaultQuery) { // 可查看和编辑 defaultQuery
        defaultQuery.plugins = [];
        defaultQuery.plugins.push(["transform-runtime", {
          "polyfill": false,
          "regenerator": true
        }]);
        defaultQuery.plugins.push('transform-decorators-legacy');
        defaultQuery.plugins.push(["import", { libraryName: "antd"}])
        return defaultQuery;
      },
      exclude: /node_modules/
    }
  }],
  // devtool:  'cheap-source-map',
  config: function (ykit) {
    return {
      exports: [
        './index.js'
      ],
      commonsChunk: {
        vendors: {
          lib: ['react', 'redux',
            'redux-thunk',
            'react-dom',
            'redux-promise',
            'react-router',
            'react-router-dom',
            'prop-types',
            'axios',
            'moment'

          ],
          lib2: [
            'brace',
            'mockjs',
            'json5'
          ]
        }
      },
      modifyWebpackConfig: function (baseConfig) {

        var ENV_PARAMS = {};
        switch (this.env) {
          case 'local':
            ENV_PARAMS = 'dev';
            break;
          case 'dev':
            ENV_PARAMS = 'dev';
            break;
          case 'prd':
            ENV_PARAMS = 'production';
            break;
          default:
        }

        baseConfig.plugins.push(new this.webpack.DefinePlugin({
          'process.env.NODE_ENV': JSON.stringify(ENV_PARAMS),
          'process.env.config': JSON.stringify(config)
        }))

        //初始化配置
        baseConfig.devtool = 'cheap-module-eval-source-map'
        baseConfig.context = path.resolve(__dirname, './client');
        baseConfig.resolve.alias.common = '/common';
        baseConfig.resolve.alias.plugins = '/plugins';
        baseConfig.output.prd.path = 'static/prd';
        baseConfig.output.prd.publicPath = '';
        baseConfig.output.prd.filename = '[name]@[chunkhash][ext]'

        baseConfig.module.loaders.push({
          test: /\.less$/,
          loader: ykit.ExtractTextPlugin.extract(
            require.resolve('style-loader'),
            require.resolve('css-loader')
            + '?sourceMap!'
            + require.resolve('less-loader') + '?sourceMap'
          )
        })
        baseConfig.module.loaders.push({
          test: /\.(sass|scss)$/,
          loader: ykit.ExtractTextPlugin.extract(
            require.resolve('css-loader')
            + '?sourceMap!'
            + require.resolve('fast-sass-loader-china') + '?sourceMap'
          )
        })
        baseConfig.module.preLoaders.push({
          test: /\.(js|jsx)$/,
          exclude: /node_modules/,
          loader: "eslint-loader"
        });

        if (this.env == 'prd') {
          baseConfig.plugins.push(assetsPluginInstance)
          baseConfig.plugins.push(compressPlugin)

        }
        return baseConfig;
      }
    }
  },
  server: {
    // true/false，默认 false，效果相当于 ykit server --hot
    hot: true,
    // true/false，默认 false，开启后可在当前打开的页面提示打包错误
    overlay: false
  },
  hooks: {},
  commands: []
};
<|endoftext|>


<commit_before>const EosKnowledgeSearch = imports.EosKnowledgeSearch;

const ContainsMatcher = imports.ContainsMatcher;

describe('QueryObject', function () {
    beforeEach(function () {
        jasmine.addMatchers(ContainsMatcher.customMatchers);
    });

    it('sets tags and ids objects properly', function () {
        let ids = ['ekn://busters-es/0123456789012345',
                   'ekn://busters-es/fabaffacabacbafa'];
        let tags = ['Venkman', 'Stantz'];
        let query_obj = new EosKnowledgeSearch.QueryObject({
            ids: ids,
            tags: tags,
        });
        expect(ids).toEqual(query_obj.ids);
        expect(tags).toEqual(query_obj.tags);
    });

    describe('new_from_object constructor', function () {
        it('duplicates properties from source object', function () {
            let tags = ['Venkman', 'Stantz'];
            let query = 'keymaster';
            let query_obj = new EosKnowledgeSearch.QueryObject({
                tags: tags,
                query: query,
            });
            let query_obj_copy = EosKnowledgeSearch.QueryObject.new_from_object(query_obj);
            expect(query_obj_copy.tags).toEqual(tags);
            expect(query_obj_copy.query).toEqual(query);
        });

        it('allows properties to be overridden', function () {
            let tags = ['Venkman', 'Stantz'];
            let query = 'keymaster';
            let query_obj = new EosKnowledgeSearch.QueryObject({
                tags: tags,
                query: query,
            });
            let new_query = 'gatekeeper';
            let new_query_object = EosKnowledgeSearch.QueryObject.new_from_object(query_obj, {
                query: new_query
            });
            expect(new_query_object.tags).toEqual(tags);
            expect(new_query_object.query).toEqual(new_query);
        });
    });

    it('should map sort property to xapian sort value', function () {
        let query_obj = new EosKnowledgeSearch.QueryObject({
            query: 'tyrion wins',
            sort: EosKnowledgeSearch.QueryObjectSort.RANK,
        });
        let result = query_obj.get_sort_value(query_obj);
        expect(result).toBe(1);

        query_obj = new EosKnowledgeSearch.QueryObject({
            query: 'tyrion wins',
        });
        let undefined_result = query_obj.get_sort_value(query_obj);
        expect(undefined_result).toBe(undefined);
    });

    it('should map match type to xapian cutoff value', () => {
        let query_obj = new EosKnowledgeSearch.QueryObject({
            query: 'tyrion wins',
            match: EosKnowledgeSearch.QueryObjectMatch.TITLE_SYNOPSIS,
        });
        let result = query_obj.get_cutoff(query_obj);
        expect(result).toBe(20);

        query_obj = new EosKnowledgeSearch.QueryObject({
            query: 'tyrion wins',
            match: EosKnowledgeSearch.QueryObjectMatch.TITLE_ONLY,
        });
        let result = query_obj.get_cutoff(query_obj);
        expect(result).toBe(10);
    });

    describe('query parser string', () => {
        it('contains expected terms', function () {
            let query_obj = new EosKnowledgeSearch.QueryObject({
                query: 'foo bar baz',
            });
            let result = query_obj.get_query_parser_string(query_obj);
            expect(result).toContain('exact_title:Foo_Bar_Baz');
            expect(result).toContain('title:foo');
            expect(result).toContain('title:bar');
            expect(result).toContain('title:baz');
        });

        it('adds wildcard terms only for incremental search', function () {
            let query_obj = new EosKnowledgeSearch.QueryObject({
                query: 'foo',
                type: EosKnowledgeSearch.QueryObjectType.INCREMENTAL,
            });
            let result = query_obj.get_query_parser_string(query_obj);
            expect(result).toContain('exact_title:Foo*');
            expect(result).toContain('title:foo*');

            query_obj = new EosKnowledgeSearch.QueryObject({
                query: 'foo',
                type: EosKnowledgeSearch.QueryObjectType.DELIMITED,
            });
            result = query_obj.get_query_parser_string(query_obj);
            expect(result).not.toContain('exact_title:Foo*');
            expect(result).not.toContain('title:foo*');
        });

        it('contains terms without title prefix if matching synopsis', function () {
            let query_obj = new EosKnowledgeSearch.QueryObject({
                query: 'littl searc',
                match: EosKnowledgeSearch.QueryObjectMatch.TITLE_SYNOPSIS,
            });
            let result = query_obj.get_query_parser_string(query_obj);
            expect(result).toContain('(littl OR littl*) AND (searc OR searc*)');
        });

        it('only uses exact title search for single character queries', function () {
            let query_obj = new EosKnowledgeSearch.QueryObject({
                query: 'a',
                type: EosKnowledgeSearch.QueryObjectType.INCREMENTAL,
            });
            let result = query_obj.get_query_parser_string(query_obj);
            expect(result).toContain('exact_title:A');
            expect(result).not.toContain('a*');
            expect(result).not.toContain('title:a');
        });

        it('should ignore excess whitespace (except for tags)', function () {
            let query_obj = new EosKnowledgeSearch.QueryObject({
                query: 'whoa      man',
            });
            let result = query_obj.get_query_parser_string(query_obj);
            expect(result).toContain('exact_title:Whoa_Man');
            expect(result).toContain('title:whoa');
            expect(result).toContain('title:man');
        });

        it('should lowercase xapian operator terms', function () {
            let query_obj = new EosKnowledgeSearch.QueryObject({
                query: 'PENN AND tELLER',
            });
            let result = query_obj.get_query_parser_string(query_obj);
            expect(result).toContain('title:and');
        });

        it('should remove parentheses in user terms', function () {
            let query_obj = new EosKnowledgeSearch.QueryObject({
                query: 'foo (bar) baz ((',
            });
            let result = query_obj.get_query_parser_string(query_obj);
            expect(result).toContain('exact_title:Foo_Bar_Baz');
        });

        it('contains ids from query object', function () {
            let query_obj = new EosKnowledgeSearch.QueryObject({
                domain: 'domain',
                ids: ['ekn://domain/0123456789abcdef',
                      'ekn://domain/fedcba9876543210'],
            });
            let result = query_obj.get_query_parser_string(query_obj);
            expect(result).toContain('id:0123456789abcdef OR id:fedcba9876543210');
        });

        it('contains tags from query object', function () {
            let query_obj = new EosKnowledgeSearch.QueryObject({
                tags: ['cats', 'dogs', 'turtles'],
            });
            let result = query_obj.get_query_parser_string(query_obj);
            expect(result).toContain('tag:"cats" OR tag:"dogs" OR tag:"turtles"');
        });

        it('should surround multiword tags in quotes', function () {
            let query_obj = new EosKnowledgeSearch.QueryObject({
                tags: ['cat zombies'],
            });
            let result = query_obj.get_query_parser_string(query_obj);
            expect(result).toContain('tag:"cat zombies"');
        });

        describe('id checking code', function () {
            it('validates a simple EKN ID', function () {
                let query_obj = new EosKnowledgeSearch.QueryObject({
                    domain: 'travel-es',
                    ids: ['ekn://travel-es/2e11617b6bce1e6d'],
                });
                expect(function () {
                    query_obj.get_query_parser_string(query_obj);
                }).not.toThrow();
            });

            it('validates an EKN ID with uppercase hex digits', function () {
                let query_obj = new EosKnowledgeSearch.QueryObject({
                    domain: 'travel-es',
                    ids: ['ekn://travel-es/2E11617B6BCE1E6D'],
                });
                expect(function () {
                    query_obj.get_query_parser_string(query_obj);
                }).not.toThrow();
            });

            it('rejects an EKN ID with an invalid hash', function () {
                let query_obj = new EosKnowledgeSearch.QueryObject({
                    domain: 'bad1',
                    ids: ['ekn://bad1/someha$h'],
                });
                expect(function () {
                    query_obj.get_query_parser_string(query_obj);
                }).toThrow();
            });

            it('rejects an EKN ID with the wrong URI scheme', function () {
                let query_obj = new EosKnowledgeSearch.QueryObject({
                    domain: 'bad1',
                    ids: ['bad1/2e11617b6bce1e6d'],
                });
                expect(function () {
                    query_obj.get_query_parser_string(query_obj);
                }).toThrow();
            });

            it('rejects an EKN ID with no hash', function () {
                let query_obj = new EosKnowledgeSearch.QueryObject({
                    domain: 'scuba-diving-es',
                    ids: ['ekn://scuba-diving-es'],
                });
                expect(function () {
                    query_obj.get_query_parser_string(query_obj);
                }).toThrow();
            });

            it('rejects an EKN ID with too many parts', function () {
                let query_obj = new EosKnowledgeSearch.QueryObject({
                    domain: 'travel-es',
                    ids: ['ekn://travel-es/2e11617b6bce1e6d/too/many/parts'],
                });
                expect(function () {
                    query_obj.get_query_parser_string(query_obj);
                }).toThrow();
            });

            it('rejects on an EKN ID domain mismatch', function () {
                let query_obj = new EosKnowledgeSearch.QueryObject({
                    domain: 'travel-es',
                    ids: ['ekn://animals-es/2e11617b6bce1e6d'],
                });
                expect(function () {
                    query_obj.get_query_parser_string(query_obj);
                }).toThrow();
            });
        });
    });
});
<commit_msg>queryObject: add test for blacklist<commit_after>const EosKnowledgeSearch = imports.EosKnowledgeSearch;
const Blacklist = imports.blacklist;

const ContainsMatcher = imports.ContainsMatcher;

describe('QueryObject', function () {
    beforeEach(function () {
        jasmine.addMatchers(ContainsMatcher.customMatchers);
    });

    it('sets tags and ids objects properly', function () {
        let ids = ['ekn://busters-es/0123456789012345',
                   'ekn://busters-es/fabaffacabacbafa'];
        let tags = ['Venkman', 'Stantz'];
        let query_obj = new EosKnowledgeSearch.QueryObject({
            ids: ids,
            tags: tags,
        });
        expect(ids).toEqual(query_obj.ids);
        expect(tags).toEqual(query_obj.tags);
    });

    describe('new_from_object constructor', function () {
        it('duplicates properties from source object', function () {
            let tags = ['Venkman', 'Stantz'];
            let query = 'keymaster';
            let query_obj = new EosKnowledgeSearch.QueryObject({
                tags: tags,
                query: query,
            });
            let query_obj_copy = EosKnowledgeSearch.QueryObject.new_from_object(query_obj);
            expect(query_obj_copy.tags).toEqual(tags);
            expect(query_obj_copy.query).toEqual(query);
        });

        it('allows properties to be overridden', function () {
            let tags = ['Venkman', 'Stantz'];
            let query = 'keymaster';
            let query_obj = new EosKnowledgeSearch.QueryObject({
                tags: tags,
                query: query,
            });
            let new_query = 'gatekeeper';
            let new_query_object = EosKnowledgeSearch.QueryObject.new_from_object(query_obj, {
                query: new_query
            });
            expect(new_query_object.tags).toEqual(tags);
            expect(new_query_object.query).toEqual(new_query);
        });
    });

    it('should map sort property to xapian sort value', function () {
        let query_obj = new EosKnowledgeSearch.QueryObject({
            query: 'tyrion wins',
            sort: EosKnowledgeSearch.QueryObjectSort.RANK,
        });
        let result = query_obj.get_sort_value(query_obj);
        expect(result).toBe(1);

        query_obj = new EosKnowledgeSearch.QueryObject({
            query: 'tyrion wins',
        });
        let undefined_result = query_obj.get_sort_value(query_obj);
        expect(undefined_result).toBe(undefined);
    });

    it('should map match type to xapian cutoff value', () => {
        let query_obj = new EosKnowledgeSearch.QueryObject({
            query: 'tyrion wins',
            match: EosKnowledgeSearch.QueryObjectMatch.TITLE_SYNOPSIS,
        });
        let result = query_obj.get_cutoff(query_obj);
        expect(result).toBe(20);

        query_obj = new EosKnowledgeSearch.QueryObject({
            query: 'tyrion wins',
            match: EosKnowledgeSearch.QueryObjectMatch.TITLE_ONLY,
        });
        let result = query_obj.get_cutoff(query_obj);
        expect(result).toBe(10);
    });

    describe('query parser string', () => {
        it('contains expected terms', function () {
            let query_obj = new EosKnowledgeSearch.QueryObject({
                query: 'foo bar baz',
            });
            let result = query_obj.get_query_parser_string(query_obj);
            expect(result).toContain('exact_title:Foo_Bar_Baz');
            expect(result).toContain('title:foo');
            expect(result).toContain('title:bar');
            expect(result).toContain('title:baz');
        });

        it('adds wildcard terms only for incremental search', function () {
            let query_obj = new EosKnowledgeSearch.QueryObject({
                query: 'foo',
                type: EosKnowledgeSearch.QueryObjectType.INCREMENTAL,
            });
            let result = query_obj.get_query_parser_string(query_obj);
            expect(result).toContain('exact_title:Foo*');
            expect(result).toContain('title:foo*');

            query_obj = new EosKnowledgeSearch.QueryObject({
                query: 'foo',
                type: EosKnowledgeSearch.QueryObjectType.DELIMITED,
            });
            result = query_obj.get_query_parser_string(query_obj);
            expect(result).not.toContain('exact_title:Foo*');
            expect(result).not.toContain('title:foo*');
        });

        it('contains terms without title prefix if matching synopsis', function () {
            let query_obj = new EosKnowledgeSearch.QueryObject({
                query: 'littl searc',
                match: EosKnowledgeSearch.QueryObjectMatch.TITLE_SYNOPSIS,
            });
            let result = query_obj.get_query_parser_string(query_obj);
            expect(result).toContain('(littl OR littl*) AND (searc OR searc*)');
        });

        it('only uses exact title search for single character queries', function () {
            let query_obj = new EosKnowledgeSearch.QueryObject({
                query: 'a',
                type: EosKnowledgeSearch.QueryObjectType.INCREMENTAL,
            });
            let result = query_obj.get_query_parser_string(query_obj);
            expect(result).toContain('exact_title:A');
            expect(result).not.toContain('a*');
            expect(result).not.toContain('title:a');
        });

        it('should ignore excess whitespace (except for tags)', function () {
            let query_obj = new EosKnowledgeSearch.QueryObject({
                query: 'whoa      man',
            });
            let result = query_obj.get_query_parser_string(query_obj);
            expect(result).toContain('exact_title:Whoa_Man');
            expect(result).toContain('title:whoa');
            expect(result).toContain('title:man');
        });

        it('should lowercase xapian operator terms', function () {
            let query_obj = new EosKnowledgeSearch.QueryObject({
                query: 'PENN AND tELLER',
            });
            let result = query_obj.get_query_parser_string(query_obj);
            expect(result).toContain('title:and');
        });

        it('should remove parentheses in user terms', function () {
            let query_obj = new EosKnowledgeSearch.QueryObject({
                query: 'foo (bar) baz ((',
            });
            let result = query_obj.get_query_parser_string(query_obj);
            expect(result).toContain('exact_title:Foo_Bar_Baz');
        });

        it('contains ids from query object', function () {
            let query_obj = new EosKnowledgeSearch.QueryObject({
                domain: 'domain',
                ids: ['ekn://domain/0123456789abcdef',
                      'ekn://domain/fedcba9876543210'],
            });
            let result = query_obj.get_query_parser_string(query_obj);
            expect(result).toContain('id:0123456789abcdef OR id:fedcba9876543210');
        });

        it('contains tags from query object', function () {
            let query_obj = new EosKnowledgeSearch.QueryObject({
                tags: ['cats', 'dogs', 'turtles'],
            });
            let result = query_obj.get_query_parser_string(query_obj);
            expect(result).toContain('tag:"cats" OR tag:"dogs" OR tag:"turtles"');
        });

        it('should surround multiword tags in quotes', function () {
            let query_obj = new EosKnowledgeSearch.QueryObject({
                tags: ['cat zombies'],
            });
            let result = query_obj.get_query_parser_string(query_obj);
            expect(result).toContain('tag:"cat zombies"');
        });

        it('contains blacklist clause when available', function () {
            Blacklist.blacklist['fake-blacklist-domain'] = ['foo', 'bar'];
            let query_obj = new EosKnowledgeSearch.QueryObject({
                domain: 'fake-blacklist-domain',
                query: 'tyrion wins',
            });
            let result = query_obj.get_query_parser_string(query_obj);
            expect(result).toContain('NOT tag:"foo"');
            expect(result).toContain('NOT tag:"bar"');
        });

        describe('id checking code', function () {
            it('validates a simple EKN ID', function () {
                let query_obj = new EosKnowledgeSearch.QueryObject({
                    domain: 'travel-es',
                    ids: ['ekn://travel-es/2e11617b6bce1e6d'],
                });
                expect(function () {
                    query_obj.get_query_parser_string(query_obj);
                }).not.toThrow();
            });

            it('validates an EKN ID with uppercase hex digits', function () {
                let query_obj = new EosKnowledgeSearch.QueryObject({
                    domain: 'travel-es',
                    ids: ['ekn://travel-es/2E11617B6BCE1E6D'],
                });
                expect(function () {
                    query_obj.get_query_parser_string(query_obj);
                }).not.toThrow();
            });

            it('rejects an EKN ID with an invalid hash', function () {
                let query_obj = new EosKnowledgeSearch.QueryObject({
                    domain: 'bad1',
                    ids: ['ekn://bad1/someha$h'],
                });
                expect(function () {
                    query_obj.get_query_parser_string(query_obj);
                }).toThrow();
            });

            it('rejects an EKN ID with the wrong URI scheme', function () {
                let query_obj = new EosKnowledgeSearch.QueryObject({
                    domain: 'bad1',
                    ids: ['bad1/2e11617b6bce1e6d'],
                });
                expect(function () {
                    query_obj.get_query_parser_string(query_obj);
                }).toThrow();
            });

            it('rejects an EKN ID with no hash', function () {
                let query_obj = new EosKnowledgeSearch.QueryObject({
                    domain: 'scuba-diving-es',
                    ids: ['ekn://scuba-diving-es'],
                });
                expect(function () {
                    query_obj.get_query_parser_string(query_obj);
                }).toThrow();
            });

            it('rejects an EKN ID with too many parts', function () {
                let query_obj = new EosKnowledgeSearch.QueryObject({
                    domain: 'travel-es',
                    ids: ['ekn://travel-es/2e11617b6bce1e6d/too/many/parts'],
                });
                expect(function () {
                    query_obj.get_query_parser_string(query_obj);
                }).toThrow();
            });

            it('rejects on an EKN ID domain mismatch', function () {
                let query_obj = new EosKnowledgeSearch.QueryObject({
                    domain: 'travel-es',
                    ids: ['ekn://animals-es/2e11617b6bce1e6d'],
                });
                expect(function () {
                    query_obj.get_query_parser_string(query_obj);
                }).toThrow();
            });
        });
    });
});
<|endoftext|>


<commit_before>import React from "react";
import { mount } from "enzyme";
import Search from "./Search";

describe("side-nav/Search", () => {
  it("allows value to be changed only by onChange", () => {
    const wrapper = mount(<Search value="foo" />);
    const input = wrapper.find("input");

    expect(input.prop("value")).toEqual("foo");
    input.simulate("change", { target: { value: "bar" } });
    expect(input.prop("value")).toEqual("bar");

    wrapper.setProps({ value: "baz" });
    expect(input.prop("value")).toEqual("bar"); // Incoming props are ignored
  });

  it("renders a button to clear input", () => {
    const wrapper = mount(<Search />);
    const input = wrapper.find("input");

    expect(wrapper.find("ClearSmall24").parent()).toHaveLength(0);
    input.simulate("change", { target: { value: "bar" } });
    expect(wrapper.find("ClearSmall24").parent()).toHaveLength(1);

    wrapper
      .find("ClearSmall24")
      .parent()
      .simulate("click");
    expect(input.prop("value")).toEqual("");
    expect(wrapper.find("ClearSmall24").parent()).toHaveLength(0);
  });
});
<commit_msg>test: update jest tests<commit_after>import React from "react";
import { mount } from "enzyme";
import Search from "./Search";

describe("side-nav/Search", () => {
  it("allows value to be changed only by onChange", () => {
    const wrapper = mount(<Search value="foo" />);
    const input = wrapper.find("input");

    expect(input.prop("value")).toEqual("foo");
    input.simulate("change", { target: { value: "bar" } });
    expect(input.prop("value")).toEqual("bar");

    wrapper.setProps({ value: "baz" });
    expect(input.prop("value")).toEqual("bar"); // Incoming props are ignored
  });

  it("renders a button to clear input", () => {
    const wrapper = mount(<Search />);
    const input = wrapper.find("input");

    expect(wrapper.find("Error24").parent()).toHaveLength(0);
    input.simulate("change", { target: { value: "bar" } });
    expect(wrapper.find("Error24").parent()).toHaveLength(1);

    wrapper
      .find("Error24")
      .parent()
      .simulate("click");
    expect(input.prop("value")).toEqual("");
    expect(wrapper.find("Error24").parent()).toHaveLength(0);
  });
});
<|endoftext|>


<commit_before>/*
 * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
 * under one or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership. Camunda licenses this file to you under the Apache License,
 * Version 2.0; you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import React, { useEffect, useState, useCallback } from "react";
import classNames from "classnames";

import { registerConsumer, unregisterConsumer } from "utils/notifications";

import "./Notifications.scss";

export default function Notifications({ className }) {
  const [notifications, setNotifications] = useState([]);
  const [consumerIndex, setConsumerIndex] = useState(null);

  const removeNotification = useCallback(
    notification => {
      notifications.splice(notifications.indexOf(notification), 1);
      setNotifications([...notifications]);
    },
    [notifications]
  );

  useEffect(() => {
    const consumer = {
      add: notification => {
        setNotifications([...notifications, notification]);
        return true;
      },
      remove: removeNotification
    };
    setConsumerIndex(registerConsumer(consumer, consumerIndex));
    return () => {
      unregisterConsumer(consumer);
    };
  }, [consumerIndex, notifications, removeNotification]);

  return (

        {notifications.map((notification, index) => (

            <button
              className="close"
              onClick={() => removeNotification(notification)}
            >
              ×
            </button>
            {notification.status}:
            {notification.message}

        ))}

  );
}
<commit_msg>fix(Notifications): allow HTML notifications<commit_after>/*
 * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
 * under one or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership. Camunda licenses this file to you under the Apache License,
 * Version 2.0; you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import React, { useEffect, useState, useCallback } from "react";
import classNames from "classnames";

import { registerConsumer, unregisterConsumer } from "utils/notifications";

import "./Notifications.scss";

export default function Notifications({ className }) {
  const [notifications, setNotifications] = useState([]);
  const [consumerIndex, setConsumerIndex] = useState(null);

  const removeNotification = useCallback(
    notification => {
      notifications.splice(notifications.indexOf(notification), 1);
      setNotifications([...notifications]);
    },
    [notifications]
  );

  useEffect(() => {
    const consumer = {
      add: notification => {
        setNotifications([...notifications, notification]);
        return true;
      },
      remove: removeNotification
    };
    setConsumerIndex(registerConsumer(consumer, consumerIndex));
    return () => {
      unregisterConsumer(consumer);
    };
  }, [consumerIndex, notifications, removeNotification]);

  return (

        {notifications.map((notification, index) => (

            <button
              className="close"
              onClick={() => removeNotification(notification)}
            >
              ×
            </button>
            {notification.status}:

        ))}

  );
}
<|endoftext|>