<commit_before>const { templateName } = require('../backends/template_maps');
const cors = require('../middleware/cors');
const userMiddleware = require('../middleware/user');

/**
 * @param {AuthApi} authApi
 * @param {PgConnection} pgConnection
 * @param {TemplateMaps} templateMaps
 * @constructor
 */
function NamedMapsAdminController(authApi, templateMaps) {
    this.authApi = authApi;
    this.templateMaps = templateMaps;
}

module.exports = NamedMapsAdminController;

NamedMapsAdminController.prototype.register = function (app) {
    const prefix = app.base_url_templated;

    app.post(
        `${prefix}/`,
        cors(),
        userMiddleware,
        this.checkContentType('POST', 'POST TEMPLATE'),
        this.authorizedByAPIKey('create', 'POST TEMPLATE'),
        this.create()
    );

    app.put(
        `${prefix}/:template_id`,
        cors(),
        userMiddleware,
        this.checkContentType('PUT', 'PUT TEMPLATE'),
        this.authorizedByAPIKey('update', 'PUT TEMPLATE'),
        this.update()
    );

    app.get(
        `${prefix}/:template_id`,
        cors(),
        userMiddleware,
        this.authorizedByAPIKey('get', 'GET TEMPLATE'),
        this.retrieve()
    );

    app.delete(
        `${prefix}/:template_id`,
        cors(),
        userMiddleware,
        this.authorizedByAPIKey('delete', 'DELETE TEMPLATE'),
        this.destroy()
    );

    app.get(
        `${prefix}/`,
        cors(),
        userMiddleware,
        this.authorizedByAPIKey('list', 'GET TEMPLATE LIST'),
        this.list()
    );

    app.options(
        `${prefix}/:template_id`,
        cors('Content-Type')
    );
};

NamedMapsAdminController.prototype.authorizedByAPIKey = function (action, label) {
    return function authorizedByAPIKeyMiddleware (req, res, next) {
        const { user } = res.locals;

        this.authApi.authorizedByAPIKey(user, req, (err, authenticated) => {
            if (err) {
                return next(err);
            }

            if (!authenticated) {
                const error = new Error(`Only authenticated user can ${action} templated maps`);
                error.http_status = 403;
                error.label = label;
                return next(error);
            }

            next();
        });
    }.bind(this);
};

NamedMapsAdminController.prototype.checkContentType = function (action, label) {
    return function checkContentTypeMiddleware (req, res, next) {
        if (!req.is('application/json')) {
            const error = new Error(`template ${action} data must be of type application/json`);
            error.label = label;
            return next(error);
        }
        next();
    };
};

NamedMapsAdminController.prototype.create = function () {
    return function createTemplateMiddleware (req, res, next) {
        const cdbuser = res.locals.user;
        const cfg = req.body;

        this.templateMaps.addTemplate(cdbuser, cfg, (err, tpl_id) => {
            if (err) {
                return next(err);
            }

            res.status(200);

            const method = req.query.callback ? 'jsonp' : 'json';
            res[method]({ template_id: tpl_id });
        });
    }.bind(this);
};

NamedMapsAdminController.prototype.update = function () {
    return function updateTemplateMiddleware (req, res, next) {
        const cdbuser = res.locals.user;
        const template = req.body;
        const tpl_id = templateName(req.params.template_id);

        this.templateMaps.updTemplate(cdbuser, tpl_id, template, (err) => {
            if (err) {
                return next(err);
            }

            res.status(200);

            const method = req.query.callback ? 'jsonp' : 'json';
            res[method]({ template_id: tpl_id });
        });
    }.bind(this);
};

NamedMapsAdminController.prototype.retrieve =  function () {
    return function updateTemplateMiddleware (req, res, next) {
        req.profiler.start('windshaft-cartodb.get_template');

        const cdbuser = res.locals.user;
        const tpl_id = templateName(req.params.template_id);

        this.templateMaps.getTemplate(cdbuser, tpl_id, (err, tpl_val) => {
            if (err) {
                return next(err);
            }

            if (!tpl_val) {
                const error = new Error(`Cannot find template '${tpl_id}' of user '${cdbuser}'`);
                error.http_status = 404;
                return next(error);
            }
            // auth_id was added by ourselves,
            // so we remove it before returning to the user
            delete tpl_val.auth_id;

            res.status(200);

            const method = req.query.callback ? 'jsonp' : 'json';
            res[method]({ template: tpl_val });
        });
    }.bind(this);
};

NamedMapsAdminController.prototype.destroy = function () {
    return function destroyTemplateMiddleware (req, res, next) {
        req.profiler.start('windshaft-cartodb.delete_template');

        const cdbuser = res.locals.user;
        const tpl_id = templateName(req.params.template_id);

        this.templateMaps.delTemplate(cdbuser, tpl_id, (err/*, tpl_val*/) => {
            if (err) {
                return next(err);
            }

            res.status(204);

            const method = req.query.callback ? 'jsonp' : 'json';
            res[method]('');
        });
    }.bind(this);
};

NamedMapsAdminController.prototype.list = function () {
    return function listTemplatesMiddleware (req, res, next) {
        req.profiler.start('windshaft-cartodb.get_template_list');

        const cdbuser = res.locals.user;

        this.templateMaps.listTemplates(cdbuser, (err, tpl_ids) => {
            if (err) {
                return next(err);
            }

            res.status(200);

            const method = req.query.callback ? 'jsonp' : 'json';
            res[method]({ template_ids: tpl_ids });
        });
    }.bind(this);
};
<commit_msg>Use original variable name<commit_after>const { templateName } = require('../backends/template_maps');
const cors = require('../middleware/cors');
const userMiddleware = require('../middleware/user');

/**
 * @param {AuthApi} authApi
 * @param {PgConnection} pgConnection
 * @param {TemplateMaps} templateMaps
 * @constructor
 */
function NamedMapsAdminController(authApi, templateMaps) {
    this.authApi = authApi;
    this.templateMaps = templateMaps;
}

module.exports = NamedMapsAdminController;

NamedMapsAdminController.prototype.register = function (app) {
    const { base_url_templated } = app;

    app.post(
        `${base_url_templated}/`,
        cors(),
        userMiddleware,
        this.checkContentType('POST', 'POST TEMPLATE'),
        this.authorizedByAPIKey('create', 'POST TEMPLATE'),
        this.create()
    );

    app.put(
        `${base_url_templated}/:template_id`,
        cors(),
        userMiddleware,
        this.checkContentType('PUT', 'PUT TEMPLATE'),
        this.authorizedByAPIKey('update', 'PUT TEMPLATE'),
        this.update()
    );

    app.get(
        `${base_url_templated}/:template_id`,
        cors(),
        userMiddleware,
        this.authorizedByAPIKey('get', 'GET TEMPLATE'),
        this.retrieve()
    );

    app.delete(
        `${base_url_templated}/:template_id`,
        cors(),
        userMiddleware,
        this.authorizedByAPIKey('delete', 'DELETE TEMPLATE'),
        this.destroy()
    );

    app.get(
        `${base_url_templated}/`,
        cors(),
        userMiddleware,
        this.authorizedByAPIKey('list', 'GET TEMPLATE LIST'),
        this.list()
    );

    app.options(
        `${base_url_templated}/:template_id`,
        cors('Content-Type')
    );
};

NamedMapsAdminController.prototype.authorizedByAPIKey = function (action, label) {
    return function authorizedByAPIKeyMiddleware (req, res, next) {
        const { user } = res.locals;

        this.authApi.authorizedByAPIKey(user, req, (err, authenticated) => {
            if (err) {
                return next(err);
            }

            if (!authenticated) {
                const error = new Error(`Only authenticated user can ${action} templated maps`);
                error.http_status = 403;
                error.label = label;
                return next(error);
            }

            next();
        });
    }.bind(this);
};

NamedMapsAdminController.prototype.checkContentType = function (action, label) {
    return function checkContentTypeMiddleware (req, res, next) {
        if (!req.is('application/json')) {
            const error = new Error(`template ${action} data must be of type application/json`);
            error.label = label;
            return next(error);
        }
        next();
    };
};

NamedMapsAdminController.prototype.create = function () {
    return function createTemplateMiddleware (req, res, next) {
        const cdbuser = res.locals.user;
        const cfg = req.body;

        this.templateMaps.addTemplate(cdbuser, cfg, (err, tpl_id) => {
            if (err) {
                return next(err);
            }

            res.status(200);

            const method = req.query.callback ? 'jsonp' : 'json';
            res[method]({ template_id: tpl_id });
        });
    }.bind(this);
};

NamedMapsAdminController.prototype.update = function () {
    return function updateTemplateMiddleware (req, res, next) {
        const cdbuser = res.locals.user;
        const template = req.body;
        const tpl_id = templateName(req.params.template_id);

        this.templateMaps.updTemplate(cdbuser, tpl_id, template, (err) => {
            if (err) {
                return next(err);
            }

            res.status(200);

            const method = req.query.callback ? 'jsonp' : 'json';
            res[method]({ template_id: tpl_id });
        });
    }.bind(this);
};

NamedMapsAdminController.prototype.retrieve =  function () {
    return function updateTemplateMiddleware (req, res, next) {
        req.profiler.start('windshaft-cartodb.get_template');

        const cdbuser = res.locals.user;
        const tpl_id = templateName(req.params.template_id);

        this.templateMaps.getTemplate(cdbuser, tpl_id, (err, tpl_val) => {
            if (err) {
                return next(err);
            }

            if (!tpl_val) {
                const error = new Error(`Cannot find template '${tpl_id}' of user '${cdbuser}'`);
                error.http_status = 404;
                return next(error);
            }
            // auth_id was added by ourselves,
            // so we remove it before returning to the user
            delete tpl_val.auth_id;

            res.status(200);

            const method = req.query.callback ? 'jsonp' : 'json';
            res[method]({ template: tpl_val });
        });
    }.bind(this);
};

NamedMapsAdminController.prototype.destroy = function () {
    return function destroyTemplateMiddleware (req, res, next) {
        req.profiler.start('windshaft-cartodb.delete_template');

        const cdbuser = res.locals.user;
        const tpl_id = templateName(req.params.template_id);

        this.templateMaps.delTemplate(cdbuser, tpl_id, (err/*, tpl_val*/) => {
            if (err) {
                return next(err);
            }

            res.status(204);

            const method = req.query.callback ? 'jsonp' : 'json';
            res[method]('');
        });
    }.bind(this);
};

NamedMapsAdminController.prototype.list = function () {
    return function listTemplatesMiddleware (req, res, next) {
        req.profiler.start('windshaft-cartodb.get_template_list');

        const cdbuser = res.locals.user;

        this.templateMaps.listTemplates(cdbuser, (err, tpl_ids) => {
            if (err) {
                return next(err);
            }

            res.status(200);

            const method = req.query.callback ? 'jsonp' : 'json';
            res[method]({ template_ids: tpl_ids });
        });
    }.bind(this);
};
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import yubikiri from 'yubikiri';
import {QueryRenderer, graphql} from 'react-relay';

import RelayNetworkLayerManager from '../relay-network-layer-manager';
import {GithubLoginModelPropType} from '../prop-types';
import {UNAUTHENTICATED, INSUFFICIENT} from '../shared/keytar-strategy';
import GithubLoginView from '../views/github-login-view';
import LoadingView from '../views/loading-view';
import QueryErrorView from '../views/query-error-view';
import ObserveModel from '../views/observe-model';
import IssueishDetailController from '../controllers/issueish-detail-controller';
import RelayEnvironment from '../views/relay-environment';
import {autobind} from '../helpers';

export default class IssueishDetailContainer extends React.Component {
  static propTypes = {
    host: PropTypes.string,
    owner: PropTypes.string.isRequired,
    repo: PropTypes.string.isRequired,
    issueishNumber: PropTypes.number.isRequired,

    repository: PropTypes.object.isRequired,
    loginModel: GithubLoginModelPropType.isRequired,

    switchToIssueish: PropTypes.func.isRequired,
    onTitleChange: PropTypes.func.isRequired,
  }

  constructor(props) {
    super(props);
    autobind(this,
      'fetchToken', 'renderWithToken',
      'fetchRepositoryData', 'renderWithRepositoryData',
      'renderWithResult',
      'handleLogin', 'handleLogout',
    );
  }

  fetchToken(loginModel) {
    return yubikiri({
      token: loginModel.getToken(this.props.host),
    });
  }

  render() {
    return (
      <ObserveModel model={this.props.loginModel} fetchData={this.fetchToken}>
        {this.renderWithToken}
      </ObserveModel>
    );
  }

  fetchRepositoryData(repository) {
    return yubikiri({
      branches: repository.getBranches(),
      remotes: repository.getRemotes(),
      isMerging: repository.isMerging(),
      isRebasing: repository.isRebasing(),
      unstagedChanges: repository.getUnstagedChanges(),
      stagedChanges: repository.getStagedChanges(),
      mergeConflicts: repository.getMergeConflicts(),
    });
  }

  renderWithToken(tokenData) {
    if (!tokenData) {
      return <LoadingView />;
    }

    if (tokenData.token === UNAUTHENTICATED) {
      return <GithubLoginView onLogin={this.handleLogin} />;
    }

    if (tokenData.token === INSUFFICIENT) {
      return (
        <GithubLoginView onLogin={this.handleLogin}>

            Your token no longer has sufficient authorizations. Please re-authenticate and generate a new one.

        </GithubLoginView>
      );
    }

    return (
      <ObserveModel model={this.props.repository} fetchData={this.fetchRepositoryData}>
        {repoData => this.renderWithRepositoryData(repoData, tokenData.token)}
      </ObserveModel>
    );
  }

  renderWithRepositoryData(repoData, token) {
    if (!repoData) {
      return <LoadingView />;
    }

    const environment = RelayNetworkLayerManager.getEnvironmentForHost(this.props.host, token);
    const query = graphql`
      query issueishDetailContainerQuery
      (
        $repoOwner: String!
        $repoName: String!
        $issueishNumber: Int!
        $timelineCount: Int!
        $timelineCursor: String
      ) {
        repository(owner: $repoOwner, name: $repoName) {
          ...issueishDetailController_repository @arguments(
            timelineCount: $timelineCount,
            timelineCursor: $timelineCursor,
            issueishNumber: $issueishNumber,
          )
        }
      }
    `;
    const variables = {
      repoOwner: this.props.owner,
      repoName: this.props.repo,
      issueishNumber: this.props.issueishNumber,
      timelineCount: 100,
      timelineCursor: null,
    };

    return (
      <RelayEnvironment environment={environment}>
        <QueryRenderer
          environment={environment}
          query={query}
          variables={variables}
          render={queryResult => this.renderWithResult(queryResult, repoData)}
        />
      </RelayEnvironment>
    );
  }

  renderWithResult({error, props, retry}, repoData) {
    if (error) {
      return (
        <QueryErrorView
          error={error}
          login={this.handleLogin}
          retry={retry}
          logout={this.handleLogout}
        />
      );
    }

    if (!props) {
      return <LoadingView />;
    }

    return (
      <IssueishDetailController
        {...props}
        {...repoData}
        issueishNumber={this.props.issueishNumber}
        onTitleChange={this.props.onTitleChange}
        switchToIssueish={this.props.switchToIssueish}
      />
    );
  }

  handleLogin(token) {
    return this.props.loginModel.setToken(this.props.host, token);
  }

  handleLogout() {
    return this.props.loginModel.removeToken(this.props.host);
  }
}
<commit_msg>Pass bound Repository functions<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import yubikiri from 'yubikiri';
import {QueryRenderer, graphql} from 'react-relay';

import RelayNetworkLayerManager from '../relay-network-layer-manager';
import {GithubLoginModelPropType} from '../prop-types';
import {UNAUTHENTICATED, INSUFFICIENT} from '../shared/keytar-strategy';
import GithubLoginView from '../views/github-login-view';
import LoadingView from '../views/loading-view';
import QueryErrorView from '../views/query-error-view';
import ObserveModel from '../views/observe-model';
import IssueishDetailController from '../controllers/issueish-detail-controller';
import RelayEnvironment from '../views/relay-environment';
import {autobind} from '../helpers';

export default class IssueishDetailContainer extends React.Component {
  static propTypes = {
    host: PropTypes.string,
    owner: PropTypes.string.isRequired,
    repo: PropTypes.string.isRequired,
    issueishNumber: PropTypes.number.isRequired,

    repository: PropTypes.object.isRequired,
    loginModel: GithubLoginModelPropType.isRequired,

    switchToIssueish: PropTypes.func.isRequired,
    onTitleChange: PropTypes.func.isRequired,
  }

  constructor(props) {
    super(props);
    autobind(this,
      'fetchToken', 'renderWithToken',
      'fetchRepositoryData', 'renderWithRepositoryData',
      'renderWithResult',
      'handleLogin', 'handleLogout',
    );
  }

  fetchToken(loginModel) {
    return yubikiri({
      token: loginModel.getToken(this.props.host),
    });
  }

  render() {
    return (
      <ObserveModel model={this.props.loginModel} fetchData={this.fetchToken}>
        {this.renderWithToken}
      </ObserveModel>
    );
  }

  fetchRepositoryData(repository) {
    return yubikiri({
      branches: repository.getBranches(),
      remotes: repository.getRemotes(),
      isMerging: repository.isMerging(),
      isRebasing: repository.isRebasing(),
    });
  }

  renderWithToken(tokenData) {
    if (!tokenData) {
      return <LoadingView />;
    }

    if (tokenData.token === UNAUTHENTICATED) {
      return <GithubLoginView onLogin={this.handleLogin} />;
    }

    if (tokenData.token === INSUFFICIENT) {
      return (
        <GithubLoginView onLogin={this.handleLogin}>

            Your token no longer has sufficient authorizations. Please re-authenticate and generate a new one.

        </GithubLoginView>
      );
    }

    return (
      <ObserveModel model={this.props.repository} fetchData={this.fetchRepositoryData}>
        {repoData => this.renderWithRepositoryData(repoData, tokenData.token)}
      </ObserveModel>
    );
  }

  renderWithRepositoryData(repoData, token) {
    if (!repoData) {
      return <LoadingView />;
    }

    const environment = RelayNetworkLayerManager.getEnvironmentForHost(this.props.host, token);
    const query = graphql`
      query issueishDetailContainerQuery
      (
        $repoOwner: String!
        $repoName: String!
        $issueishNumber: Int!
        $timelineCount: Int!
        $timelineCursor: String
      ) {
        repository(owner: $repoOwner, name: $repoName) {
          ...issueishDetailController_repository @arguments(
            timelineCount: $timelineCount,
            timelineCursor: $timelineCursor,
            issueishNumber: $issueishNumber,
          )
        }
      }
    `;
    const variables = {
      repoOwner: this.props.owner,
      repoName: this.props.repo,
      issueishNumber: this.props.issueishNumber,
      timelineCount: 100,
      timelineCursor: null,
    };

    return (
      <RelayEnvironment environment={environment}>
        <QueryRenderer
          environment={environment}
          query={query}
          variables={variables}
          render={queryResult => this.renderWithResult(queryResult, repoData)}
        />
      </RelayEnvironment>
    );
  }

  renderWithResult({error, props, retry}, repoData) {
    if (error) {
      return (
        <QueryErrorView
          error={error}
          login={this.handleLogin}
          retry={retry}
          logout={this.handleLogout}
        />
      );
    }

    if (!props) {
      return <LoadingView />;
    }

    const {repository} = this.props;

    return (
      <IssueishDetailController
        {...props}
        {...repoData}
        issueishNumber={this.props.issueishNumber}
        fetch={repository.fetch.bind(repository)}
        checkout={repository.checkout.bind(repository)}
        pull={repository.pull.bind(repository)}
        addRemote={repository.addRemote.bind(repository)}
        onTitleChange={this.props.onTitleChange}
        switchToIssueish={this.props.switchToIssueish}
      />
    );
  }

  handleLogin(token) {
    return this.props.loginModel.setToken(this.props.host, token);
  }

  handleLogout() {
    return this.props.loginModel.removeToken(this.props.host);
  }
}
<|endoftext|>


<commit_before>import $ from "jquery";

import render_message_view_header from "../templates/message_view_header.hbs";

import {$t} from "./i18n";
import * as narrow_state from "./narrow_state";
import {page_params} from "./page_params";
import * as peer_data from "./peer_data";
import * as recent_topics_util from "./recent_topics_util";
import * as rendered_markdown from "./rendered_markdown";
import * as search from "./search";

function get_formatted_sub_count(sub_count) {
    if (sub_count >= 1000) {
        // parseInt() is used to floor the value of division to an integer
        sub_count = Number.parseInt(sub_count / 1000, 10) + "k";
    }
    return sub_count;
}

function make_message_view_header(filter) {
    const message_view_header = {};
    if (recent_topics_util.is_visible()) {
        return {
            title: $t({defaultMessage: "Recent topics"}),
            icon: "clock-o",
        };
    }
    if (filter === undefined) {
        return {
            title: $t({defaultMessage: "All messages"}),
            icon: "align-left",
        };
    }
    message_view_header.title = filter.get_title();
    message_view_header.icon = filter.get_icon();
    if (message_view_header.icon === "globe") {
        // This is a bit hacky, but it works as a way to communicate
        // to the HTML template that we need to use the different HTML
        // required for the globe icon.
        message_view_header.web_public_stream = true;
    }
    if (filter.has_operator("stream") && !filter._sub) {
        message_view_header.sub_count = "0";
        message_view_header.formatted_sub_count = "0";
        message_view_header.rendered_narrow_description = $t({
            defaultMessage: "This stream does not exist or is private.",
        });
        return message_view_header;
    }
    if (filter._sub) {
        // We can now be certain that the narrow
        // involves a stream which exists and
        // the current user can access.
        const current_stream = filter._sub;
        message_view_header.rendered_narrow_description = current_stream.rendered_description;
        const sub_count = peer_data.get_subscriber_count(current_stream.stream_id);
        message_view_header.sub_count = sub_count;
        message_view_header.formatted_sub_count = get_formatted_sub_count(sub_count);
        // the "title" is passed as a variable and doesn't get translated (nor should it)
        message_view_header.sub_count_tooltip_text = $t(
            {defaultMessage: "This stream has {count} subscribers."},
            {count: message_view_header.sub_count, title: message_view_header.title},
        );
        message_view_header.stream_settings_link =
            "#streams/" + current_stream.stream_id + "/" + current_stream.name;
    }
    return message_view_header;
}

export function colorize_message_view_header() {
    const filter = narrow_state.filter();
    if (filter === undefined || !filter._sub) {
        return;
    }
    $("#message_view_header .stream > .fa").css("color", filter._sub.color);
}

function append_and_display_title_area(message_view_header_data) {
    const $message_view_header_elem = $("#message_view_header");
    $message_view_header_elem.empty();
    const rendered = render_message_view_header(message_view_header_data);
    $message_view_header_elem.append(rendered);
    if (message_view_header_data.stream_settings_link) {
        colorize_message_view_header();
    }
    $message_view_header_elem.removeClass("notdisplayed");
    const $content = $message_view_header_elem.find("span.rendered_markdown");
    if ($content) {
        // Update syntax like stream names, emojis, mentions, timestamps.
        rendered_markdown.update_elements($content);
    }
}

function bind_title_area_handlers() {
    $(".search_closed").on("click", (e) => {
        search.initiate_search();
        e.preventDefault();
        e.stopPropagation();
    });

    $("#message_view_header .navbar-click-opens-search").on("click", (e) => {
        if (document.getSelection().type === "Range") {
            // Allow copy/paste to work normally without interference.
            return;
        }

        // Let links behave normally, ie, do nothing if
        if ($(e.target).closest("a").length === 0) {
            search.initiate_search();
            e.preventDefault();
            e.stopPropagation();
        }
    });

    // handler that makes sure that hover plays nicely
    // with whether search is being opened or not.
    $("#message_view_header .narrow_description > a")
        .on("mouseenter", () => {
            $("#message_view_header .search_closed").css("opacity", 0.5);
        })
        .on("mouseleave", () => {
            $("#message_view_header .search_closed").css("opacity", "");
        });
}

function build_message_view_header(filter) {
    // This makes sure we don't waste time appending
    // message_view_header on a template where it's never used
    if (filter && !filter.is_common_narrow()) {
        open_search_bar_and_close_narrow_description();
    } else {
        const message_view_header_data = make_message_view_header(filter);
        append_and_display_title_area(message_view_header_data);
        bind_title_area_handlers();
        if (page_params.search_pills_enabled && $("#search_query").is(":focus")) {
            open_search_bar_and_close_narrow_description();
        } else {
            close_search_bar_and_open_narrow_description();
        }
    }
}

// we rely entirely on this function to ensure
// the searchbar has the right text.
export function reset_searchbox_text() {
    let search_string = narrow_state.search_string();
    if (search_string !== "") {
        if (!page_params.search_pills_enabled && !narrow_state.filter().is_search()) {
            // saves the user a keystroke for quick searches
            search_string = search_string + " ";
        }
        $("#search_query").val(search_string);
    }
}

export function exit_search() {
    const filter = narrow_state.filter();
    if (!filter || filter.is_common_narrow()) {
        // for common narrows, we change the UI (and don't redirect)
        close_search_bar_and_open_narrow_description();
    } else {
        // for "searching narrows", we redirect
        window.location.href = filter.generate_redirect_url();
    }
    $(".app").trigger("focus");
}

export function initialize() {
    render_title_area();

    // register searchbar click handler
    $("#search_exit").on("click", (e) => {
        exit_search();
        e.preventDefault();
        e.stopPropagation();
    });
}

export function render_title_area() {
    const filter = narrow_state.filter();
    build_message_view_header(filter);
}

// This function checks if "modified_sub" which is the stream whose values
// have been updated is the same as the stream which is currently
// narrowed (filter._sub) and rerenders if necessary
export function maybe_rerender_title_area_for_stream(modified_sub) {
    const filter = narrow_state.filter();
    if (filter && filter._sub && filter._sub.stream_id === modified_sub.stream_id) {
        render_title_area();
    }
}

export function open_search_bar_and_close_narrow_description() {
    reset_searchbox_text();
    $(".navbar-search").addClass("expanded");
    $("#message_view_header").addClass("hidden");
}

export function close_search_bar_and_open_narrow_description() {
    const filter = narrow_state.filter();
    if (!(filter && !filter.is_common_narrow())) {
        $(".navbar-search").removeClass("expanded");
        $("#message_view_header").removeClass("hidden");
    }
}
<commit_msg>message_view_header: Color web public stream globe icon.<commit_after>import $ from "jquery";

import render_message_view_header from "../templates/message_view_header.hbs";

import {$t} from "./i18n";
import * as narrow_state from "./narrow_state";
import {page_params} from "./page_params";
import * as peer_data from "./peer_data";
import * as recent_topics_util from "./recent_topics_util";
import * as rendered_markdown from "./rendered_markdown";
import * as search from "./search";

function get_formatted_sub_count(sub_count) {
    if (sub_count >= 1000) {
        // parseInt() is used to floor the value of division to an integer
        sub_count = Number.parseInt(sub_count / 1000, 10) + "k";
    }
    return sub_count;
}

function make_message_view_header(filter) {
    const message_view_header = {};
    if (recent_topics_util.is_visible()) {
        return {
            title: $t({defaultMessage: "Recent topics"}),
            icon: "clock-o",
        };
    }
    if (filter === undefined) {
        return {
            title: $t({defaultMessage: "All messages"}),
            icon: "align-left",
        };
    }
    message_view_header.title = filter.get_title();
    message_view_header.icon = filter.get_icon();
    if (message_view_header.icon === "globe") {
        // This is a bit hacky, but it works as a way to communicate
        // to the HTML template that we need to use the different HTML
        // required for the globe icon.
        message_view_header.web_public_stream = true;
    }
    if (filter.has_operator("stream") && !filter._sub) {
        message_view_header.sub_count = "0";
        message_view_header.formatted_sub_count = "0";
        message_view_header.rendered_narrow_description = $t({
            defaultMessage: "This stream does not exist or is private.",
        });
        return message_view_header;
    }
    if (filter._sub) {
        // We can now be certain that the narrow
        // involves a stream which exists and
        // the current user can access.
        const current_stream = filter._sub;
        message_view_header.rendered_narrow_description = current_stream.rendered_description;
        const sub_count = peer_data.get_subscriber_count(current_stream.stream_id);
        message_view_header.sub_count = sub_count;
        message_view_header.formatted_sub_count = get_formatted_sub_count(sub_count);
        // the "title" is passed as a variable and doesn't get translated (nor should it)
        message_view_header.sub_count_tooltip_text = $t(
            {defaultMessage: "This stream has {count} subscribers."},
            {count: message_view_header.sub_count, title: message_view_header.title},
        );
        message_view_header.stream_settings_link =
            "#streams/" + current_stream.stream_id + "/" + current_stream.name;
    }
    return message_view_header;
}

export function colorize_message_view_header() {
    const filter = narrow_state.filter();
    if (filter === undefined || !filter._sub) {
        return;
    }
    // selecting i instead of .fa because web public streams have custom icon.
    $("#message_view_header a.stream i").css("color", filter._sub.color);
}

function append_and_display_title_area(message_view_header_data) {
    const $message_view_header_elem = $("#message_view_header");
    $message_view_header_elem.empty();
    const rendered = render_message_view_header(message_view_header_data);
    $message_view_header_elem.append(rendered);
    if (message_view_header_data.stream_settings_link) {
        colorize_message_view_header();
    }
    $message_view_header_elem.removeClass("notdisplayed");
    const $content = $message_view_header_elem.find("span.rendered_markdown");
    if ($content) {
        // Update syntax like stream names, emojis, mentions, timestamps.
        rendered_markdown.update_elements($content);
    }
}

function bind_title_area_handlers() {
    $(".search_closed").on("click", (e) => {
        search.initiate_search();
        e.preventDefault();
        e.stopPropagation();
    });

    $("#message_view_header .navbar-click-opens-search").on("click", (e) => {
        if (document.getSelection().type === "Range") {
            // Allow copy/paste to work normally without interference.
            return;
        }

        // Let links behave normally, ie, do nothing if
        if ($(e.target).closest("a").length === 0) {
            search.initiate_search();
            e.preventDefault();
            e.stopPropagation();
        }
    });

    // handler that makes sure that hover plays nicely
    // with whether search is being opened or not.
    $("#message_view_header .narrow_description > a")
        .on("mouseenter", () => {
            $("#message_view_header .search_closed").css("opacity", 0.5);
        })
        .on("mouseleave", () => {
            $("#message_view_header .search_closed").css("opacity", "");
        });
}

function build_message_view_header(filter) {
    // This makes sure we don't waste time appending
    // message_view_header on a template where it's never used
    if (filter && !filter.is_common_narrow()) {
        open_search_bar_and_close_narrow_description();
    } else {
        const message_view_header_data = make_message_view_header(filter);
        append_and_display_title_area(message_view_header_data);
        bind_title_area_handlers();
        if (page_params.search_pills_enabled && $("#search_query").is(":focus")) {
            open_search_bar_and_close_narrow_description();
        } else {
            close_search_bar_and_open_narrow_description();
        }
    }
}

// we rely entirely on this function to ensure
// the searchbar has the right text.
export function reset_searchbox_text() {
    let search_string = narrow_state.search_string();
    if (search_string !== "") {
        if (!page_params.search_pills_enabled && !narrow_state.filter().is_search()) {
            // saves the user a keystroke for quick searches
            search_string = search_string + " ";
        }
        $("#search_query").val(search_string);
    }
}

export function exit_search() {
    const filter = narrow_state.filter();
    if (!filter || filter.is_common_narrow()) {
        // for common narrows, we change the UI (and don't redirect)
        close_search_bar_and_open_narrow_description();
    } else {
        // for "searching narrows", we redirect
        window.location.href = filter.generate_redirect_url();
    }
    $(".app").trigger("focus");
}

export function initialize() {
    render_title_area();

    // register searchbar click handler
    $("#search_exit").on("click", (e) => {
        exit_search();
        e.preventDefault();
        e.stopPropagation();
    });
}

export function render_title_area() {
    const filter = narrow_state.filter();
    build_message_view_header(filter);
}

// This function checks if "modified_sub" which is the stream whose values
// have been updated is the same as the stream which is currently
// narrowed (filter._sub) and rerenders if necessary
export function maybe_rerender_title_area_for_stream(modified_sub) {
    const filter = narrow_state.filter();
    if (filter && filter._sub && filter._sub.stream_id === modified_sub.stream_id) {
        render_title_area();
    }
}

export function open_search_bar_and_close_narrow_description() {
    reset_searchbox_text();
    $(".navbar-search").addClass("expanded");
    $("#message_view_header").addClass("hidden");
}

export function close_search_bar_and_open_narrow_description() {
    const filter = narrow_state.filter();
    if (!(filter && !filter.is_common_narrow())) {
        $(".navbar-search").removeClass("expanded");
        $("#message_view_header").removeClass("hidden");
    }
}
<|endoftext|>


<commit_before>function StoryScreen() {
    this.element = new createjs.Container();
}

StoryScreen.prototype.start = function() {

};

StoryScreen.prototype.reset = function() {
    this.element.removeAllChildren();
};

module.exports = StoryScreen;
<commit_msg>we can haz speech bubblz<commit_after>var GameConsts = require('./../GameConsts');

function StoryScreen() {
    this.element = new createjs.Container();
}

StoryScreen.prototype.start = function() {
	this.drawBubble(100, 200, 'Hello');
	this.drawBubble(GameConsts.GAME_WIDTH - 400, 300, 'Hi', true);
};

StoryScreen.prototype.reset = function() {
    this.element.removeAllChildren();
};

StoryScreen.prototype.drawBubble = function(x, y, text, isRight) {
	var w = 300;
	var h = 150;
	var r = x + w;
	var b = y + h;
	var radius = 10;

	var container = new createjs.Container();
	container.x = x;
	container.y = y;

	var bubble = new createjs.Shape();

	x= y = 0;

	bubble.graphics
		.beginFill('#fff')
		.beginStroke('#000')
		.setStrokeStyle(3)
		.moveTo(x + radius, y)
		.lineTo(x + radius / 2, y - 10)
		.lineTo(x + radius * 2, y)
		.lineTo(r - radius, y)
		.quadraticCurveTo(r, y, r, y + radius)
		.lineTo(r, y + h - radius)
		.quadraticCurveTo(r, b, r - radius, b)
		.lineTo(x + radius, b)
		.quadraticCurveTo(x, b, x, b - radius)
		.lineTo(x, y + radius)
		.quadraticCurveTo(x, y, x + radius, y)
		.closePath();

	bubble.scaleY = -1;
	bubble.y = h;

	if (isRight) {
		bubble.scaleX = -1;
		bubble.x = w;
	}

	container.addChild(bubble);

	var textElement = new createjs.Text(text, '25px Komika', '#000');
	textElement.x = 0;
	textElement.y = 0;
	container.addChild(textElement);

	this.element.addChild(container);
};

module.exports = StoryScreen;
<|endoftext|>


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

var challengeServices = angular.module('challengeServices', [
    'ngResource',
    'globalServices']);

challengeServices.service('challengeService', [
    '$resource',
    '$rootScope',
    '$cacheFactory',
    '$timeout',
    function($resource, $rootScope, $cacheFactory, $timeout) {
      var cache = $cacheFactory('challengeCache');
      var cacheTimeout = 30000;
      var res = $resource('/api/challenges/:cid', {}, {
        'get': {method: 'GET', cache: cache},
        'save': {method: 'PUT'},
        'create': {method: 'POST'},
      });
      this.get = res.get;
      this.save = function() {
        cache.removeAll();
        return res.save.apply(res, arguments);
      };
      this.create = function() {
        cache.removeAll();
        return res.create.apply(res, arguments);
      };
      this.flush = cache.removeAll;
      $rootScope.$on('correctAnswer', cache.removeAll);
      return this;
    }]);

challengeServices.service('tagService', [
    '$resource',
    '$rootScope',
    '$cacheFactory',
    '$timeout',
    function($resource, $rootScope, $cacheFactory, $timeout) {
        var tagCache = $cacheFactory('tagCache');

        this.res = $resource('/api/tags/:tagslug', {}, {
            'get': {method: 'GET', tagCache},
            'save': {method: 'PUT'},
            'create': {method: 'POST'},
        })

        this.get = this.res.get;
        this.save = this.res.save;
        this.create = this.res.create;
        this.delete = this.res.delete;

        this.getList = function(callback) {
            if (this.taglist) {
                callback(this.taglist);
                return;
            }
            this.res.get(angular.bind(this, function(data) {
                this.taglist = data;
                $timeout(
                    angular.bind(this, function() {
                        this.taglist = null;
                        tagCache.removeAll();
                    }),
                30000, false);
                callback(data);
            }))
            $rootScope.$on('$locationChangeSuccess', function() {
                this.taglist = null;
                tagCache.removeAll();
            });
        }

    }
])

challengeServices.service('attachService', [
    '$resource',
    '$rootScope',
    '$cacheFactory',
    '$timeout',
    function($resource, $rootScope, $cacheFactory, $timeout) {
        var attachCache = $cacheFactory('attachCache');

        this.res = $resource('/api/attachments/:aid', {}, {
            'get': {method: 'GET', attachCache},
            'save': {method: 'PUT'},
        })

        this.get = this.res.get;
        this.create = this.res.create;
        this.save = this.res.save;
        this.delete = this.res.delete;

        this.getList = function(callback) {
            if (this.attachlist) {
                callback(this.attachlist);
                return;
            }
            this.res.get(angular.bind(this, function(data) {
                this.attachlist = data;
                $timeout(
                    angular.bind(this, function() {
                        this.attachlist = null;
                        attachCache.removeAll();
                    }),
                30000, false);
                callback(data);
            }))
            $rootScope.$on('$locationChangeSuccess', function() {
                this.attachlist = null;
                attachCache.removeAll();
            });
        }

    }
])

challengeServices.service('answerService', [
    '$resource',
    '$rootScope',
    function($resource, $rootScope) {
      this.res = $resource('/api/answers/:aid', {}, {
        'create': {method: 'POST'}
      });
      this.create = function(what, success, failure) {
        this.res.create(what,
            function(resp) {
              success(resp);
              $rootScope.$broadcast('correctAnswer');
            },
            failure);
      };
    }]);

challengeServices.service('validatorService', [
    '$resource',
    '$rootScope',
    function($resource, $rootScope) {
      this.res = $resource('/api/validator', {}, {
        'create': {method: 'POST'}
      });
      this.create = function(what, success, failure) {
        this.res.create(what,
            function(resp) {
              success(resp);
            },
            failure);
      };
    }]);

challengeServices.service('scoreService', [
    'configService',
    function(configService) {
      this.scoring = 'plain';
      configService.get(angular.bind(this, function(cfg) {
        this.scoring = cfg.scoring;
      }));
      this.getCurrentPoints = function(challenge) {
        if (!challenge)
          return 0;
        if (this.scoring === 'plain')
          return challenge.points;
        if (this.scoring === 'progressive')
          return Math.floor(challenge.points / Math.max(challenge.solves, 1));
      };
    }])
<commit_msg>Add the missing delete method.  Fixes #190.<commit_after>/**
 * Copyright 2018 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var challengeServices = angular.module('challengeServices', [
    'ngResource',
    'globalServices']);

challengeServices.service('challengeService', [
    '$resource',
    '$rootScope',
    '$cacheFactory',
    '$timeout',
    function($resource, $rootScope, $cacheFactory, $timeout) {
      var cache = $cacheFactory('challengeCache');
      var cacheTimeout = 30000;
      var res = $resource('/api/challenges/:cid', {}, {
        'get': {method: 'GET', cache: cache},
        'save': {method: 'PUT'},
        'create': {method: 'POST'},
        'delete': {method: 'DELETE'},
      });
      this.get = res.get;
      this.delete = res.delete;
      this.save = function() {
        cache.removeAll();
        return res.save.apply(res, arguments);
      };
      this.create = function() {
        cache.removeAll();
        return res.create.apply(res, arguments);
      };
      this.flush = cache.removeAll;
      $rootScope.$on('correctAnswer', cache.removeAll);
      return this;
    }]);

challengeServices.service('tagService', [
    '$resource',
    '$rootScope',
    '$cacheFactory',
    '$timeout',
    function($resource, $rootScope, $cacheFactory, $timeout) {
        var tagCache = $cacheFactory('tagCache');

        this.res = $resource('/api/tags/:tagslug', {}, {
            'get': {method: 'GET', tagCache},
            'save': {method: 'PUT'},
            'create': {method: 'POST'},
        })

        this.get = this.res.get;
        this.save = this.res.save;
        this.create = this.res.create;
        this.delete = this.res.delete;

        this.getList = function(callback) {
            if (this.taglist) {
                callback(this.taglist);
                return;
            }
            this.res.get(angular.bind(this, function(data) {
                this.taglist = data;
                $timeout(
                    angular.bind(this, function() {
                        this.taglist = null;
                        tagCache.removeAll();
                    }),
                30000, false);
                callback(data);
            }))
            $rootScope.$on('$locationChangeSuccess', function() {
                this.taglist = null;
                tagCache.removeAll();
            });
        }

    }
])

challengeServices.service('attachService', [
    '$resource',
    '$rootScope',
    '$cacheFactory',
    '$timeout',
    function($resource, $rootScope, $cacheFactory, $timeout) {
        var attachCache = $cacheFactory('attachCache');

        this.res = $resource('/api/attachments/:aid', {}, {
            'get': {method: 'GET', attachCache},
            'save': {method: 'PUT'},
        })

        this.get = this.res.get;
        this.create = this.res.create;
        this.save = this.res.save;
        this.delete = this.res.delete;

        this.getList = function(callback) {
            if (this.attachlist) {
                callback(this.attachlist);
                return;
            }
            this.res.get(angular.bind(this, function(data) {
                this.attachlist = data;
                $timeout(
                    angular.bind(this, function() {
                        this.attachlist = null;
                        attachCache.removeAll();
                    }),
                30000, false);
                callback(data);
            }))
            $rootScope.$on('$locationChangeSuccess', function() {
                this.attachlist = null;
                attachCache.removeAll();
            });
        }

    }
])

challengeServices.service('answerService', [
    '$resource',
    '$rootScope',
    function($resource, $rootScope) {
      this.res = $resource('/api/answers/:aid', {}, {
        'create': {method: 'POST'}
      });
      this.create = function(what, success, failure) {
        this.res.create(what,
            function(resp) {
              success(resp);
              $rootScope.$broadcast('correctAnswer');
            },
            failure);
      };
    }]);

challengeServices.service('validatorService', [
    '$resource',
    '$rootScope',
    function($resource, $rootScope) {
      this.res = $resource('/api/validator', {}, {
        'create': {method: 'POST'}
      });
      this.create = function(what, success, failure) {
        this.res.create(what,
            function(resp) {
              success(resp);
            },
            failure);
      };
    }]);

challengeServices.service('scoreService', [
    'configService',
    function(configService) {
      this.scoring = 'plain';
      configService.get(angular.bind(this, function(cfg) {
        this.scoring = cfg.scoring;
      }));
      this.getCurrentPoints = function(challenge) {
        if (!challenge)
          return 0;
        if (this.scoring === 'plain')
          return challenge.points;
        if (this.scoring === 'progressive')
          return Math.floor(challenge.points / Math.max(challenge.solves, 1));
      };
    }])
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var chalk = require('chalk');

module.exports = function(plugin, manager) {

  manager.registerTask('list', function(){
    var i = 1;
    manager.getApps(function(apps) {
      console.log('');

      _(apps).each(function(a) {
        var status = '';
        if (a.status == 'enabled') {
          status = 'Enabled';
          console.log(chalk.green(" " + i + ". " + a.config.title + " (" + a.name + ")\t\t", a.url + "\t\t", status));
        }
        else if (a.status == 'disabled') {
          status = 'Disabled';
          console.log(chalk.magenta(" " + i + ". " + a.config.title + " (" + a.name + ")\t\t", a.url + "\t\t", status));
        }
        else {
          status = 'Uninstalled';
          console.log(chalk.red(" " + i + ". " + a.config.title + " (" + a.name + ")\t\t", a.url + "\t\t", status));
        }
        i++;
      });
      console.log('');
    });
  });

};<commit_msg>added purge task<commit_after>'use strict';

var _ = require('lodash');
var chalk = require('chalk');

module.exports = function(plugin, manager) {
  manager.registerTask('list', function(){
    var i = 1;
    manager.getApps(function(apps) {
      console.log('');

      _(apps).each(function(a) {
        var status = '';
        if (a.status == 'enabled') {
          status = 'Enabled';
          console.log(chalk.green(" " + i + ". " + a.config.title + " (" + a.name + ")\t\t", a.url + "\t\t", status));
        }
        else if (a.status == 'disabled') {
          status = 'Disabled';
          console.log(chalk.magenta(" " + i + ". " + a.config.title + " (" + a.name + ")\t\t", a.url + "\t\t", status));
        }
        else {
          status = 'Uninstalled';
          console.log(chalk.red(" " + i + ". " + a.config.title + " (" + a.name + ")\t\t", a.url + "\t\t", status));
        }
        i++;
      });
      console.log('');
    });
  });

  manager.registerTask('pc', function(){
    manager.purgeContainers(function(){
      console.log(container);
    });
  });
};<|endoftext|>


<commit_before>
// Grab configuration blob and construct our graph urls
var renderGraphs = function() {
  var myUrl = window.location.pathname;
  if (mySearchString.length > 0) {
    myUrl += '?search=' + encodeURI(mySearchString);
  }
  return $.ajax({
    accepts: {json: 'application/json'},
    cache: false,
    dataType: 'json',
    error: function(xhr, textStatus, errorThrown) { console.log(errorThrown); },
    url: myUrl
  }).done(function(d) {
    if (d.graphs.length === 0) {
      console.log('No graphs found');
    }
    var row = 0;
    $('div.graphs').append('

');
    for (var i=0; i < d.graphs.length; i++) {
      var targets = [];
      for (var j in $.parseJSON(d.graphs[i].configuration).target) {
        targets.push({name: $.parseJSON(d.graphs[i].configuration).target[j]});
      }
      var c = $.extend($.parseJSON(d.graphs[i].configuration), $.parseJSON(d.graphs[i].overrides), {targets: targets});
      row = Math.floor( i / myColumns );
      var spanSize = ( 12 / myColumns );
      if (($('div.graphs div.row').length - 1) !== row) {
        $('div.graphs').append('

');
      }
      $($('div.graphs div.row')[row]).append('
');
      var myGraphWidth = $($('div.row span.graph')[0]).width();
      var graphCloseIcon = '';
      $('div.graphs div.row span#' + d.graphs[i].uuid).append('' + d.graphs[i].name + '');
      $('div.graphs div.row span#' + d.graphs[i].uuid).append('');
      $('div.graphs div.row span.graph img').load(function() {
        // hide spinner on successful load
        $(this).parent('a').parent('span').css('background-image', 'none')
      }).error(function() {
        console.log('failed to load ' + $(this)[0].name);
        var broken_img = $(this);
        // hide spinner and set background color
        broken_img.css('display', 'none');
        broken_img.parent('a').parent('span').css('background-image', 'none').css('background-color', '#eee')
        broken_img.parent('a').parent('span').find('label').css('margin', '10px 0 0 15px');
        // change label and link to image profile
        broken_img.parent('a').parent('span').find('label').html('Unable to load ' + broken_img[0].alt + '');
      });
    }
    selectActiveColumnButton();
    selectActiveIntervalButton();
    setImageDestroyMode();
    renderTitle();
  });
};

// Not used in dashboards
var scrollNextPage = function() {
  return true;
}
<commit_msg>bind [un]favoriting events to the star states<commit_after>
// Grab configuration blob and construct our graph urls
var renderGraphs = function() {
  var myUrl = window.location.pathname;
  if (mySearchString.length > 0) {
    myUrl += '?search=' + encodeURI(mySearchString);
  }
  return $.ajax({
    accepts: {json: 'application/json'},
    cache: false,
    dataType: 'json',
    error: function(xhr, textStatus, errorThrown) { console.log(errorThrown); },
    url: myUrl
  }).done(function(d) {
    if (d.graphs.length === 0) {
      console.log('No graphs found');
    }
    var row = 0;
    $('div.graphs').append('

');
    for (var i=0; i < d.graphs.length; i++) {
      var targets = [];
      for (var j in $.parseJSON(d.graphs[i].configuration).target) {
        targets.push({name: $.parseJSON(d.graphs[i].configuration).target[j]});
      }
      var c = $.extend($.parseJSON(d.graphs[i].configuration), $.parseJSON(d.graphs[i].overrides), {targets: targets});
      row = Math.floor( i / myColumns );
      var spanSize = ( 12 / myColumns );
      if (($('div.graphs div.row').length - 1) !== row) {
        $('div.graphs').append('

');
      }
      $($('div.graphs div.row')[row]).append('
');
      var myGraphWidth = $($('div.row span.graph')[0]).width();
      var graphCloseIcon = '';
      $('div.graphs div.row span#' + d.graphs[i].uuid).append('' + d.graphs[i].name + '');
      $('div.graphs div.row span#' + d.graphs[i].uuid).append('');
      $('div.graphs div.row span.graph img').load(function() {
        // hide spinner on successful load
        $(this).parent('a').parent('span').css('background-image', 'none')
      }).error(function() {
        console.log('failed to load ' + $(this)[0].name);
        var broken_img = $(this);
        // hide spinner and set background color
        broken_img.css('display', 'none');
        broken_img.parent('a').parent('span').css('background-image', 'none').css('background-color', '#eee')
        broken_img.parent('a').parent('span').find('label').css('margin', '10px 0 0 15px');
        // change label and link to image profile
        broken_img.parent('a').parent('span').find('label').html('Unable to load ' + broken_img[0].alt + '');
      });
    }
    selectActiveColumnButton();
    selectActiveIntervalButton();
    setImageDestroyMode();
    renderTitle();
  });
};

// bind the favorite() action to an inactive star
$('span.star').on('click', 'a.inactive', function() {
  $('.star a').addClass('active')
  $('.star a').removeClass('inactive')
  console.log('making active')
})

// bind the unfavorite() action to an active star
$('span.star').on('click', 'a.active', function() {
  $('.star a').addClass('inactive')
  $('.star a').removeClass('active')
  console.log('making inactive')
})

// Not used in dashboards
var scrollNextPage = function() {
  return true;
}
<|endoftext|>


<commit_before>"use strict";
var AbstractConnectionManager = require('../abstract/connection-manager')
  , ConnectionManager
  , Utils = require('../../utils')
  , Promise = require('../../promise');

ConnectionManager = function(dialect, sequelize) {
  AbstractConnectionManager.call(this, dialect, sequelize);

  this.sequelize = sequelize;
  this.sequelize.config.port = this.sequelize.config.port || 5432;
  try {
    this.lib = sequelize.config.native ? require(sequelize.config.dialectModulePath || 'pg').native : require(sequelize.config.dialectModulePath || 'pg');
  } catch (err) {
    throw new Error('Please install postgres package manually');
  }
};

Utils._.extend(ConnectionManager.prototype, AbstractConnectionManager.prototype);

ConnectionManager.prototype.connect = function(config) {
  var self = this
    , connectionConfig = {};

  config.user = config.username;
  connectionConfig = Utils._.pick(config, [
    'user', 'password', 'host', 'database', 'port'
  ]);

  if (config.dialectOptions) {
    Utils._.merge(connectionConfig,
                  Utils._.pick(config.dialectOptions, [
      // see [http://www.postgresql.org/docs/9.3/static/runtime-config-logging.html#GUC-APPLICATION-NAME]
      'application_name',
      // choose the SSL mode with the PGSSLMODE environment variable
      // object format: [https://github.com/brianc/node-postgres/blob/master/lib/connection.js#L79]
      // see also [http://www.postgresql.org/docs/9.3/static/libpq-ssl.html]
      'ssl',
      // In addition to the values accepted by the corresponding server,
      // you can use "auto" to determine the right encoding from the
      // current locale in the client (LC_CTYPE environment variable on Unix systems)
      'client_encoding',
      // !! DONT SET THIS TO TRUE !!
      // (unless you know what you're doing)
      // see [http://www.postgresql.org/message-id/flat/bc9549a50706040852u27633f41ib1e6b09f8339d845@mail.gmail.com#bc9549a50706040852u27633f41ib1e6b09f8339d845@mail.gmail.com]
      'binary'
    ]));
  }

  return new Promise(function (resolve, reject) {
    var connection = new self.lib.Client(connectionConfig)
      , responded = false;

    connection.connect(function(err) {
      if (err) {
        if (err.code) {
          switch (err.code) {
          case 'ECONNREFUSED':
            reject(new Error('Failed to authenticate for PostgresSQL. Please double check your settings.'));
            break;
          case 'ENOTFOUND':
          case 'EHOSTUNREACH':
          case 'EINVAL':
            reject(new Error('Failed to find PostgresSQL server. Please double check your settings.'));
            break;
          default:
            reject(err);
            break;
          }
        } else {
          reject(new Error(err.message));
        }
        return;
      }
      responded = true;
      resolve(connection);
    });

    // If we didn't ever hear from the client.connect() callback the connection timeout, node-postgres does not treat this as an error since no active query was ever emitted
    connection.on('end', function () {
      if (!responded) {
        reject(new Error('Connection timed out'));
      }
    });
  }).tap(function (connection) {
    if (self.sequelize.config.keepDefaultTimezone) return;
    return new Promise(function (resolve, reject) {
      connection.query("SET TIME ZONE INTERVAL '" + self.sequelize.options.timezone + "' HOUR TO MINUTE").on('error', function (err) {
        reject(err);
      }).on('end', function () {
        resolve();
      });
    });
  });
};
ConnectionManager.prototype.disconnect = function(connection) {
  return new Promise(function (resolve, reject) {
    connection.end();
    resolve();
  });
};

module.exports = ConnectionManager;
<commit_msg>Mark a pg connection as invalid on connection err. Builds on PR #2557 by @jawj<commit_after>"use strict";
var AbstractConnectionManager = require('../abstract/connection-manager')
  , ConnectionManager
  , Utils = require('../../utils')
  , Promise = require('../../promise');

ConnectionManager = function(dialect, sequelize) {
  AbstractConnectionManager.call(this, dialect, sequelize);

  this.sequelize = sequelize;
  this.sequelize.config.port = this.sequelize.config.port || 5432;
  try {
    this.lib = sequelize.config.native ? require(sequelize.config.dialectModulePath || 'pg').native : require(sequelize.config.dialectModulePath || 'pg');
  } catch (err) {
    throw new Error('Please install postgres package manually');
  }
};

Utils._.extend(ConnectionManager.prototype, AbstractConnectionManager.prototype);

ConnectionManager.prototype.connect = function(config) {
  var self = this
    , connectionConfig = {};

  config.user = config.username;
  connectionConfig = Utils._.pick(config, [
    'user', 'password', 'host', 'database', 'port'
  ]);

  if (config.dialectOptions) {
    Utils._.merge(connectionConfig,
                  Utils._.pick(config.dialectOptions, [
      // see [http://www.postgresql.org/docs/9.3/static/runtime-config-logging.html#GUC-APPLICATION-NAME]
      'application_name',
      // choose the SSL mode with the PGSSLMODE environment variable
      // object format: [https://github.com/brianc/node-postgres/blob/master/lib/connection.js#L79]
      // see also [http://www.postgresql.org/docs/9.3/static/libpq-ssl.html]
      'ssl',
      // In addition to the values accepted by the corresponding server,
      // you can use "auto" to determine the right encoding from the
      // current locale in the client (LC_CTYPE environment variable on Unix systems)
      'client_encoding',
      // !! DONT SET THIS TO TRUE !!
      // (unless you know what you're doing)
      // see [http://www.postgresql.org/message-id/flat/bc9549a50706040852u27633f41ib1e6b09f8339d845@mail.gmail.com#bc9549a50706040852u27633f41ib1e6b09f8339d845@mail.gmail.com]
      'binary'
    ]));
  }

  return new Promise(function (resolve, reject) {
    var connection = new self.lib.Client(connectionConfig)
      , responded = false;

    connection.connect(function(err) {
      if (err) {
        if (err.code) {
          switch (err.code) {
          case 'ECONNREFUSED':
            reject(new Error('Failed to authenticate for PostgresSQL. Please double check your settings.'));
            break;
          case 'ENOTFOUND':
          case 'EHOSTUNREACH':
          case 'EINVAL':
            reject(new Error('Failed to find PostgresSQL server. Please double check your settings.'));
            break;
          default:
            reject(err);
            break;
          }
        } else {
          reject(new Error(err.message));
        }
        return;
      }
      responded = true;
      resolve(connection);
    });

    // If we didn't ever hear from the client.connect() callback the connection timeout, node-postgres does not treat this as an error since no active query was ever emitted
    connection.on('end', function () {
      if (!responded) {
        reject(new Error('Connection timed out'));
      }
    });

    // Don't let a Postgres restart (or error) to take down the whole app
    connection.on('error', function(err, client) {
      connection._invalid = true;
    });
  }).tap(function (connection) {
    if (self.sequelize.config.keepDefaultTimezone) return;
    return new Promise(function (resolve, reject) {
      connection.query("SET TIME ZONE INTERVAL '" + self.sequelize.options.timezone + "' HOUR TO MINUTE").on('error', function (err) {
        reject(err);
      }).on('end', function () {
        resolve();
      });
    });
  });
};
ConnectionManager.prototype.disconnect = function(connection) {
  return new Promise(function (resolve, reject) {
    connection.end();
    resolve();
  });
};

ConnectionManager.prototype.validate = function(connection) {
  return connection._invalid === undefined;
};

module.exports = ConnectionManager;
<|endoftext|>


<commit_before>var creep_Kebab = {

    /** @param {Creep} creep **/
    run: function(creep) {
        if (Game.flags["RemoveKebab"] && Game.flags["RemoveKebab"].pos.roomName != creep.pos.roomName) {
            if (creep.memory.path) {
                creep.moveTo(new RoomPosition(25, 25, creep.memory.path[0]));
                if (creep.memory.path[0] == creep.room.name) {
                    creep.memory.path.splice(0, 1);
                    if (creep.memory.path.length == 0) {
                        creep.memory.path = undefined;
                    }
                }
            } else {
                if (Game.flags["WallFlag"] && Game.flags["WallFlag"].pos) {
                    creep.moveTo(Game.flags["WallFlag"], {
                        reusePath: 25
                    });
                } else if (Game.flags["RemoveKebab"].pos) {
                    creep.moveTo(Game.flags["RemoveKebab"], {
                        reusePath: 25
                    });
                } else {
                    creep.moveTo(new RoomPosition(25, 25, Game.flags["RemoveKebab"].pos.roomName), {
                        reusePath: 25
                    });
                }
            }
        } else if (Game.flags["RemoveKebab"]) {
            //In target room
            var somethingNearby = creep.pos.findClosestByRange(FIND_STRUCTURES);
            if (somethingNearby) {
                creep.dismantle(somethingNearby);
            }

            if (Game.flags["WallFlag"]) {
                var thisWall = Game.flags["WallFlag"].pos.lookFor(LOOK_STRUCTURES);
                if (thisWall.length) {
                    creep.moveTo(thisWall[0]);
                    creep.dismantle(thisWall[0]);
                } else {
                    Game.flags["WallFlag"].remove();
                }
            } else if (creep.memory.targetSpawn) {
                var thisSpawn = Game.getObjectById(creep.memory.targetSpawn);
                if (thisSpawn) {
                    creep.moveTo(thisSpawn, {
                        maxRooms: 1
                    });
                    creep.dismantle(thisSpawn);
                } else {
                    creep.memory.targetSpawn = undefined;
                }
            } else {
                var eExt = creep.pos.findClosestByRange(FIND_HOSTILE_STRUCTURES, {
                    filter: (structure) => (structure.structureType == STRUCTURE_EXTENSION || structure.structureType == STRUCTURE_TOWER)
                });
                if (eExt) {
                    creep.moveTo(eExt, {
                        maxRooms: 1
                    });
                    creep.dismantle(eExt);
                } else {
                    var eSpawns = creep.room.find(FIND_HOSTILE_SPAWNS);
                    if (eSpawns.length) {
                        creep.memory.targetSpawn = eSpawns[Math.floor(Math.random() * eSpawns.length)].id;
                        var thisSpawn = Game.getObjectById(creep.memory.targetSpawn);
                        if (thisSpawn) {
                            creep.moveTo(thisSpawn, {
                                maxRooms: 1
                            });
                            creep.dismantle(thisSpawn);
                        }
                    } else {
                        //Assume we're done here.
                        if (Game.flags["RemoveKebab"]) {
                            Game.flags["RemoveKebab"].remove();
                        }
                    }
                }
            }
        }
    }
};

module.exports = creep_Kebab;<commit_msg>don't wreck roads<commit_after>var creep_Kebab = {

    /** @param {Creep} creep **/
    run: function(creep) {
        if (Game.flags["RemoveKebab"] && Game.flags["RemoveKebab"].pos.roomName != creep.pos.roomName) {
            if (creep.memory.path) {
                creep.moveTo(new RoomPosition(25, 25, creep.memory.path[0]));
                if (creep.memory.path[0] == creep.room.name) {
                    creep.memory.path.splice(0, 1);
                    if (creep.memory.path.length == 0) {
                        creep.memory.path = undefined;
                    }
                }
            } else {
                if (Game.flags["WallFlag"] && Game.flags["WallFlag"].pos) {
                    creep.moveTo(Game.flags["WallFlag"], {
                        reusePath: 25
                    });
                } else if (Game.flags["RemoveKebab"].pos) {
                    creep.moveTo(Game.flags["RemoveKebab"], {
                        reusePath: 25
                    });
                } else {
                    creep.moveTo(new RoomPosition(25, 25, Game.flags["RemoveKebab"].pos.roomName), {
                        reusePath: 25
                    });
                }
            }
        } else if (Game.flags["RemoveKebab"]) {
            //In target room
            var somethingNearby = creep.pos.findClosestByRange(FIND_STRUCTURES, {
                filter: (structure) => (structure.structureType != STRUCTURE_ROAD)
            });
            if (somethingNearby) {
                creep.dismantle(somethingNearby);
            }

            if (Game.flags["WallFlag"]) {
                var thisWall = Game.flags["WallFlag"].pos.lookFor(LOOK_STRUCTURES);
                if (thisWall.length) {
                    creep.moveTo(thisWall[0]);
                    creep.dismantle(thisWall[0]);
                } else {
                    Game.flags["WallFlag"].remove();
                }
            } else if (creep.memory.targetSpawn) {
                var thisSpawn = Game.getObjectById(creep.memory.targetSpawn);
                if (thisSpawn) {
                    creep.moveTo(thisSpawn, {
                        maxRooms: 1
                    });
                    creep.dismantle(thisSpawn);
                } else {
                    creep.memory.targetSpawn = undefined;
                }
            } else {
                var eExt = creep.pos.findClosestByRange(FIND_HOSTILE_STRUCTURES, {
                    filter: (structure) => (structure.structureType == STRUCTURE_EXTENSION || structure.structureType == STRUCTURE_TOWER)
                });
                if (eExt) {
                    creep.moveTo(eExt, {
                        maxRooms: 1
                    });
                    creep.dismantle(eExt);
                } else {
                    var eSpawns = creep.room.find(FIND_HOSTILE_SPAWNS);
                    if (eSpawns.length) {
                        creep.memory.targetSpawn = eSpawns[Math.floor(Math.random() * eSpawns.length)].id;
                        var thisSpawn = Game.getObjectById(creep.memory.targetSpawn);
                        if (thisSpawn) {
                            creep.moveTo(thisSpawn, {
                                maxRooms: 1
                            });
                            creep.dismantle(thisSpawn);
                        }
                    } else {
                        //Assume we're done here.
                        if (Game.flags["RemoveKebab"]) {
                            Game.flags["RemoveKebab"].remove();
                        }
                    }
                }
            }
        }
    }
};

module.exports = creep_Kebab;<|endoftext|>


<commit_before>$(function(){
  $('form').submit(function() {
    message = $(this).find('#message').val();

    $.post('/channel/echo', {message: message});
    return false;
  });

  var render_message = function(client_id, message) {
    $('#messages').append('
' + client_id + '
');
    $('#messages').append('
' + message + '
');
  };

  var connect = function(data) {
    channel = new goog.appengine.Channel(data.token);
    socket = channel.open();

    socket.onopen = function() {
      console.log('channel opened');
    };

    socket.onmessage = function(data) {
      console.log('channel data:');
      console.log(data);

      var data = $.parseJSON(data.data);

      render_message(data.client_id, data.message);
    };

    socket.onerror = function(error) {
      console.log('channel error: code=' + error.code + ' desc=' + error.description);
    };

    socket.onclose = function() {
      console.log('channel closeed');
    };
  };

  $.getJSON('/channel', {client_id: client_id}, connect);
});
<commit_msg>fixed main.js<commit_after>$(function(){
  $('form').submit(function() {
    var message = $(this).find('#message').val();

    $.post('/channel/echo', {message: message});
    return false;
  });

  var render_message = function(client_id, message) {
    $('#messages')
      .append('
' + client_id + '
')
      .append('
' + message + '
');
  };

  var onopen = function() {
    console.log('channel opened');
  };

  var onmessage = function(data) {
    console.log('channel data:');
    console.log(data);

    var data = $.parseJSON(data.data);

    render_message(data.client_id, data.message);
  };

  var onerror = function(error) {
    console.log('channel error: code=' + error.code + ' desc=' + error.description);
  };

  var onclose = function() {
    console.log('channel closeed');
  };

  var connect = function(data) {
    var channel = new goog.appengine.Channel(data.token);
    var socket = channel.open({
      onopen: onopen,
      onmessage: onmessage,
      onerror: onerror,
      onclose: onclose
    });
  };

  $.getJSON('/channel', {client_id: client_id}, connect);
});
<|endoftext|>


<commit_before>const glob = require('glob');
const path = require('path');
const Console = require("./lib/util/console.js");
const Config = require("./lib/core/config.js");
const EXT_JS = ".js";
const DEEP_EXT_JS = "**/*.js";
const FILE_EXT_JS = "*.js";
const MIDDLEWARE_PATH = "lib/middleware/*";
const HANDLER_PATH = "controller";
const DATABASE_PATH = "database";
const UTIL_PATH = "util";

class Smash extends Console {
    constructor() {
        super();
        this._config = new Config();
        this._middlewares = null;
        this._magics = [];
        this._handlers = null;
    }

    _clearExpose() {
        for (let i = 0, length = this._magics.length; i < length; i++) {
            delete this[this._magics[i]];
        }
        this._magics = [];
        return this;
    }

    _processExpose(module) {
        if (typeof module !== 'object' || typeof module.expose !== 'function') {
            this.error("Middlewares must be object with a function called expose, " + this.typeof(module) + ' ' + this.typeof(module.expose) + ' given');
            throw new Error("Middlewares must be object with a function called expose, " + this.typeof(module) + ' ' + this.typeof(module.expose) + ' given');
        }
        const expose = module.expose();
        const that = this;
        for (let i = 0, length = expose.length; i < length; i++) {
            if (this[expose[i].functionName]) {
                this.error("Function " + expose[i].functionName + " already exist in smash, overwrite is not allowed");
                throw new Error("Function " + expose[i].functionName + " already exist in smash, overwrite is not allowed");
            }
            this[expose[i].functionName] = function () {
                module[expose[i].function].apply(module, arguments);
                return that;
            };
            this._magics.push(expose[i].functionName);
        }
        return this;
    }

    _registerMiddlewares() {
        this._clearExpose();
        this._middlewares = [];
        const files = glob.sync(path.join(__dirname, MIDDLEWARE_PATH, FILE_EXT_JS));
        for (let i = 0, length = files.length; i < length; i++) {
            const Module = require(path.resolve(files[i]));
            const module = new Module();
            this._processExpose(module);
            this._middlewares.push(module);
            this.info("Register middleware: " + module.constructor.name);
        }
        return this;
    }

    _clearHandlers() {
        const files = glob.sync(path.resolve(path.join(process.cwd(), HANDLER_PATH, DEEP_EXT_JS)));
        for (let i = 0, length = files.length; i < length; i++) {
            delete require.cache[require.resolve(path.resolve(files[i]))]
        }
        return this;
    }

    _registerHandlers() {
        this._clearHandlers();
        this._handlers = [];
        const files = glob.sync(path.resolve(path.join(process.cwd(), HANDLER_PATH, DEEP_EXT_JS)));
        for (let i = 0, length = files.length; i < length; i++) {
            this._handlers.push(require(path.resolve(files[i])));
        }
        this.info("Handler loaded: " + files.length);
        return this;
    }

    _buildEnv(context) {
        delete this._env;
        this._env = {};
        Object.assign(this._env, process.env);
        this._setEnv("ENV", context.functionVersion);
        Object.freeze(this._env);
        return this;
    }

    boot() {
        this._registerMiddlewares();
        this._registerHandlers();
    }

    handleEvent(event, context, callback) {
        if (this._middlewares === null) {
            this.error("Smash has not been booted, you must call boot() first", event);
            callback(new Error("Smash has not been booted, you must call boot() first"));
        } else {
            this._buildEnv(context);
            for (let i = 0, length = this._middlewares.length; i < length; i++) {
                if (this._middlewares[i].isEvent(event)) {
                    this._middlewares[i].handleEvent(event, context, callback);
                    return this;
                }
            }
            this.error("No middleware found to process event", event);
            callback(new Error("No middleware found to process event"));
        }
        return this;
    }

    get env() {
        return this._env;
    }

    getEnv(key) {
        return this._env[key];
    }

    _setEnv(key, value) {
        this._env[key] = value;
    }

    util(module) {
        if (typeof module !== 'string' || module.length === 0) {
            throw new Error("First parameter of util must be a valid string, " + this.typeOf(module) + "given");
        }
        return require(path.resolve(path.join(process.cwd(), UTIL_PATH, module + EXT_JS)));
    }

    database(module) {
        if (typeof module !== 'string' || module.length === 0) {
            throw new Error("First parameter of util must be a valid string, " + this.typeOf(module) + "given");
        }
        return require(path.resolve(path.join(process.cwd(), DATABASE_PATH, module + EXT_JS)));
    }

    get config() {
        return this._config;
    }

    get Model() {
        return require(path.resolve(path.join(__dirname, "lib/util/model.js")));
    }

    get Console() {
        return require(path.resolve(path.join(__dirname, "lib/util/console.js")));
    }

    set Console(console) {

    }
}

if (!global.smash) {
    global.smash = new Smash();
}
module.exports = global.smash;

<commit_msg>Add error handling when loading handlers<commit_after>const glob = require('glob');
const path = require('path');
const Console = require("./lib/util/console.js");
const Config = require("./lib/core/config.js");
const EXT_JS = ".js";
const DEEP_EXT_JS = "**/*.js";
const FILE_EXT_JS = "*.js";
const MIDDLEWARE_PATH = "lib/middleware/*";
const HANDLER_PATH = "controller";
const DATABASE_PATH = "database";
const UTIL_PATH = "util";

class Smash extends Console {
    constructor() {
        super();
        this._config = new Config();
        this._middlewares = null;
        this._magics = [];
        this._handlers = null;
    }

    _clearExpose() {
        for (let i = 0, length = this._magics.length; i < length; i++) {
            delete this[this._magics[i]];
        }
        this._magics = [];
        return this;
    }

    _processExpose(module) {
        if (typeof module !== 'object' || typeof module.expose !== 'function') {
            this.error("Middlewares must be object with a function called expose, " + this.typeof(module) + ' ' + this.typeof(module.expose) + ' given');
            throw new Error("Middlewares must be object with a function called expose, " + this.typeof(module) + ' ' + this.typeof(module.expose) + ' given');
        }
        const expose = module.expose();
        const that = this;
        for (let i = 0, length = expose.length; i < length; i++) {
            if (this[expose[i].functionName]) {
                this.error("Function " + expose[i].functionName + " already exist in smash, overwrite is not allowed");
                throw new Error("Function " + expose[i].functionName + " already exist in smash, overwrite is not allowed");
            }
            this[expose[i].functionName] = function () {
                module[expose[i].function].apply(module, arguments);
                return that;
            };
            this._magics.push(expose[i].functionName);
        }
        return this;
    }

    _registerMiddlewares() {
        this._clearExpose();
        this._middlewares = [];
        const files = glob.sync(path.join(__dirname, MIDDLEWARE_PATH, FILE_EXT_JS));
        for (let i = 0, length = files.length; i < length; i++) {
            const Module = require(path.resolve(files[i]));
            const module = new Module();
            this._processExpose(module);
            this._middlewares.push(module);
            this.info("Register middleware: " + module.constructor.name);
        }
        return this;
    }

    _clearHandlers() {
        const files = glob.sync(path.resolve(path.join(process.cwd(), HANDLER_PATH, DEEP_EXT_JS)));
        for (let i = 0, length = files.length; i < length; i++) {
            delete require.cache[require.resolve(path.resolve(files[i]))]
        }
        return this;
    }

    _registerHandlers() {
        this._clearHandlers();
        this._handlers = [];
        const files = glob.sync(path.resolve(path.join(process.cwd(), HANDLER_PATH, DEEP_EXT_JS)));
        for (let i = 0, length = files.length; i < length; i++) {
            try {
                this._handlers.push(require(path.resolve(files[i])));
            } catch (error) {
                this.error("Failed to register handler " + files[i], error);
                throw new Error("Failed to boot smash");
            }
        }
        this.info("Handler loaded: " + files.length);
        return this;
    }

    _buildEnv(context) {
        delete this._env;
        this._env = {};
        Object.assign(this._env, process.env);
        this._setEnv("ENV", context.functionVersion);
        Object.freeze(this._env);
        return this;
    }

    boot() {
        this._registerMiddlewares();
        this._registerHandlers();
    }

    handleEvent(event, context, callback) {
        if (this._middlewares === null) {
            this.error("Smash has not been booted, you must call boot() first", event);
            callback(new Error("Smash has not been booted, you must call boot() first"));
        } else {
            this._buildEnv(context);
            for (let i = 0, length = this._middlewares.length; i < length; i++) {
                if (this._middlewares[i].isEvent(event)) {
                    this._middlewares[i].handleEvent(event, context, callback);
                    return this;
                }
            }
            this.error("No middleware found to process event", event);
            callback(new Error("No middleware found to process event"));
        }
        return this;
    }

    get env() {
        return this._env;
    }

    getEnv(key) {
        return this._env[key];
    }

    _setEnv(key, value) {
        this._env[key] = value;
    }

    util(module) {
        if (typeof module !== 'string' || module.length === 0) {
            throw new Error("First parameter of util must be a valid string, " + this.typeOf(module) + "given");
        }
        return require(path.resolve(path.join(process.cwd(), UTIL_PATH, module + EXT_JS)));
    }

    database(module) {
        if (typeof module !== 'string' || module.length === 0) {
            throw new Error("First parameter of util must be a valid string, " + this.typeOf(module) + "given");
        }
        return require(path.resolve(path.join(process.cwd(), DATABASE_PATH, module + EXT_JS)));
    }

    get config() {
        return this._config;
    }

    get Model() {
        return require(path.resolve(path.join(__dirname, "lib/util/model.js")));
    }

    get Console() {
        return require(path.resolve(path.join(__dirname, "lib/util/console.js")));
    }

    set Console(console) {

    }
}

if (!global.smash) {
    global.smash = new Smash();
}
module.exports = global.smash;

<|endoftext|>


<commit_before>import Reflux from 'reflux';

import Build from '../models/Build';
import Log from '../models/Log';
import BuildTrigger from '../models/BuildTrigger';
import BranchDefinition from '../models/BranchDefinition';
import BranchModules from '../collections/BranchModules';
import {find} from 'underscore';
import BuildStates from '../constants/BuildStates';
import BuildHistoryActions from '../actions/buildHistoryActions';

// builds we are polling
let builds = {};
// requested build params
let requestedBuild = {};

const BuildActions = Reflux.createActions([
  'loadBuild',
  'loadBuildSuccess',
  'loadBuildError',
  'reloadBuild',
  'triggerBuildSuccess',
  'triggerBuildError',
  'triggerBuildStart'
]);

BuildActions.loadBuild.preEmit = function(data) {
  BuildActions.setupBuildRequest(data);
};

BuildActions.reloadBuild = function(data) {
  BuildActions.setupBuildRequest(data);
};

BuildActions.setupBuildRequest = function(data) {
  requestedBuild.gitInfo = data;

  getBranchId()
    .then(getModule)
    .then(getBuild)
    .then(processBuild.bind(this));
};

BuildActions.stopWatchingBuild = function(moduleId) {
  if (builds[moduleId]) {
    console.info('set build #' + builds[moduleId].build.buildNumber + ' to inactive');
    builds[moduleId].isActive = false;
  }
  else {
    // Hack - if user tries to navigate too quickly from one
    // build to the next, we dont have time to load the moduleId
    // and check if we need to clear polling
    // To do: find a better approach
    window.location.reload();
  }

};

BuildActions.triggerBuild = function(moduleId) {
  BuildActions.triggerBuildStart();
  const trigger = new BuildTrigger(moduleId);
  const promise = trigger.fetch();
  promise.then(() => {
    BuildActions.triggerBuildSuccess();
    BuildHistoryActions.fetchLatestHistory();
  },
  (data, textStatus, jqXHR) => {
    BuildActions.triggerBuildError(jqXHR);
  });
};

function getBranchId() {
  const branchDefinition = new BranchDefinition(requestedBuild.gitInfo);
  const branchPromise =  branchDefinition.fetch();

  branchPromise.done(() => {
    requestedBuild.gitInfo.branchId = branchDefinition.data.id;
  });
  branchPromise.error(() => {
    BuildHistoryActions.loadBuildHistoryError('an error occured');
  });

  return branchPromise;
}

function getModule() {
  const branchModules = new BranchModules(requestedBuild.gitInfo.branchId);
  const modulesPromise = branchModules.fetch();

  modulesPromise.done(() => {
    requestedBuild.gitInfo.moduleId = find(branchModules.data, (m) => {
      return m.name === requestedBuild.gitInfo.module;
    }).id;
  });
  modulesPromise.error(() => {
    BuildHistoryActions.loadBuildHistoryError('an error occured');
  });

  return modulesPromise;
}

function getBuild() {
  builds[requestedBuild.gitInfo.moduleId] = new Build(requestedBuild.gitInfo);
  builds[requestedBuild.gitInfo.moduleId].isActive = true;
  console.info(`setting build #${requestedBuild.gitInfo.buildNumber} to active`);
  const buildPromise = builds[requestedBuild.gitInfo.moduleId].fetch();

  buildPromise.error(() => {
    BuildActions.loadBuildError("
Error retrieving build log");
  });

  return buildPromise;
}

function processBuild() {
  const buildToProcess = builds[requestedBuild.gitInfo.moduleId];

  if (!buildToProcess.isActive) {
    return;
  }

  if (buildToProcess.data.build.state === BuildStates.LAUNCHING) {
    BuildActions.loadBuildSuccess({
      build: buildToProcess.data
    });
    return;
  }

  if (buildToProcess.data.build.state === BuildStates.IN_PROGRESS) {
    processInProgressBuild(buildToProcess);
  }

  else {
    processInactiveBuild(buildToProcess);
  }
}

function processInProgressBuild(build) {
  let inProgressBuild = {
    logLines: '',
    offset: 0
  };

  (function fetchLog() {
    if (!builds[build.data.module.id].isActive) {
      console.info(`build # ${build.data.build.buildNumber} is not active, do not continue polling for build log.`);
      return;
    }

    const log = new Log({
      buildNumber: build.data.build.id,
      offset: inProgressBuild.offset
    });

    const logPromise = log.fetch();
    logPromise.always( (data, textStatus, jqxhr) => {
      console.info(`Promise complete for build #${build.data.build.buildNumber }. isActive: ${build.isActive}`);
      inProgressBuild.logLines += log.formatLog(jqxhr);
      inProgressBuild.offset = data.nextOffset;

      if (data.nextOffset === -1) {
        // get latest build detail when log fetching is complete
        // so we can update status section at top of build page
        const lastBuild = new Build(requestedBuild.gitInfo);
        const buildPromise = lastBuild.fetch();

        buildPromise.done(() => {
          BuildActions.loadBuildSuccess({
            build: lastBuild.data,
            log: inProgressBuild.logLines,
            fetchingLog: false
          });
        });
      }

      // still building
      else {
        BuildActions.loadBuildSuccess({
          build: build.data,
          log: inProgressBuild.logLines,
          fetchingLog: true
        });

        setTimeout(() => {
          fetchLog();
        }, 5000);
      }

    });

  })();
}

function processInactiveBuild(build) {
  let logLines = '';
  let offset = 0;

  (function fetchLog() {
    const log = new Log({
      buildNumber: build.data.build.id,
      offset: offset
    });

    const logPromise = log.fetch();
    logPromise.always( (data, textStatus, jqxhr) => {

      logLines += log.formatLog(jqxhr);

      if (jqxhr.responseJSON === undefined || textStatus !== 'success') {
        BuildActions.loadBuildSuccess({
          build: build,
          log: `<p class='roomy-xy'>${data.responseText}</p>`,
          fetchingLog: false
        });
        return;
      }

      BuildActions.loadBuildSuccess({
        build: build.data,
        log: logLines,
        fetchingLog: true
      });

      // more log lines exist
      if (jqxhr.responseJSON.nextOffset !== -1) {
        offset = jqxhr.responseJSON.nextOffset;
        fetchLog();
      }

      // got all log lines
      else {
        BuildActions.loadBuildSuccess({
          build: build.data,
          log: logLines,
          fetchingLog: false
        });
      }

    });

  })();
}

export default BuildActions;
<commit_msg>check that we have a build state to test<commit_after>import Reflux from 'reflux';

import Build from '../models/Build';
import Log from '../models/Log';
import BuildTrigger from '../models/BuildTrigger';
import BranchDefinition from '../models/BranchDefinition';
import BranchModules from '../collections/BranchModules';
import {find, has} from 'underscore';
import BuildStates from '../constants/BuildStates';
import BuildHistoryActions from '../actions/buildHistoryActions';

// builds we are polling
let builds = {};
// requested build params
let requestedBuild = {};

const BuildActions = Reflux.createActions([
  'loadBuild',
  'loadBuildSuccess',
  'loadBuildError',
  'reloadBuild',
  'triggerBuildSuccess',
  'triggerBuildError',
  'triggerBuildStart'
]);

BuildActions.loadBuild.preEmit = function(data) {
  BuildActions.setupBuildRequest(data);
};

BuildActions.reloadBuild = function(data) {
  BuildActions.setupBuildRequest(data);
};

BuildActions.setupBuildRequest = function(data) {
  requestedBuild.gitInfo = data;

  getBranchId()
    .then(getModule)
    .then(getBuild)
    .then(processBuild.bind(this));
};

BuildActions.stopWatchingBuild = function(moduleId) {
  if (builds[moduleId]) {
    console.info('set build #' + builds[moduleId].build.buildNumber + ' to inactive');
    builds[moduleId].isActive = false;
  }
  else {
    // Hack - if user tries to navigate too quickly from one
    // build to the next, we dont have time to load the moduleId
    // and check if we need to clear polling
    // To do: find a better approach
    window.location.reload();
  }

};

BuildActions.triggerBuild = function(moduleId) {
  BuildActions.triggerBuildStart();
  const trigger = new BuildTrigger(moduleId);
  const promise = trigger.fetch();
  promise.then(() => {
    BuildActions.triggerBuildSuccess();
    BuildHistoryActions.fetchLatestHistory();
  },
  (data, textStatus, jqXHR) => {
    BuildActions.triggerBuildError(jqXHR);
  });
};

function getBranchId() {
  const branchDefinition = new BranchDefinition(requestedBuild.gitInfo);
  const branchPromise =  branchDefinition.fetch();

  branchPromise.done(() => {
    requestedBuild.gitInfo.branchId = branchDefinition.data.id;
  });
  branchPromise.error(() => {
    BuildHistoryActions.loadBuildHistoryError('an error occured');
  });

  return branchPromise;
}

function getModule() {
  const branchModules = new BranchModules(requestedBuild.gitInfo.branchId);
  const modulesPromise = branchModules.fetch();

  modulesPromise.done(() => {
    requestedBuild.gitInfo.moduleId = find(branchModules.data, (m) => {
      return m.name === requestedBuild.gitInfo.module;
    }).id;
  });
  modulesPromise.error(() => {
    BuildHistoryActions.loadBuildHistoryError('an error occured');
  });

  return modulesPromise;
}

function getBuild() {
  builds[requestedBuild.gitInfo.moduleId] = new Build(requestedBuild.gitInfo);
  builds[requestedBuild.gitInfo.moduleId].isActive = true;
  console.info(`setting build #${requestedBuild.gitInfo.buildNumber} to active`);
  const buildPromise = builds[requestedBuild.gitInfo.moduleId].fetch();

  buildPromise.error(() => {
    BuildActions.loadBuildError("
Error retrieving build log");
  });

  return buildPromise;
}

function processBuild() {
  const buildToProcess = builds[requestedBuild.gitInfo.moduleId];

  // to do: find out why we dont have state at this point
  if (!has(buildToProcess.data.build, 'state')) {
    return;
  }

  if (!buildToProcess.isActive) {
    return;
  }

  if (buildToProcess.data.build.state === BuildStates.LAUNCHING) {
    BuildActions.loadBuildSuccess({
      build: buildToProcess.data
    });
    return;
  }

  if (buildToProcess.data.build.state === BuildStates.IN_PROGRESS) {
    processInProgressBuild(buildToProcess);
  }

  else {
    processInactiveBuild(buildToProcess);
  }
}

function processInProgressBuild(build) {
  let inProgressBuild = {
    logLines: '',
    offset: 0
  };

  (function fetchLog() {
    if (!builds[build.data.module.id].isActive) {
      console.info(`build # ${build.data.build.buildNumber} is not active, do not continue polling for build log.`);
      return;
    }

    const log = new Log({
      buildNumber: build.data.build.id,
      offset: inProgressBuild.offset
    });

    const logPromise = log.fetch();
    logPromise.always( (data, textStatus, jqxhr) => {
      console.info(`Promise complete for build #${build.data.build.buildNumber }. isActive: ${build.isActive}`);
      inProgressBuild.logLines += log.formatLog(jqxhr);
      inProgressBuild.offset = data.nextOffset;

      if (data.nextOffset === -1) {
        // get latest build detail when log fetching is complete
        // so we can update status section at top of build page
        const lastBuild = new Build(requestedBuild.gitInfo);
        const buildPromise = lastBuild.fetch();

        buildPromise.done(() => {
          BuildActions.loadBuildSuccess({
            build: lastBuild.data,
            log: inProgressBuild.logLines,
            fetchingLog: false
          });
        });
      }

      // still building
      else {
        BuildActions.loadBuildSuccess({
          build: build.data,
          log: inProgressBuild.logLines,
          fetchingLog: true
        });

        setTimeout(() => {
          fetchLog();
        }, 5000);
      }

    });

  })();
}

function processInactiveBuild(build) {
  let logLines = '';
  let offset = 0;

  (function fetchLog() {
    const log = new Log({
      buildNumber: build.data.build.id,
      offset: offset
    });

    const logPromise = log.fetch();
    logPromise.always( (data, textStatus, jqxhr) => {

      logLines += log.formatLog(jqxhr);

      if (jqxhr.responseJSON === undefined || textStatus !== 'success') {
        BuildActions.loadBuildSuccess({
          build: build,
          log: `<p class='roomy-xy'>${data.responseText}</p>`,
          fetchingLog: false
        });
        return;
      }

      BuildActions.loadBuildSuccess({
        build: build.data,
        log: logLines,
        fetchingLog: true
      });

      // more log lines exist
      if (jqxhr.responseJSON.nextOffset !== -1) {
        offset = jqxhr.responseJSON.nextOffset;
        fetchLog();
      }

      // got all log lines
      else {
        BuildActions.loadBuildSuccess({
          build: build.data,
          log: logLines,
          fetchingLog: false
        });
      }

    });

  })();
}

export default BuildActions;
<|endoftext|>