<commit_before>'use strict';

const electron = require('electron');
const app = electron.app;
const childProcess = require('child_process');
const fs = require('fs');
const os = require('os');
const path = require('path');

const { isMac, isDevEnv } = require('../utils/misc.js');
const log = require('../log.js');
const logLevels = require('../enums/logLevels.js');
const eventEmitter = require('.././eventEmitter');

// static ref to child process, only allow one screen snippet at time, so
// hold ref to prev, so can kill before starting next snippet.
let child;
let isAlwaysOnTop;

/**
 * Captures a user selected portion of the monitor and returns jpeg image
 * encoded in base64 format.
 */
class ScreenSnippet {
    /**
     * Returns promise.
     *
     * If successful will resolves with jpeg image encoded in base64 format:
     * {
     *     type: 'image/jpg;base64',
     *     data: base64-data
     * }
     *
     * Otherwise if not successful will reject with object
     * containing: { type: ['WARN','ERROR'], message: String }
     */
    capture() {
        return new Promise((resolve, reject) => {
            let captureUtil, captureUtilArgs;

            log.send(logLevels.INFO, 'ScreenSnippet: starting screen capture');

            let tmpFilename = 'symphonyImage-' + Date.now() + '.jpg';
            let tmpDir = os.tmpdir();

            let outputFileName = path.join(tmpDir, tmpFilename);

            if (isMac) {
                // utilize Mac OSX built-in screencapture tool which has been
                // available since OSX ver 10.2.
                captureUtil = '/usr/sbin/screencapture';
                captureUtilArgs = ['-i', '-s', '-t', 'jpg', outputFileName];
            } else {
                // use custom built windows screen capture tool
                if (isDevEnv) {
                    // for dev env pick up tool from node nodules
                    captureUtil =
                        path.join(__dirname,
                            '../../node_modules/screen-snippet/bin/Release/ScreenSnippet.exe');
                } else {
                    // for production gets installed next to exec.
                    let execPath = path.dirname(app.getPath('exe'));
                    captureUtil = path.join(execPath, 'ScreenSnippet.exe');
                }

                // Method to verify and disable always on top property
                // as an issue with the ScreenSnippet.exe not being on top
                // of the electron wrapper
                const windows = electron.BrowserWindow.getAllWindows();
                if (windows && windows.length > 0) {
                    isAlwaysOnTop = windows[ 0 ].isAlwaysOnTop();
                    if (isAlwaysOnTop) {
                        eventEmitter.emit('isAlwaysOnTop', false);
                    }
                }

                captureUtilArgs = [outputFileName];
            }

            log.send(logLevels.INFO, 'ScreenSnippet: starting screen capture util: ' + captureUtil + ' with args=' + captureUtilArgs);

            // only allow one screen capture at a time.
            if (child) {
                child.kill();
            }

            child = childProcess.execFile(captureUtil, captureUtilArgs, (error) => {
                // will be called when child process exits.
                if (error && error.killed) {
                    // Method to reset always on top feature
                    if (isAlwaysOnTop) {
                        eventEmitter.emit('isAlwaysOnTop', true);
                    }
                    // processs was killed, just resolve with no data.
                    resolve();
                } else {
                    // Method to reset always on top feature
                    if (isAlwaysOnTop) {
                        eventEmitter.emit('isAlwaysOnTop', true);
                    }
                    readResult.call(this, outputFileName, resolve, reject, error);
                }
            });
        });
    }
}

/**
 * this function was moved outside of class since class is exposed to web
 * client via preload API, we do NOT want web client to be able to call this
 * method - then they could read any file on the disk!
 * @param outputFileName
 * @param resolve
 * @param reject
 * @param childProcessErr
 */
function readResult(outputFileName, resolve, reject, childProcessErr) {
    fs.readFile(outputFileName, (readErr, data) => {
        if (readErr) {
            let returnErr;
            if (readErr.code === 'ENOENT') {
                // no such file exists, user likely aborted
                // creating snippet. also include any error when
                // creating child process.
                returnErr = createWarn('file does not exist ' +
                    childProcessErr);
            } else {
                returnErr = createError(readErr + ',' +
                    childProcessErr);
            }

            reject(returnErr);
            return;
        }

        if (!data) {
            reject(createWarn('no file data provided'));
            return;
        }

        try {
            // convert binary data to base64 encoded string
            let output = Buffer(data).toString('base64');
            resolve({
                type: 'image/jpg;base64',
                data: output
            });
        } catch (error) {
            reject(createError(error));
        } finally {
            // remove tmp file (async)
            fs.unlink(outputFileName, function(removeErr) {
                // note: node complains if calling async
                // func without callback.
                if (removeErr) {
                    log.send(logLevels.ERROR, 'ScreenSnippet: error removing temp snippet file: ' +
                        outputFileName + ', err:' + removeErr);
                }
            });
        }
    });
}

/* eslint-disable class-methods-use-this */
/**
 * Create an error object with the ERROR level
 * @param msg
 * @returns {Error}
 */
function createError(msg) {
    let err = new Error(msg);
    err.type = 'ERROR';
    return err;
}

/**
 * Create an error object with the WARN level
 * @param msg
 * @returns {Error}
 */
function createWarn(msg) {
    let err = new Error(msg);
    err.type = 'WARN';
    return err;
}
/* eslint-enable class-methods-use-this */

module.exports = {
    ScreenSnippet: ScreenSnippet,
    // note: readResult only exposed for testing purposes
    readResult: readResult
};<commit_msg>Electron-118 - removed the duplicate code block<commit_after>'use strict';

const electron = require('electron');
const app = electron.app;
const childProcess = require('child_process');
const fs = require('fs');
const os = require('os');
const path = require('path');

const { isMac, isDevEnv } = require('../utils/misc.js');
const log = require('../log.js');
const logLevels = require('../enums/logLevels.js');
const eventEmitter = require('.././eventEmitter');

// static ref to child process, only allow one screen snippet at time, so
// hold ref to prev, so can kill before starting next snippet.
let child;
let isAlwaysOnTop;

/**
 * Captures a user selected portion of the monitor and returns jpeg image
 * encoded in base64 format.
 */
class ScreenSnippet {
    /**
     * Returns promise.
     *
     * If successful will resolves with jpeg image encoded in base64 format:
     * {
     *     type: 'image/jpg;base64',
     *     data: base64-data
     * }
     *
     * Otherwise if not successful will reject with object
     * containing: { type: ['WARN','ERROR'], message: String }
     */
    capture() {
        return new Promise((resolve, reject) => {
            let captureUtil, captureUtilArgs;

            log.send(logLevels.INFO, 'ScreenSnippet: starting screen capture');

            let tmpFilename = 'symphonyImage-' + Date.now() + '.jpg';
            let tmpDir = os.tmpdir();

            let outputFileName = path.join(tmpDir, tmpFilename);

            if (isMac) {
                // utilize Mac OSX built-in screencapture tool which has been
                // available since OSX ver 10.2.
                captureUtil = '/usr/sbin/screencapture';
                captureUtilArgs = ['-i', '-s', '-t', 'jpg', outputFileName];
            } else {
                // use custom built windows screen capture tool
                if (isDevEnv) {
                    // for dev env pick up tool from node nodules
                    captureUtil =
                        path.join(__dirname,
                            '../../node_modules/screen-snippet/bin/Release/ScreenSnippet.exe');
                } else {
                    // for production gets installed next to exec.
                    let execPath = path.dirname(app.getPath('exe'));
                    captureUtil = path.join(execPath, 'ScreenSnippet.exe');
                }

                // Method to verify and disable always on top property
                // as an issue with the ScreenSnippet.exe not being on top
                // of the electron wrapper
                const windows = electron.BrowserWindow.getAllWindows();
                if (windows && windows.length > 0) {
                    isAlwaysOnTop = windows[ 0 ].isAlwaysOnTop();
                    if (isAlwaysOnTop) {
                        eventEmitter.emit('isAlwaysOnTop', false);
                    }
                }

                captureUtilArgs = [outputFileName];
            }

            log.send(logLevels.INFO, 'ScreenSnippet: starting screen capture util: ' + captureUtil + ' with args=' + captureUtilArgs);

            // only allow one screen capture at a time.
            if (child) {
                child.kill();
            }

            child = childProcess.execFile(captureUtil, captureUtilArgs, (error) => {
                // Method to reset always on top feature
                if (isAlwaysOnTop) {
                    eventEmitter.emit('isAlwaysOnTop', true);
                }
                // will be called when child process exits.
                if (error && error.killed) {
                    // processs was killed, just resolve with no data.
                    resolve();
                } else {
                    readResult.call(this, outputFileName, resolve, reject, error);
                }
            });
        });
    }
}

/**
 * this function was moved outside of class since class is exposed to web
 * client via preload API, we do NOT want web client to be able to call this
 * method - then they could read any file on the disk!
 * @param outputFileName
 * @param resolve
 * @param reject
 * @param childProcessErr
 */
function readResult(outputFileName, resolve, reject, childProcessErr) {
    fs.readFile(outputFileName, (readErr, data) => {
        if (readErr) {
            let returnErr;
            if (readErr.code === 'ENOENT') {
                // no such file exists, user likely aborted
                // creating snippet. also include any error when
                // creating child process.
                returnErr = createWarn('file does not exist ' +
                    childProcessErr);
            } else {
                returnErr = createError(readErr + ',' +
                    childProcessErr);
            }

            reject(returnErr);
            return;
        }

        if (!data) {
            reject(createWarn('no file data provided'));
            return;
        }

        try {
            // convert binary data to base64 encoded string
            let output = Buffer(data).toString('base64');
            resolve({
                type: 'image/jpg;base64',
                data: output
            });
        } catch (error) {
            reject(createError(error));
        } finally {
            // remove tmp file (async)
            fs.unlink(outputFileName, function(removeErr) {
                // note: node complains if calling async
                // func without callback.
                if (removeErr) {
                    log.send(logLevels.ERROR, 'ScreenSnippet: error removing temp snippet file: ' +
                        outputFileName + ', err:' + removeErr);
                }
            });
        }
    });
}

/* eslint-disable class-methods-use-this */
/**
 * Create an error object with the ERROR level
 * @param msg
 * @returns {Error}
 */
function createError(msg) {
    let err = new Error(msg);
    err.type = 'ERROR';
    return err;
}

/**
 * Create an error object with the WARN level
 * @param msg
 * @returns {Error}
 */
function createWarn(msg) {
    let err = new Error(msg);
    err.type = 'WARN';
    return err;
}
/* eslint-enable class-methods-use-this */

module.exports = {
    ScreenSnippet: ScreenSnippet,
    // note: readResult only exposed for testing purposes
    readResult: readResult
};<|endoftext|>


<commit_before>var bluebird = require('bluebird');
var joi = require('joi');
var validate = bluebird.promisify(joi.validate);
var createSchema = joi.object().keys({
    boardName: joi.string().alphanum().min(3).max(24).required(),
    gutters: joi.array().items(joi.string().required()).unique().required()
});

function BoardController(nedb) {
    this.nedb = nedb;
}

BoardController.prototype.createBoard = function(req, res) {
    var self = this;
    var body = req.body;
    return validate(body, createSchema).then(function(result) {
        return self.nedb.findAsync({
            boardName: body.boardName
        });
    }).then(function(documents) {
        if (documents.length > 0) {
            return bluebird.reject({
                name: "UserError",
                message: "Board already exists."
            });
        }
    }).then(function() {
        var gutters = {};
        // Transform the gutters for the board into arrays for nedb
        for(var i = 0; i < body.gutters.length; i++) {
            var name = body.gutters[i];
            gutters[name] = {
                items: [],
                order: i,
                name: name
            };
        }

        return self.nedb.insertAsync({
            "boardName": body.boardName,
            "gutters": gutters,
            "createdAt": new Date()
        });
    });
};

BoardController.prototype.listBoards = function() {
    return this.nedb.findAsync({}, { boardName: 1 }).then(function(documents) {
        if(documents.length === 0) {
            return [];
        }
        return documents;
    })
}

BoardController.prototype.getBoardByName = function(name) {
    return this.nedb.findAsync({ boardName: name}).then(function(documents) {
        if(documents.length === 0) {
            return [];
        }
        return documents;
    })
}

module.exports = BoardController;
<commit_msg>Revert "investigating sails js"<commit_after>var bluebird = require('bluebird');
var joi = require('joi');
var validate = bluebird.promisify(joi.validate);
var createSchema = joi.object().keys({
    boardName: joi.string().alphanum().min(3).max(24).required(),
    gutters: joi.array().items(joi.string().required()).unique().required()
});

function BoardController(nedb) {
    this.nedb = nedb;
}

BoardController.prototype.createBoard = function(body) {
    var self = this;
    return validate(body, createSchema).then(function(result) {
        return self.nedb.findAsync({
            boardName: body.boardName
        });
    }).then(function(documents) {
        if (documents.length > 0) {
            return bluebird.reject({
                name: "UserError",
                message: "Board already exists."
            })
        }
    }).then(function() {
        var gutters = {};
        // Transform the gutters for the board into arrays for nedb
        for(var i = 0; i < body.gutters.length; i++) {
            var name = body.gutters[i];
            gutters[name] = {
                items: [],
                order: i,
                name: name
            };
        }

        return self.nedb.insertAsync({
            "boardName": body.boardName,
            "gutters": gutters,
            "createdAt": new Date()
        });
    });
};

BoardController.prototype.listBoards = function() {
    return this.nedb.findAsync({}, { boardName: 1 }).then(function(documents) {
        if(documents.length === 0) {
            return [];
        }
        return documents;
    })
}

BoardController.prototype.getBoardByName = function(name) {
    return this.nedb.findAsync({ boardName: name}).then(function(documents) {
        if(documents.length === 0) {
            return [];
        }
        return documents;
    })
}

module.exports = BoardController;
<|endoftext|>


<commit_before>import React from "react";
import Button from "./button";
import { storiesOf } from "@kadira/storybook";
import Inline, { InlineElement } from "../src/components/groupings/inline";
import Collapsable from "../src/components/groupings/collapsable";
import Tabbable from "../src/components/groupings/tabbable";
import HtmlView from "../src/components/sections/htmlview";
import ReactView from "../src/components/sections/reactview";
import CssView from "../src/components/sections/cssview";

import Rawview from '../src/components/sections/rawview';
import Group from '../src/components/groupings/group';

import buttonSrc from '!!raw-loader!./button.js';

storiesOf('Button')
    .addWithSections('No leaking styles', () => (

Should not be styled

Nor this

            or this

    ))
    .addWithSections('Global sections', (context, action) => {
        return (
            <Button onClick={action('global click')}>Simple</Button>
        )
    })
    .addWithSections('Single section', () => (
        <Button>Simple</Button>
    ), ReactView)
    .addWithSections('Single inline section', () => (
        <Button>Simple</Button>
    ), Inline(ReactView))
    .addWithSections('Multiple inline section', () => (
        <Button>Simple</Button>
    ), Inline(ReactView, HtmlView))
    .addWithSections('Peeling wrapper divs', () => (

                    <Button>Simple</Button>

                    <Button>Simple</Button>

                    <Button>Simple</Button>

    ), Inline(Group(ReactView.withProps({peel: 3}), HtmlView.withProps({ peel: 3 }), CssView.withProps({specificity: 15})).withTitle('Test')))
    .addWithSections('Single collapsable section', () => (
        <Button>Simple</Button>
    ), Collapsable(ReactView))
    .addWithSections('Multiple collapsable section', () => (
        <Button>Simple</Button>
    ), Collapsable(ReactView, HtmlView), Collapsable(ReactView, HtmlView))
    .addWithSections('Single tabbable section', () => (
        <Button>Simple</Button>
    ), Tabbable(ReactView))
    .addWithSections('Multiple tabbable section', () => (
        <Button>Simple</Button>
    ), Tabbable(ReactView, HtmlView), Tabbable(ReactView, HtmlView))
    .addWithSections('Even more multiple tabbable section', () => (
        <Button>Simple</Button>
    ), Tabbable(ReactView.withTitle('JSX'), HtmlView, CssView))
    .addWithSections('Multiple sections', (_, action) => (

            <Button onClick={action('btn')}>
                Sections Test Skjer a?
            </Button>

    ), ReactView, HtmlView, CssView)
    .addWithSections('Combination section', () => (
        <Button>Simple</Button>
    ), CssView, Inline(CssView), Tabbable(ReactView, HtmlView), Collapsable(ReactView, HtmlView))
    .addWithSections('Props', () => (

            <Button>Simple</Button>

    ), Tabbable(ReactView, HtmlView.withTitle('Min tittel')))
    .addWithSections('Nested groups', () => (

            <Button>Simple</Button>

    ), Tabbable(Collapsable(ReactView, HtmlView).withTitle('Markup'), Collapsable(CssView).withTitle('Styling')))
    .addWithSections('Nested groups again', () => (

            <Button>Simple</Button>

    ), Collapsable(Tabbable(ReactView, HtmlView).withTitle('Markup'), Tabbable(CssView).withTitle('Styling')))
    .addWithSections('Deep nesting again', () => (

                <Button>Simple</Button>

        ), Collapsable(Collapsable(Collapsable(Collapsable(Inline(HtmlView.withTitle('Min html')).withTitle('Ingenting')).withTitle('I the middle'))).withTitle('top-level')),
        Collapsable(Tabbable(Collapsable(Tabbable(Inline(HtmlView).withTitle('My header')).withTitle('tabbable')).withTitle('collapsable'))),
        Tabbable(Tabbable(Tabbable(Tabbable(Inline(HtmlView.withTitle('content')).withTitle('tab0')).withTitle('tab1')).withTitle('tab2')).withTitle('tab3')))
    .addWithSections('Pure grouping', () => (

            <Button>Simple</Button>

    ), Collapsable(ReactView, HtmlView), Collapsable(Group(ReactView, HtmlView).withTitle('custom title')))
    .addWithSections('Raw view', () => (

            <Button>Simple</Button>

    ), Tabbable(Rawview(buttonSrc, 'javascript').withTitle('Button')));
<commit_msg>Removed unused import<commit_after>import React from "react";
import Button from "./button";
import { storiesOf } from "@kadira/storybook";
import Inline from "../src/components/groupings/inline";
import Collapsable from "../src/components/groupings/collapsable";
import Tabbable from "../src/components/groupings/tabbable";
import HtmlView from "../src/components/sections/htmlview";
import ReactView from "../src/components/sections/reactview";
import CssView from "../src/components/sections/cssview";

import Rawview from '../src/components/sections/rawview';
import Group from '../src/components/groupings/group';

import buttonSrc from '!!raw-loader!./button.js';

storiesOf('Button')
    .addWithSections('No leaking styles', () => (

Should not be styled

Nor this

            or this

    ))
    .addWithSections('Global sections', (context, action) => {
        return (
            <Button onClick={action('global click')}>Simple</Button>
        )
    })
    .addWithSections('Single section', () => (
        <Button>Simple</Button>
    ), ReactView)
    .addWithSections('Single inline section', () => (
        <Button>Simple</Button>
    ), Inline(ReactView))
    .addWithSections('Multiple inline section', () => (
        <Button>Simple</Button>
    ), Inline(ReactView, HtmlView))
    .addWithSections('Peeling wrapper divs', () => (

                    <Button>Simple</Button>

                    <Button>Simple</Button>

                    <Button>Simple</Button>

    ), Inline(Group(ReactView.withProps({peel: 3}), HtmlView.withProps({ peel: 3 }), CssView.withProps({specificity: 15})).withTitle('Test')))
    .addWithSections('Single collapsable section', () => (
        <Button>Simple</Button>
    ), Collapsable(ReactView))
    .addWithSections('Multiple collapsable section', () => (
        <Button>Simple</Button>
    ), Collapsable(ReactView, HtmlView), Collapsable(ReactView, HtmlView))
    .addWithSections('Single tabbable section', () => (
        <Button>Simple</Button>
    ), Tabbable(ReactView))
    .addWithSections('Multiple tabbable section', () => (
        <Button>Simple</Button>
    ), Tabbable(ReactView, HtmlView), Tabbable(ReactView, HtmlView))
    .addWithSections('Even more multiple tabbable section', () => (
        <Button>Simple</Button>
    ), Tabbable(ReactView.withTitle('JSX'), HtmlView, CssView))
    .addWithSections('Multiple sections', (_, action) => (

            <Button onClick={action('btn')}>
                Sections Test Skjer a?
            </Button>

    ), ReactView, HtmlView, CssView)
    .addWithSections('Combination section', () => (
        <Button>Simple</Button>
    ), CssView, Inline(CssView), Tabbable(ReactView, HtmlView), Collapsable(ReactView, HtmlView))
    .addWithSections('Props', () => (

            <Button>Simple</Button>

    ), Tabbable(ReactView, HtmlView.withTitle('Min tittel')))
    .addWithSections('Nested groups', () => (

            <Button>Simple</Button>

    ), Tabbable(Collapsable(ReactView, HtmlView).withTitle('Markup'), Collapsable(CssView).withTitle('Styling')))
    .addWithSections('Nested groups again', () => (

            <Button>Simple</Button>

    ), Collapsable(Tabbable(ReactView, HtmlView).withTitle('Markup'), Tabbable(CssView).withTitle('Styling')))
    .addWithSections('Deep nesting again', () => (

                <Button>Simple</Button>

        ), Collapsable(Collapsable(Collapsable(Collapsable(Inline(HtmlView.withTitle('Min html')).withTitle('Ingenting')).withTitle('I the middle'))).withTitle('top-level')),
        Collapsable(Tabbable(Collapsable(Tabbable(Inline(HtmlView).withTitle('My header')).withTitle('tabbable')).withTitle('collapsable'))),
        Tabbable(Tabbable(Tabbable(Tabbable(Inline(HtmlView.withTitle('content')).withTitle('tab0')).withTitle('tab1')).withTitle('tab2')).withTitle('tab3')))
    .addWithSections('Pure grouping', () => (

            <Button>Simple</Button>

    ), Collapsable(ReactView, HtmlView), Collapsable(Group(ReactView, HtmlView).withTitle('custom title')))
    .addWithSections('Raw view', () => (

            <Button>Simple</Button>

    ), Tabbable(Rawview(buttonSrc, 'javascript').withTitle('Button')));
<|endoftext|>


<commit_before>var TelegramBotWebHook = require('./telegramWebHook');
var TelegramBotPolling = require('./telegramPolling');
var debug = require('debug')('node-telegram-bot-api');
var EventEmitter = require('events').EventEmitter;
var Promise = require("bluebird");
var request = require("request");
var stream = require('stream');
var util = require('util');
var mime = require('mime');
var path = require('path');
var URL = require('url');
var fs = require('fs');

var requestPromise = Promise.promisify(request);

/**
 * Both request method to obtain messages are implemented. To use standard polling, set `polling: true`
 * on `options`. Notice that [webHook](https://core.telegram.org/bots/api#setwebhook) will need a valid (not self signed) SSL certificate.
 * Emmits `message` when a message arrives.
 *
 * @class TelegramBot
 * @constructor
 * @param {String} token Bot Token
 * @param {Object} [options]
 * @param {Boolean|Object} [options.polling=false] Set true to enable polling or set options
 * @param {String|Number} [options.polling.timeout=4] Polling time
 * @param {String|Number} [options.polling.interval=2000] Interval between requests in miliseconds
 * @param {Boolean|Object} [options.webHook=false] Set true to enable WebHook or set options
 * @param {String} [options.webHook.key] PEM private key to webHook server
 * @param {String} [options.webHook.cert] PEM certificate key to webHook server
 * @see https://core.telegram.org/bots/api
 */
var TelegramBot = function (token, options) {
  options = options || {};
  this.token = token;

  var processUpdate = this._processUpdate.bind(this);

  if (options.polling) {
    this._polling = new TelegramBotPolling(token, options.polling, processUpdate);
  }

  if (options.webHook) {
    this._WebHook = new TelegramBotWebHook(token, options.webHook, processUpdate);
  }
};

util.inherits(TelegramBot, EventEmitter);

TelegramBot.prototype._processUpdate = function (update) {
  debug('Process Update', update);
  debug('Process Update message', update.message);
  if (update.message) {
    this.emit('message', update.message);
  }
};

TelegramBot.prototype._request = function (path, options) {
  if (!this.token) {
    throw new Error('Telegram Bot Token not provided!');
  }
  options = options || {};
  options.url = URL.format({
    protocol: 'https',
    host: 'api.telegram.org',
    pathname: '/bot'+this.token+'/'+path
  });
  debug('HTTP request: %j', options);
  return requestPromise(options)
    .then(function (resp) {
      if (resp[0].statusCode !== 200) {
        throw new Error(resp[0].statusCode+' '+resp[0].body);
      }
      var data = JSON.parse(resp[0].body);
      if (data.ok) {
        return data.result;
      } else {
        throw new Error(data.error_code+' '+data.description);
      }
    });
};

/**
 * Returns basic information about the bot in form of a `User` object.
 * @return {Promise}
 * @see https://core.telegram.org/bots/api#getme
 */
TelegramBot.prototype.getMe = function () {
  var path = 'getMe';
  return this._request(path);
};

/**
 * Specify an url to receive incoming updates via an outgoing webHook.
 * @param {String} url URL where Telegram will make HTTP Post. Leave empty to
 * delete webHook.
 * @see https://core.telegram.org/bots/api#setwebhook
 */
TelegramBot.prototype.setWebHook = function (url) {
  var path = 'setWebHook';
  var qs = {url: url};
  return this._request(path, {qs: qs})
    .then(function (resp) {
      if (!resp) {
        throw new Error(resp);
      }
      return resp;
    });
};

/**
 * Use this method to receive incoming updates using long polling
 * @param  {Number|String} [timeout] Timeout in seconds for long polling.
 * @param  {Number|String} [limit] Limits the number of updates to be retrieved.
 * @param  {Number|String} [offset] Identifier of the first update to be returned.
 * @return {Promise} Updates
 * @see https://core.telegram.org/bots/api#getupdates
 */
TelegramBot.prototype.getUpdates = function (timeout, limit, offset) {
  var query = {
    offset: offset,
    limit: limit,
    timeout: timeout
  };

  return this._request('getUpdates', {qs: query});
};

/**
 * Send text message.
 * @param  {Number|String} chatId Unique identifier for the message recipient
 * @param  {String} text Text of the message to be sent
 * @param  {Object} [options] Additional Telegram query options
 * @return {Promise}
 * @see https://core.telegram.org/bots/api#sendmessage
 */
TelegramBot.prototype.sendMessage = function (chatId, text, options) {
  var query = options || {};
  query.chat_id = chatId;
  query.text = text;
  return this._request('sendMessage', {qs: query});
};

/**
 * Forward messages of any kind.
 * @param  {Number|String} chatId     Unique identifier for the message recipient
 * @param  {Number|String} fromChatId Unique identifier for the chat where the
 * original message was sent
 * @param  {Number|String} messageId  Unique message identifier
 * @return {Promise}
 */
TelegramBot.prototype.forwardMessage = function (chatId, fromChatId, messageId) {
  var query = {
    chat_id: chatId,
    from_chat_id: fromChatId,
    message_id: messageId
  };
  return this._request('forwardMessage', {qs: query});
};

TelegramBot.prototype._formatSendData = function (type, data) {
  var formData;
  var fileName;
  var fileId;
  if (data instanceof stream.Stream) {
    fileName = URL.parse(path.basename(data.path)).pathname;
    formData = {};
    formData[type] = {
      value: data,
      options: {
        filename: fileName,
        contentType: mime.lookup(fileName)
      }
    };
  } else if (fs.existsSync(data)) {
    fileName = path.basename(data);
    formData = {};
    formData[type] = {
      value: fs.createReadStream(data),
      options: {
        filename: fileName,
        contentType: mime.lookup(fileName)
      }
    };
  } else {
    fileId = data;
  }
  return [formData, fileId];
};

/**
 * Send photo
 * @param  {Number|String} chatId  Unique identifier for the message recipient
 * @param  {String|stream.Stream} photo A file path or a Stream. Can
 * also be a `file_id` previously uploaded
 * @param  {Object} [options] Additional Telegram query options
 * @return {Promise}
 * @see https://core.telegram.org/bots/api#sendphoto
 */
TelegramBot.prototype.sendPhoto = function (chatId, photo, options) {
  var opts = {
    qs: options || {}
  };
  opts.qs.chat_id = chatId;
  var content = this._formatSendData('photo', photo);
  opts.formData = content[0];
  opts.qs.photo = content[1];
  return this._request('sendPhoto', opts);
};

/**
 * Send audio
 * @param  {Number|String} chatId  Unique identifier for the message recipient
 * @param  {String|stream.Stream} audio A file path or a Stream. Can
 * also be a `file_id` previously uploaded.
 * @param  {Object} [options] Additional Telegram query options
 * @return {Promise}
 * @see https://core.telegram.org/bots/api#sendaudio
 */
TelegramBot.prototype.sendAudio = function (chatId, audio, options) {
  var opts = {
    qs: options || {}
  };
  opts.qs.chat_id = chatId;
  var content = this._formatSendData('audio', audio);
  opts.formData = content[0];
  opts.qs.audio = content[1];
  return this._request('sendAudio', opts);
};

/**
 * Send Document
 * @param  {Number|String} chatId  Unique identifier for the message recipient
 * @param  {String|stream.Stream} A file path or a Stream. Can
 * also be a `file_id` previously uploaded.
 * @param  {Object} [options] Additional Telegram query options
 * @return {Promise}
 * @see https://core.telegram.org/bots/api#sendDocument
 */
TelegramBot.prototype.sendDocument = function (chatId, doc, options) {
  var opts = {
    qs: options || {}
  };
  opts.qs.chat_id = chatId;
  var content = this._formatSendData('document', doc);
  opts.formData = content[0];
  opts.qs.document = content[1];
  return this._request('sendDocument', opts);
};

/**
 * Send .webp stickers.
 * @param  {Number|String} chatId  Unique identifier for the message recipient
 * @param  {String|stream.Stream} A file path or a Stream. Can
 * also be a `file_id` previously uploaded.
 * @param  {Object} [options] Additional Telegram query options
 * @return {Promise}
 * @see https://core.telegram.org/bots/api#sendsticker
 */
TelegramBot.prototype.sendSticker = function (chatId, sticker, options) {
  var opts = {
    qs: options || {}
  };
  opts.qs.chat_id = chatId;
  var content = this._formatSendData('sticker', sticker);
  opts.formData = content[0];
  opts.qs.sticker = content[1];
  return this._request('sendSticker', opts);
};

/**
 * Send video files, Telegram clients support mp4 videos (other formats may be sent whith `sendDocument`)
 * @param  {Number|String} chatId  Unique identifier for the message recipient
 * @param  {String|stream.Stream} A file path or a Stream. Can
 * also be a `file_id` previously uploaded.
 * @param  {Object} [options] Additional Telegram query options
 * @return {Promise}
 * @see https://core.telegram.org/bots/api#sendvideo
 */
TelegramBot.prototype.sendVideo = function (chatId, video, options) {
  var opts = {
    qs: options || {}
  };
  opts.qs.chat_id = chatId;
  var content = this._formatSendData('video', video);
  opts.formData = content[0];
  opts.qs.video = content[1];
  return this._request('sendVideo', opts);
};

/**
 * Send chat action.
 * `typing` for text messages,
 * `upload_photo` for photos, `record_video` or `upload_video` for videos,
 * `record_audio` or `upload_audio` for audio files, `upload_document` for general files,
 * `find_location` for location data.
 *
 * @param  {Number|String} chatId  Unique identifier for the message recipient
 * @param  {String} action Type of action to broadcast.
 * @return {Promise}
 * @see https://core.telegram.org/bots/api#sendchataction
 */
TelegramBot.prototype.sendChatAction = function (chatId, action) {
  var query = {
    chat_id: chatId,
    action: action
  };
  return this._request('sendChatAction', {qs: query});
};

/**
 * Use this method to get a list of profile pictures for a user.
 * Returns a [UserProfilePhotos](https://core.telegram.org/bots/api#userprofilephotos) object.
 *
 * @param  {Number|String} userId  Unique identifier of the target user
 * @param  {Number} [offset] Sequential number of the first photo to be returned. By default, all photos are returned.
 * @param  {Number} [limit] Limits the number of photos to be retrieved. Values between 1—100 are accepted. Defaults to 100.
 * @return {Promise}
 * @see https://core.telegram.org/bots/api#getuserprofilephotos
 */
TelegramBot.prototype.getUserProfilePhotos = function (userId, offset, limit) {
  var query = {
    user_id: userId,
    offset: offset,
    limit: limit
  };
  return this._request('getUserProfilePhotos', {qs: query});
};

/**
 * Send location.
 * Use this method to send point on the map.
 *
 * @param  {Number|String} chatId  Unique identifier for the message recipient
 * @param  {Float} latitude Latitude of location
 * @param  {Float} longitude Longitude of location
 * @param  {Object} [options] Additional Telegram query options
 * @return {Promise}
 * @see https://core.telegram.org/bots/api#sendlocation
 */
TelegramBot.prototype.sendLocation = function (chatId, latitude, longitude, options) {
  var query = options || {};
  query.chat_id = chatId;
  query.latitude = latitude;
  query.longitude = longitude;
  return this._request('sendLocation', {qs: query});
};

module.exports = TelegramBot;
<commit_msg>POST request<commit_after>var TelegramBotWebHook = require('./telegramWebHook');
var TelegramBotPolling = require('./telegramPolling');
var debug = require('debug')('node-telegram-bot-api');
var EventEmitter = require('events').EventEmitter;
var Promise = require("bluebird");
var request = require("request");
var stream = require('stream');
var util = require('util');
var mime = require('mime');
var path = require('path');
var URL = require('url');
var fs = require('fs');

var requestPromise = Promise.promisify(request);

/**
 * Both request method to obtain messages are implemented. To use standard polling, set `polling: true`
 * on `options`. Notice that [webHook](https://core.telegram.org/bots/api#setwebhook) will need a valid (not self signed) SSL certificate.
 * Emmits `message` when a message arrives.
 *
 * @class TelegramBot
 * @constructor
 * @param {String} token Bot Token
 * @param {Object} [options]
 * @param {Boolean|Object} [options.polling=false] Set true to enable polling or set options
 * @param {String|Number} [options.polling.timeout=4] Polling time
 * @param {String|Number} [options.polling.interval=2000] Interval between requests in miliseconds
 * @param {Boolean|Object} [options.webHook=false] Set true to enable WebHook or set options
 * @param {String} [options.webHook.key] PEM private key to webHook server
 * @param {String} [options.webHook.cert] PEM certificate key to webHook server
 * @see https://core.telegram.org/bots/api
 */
var TelegramBot = function (token, options) {
  options = options || {};
  this.token = token;

  var processUpdate = this._processUpdate.bind(this);

  if (options.polling) {
    this._polling = new TelegramBotPolling(token, options.polling, processUpdate);
  }

  if (options.webHook) {
    this._WebHook = new TelegramBotWebHook(token, options.webHook, processUpdate);
  }
};

util.inherits(TelegramBot, EventEmitter);

TelegramBot.prototype._processUpdate = function (update) {
  debug('Process Update', update);
  debug('Process Update message', update.message);
  if (update.message) {
    this.emit('message', update.message);
  }
};

TelegramBot.prototype._request = function (path, options) {
  if (!this.token) {
    throw new Error('Telegram Bot Token not provided!');
  }
  options = options || {};
  options.url = URL.format({
    protocol: 'https',
    host: 'api.telegram.org',
    pathname: '/bot'+this.token+'/'+path
  });
  if (options.method === 'POST') {
    options.formData = options.formData || {};
    Object.keys(options.qs).forEach(function (k) {
      options.formData[k] = options.qs[k];
      delete options.qs[k];
    });
  }
  debug('HTTP request: %j', options);
  return requestPromise(options)
    .then(function (resp) {
      if (resp[0].statusCode !== 200) {
        throw new Error(resp[0].statusCode+' '+resp[0].body);
      }
      var data = JSON.parse(resp[0].body);
      if (data.ok) {
        return data.result;
      } else {
        throw new Error(data.error_code+' '+data.description);
      }
    });
};

/**
 * Returns basic information about the bot in form of a `User` object.
 * @return {Promise}
 * @see https://core.telegram.org/bots/api#getme
 */
TelegramBot.prototype.getMe = function () {
  var path = 'getMe';
  return this._request(path);
};

/**
 * Specify an url to receive incoming updates via an outgoing webHook.
 * @param {String} url URL where Telegram will make HTTP Post. Leave empty to
 * delete webHook.
 * @see https://core.telegram.org/bots/api#setwebhook
 */
TelegramBot.prototype.setWebHook = function (url) {
  var path = 'setWebHook';
  var qs = {url: url};
  return this._request(path, {qs: qs})
    .then(function (resp) {
      if (!resp) {
        throw new Error(resp);
      }
      return resp;
    });
};

/**
 * Use this method to receive incoming updates using long polling
 * @param  {Number|String} [timeout] Timeout in seconds for long polling.
 * @param  {Number|String} [limit] Limits the number of updates to be retrieved.
 * @param  {Number|String} [offset] Identifier of the first update to be returned.
 * @return {Promise} Updates
 * @see https://core.telegram.org/bots/api#getupdates
 */
TelegramBot.prototype.getUpdates = function (timeout, limit, offset) {
  var query = {
    offset: offset,
    limit: limit,
    timeout: timeout
  };

  return this._request('getUpdates', {qs: query});
};

/**
 * Send text message.
 * @param  {Number|String} chatId Unique identifier for the message recipient
 * @param  {String} text Text of the message to be sent
 * @param  {Object} [options] Additional Telegram query options
 * @return {Promise}
 * @see https://core.telegram.org/bots/api#sendmessage
 */
TelegramBot.prototype.sendMessage = function (chatId, text, options) {
  var query = options || {};
  query.chat_id = chatId;
  query.text = text;
  return this._request('sendMessage', {qs: query, method: 'POST'});
};

/**
 * Forward messages of any kind.
 * @param  {Number|String} chatId     Unique identifier for the message recipient
 * @param  {Number|String} fromChatId Unique identifier for the chat where the
 * original message was sent
 * @param  {Number|String} messageId  Unique message identifier
 * @return {Promise}
 */
TelegramBot.prototype.forwardMessage = function (chatId, fromChatId, messageId) {
  var query = {
    chat_id: chatId,
    from_chat_id: fromChatId,
    message_id: messageId
  };
  return this._request('forwardMessage', {qs: query, method: 'POST'});
};

TelegramBot.prototype._formatSendData = function (type, data) {
  var formData;
  var fileName;
  var fileId;
  if (data instanceof stream.Stream) {
    fileName = URL.parse(path.basename(data.path)).pathname;
    formData = {};
    formData[type] = {
      value: data,
      options: {
        filename: fileName,
        contentType: mime.lookup(fileName)
      }
    };
  } else if (fs.existsSync(data)) {
    fileName = path.basename(data);
    formData = {};
    formData[type] = {
      value: fs.createReadStream(data),
      options: {
        filename: fileName,
        contentType: mime.lookup(fileName)
      }
    };
  } else {
    fileId = data;
  }
  return [formData, fileId];
};

/**
 * Send photo
 * @param  {Number|String} chatId  Unique identifier for the message recipient
 * @param  {String|stream.Stream} photo A file path or a Stream. Can
 * also be a `file_id` previously uploaded
 * @param  {Object} [options] Additional Telegram query options
 * @return {Promise}
 * @see https://core.telegram.org/bots/api#sendphoto
 */
TelegramBot.prototype.sendPhoto = function (chatId, photo, options) {
  var opts = {
    qs: options || {},
    method: 'POST'
  };
  opts.qs.chat_id = chatId;
  var content = this._formatSendData('photo', photo);
  opts.formData = content[0];
  opts.qs.photo = content[1];
  return this._request('sendPhoto', opts);
};

/**
 * Send audio
 * @param  {Number|String} chatId  Unique identifier for the message recipient
 * @param  {String|stream.Stream} audio A file path or a Stream. Can
 * also be a `file_id` previously uploaded.
 * @param  {Object} [options] Additional Telegram query options
 * @return {Promise}
 * @see https://core.telegram.org/bots/api#sendaudio
 */
TelegramBot.prototype.sendAudio = function (chatId, audio, options) {
  var opts = {
    qs: options || {}
  };
  opts.qs.chat_id = chatId;
  var content = this._formatSendData('audio', audio);
  opts.formData = content[0];
  opts.qs.audio = content[1];
  return this._request('sendAudio', opts);
};

/**
 * Send Document
 * @param  {Number|String} chatId  Unique identifier for the message recipient
 * @param  {String|stream.Stream} A file path or a Stream. Can
 * also be a `file_id` previously uploaded.
 * @param  {Object} [options] Additional Telegram query options
 * @return {Promise}
 * @see https://core.telegram.org/bots/api#sendDocument
 */
TelegramBot.prototype.sendDocument = function (chatId, doc, options) {
  var opts = {
    qs: options || {}
  };
  opts.qs.chat_id = chatId;
  var content = this._formatSendData('document', doc);
  opts.formData = content[0];
  opts.qs.document = content[1];
  return this._request('sendDocument', opts);
};

/**
 * Send .webp stickers.
 * @param  {Number|String} chatId  Unique identifier for the message recipient
 * @param  {String|stream.Stream} A file path or a Stream. Can
 * also be a `file_id` previously uploaded.
 * @param  {Object} [options] Additional Telegram query options
 * @return {Promise}
 * @see https://core.telegram.org/bots/api#sendsticker
 */
TelegramBot.prototype.sendSticker = function (chatId, sticker, options) {
  var opts = {
    qs: options || {}
  };
  opts.qs.chat_id = chatId;
  var content = this._formatSendData('sticker', sticker);
  opts.formData = content[0];
  opts.qs.sticker = content[1];
  return this._request('sendSticker', opts);
};

/**
 * Send video files, Telegram clients support mp4 videos (other formats may be sent whith `sendDocument`)
 * @param  {Number|String} chatId  Unique identifier for the message recipient
 * @param  {String|stream.Stream} A file path or a Stream. Can
 * also be a `file_id` previously uploaded.
 * @param  {Object} [options] Additional Telegram query options
 * @return {Promise}
 * @see https://core.telegram.org/bots/api#sendvideo
 */
TelegramBot.prototype.sendVideo = function (chatId, video, options) {
  var opts = {
    qs: options || {}
  };
  opts.qs.chat_id = chatId;
  var content = this._formatSendData('video', video);
  opts.formData = content[0];
  opts.qs.video = content[1];
  return this._request('sendVideo', opts);
};

/**
 * Send chat action.
 * `typing` for text messages,
 * `upload_photo` for photos, `record_video` or `upload_video` for videos,
 * `record_audio` or `upload_audio` for audio files, `upload_document` for general files,
 * `find_location` for location data.
 *
 * @param  {Number|String} chatId  Unique identifier for the message recipient
 * @param  {String} action Type of action to broadcast.
 * @return {Promise}
 * @see https://core.telegram.org/bots/api#sendchataction
 */
TelegramBot.prototype.sendChatAction = function (chatId, action) {
  var query = {
    chat_id: chatId,
    action: action
  };
  return this._request('sendChatAction', {qs: query});
};

/**
 * Use this method to get a list of profile pictures for a user.
 * Returns a [UserProfilePhotos](https://core.telegram.org/bots/api#userprofilephotos) object.
 *
 * @param  {Number|String} userId  Unique identifier of the target user
 * @param  {Number} [offset] Sequential number of the first photo to be returned. By default, all photos are returned.
 * @param  {Number} [limit] Limits the number of photos to be retrieved. Values between 1—100 are accepted. Defaults to 100.
 * @return {Promise}
 * @see https://core.telegram.org/bots/api#getuserprofilephotos
 */
TelegramBot.prototype.getUserProfilePhotos = function (userId, offset, limit) {
  var query = {
    user_id: userId,
    offset: offset,
    limit: limit
  };
  return this._request('getUserProfilePhotos', {qs: query});
};

/**
 * Send location.
 * Use this method to send point on the map.
 *
 * @param  {Number|String} chatId  Unique identifier for the message recipient
 * @param  {Float} latitude Latitude of location
 * @param  {Float} longitude Longitude of location
 * @param  {Object} [options] Additional Telegram query options
 * @return {Promise}
 * @see https://core.telegram.org/bots/api#sendlocation
 */
TelegramBot.prototype.sendLocation = function (chatId, latitude, longitude, options) {
  var query = options || {};
  query.chat_id = chatId;
  query.latitude = latitude;
  query.longitude = longitude;
  return this._request('sendLocation', {qs: query});
};

module.exports = TelegramBot;
<|endoftext|>


<commit_before>function loadNavbar() {
    $(document).ready(function () {
        $("div.navbar-frame").load(location.protocol + '//' + document.domain + ':' + location.port + "/shared/navbar.html");
    });
}

function checkAuthState() {
    if (!isAuthenticated()) {
        window.location.replace(location.protocol + '//' + document.domain + ':' + location.port);
    }
}

function fillUsersTable() {
    var users = getUsers();
    $(function() {
        var role= "";
        $.each(users, function(i, item) {
            if (item.authorities[1] === "ROLE_ADMIN") {
                role = "ADMIN";
            }
            if (item.authorities[1] == undefined) {
                role = "USER";
            }
            var tr = $('
').append(
                $('
'),
                $('').text(item.id),
                $('').text(item.login),
                $('').text(item.firstName),
                $('').text(item.lastName),
                $('').text(item.email),
                $('').html(role),
                $('').text(item.createdDate),
                $('').html("<button type=\"button\" class=\"btn btn-danger btn-xs\" onclick=\"deleteUser(" +item.login + "); location.reload(); \"> </button>")
            );
            $(".table").append(tr.html());
        });
    });
}

function fillTeamsTable() {
    var teams = getTeams();
    $(function() {
        $.each(teams, function(i, item) {
            var tr = $('
').append(
                $('
'),
                $('').text(item.id),
                $('').text(item.teamName),
                $('').text(item.teamDescription),
                $('').html("<button type=\"button\" class=\"btn btn-danger btn-xs\" onclick=\"deleteTeam(" +item.id + "); location.reload(); \"> </button>")
            );
            $(".table").append(tr.html());
        });
    });
}

function fillProjectsTable() {
    var projects = getProjects();
    $(function() {
        $.each(projects, function(i, item) {
            var tr = $('
').append(
                $('
'),
                $('').text(item.id),
                $('').text(item.projectName),
                $('').text(item.projectDescription),
                $('').html("" + item.projectWebsite + ""),
                $('').html("<button type=\"button\" class=\"btn btn-danger btn-xs\" onclick=\"deleteProject(" +item.id + "); location.reload(); \"> </button>")

        );
            $(".table").append(tr.html());
        });
    });
}

function fillEnginesTable() {
    var engines = getEngines();
    $(function() {
        $.each(engines, function(i, item) {
            var tr = $('
').append(
                $('
'),
                $('').text(item.id),
                $('').text(item.engineName),
                $('').text(item.engineDescription),
                $('').html("<button type=\"button\" class=\"btn btn-danger btn-xs\" onclick=\"deleteEngine(" +item.id + "); location.reload(); \"> </button>")
        );
            $(".table").append(tr.html());
        });
    });
}

function fillEmailAccountsTable() {
    var accounts = getEmailAccounts();
    $(function() {
        $.each(accounts, function(i, item) {
            var tr = $('
').append(
                $('
'),
                $('').text(item.id),
                $('').text(item.emailAccountName),
                $('').text(item.emailAccountDescription),
                $('').html("<button type=\"button\" class=\"btn btn-danger btn-xs\" onclick=\"deleteEmailAccount(" +item.id + "); location.reload(); \"> </button>")
            );
            $(".table").append(tr.html());
        });
    });
}

function fillIRCBotsTable() {
    var bots = getIRCBots();
    $(function() {
        $.each(bots, function(i, item) {
            var tr = $('
').append(
                $('
'),
                $('').text(item.id),
                $('').text(item.ircBotName),
                $('').text(item.ircBotDescription),
                $('').html("<button type=\"button\" class=\"btn btn-danger btn-xs\" onclick=\"deleteIRCBot(" +item.id + "); location.reload(); \"> </button>")
            );
            $(".table").append(tr.html());
        });
    });
}

function fillSlackAccountTable() {
    var bots = getSlackAccounts();
    $(function() {
        $.each(bots, function(i, item) {
            var tr = $('
').append(
                $('
'),
                $('').text(item.id),
                $('').text(item.slackAccountName),
                $('').text(item.slackAccountDescription),
                $('').html("<button type=\"button\" class=\"btn btn-danger btn-xs\" onclick=\"deleteSlackAccount(" +item.id + "); location.reload(); \"> </button>")
            );
            $(".table").append(tr.html());
        });
    });
}

function fillTelegramBotsTable() {
    var bots = getTelegramBots();
    $(function() {
        $.each(bots, function(i, item) {
            var tr = $('
').append(
                $('
'),
                $('').text(item.id),
                $('').text(item.telegramBotName),
                $('').text(item.telegramBotDescription),
                $('').html("<button type=\"button\" class=\"btn btn-danger btn-xs\" onclick=\"deleteTelegramBot(" +item.id + "); location.reload(); \"> </button>")
            );
            $(".table").append(tr.html());
        });
    });
}

function fillTwitterBotsTable() {
    var bots = getTwitterBots();
    $(function() {
        $.each(bots, function(i, item) {
            var tr = $('
').append(
                $('
'),
                $('').text(item.id),
                $('').text(item.twitterBotName),
                $('').text(item.twitterBotDescription),
                $('').html("<button type=\"button\" class=\"btn btn-danger btn-xs\" onclick=\"deleteTwitterBot(" +item.id + "); location.reload(); \"> </button>")
            );
            $(".table").append(tr.html());
        });
    });
}

function fillSettingsForm(username) {
    var accountInformation = getAccountInformation(username);
    $(document).ready(function () {
        document.getElementById('firstname').value = accountInformation.firstName;
        document.getElementById('lastname').value = accountInformation.lastName;
        document.getElementById('email').value = accountInformation.email;
        document.getElementById('language').value = localStorage.getItem("language");
    });

}<commit_msg>Disable delete button on current user account in Gamecraft UI<commit_after>function loadNavbar() {
    $(document).ready(function () {
        $("div.navbar-frame").load(location.protocol + '//' + document.domain + ':' + location.port + "/shared/navbar.html");
    });
}

function checkAuthState() {
    if (!isAuthenticated()) {
        window.location.replace(location.protocol + '//' + document.domain + ':' + location.port);
    }
}

function fillUsersTable() {
    var users = getUsers();
    $(function() {
        var role= "";
        $.each(users, function(i, item) {
            if (item.authorities[1] === "ROLE_ADMIN") {
                role = "ADMIN";
            }
            if (item.authorities[1] == undefined) {
                role = "USER";
            }
            if (item.login == getUsername()) {
                var tr = $('
').append(
                    $('
'),
                    $('').text(item.id),
                    $('').text(item.login),
                    $('').text(item.firstName),
                    $('').text(item.lastName),
                    $('').text(item.email),
                    $('').html(role),
                    $('').text(item.createdDate)
                );
                $(".table").append(tr.html());
            }
            else {
                var tr = $('
').append(
                    $('
'),
                    $('').text(item.id),
                    $('').text(item.login),
                    $('').text(item.firstName),
                    $('').text(item.lastName),
                    $('').text(item.email),
                    $('').html(role),
                    $('').text(item.createdDate),
                    $('').html("<button type=\"button\" class=\"btn btn-danger btn-xs\" onclick=\"deleteUser(" +item.login + "); location.reload(); \"> </button>")
                );
                $(".table").append(tr.html());

            }

        });
    });
}

function fillTeamsTable() {
    var teams = getTeams();
    $(function() {
        $.each(teams, function(i, item) {
            var tr = $('
').append(
                $('
'),
                $('').text(item.id),
                $('').text(item.teamName),
                $('').text(item.teamDescription),
                $('').html("<button type=\"button\" class=\"btn btn-danger btn-xs\" onclick=\"deleteTeam(" +item.id + "); location.reload(); \"> </button>")
            );
            $(".table").append(tr.html());
        });
    });
}

function fillProjectsTable() {
    var projects = getProjects();
    $(function() {
        $.each(projects, function(i, item) {
            var tr = $('
').append(
                $('
'),
                $('').text(item.id),
                $('').text(item.projectName),
                $('').text(item.projectDescription),
                $('').html("" + item.projectWebsite + ""),
                $('').html("<button type=\"button\" class=\"btn btn-danger btn-xs\" onclick=\"deleteProject(" +item.id + "); location.reload(); \"> </button>")

        );
            $(".table").append(tr.html());
        });
    });
}

function fillEnginesTable() {
    var engines = getEngines();
    $(function() {
        $.each(engines, function(i, item) {
            var tr = $('
').append(
                $('
'),
                $('').text(item.id),
                $('').text(item.engineName),
                $('').text(item.engineDescription),
                $('').html("<button type=\"button\" class=\"btn btn-danger btn-xs\" onclick=\"deleteEngine(" +item.id + "); location.reload(); \"> </button>")
        );
            $(".table").append(tr.html());
        });
    });
}

function fillEmailAccountsTable() {
    var accounts = getEmailAccounts();
    $(function() {
        $.each(accounts, function(i, item) {
            var tr = $('
').append(
                $('
'),
                $('').text(item.id),
                $('').text(item.emailAccountName),
                $('').text(item.emailAccountDescription),
                $('').html("<button type=\"button\" class=\"btn btn-danger btn-xs\" onclick=\"deleteEmailAccount(" +item.id + "); location.reload(); \"> </button>")
            );
            $(".table").append(tr.html());
        });
    });
}

function fillIRCBotsTable() {
    var bots = getIRCBots();
    $(function() {
        $.each(bots, function(i, item) {
            var tr = $('
').append(
                $('
'),
                $('').text(item.id),
                $('').text(item.ircBotName),
                $('').text(item.ircBotDescription),
                $('').html("<button type=\"button\" class=\"btn btn-danger btn-xs\" onclick=\"deleteIRCBot(" +item.id + "); location.reload(); \"> </button>")
            );
            $(".table").append(tr.html());
        });
    });
}

function fillSlackAccountTable() {
    var bots = getSlackAccounts();
    $(function() {
        $.each(bots, function(i, item) {
            var tr = $('
').append(
                $('
'),
                $('').text(item.id),
                $('').text(item.slackAccountName),
                $('').text(item.slackAccountDescription),
                $('').html("<button type=\"button\" class=\"btn btn-danger btn-xs\" onclick=\"deleteSlackAccount(" +item.id + "); location.reload(); \"> </button>")
            );
            $(".table").append(tr.html());
        });
    });
}

function fillTelegramBotsTable() {
    var bots = getTelegramBots();
    $(function() {
        $.each(bots, function(i, item) {
            var tr = $('
').append(
                $('
'),
                $('').text(item.id),
                $('').text(item.telegramBotName),
                $('').text(item.telegramBotDescription),
                $('').html("<button type=\"button\" class=\"btn btn-danger btn-xs\" onclick=\"deleteTelegramBot(" +item.id + "); location.reload(); \"> </button>")
            );
            $(".table").append(tr.html());
        });
    });
}

function fillTwitterBotsTable() {
    var bots = getTwitterBots();
    $(function() {
        $.each(bots, function(i, item) {
            var tr = $('
').append(
                $('
'),
                $('').text(item.id),
                $('').text(item.twitterBotName),
                $('').text(item.twitterBotDescription),
                $('').html("<button type=\"button\" class=\"btn btn-danger btn-xs\" onclick=\"deleteTwitterBot(" +item.id + "); location.reload(); \"> </button>")
            );
            $(".table").append(tr.html());
        });
    });
}

function fillSettingsForm(username) {
    var accountInformation = getAccountInformation(username);
    $(document).ready(function () {
        document.getElementById('firstname').value = accountInformation.firstName;
        document.getElementById('lastname').value = accountInformation.lastName;
        document.getElementById('email').value = accountInformation.email;
        document.getElementById('language').value = localStorage.getItem("language");
    });

}<|endoftext|>


<commit_before>function CalculatorController($scope) {
    $scope.inputs= [
        [1,2,3,"+"],
        [4,5,6,"-"],
        [7,8,9,"*"],
        [".",0,"","/"]
    ];

    var operators = ["+","-","*","/"];

    $scope.displayValue= "";
    $scope.add = function(value){

        if(operators.indexOf(value)>-1 && operators.indexOf($scope.displayValue.slice(-1))>-1) {
            $scope.deleteLast();
        }
        $scope.displayValue += value;
    };

    $scope.solve = function() {
        $scope.displayValue = eval($scope.displayValue);
    };

    $scope.clean = function() {
        $scope.displayValue= "";
    };

    $scope.deleteLast = function() {
        $scope.displayValue = $scope.displayValue.slice(0,-1);
    };
}<commit_msg>bugfix: keep displayvalue a string<commit_after>function CalculatorController($scope) {
    $scope.inputs= [
        [1,2,3,"+"],
        [4,5,6,"-"],
        [7,8,9,"*"],
        [".",0,"","/"]
    ];

    var operators = ["+","-","*","/"];

    $scope.displayValue= "";
    $scope.add = function(value){

        if(operators.indexOf(value)>-1 && operators.indexOf($scope.displayValue.slice(-1))>-1) {
            $scope.deleteLast();
        }
        $scope.displayValue += value;
    };

    $scope.solve = function() {
        $scope.displayValue = "" + eval($scope.displayValue);
    };

    $scope.clean = function() {
        $scope.displayValue= "";
    };

    $scope.deleteLast = function() {
        $scope.displayValue = $scope.displayValue.slice(0,-1);
    };
}<|endoftext|>


<commit_before>/* global -Promise */
'use strict';

var superagent = require('superagent'),
    Promise = require('bluebird');

var request = function(url) {
    var deferred = Promise.defer();

    if (typeof url !== 'string') {
      deferred.reject(new Error('The URL/path must be a string.'));
    }

    var body = '';
    superagent
        .get(url)
        .end(function(err, res) {
            if (err) {
                return deferred.reject(err);
            }
            if (res.statusCode >= 300) {
                return deferred.reject(new Error('Server responded with status code '+ res.statusCode +' for url ' + url));
            }

            deferred.resolve(res.text);
        });

    return deferred.promise;
};

module.exports = request;<commit_msg>Remove extraneous variable from promise-superagent<commit_after>/* global -Promise */
'use strict';

var superagent = require('superagent'),
    Promise = require('bluebird');

var request = function(url) {
    var deferred = Promise.defer();

    if (typeof url !== 'string') {
      deferred.reject(new Error('The URL/path must be a string.'));
    }

    superagent
        .get(url)
        .end(function(err, res) {
            if (err) {
                return deferred.reject(err);
            }
            if (res.statusCode >= 300) {
                return deferred.reject(new Error('Server responded with status code '+ res.statusCode +' for url ' + url));
            }

            deferred.resolve(res.text);
        });

    return deferred.promise;
};

module.exports = request;<|endoftext|>


<commit_before>

define(["sugar-web/activity/activity","sugar-web/datastore"], function (activity, datastore) {
	if (!Abcd) {
		Abcd = {};
	}
	Abcd.activity = activity;
	Abcd.datastore = datastore;
	app = null;

	// Manipulate the DOM only when it is ready.
	requirejs(['domReady!'], function (doc) {
		// Initialize the activity
		Abcd.activity.setup();

		// Create sound component
		Abcd.sound = new Abcd.Audio();
		Abcd.sound.renderInto(document.getElementById("header"));

		// Load Database
		Abcd.loadDatabase(function(err) {
			// Init localization
			Abcd.initL10n();

			// Create and display first screen
			app = new Abcd.App().renderInto(document.getElementById("body"));

			// Load context
			Abcd.loadContext(function() {
				app.restartLastGame();
			});
		});

		// Stop sound at end of game to sanitize media environment, specifically on Android
		document.getElementById("stop-button").addEventListener('click', function (event) {
			Abcd.sound.pause();
		});

		// Full screen
		document.getElementById("fullscreen-button").addEventListener('click', function() {
			document.getElementById("main-toolbar").style.opacity = 0;
			document.getElementById("canvas").style.top = "0px";
			document.getElementById("unfullscreen-button").style.visibility = "visible";
			document.getElementById("learn_caseButton").style.visibility = "hidden";
			document.getElementById("learn_languageButton").style.visibility = "hidden";
		});
		document.getElementById("unfullscreen-button").addEventListener('click', function() {
			document.getElementById("main-toolbar").style.opacity = 1;
			document.getElementById("canvas").style.top = "55px";
			document.getElementById("unfullscreen-button").style.visibility = "hidden";
			document.getElementById("learn_caseButton").style.visibility = "visible";
			document.getElementById("learn_languageButton").style.visibility = "visible";
		});
	});

});
<commit_msg>Removed buttons on fullscreen.<commit_after>

define(["sugar-web/activity/activity","sugar-web/datastore"], function (activity, datastore) {
	if (!Abcd) {
		Abcd = {};
	}
	Abcd.activity = activity;
	Abcd.datastore = datastore;
	app = null;

	// Manipulate the DOM only when it is ready.
	requirejs(['domReady!'], function (doc) {
		// Initialize the activity
		Abcd.activity.setup();

		// Create sound component
		Abcd.sound = new Abcd.Audio();
		Abcd.sound.renderInto(document.getElementById("header"));

		// Load Database
		Abcd.loadDatabase(function(err) {
			// Init localization
			Abcd.initL10n();

			// Create and display first screen
			app = new Abcd.App().renderInto(document.getElementById("body"));

			// Load context
			Abcd.loadContext(function() {
				app.restartLastGame();
			});
		});

		// Stop sound at end of game to sanitize media environment, specifically on Android
		document.getElementById("stop-button").addEventListener('click', function (event) {
			Abcd.sound.pause();
		});
		function hidebutton(){
			var x = document.getElementsByClassName("switchCase");
			var y = document.getElementsByClassName("switchLang");
			var i;
			for (i = 0; i < x.length; i++) {
  			x[i].style.visibility = "hidden";
  			}
  			for (i = 0; i < y.length; i++) {
  			y[i].style.visibility = "hidden";
  			}
  		}
  		function showbutton(){
			var x = document.getElementsByClassName("switchCase");
			var y = document.getElementsByClassName("switchLang");
			var i;
			for (i = 0; i < x.length; i++) {
  			x[i].style.visibility = "visible";
  			}
  			for (i = 0; i < y.length; i++) {
  			y[i].style.visibility = "visible";
  			}
  		}

		// Full screen
		document.getElementById("fullscreen-button").addEventListener('click', function() {
			document.getElementById("main-toolbar").style.opacity = 0;
			document.getElementById("canvas").style.top = "0px";
			document.getElementById("unfullscreen-button").style.visibility = "visible";
			hidebutton();
		});
		document.getElementById("unfullscreen-button").addEventListener('click', function() {
			document.getElementById("main-toolbar").style.opacity = 1;
			document.getElementById("canvas").style.top = "55px";
			document.getElementById("unfullscreen-button").style.visibility = "hidden";
			showbutton();
		});
	});

});
<|endoftext|>


<commit_before>import React, { PureComponent } from 'react';

// Components
import Spinner from 'components/ui/Spinner';
import Field from 'components/form/Field';
import Input from 'components/form/Input';
import Select from 'components/form/SelectInput';

// Constants
import { FORM_COUNTRIES } from './constants';

class NewsletterModalComponent extends PureComponent {

  render() {
    return (

Sign up for the Resource Watch newsletter

Get the latest stoires on the data that powers your world.

        <form
          className="c-form"
          accept-charset="UTF-8"
          method="post"
          action="https://go.pardot.com/l/120942/2018-01-25/3nzl13"
          id="pardot-form">
          <Field
            validations={['required']}
            className="-fluid"
            properties={{
              name: 'first_name',
              label: 'First name',
              type: 'text',
              required: true,
            }}
          >
            {Input}
          </Field>
          <Field
            validations={['required']}
            className="-fluid"
            properties={{
              name: 'last_name',
              label: 'Last name',
              type: 'text',
              required: true,
            }}
          >
            {Input}
          </Field>
          <Field
            validations={['required', 'email']}
            className="-fluid"
            properties={{
              name: 'email',
              label: 'Email',
              type: 'email',
              required: true,
            }}
          >
            {Input}
          </Field>
          <Field
            validations={['required']}
            className="-fluid"
            properties={{
              name: 'company',
              label: 'Company',
              type: 'text',
              required: true,
            }}
          >
            {Input}
          </Field>
          <Field
            className="-fluid"
            properties={{
              name: 'job_title',
              label: 'Job title',
              type: 'text',
              required: false,
            }}
          >
            {Input}
          </Field>
          <Field
            validations={['required']}
            className="-fluid"
            properties={{
              name: 'city',
              label: 'City',
              type: 'text',
              required: true,
            }}
          >
            {Input}
          </Field>
          <Field
            validations={['required']}
            className="-fluid"
            options={ FORM_COUNTRIES.options }
            properties={{
              name: 'country',
              label: 'Country',
              type: 'text',
              required: true,
            }}
          >
            {Select}
          </Field>
          { /* pardot honeypot field */ }
          <Field
            className={'-pi-hidden'}
            properties={{
              name: 'pi_extra_field',
              label: 'Comments',
              type: 'text',
              required: false,
            }}
          >
            {Input}
          </Field>

            <button type="submit" className={`c-btn -primary`}>
              Submit
            </button>

        </form>

    );
  }
}

export default NewsletterModalComponent;
<commit_msg>fix linter warnings<commit_after>import React, { PureComponent } from 'react';

// Components
import Spinner from 'components/ui/Spinner';
import Field from 'components/form/Field';
import Input from 'components/form/Input';
import Select from 'components/form/SelectInput';

// Constants
import { FORM_COUNTRIES } from './constants';

class NewsletterModalComponent extends PureComponent {

  render() {
    return (

Sign up for the Resource Watch newsletter

Get the latest stoires on the data that powers your world.

        <form
          className="c-form"
          accept-charset="UTF-8"
          method="post"
          action="https://go.pardot.com/l/120942/2018-01-25/3nzl13"
          id="pardot-form"
        >
          <Field
            validations={['required']}
            className="-fluid"
            properties={{
              name: 'first_name',
              label: 'First name',
              type: 'text',
              required: true
            }}
          >
            {Input}
          </Field>
          <Field
            validations={['required']}
            className="-fluid"
            properties={{
              name: 'last_name',
              label: 'Last name',
              type: 'text',
              required: true
            }}
          >
            {Input}
          </Field>
          <Field
            validations={['required', 'email']}
            className="-fluid"
            properties={{
              name: 'email',
              label: 'Email',
              type: 'email',
              required: true
            }}
          >
            {Input}
          </Field>
          <Field
            validations={['required']}
            className="-fluid"
            properties={{
              name: 'company',
              label: 'Company',
              type: 'text',
              required: true
            }}
          >
            {Input}
          </Field>
          <Field
            className="-fluid"
            properties={{
              name: 'job_title',
              label: 'Job title',
              type: 'text',
              required: false
            }}
          >
            {Input}
          </Field>
          <Field
            validations={['required']}
            className="-fluid"
            properties={{
              name: 'city',
              label: 'City',
              type: 'text',
              required: true
            }}
          >
            {Input}
          </Field>
          <Field
            validations={['required']}
            className="-fluid"
            options={FORM_COUNTRIES.options}
            properties={{
              name: 'country',
              label: 'Country',
              type: 'text',
              required: true
            }}
          >
            {Select}
          </Field>
          { /* pardot honeypot field */ }
          <Field
            className="-pi-hidden"
            properties={{
              name: 'pi_extra_field',
              label: 'Comments',
              type: 'text',
              required: false
            }}
          >
            {Input}
          </Field>

            <button type="submit" className="c-btn -primary">
              Submit
            </button>

        </form>

    );
  }
}

export default NewsletterModalComponent;
<|endoftext|>


<commit_before>

// showView('.view-decision-result');

//

// function to write message on side panels
function myMsg(message){
	// return txt;
	showView('.view-text');
	var canvases = document.querySelectorAll("canvas");

	for (var i=0; i<canvases.length; i++) {
		var ctx = canvases[i].getContext("2d");
	 	animateWords(ctx);
	}

	function animateWords(ctx) {
		var dashLen = 120, dashOffset = dashLen, speed = 5,
	    txt = message, x = 1, i = 0;
		ctx.font = "20px Dosis";
		ctx.lineWidth = 1; ctx.lineJoin = "round"; ctx.globalAlpha = 2/3;
		ctx.strokeStyle = ctx.fillStyle = "#ffffff";
		const numberOfLines = (txt.match(/\n/g) || []).length;
		const lineHeight = 50;
		const lineSpacing = 20;
		var y = 90 - (numberOfLines / 2) * (lineHeight + lineSpacing);

		(function loop() {
		  ctx.clearRect(x, y - lineHeight, 60, 150);
		  ctx.setLineDash([dashLen - dashOffset, dashOffset - speed]); // create a long dash mask
		  dashOffset -= speed;                                         // reduce dash length
		  var letter = txt[i];
		  if (letter === "\n") {
		  	i += 1;
		  	letter = txt[i]
		  	y += lineHeight + lineSpacing;
		  	x = 0;
		  }
		  var nextLetter = txt[i];

		  ctx.strokeText(txt[i], x, y);                               // stroke letter

		  if (dashOffset > 0) {
			requestAnimationFrame(loop);             // animate
		  } else {
		    ctx.fillText(txt[i], x, y);                               // fill final letter
		    dashOffset = dashLen;                                      // prep next char
		    x += ctx.measureText(nextLetter).width + ctx.lineWidth * (0.5 + 0.5);
		    ctx.setTransform(1, 0, 0, 1, 0, 3 * 0.1);        // random y-delta
		    //ctx.rotate(0.5 * 0.005);                         // random rotation
		    i += 1;
		    if (i < txt.length) {
		    	requestAnimationFrame(loop);
		    }
		  }
		})();
	}
}

//function to clear side panels
function clearMsg(){
	var canvases = document.querySelectorAll("canvas");

	for (var i=0; i<canvases.length; i++) {
		var ctx = canvases[i].getContext("2d");
	 	ctx.clearRect(0, 0, canvases[i].width, canvases[i].height);
	 }
}

<commit_msg>fix spacing<commit_after>

// showView('.view-decision-result');

//

// function to write message on side panels
function myMsg(message){
	// return txt;
	showView('.view-text');
	var canvases = document.querySelectorAll("canvas");

	for (var i=0; i<canvases.length; i++) {
		var ctx = canvases[i].getContext("2d");
	 	animateWords(ctx);
	}

	function animateWords(ctx) {
		var dashLen = 120, dashOffset = dashLen, speed = 5,
	    txt = message, x = 1, i = 0;
		ctx.font = "20px Dosis";
		ctx.lineWidth = 1; ctx.lineJoin = "round"; ctx.globalAlpha = 2/3;
		ctx.strokeStyle = ctx.fillStyle = "#ffffff";
		const numberOfLines = (txt.match(/\n/g) || []).length;
		const lineHeight = 30;
		const lineSpacing = 10;
		var y = 90 - (numberOfLines / 2) * (lineHeight + lineSpacing);

		(function loop() {
		  ctx.clearRect(x, y - lineHeight, 60, 150);
		  ctx.setLineDash([dashLen - dashOffset, dashOffset - speed]); // create a long dash mask
		  dashOffset -= speed;                                         // reduce dash length
		  var letter = txt[i];
		  if (letter === "\n") {
		  	i += 1;
		  	letter = txt[i]
		  	y += lineHeight + lineSpacing;
		  	x = 0;
		  }
		  var nextLetter = txt[i];

		  ctx.strokeText(txt[i], x, y);                               // stroke letter

		  if (dashOffset > 0) {
			requestAnimationFrame(loop);             // animate
		  } else {
		    ctx.fillText(txt[i], x, y);                               // fill final letter
		    dashOffset = dashLen;                                      // prep next char
		    x += ctx.measureText(nextLetter).width + ctx.lineWidth;
		    ctx.setTransform(1, 0, 0, 1, 0, 3 * 0.1);        // random y-delta
		    //ctx.rotate(0.5 * 0.005);                         // random rotation
		    i += 1;
		    if (i < txt.length) {
		    	requestAnimationFrame(loop);
		    }
		  }
		})();
	}
}

//function to clear side panels
function clearMsg(){
	var canvases = document.querySelectorAll("canvas");

	for (var i=0; i<canvases.length; i++) {
		var ctx = canvases[i].getContext("2d");
	 	ctx.clearRect(0, 0, canvases[i].width, canvases[i].height);
	 }
}

<|endoftext|>


<commit_before>D.import_port_flavour('socket-out', {
  dir: 'out',
  outside_exit: function(ship) {
<<<<<<< HEAD
    var channel = 'bounce'

    if(this.settings.all.length > 2)
      channel = this.settings.thing // explicit third param only -- no sugar

    if(!D.Etc.socket)
      return D.set_error('You must place a valid socket connection in D.Etc.socket')

    D.Etc.socket.emit(channel, ship)
  }
})
<commit_msg>oops decapitated<commit_after>D.import_port_flavour('socket-out', {
  dir: 'out',
  outside_exit: function(ship) {
    var channel = 'bounce'

    if(this.settings.all.length > 2)
      channel = this.settings.thing // explicit third param only -- no sugar

    if(!D.Etc.socket)
      return D.set_error('You must place a valid socket connection in D.Etc.socket')

    D.Etc.socket.emit(channel, ship)
  }
})
<|endoftext|>


<commit_before>'use strict';

var request = require('request');
var geocoder = require('geocoder');
var events = require('events');
var ProtoBuf = require('protobufjs');
var GoogleOAuth = require('gpsoauthnode');

var Logins = require('./logins');

var builder = ProtoBuf.loadProtoFile('pokemon.proto');
if (builder === null) {
    builder = ProtoBuf.loadProtoFile('./node_modules/pokemon-go-node-api/pokemon.proto');
}

var pokemonProto = builder.build();
var RequestEnvelop = pokemonProto.RequestEnvelop;
var ResponseEnvelop = pokemonProto.ResponseEnvelop;

var EventEmitter = events.EventEmitter;

var api_url = 'https://pgorelease.nianticlabs.com/plfe/rpc';

function Pokeio() {
    var self = this;
    self.events = new EventEmitter();
    self.j = request.jar();
    self.request = request.defaults({ jar: self.j });

    self.google = new GoogleOAuth();

    self.playerInfo = {
        'accessToken': '',
        'debug': true,
        'latitude': 0,
        'longitude': 0,
        'altitude': 0,
        'locationName': '',
        'provider': '',
        'apiEndpoint': ''
    };

    self.DebugPrint = function(str) {
        if (self.playerInfo.debug === true) {
            //self.events.emit('debug',str)
            console.log(str);
        }
    };

    function api_req(api_endpoint, access_token, req, callback) {
        // Auth
        var auth = new RequestEnvelop.AuthInfo({
            'provider': self.playerInfo.provider,
            'token': new RequestEnvelop.AuthInfo.JWT(access_token, 59)
        });

        var f_req = new RequestEnvelop({
            'unknown1': 2,
            'rpc_id': 1469378659230941192,

            'requests': req,

            'latitude': self.playerInfo.latitude,
            'longitude': self.playerInfo.longitude,
            'altitude': self.playerInfo.altitude,

            'auth': auth,
            'unknown12': 989
        });

        var protobuf = f_req.encode().toBuffer();

        var options = {
            url: api_endpoint,
            body: protobuf,
            encoding: null,
            headers: {
                'User-Agent': 'Niantic App'
            }
        };

        self.request.post(options, function(err, response, body) {
            if (response === undefined || body === undefined) {
                console.error('[!] RPC Server offline');
                return callback(new Error('RPC Server offline'));
            }

            try {
                var f_ret = ResponseEnvelop.decode(body);
            } catch (e) {
                if (e.decoded) { // Truncated
                    console.warn(e);
                    f_ret = e.decoded; // Decoded message with missing required fields
                }
            }

            return callback(null, f_ret);
        });

    }

    self.init = function(username, password, location, provider, callback) {
        if (provider !== 'ptc' && provider !== 'google') {
            throw new Error('Invalid provider');
        }
        // set provider
        self.playerInfo.provider = provider;
        // Updating location
        self.SetLocation(location, function(err, loc) {
            if (err) {
                return callback(err);
            }
            // Getting access token
            self.GetAccessToken(username, password, function(err, token) {
                if (err) {
                    return callback(err);
                }
                // Getting api endpoint
                self.GetApiEndpoint(function(err, api_endpoint) {
                    if (err) {
                        return callback(err);
                    }
                    callback(null);
                });
            });
        });

    };

    self.GetAccessToken = function(user, pass, callback) {
        self.DebugPrint('[i] Logging with user: ' + user);
        if (self.playerInfo.provider === 'ptc') {
            Logins.PokemonClub(user, pass, self, function(err, token) {
                if (err) {
                    return callback(err);
                }

                self.playerInfo.accessToken = token;
                self.DebugPrint("[i] Received PTC access token!")
                callback(null, token);
            });
        } else {
            Logins.GoogleAccount(user, pass, self, function(err, token) {
                if (err) {
                    return callback(err);
                }

                self.playerInfo.accessToken = token;
                self.DebugPrint("[i] Received Google access token!")
                callback(null, token);
            });
        }
    };

    self.GetApiEndpoint = function(callback) {
        var req = [];
        req.push(
            new RequestEnvelop.Requests(2),
            new RequestEnvelop.Requests(126),
            new RequestEnvelop.Requests(4),
            new RequestEnvelop.Requests(129),
            new RequestEnvelop.Requests(5)
        );

        api_req(api_url, self.playerInfo.accessToken, req, function(err, f_ret) {
            if (err) {
                return callback(err);
            }
            var api_endpoint = 'https://' + f_ret.api_url + '/rpc';
            self.playerInfo.apiEndpoint = api_endpoint;
            self.DebugPrint('[i] Received API Endpoint: ' + api_endpoint);
            callback(null, api_endpoint);
        });
    };

    self.GetProfile = function(callback) {
        var req = new RequestEnvelop.Requests(2);
        api_req(self.playerInfo.apiEndpoint, self.playerInfo.accessToken, req, function(err, f_ret) {
            if (err) {
                return callback(err);
            }
            var profile = ResponseEnvelop.ProfilePayload.decode(f_ret.payload[0]).profile

            if (profile.username) {
                self.DebugPrint('[i] Logged in!');
            }
            callback(null, profile);
        });
    };

    self.GetLocation = function(callback) {
        geocoder.reverseGeocode(self.playerInfo.latitude, self.playerInfo.longitude, function(err, data) {
            console.log('[i] lat/long/alt: ' + self.playerInfo.latitude + ' ' + self.playerInfo.longitude + ' ' + self.playerInfo.altitude);
            if (data.status === 'ZERO_RESULTS') {
                return callback(new Error('location not found'));
            }

            callback(null, data.results[0].formatted_address);
        });
    };

    self.GetLocationCoords = function() {
        var coords = {
            latitude: self.playerInfo.latitude,
            longitude: self.playerInfo.longitude,
            altitude: self.playerInfo.altitude,
        };

        return coords;
    };

    self.SetLocation = function(location, callback) {
        if (location.type !== 'name' && location.type !== 'coords') {
            throw new Error('Invalid location type');
        }

        if (location.type === 'name') {
            if (!location.name) {
                throw new Error('You should add a location name');
            }
            var locationName = location.name;
            geocoder.geocode(locationName, function(err, data) {
                if (err || data.status === 'ZERO_RESULTS') {
                    return callback(new Error('location not found'));
                }

                self.playerInfo.latitude = data.results[0].geometry.location.lat;
                self.playerInfo.longitude = data.results[0].geometry.location.lng;
                self.playerInfo.locationName = locationName;

                var coords = {
                    latitude: self.playerInfo.latitude,
                    longitude: self.playerInfo.longitude,
                    altitude: self.playerInfo.altitude,
                };

                callback(null, coords);
            });
        } else if (location.type === 'coords') {
            if (!location.coords) {
                throw new Error('Coords object missing');
            }

            self.playerInfo.latitude = coords.latitude ? coords.latitude : self.playerInfo.latitude;
            self.playerInfo.longitude = coords.longitude ? coords.longitude : self.playerInfo.longitude;
            self.playerInfo.altitude = coords.altitude ? coords.altitude : self.playerInfo.altitude;

            var coords = {
                latitude: self.playerInfo.latitude,
                longitude: self.playerInfo.longitude,
                altitude: self.playerInfo.altitude,
            };

            geocoder.reverseGeocode(self.playerInfo.latitude, self.playerInfo.longitude, function(err, data) {
                if (data.status !== 'ZERO_RESULTS') {
                    self.playerInfo.locationName = data.results[0].formatted_address;
                }
                callback(null, coords);
            });
        }
    };
}

module.exports = new Pokeio();
module.exports.Pokeio = Pokeio;
<commit_msg>fixed location and errors<commit_after>'use strict';

var request = require('request');
var geocoder = require('geocoder');
var events = require('events');
var ProtoBuf = require('protobufjs');
var GoogleOAuth = require('gpsoauthnode');

var Logins = require('./logins');

var builder = ProtoBuf.loadProtoFile('pokemon.proto');
if (builder === null) {
    builder = ProtoBuf.loadProtoFile('./node_modules/pokemon-go-node-api/pokemon.proto');
}

var pokemonProto = builder.build();
var RequestEnvelop = pokemonProto.RequestEnvelop;
var ResponseEnvelop = pokemonProto.ResponseEnvelop;

var EventEmitter = events.EventEmitter;

var api_url = 'https://pgorelease.nianticlabs.com/plfe/rpc';

function Pokeio() {
    var self = this;
    self.events = new EventEmitter();
    self.j = request.jar();
    self.request = request.defaults({ jar: self.j });

    self.google = new GoogleOAuth();

    self.playerInfo = {
        'accessToken': '',
        'debug': true,
        'latitude': 0,
        'longitude': 0,
        'altitude': 0,
        'locationName': '',
        'provider': '',
        'apiEndpoint': ''
    };

    self.DebugPrint = function(str) {
        if (self.playerInfo.debug === true) {
            //self.events.emit('debug',str)
            console.log(str);
        }
    };

    function api_req(api_endpoint, access_token, req, callback) {
        // Auth
        var auth = new RequestEnvelop.AuthInfo({
            'provider': self.playerInfo.provider,
            'token': new RequestEnvelop.AuthInfo.JWT(access_token, 59)
        });

        var f_req = new RequestEnvelop({
            'unknown1': 2,
            'rpc_id': 1469378659230941192,

            'requests': req,

            'latitude': self.playerInfo.latitude,
            'longitude': self.playerInfo.longitude,
            'altitude': self.playerInfo.altitude,

            'auth': auth,
            'unknown12': 989
        });

        var protobuf = f_req.encode().toBuffer();

        var options = {
            url: api_endpoint,
            body: protobuf,
            encoding: null,
            headers: {
                'User-Agent': 'Niantic App'
            }
        };

        self.request.post(options, function(err, response, body) {
            if (response === undefined || body === undefined) {
                console.error('[!] RPC Server offline');
                return callback(new Error('RPC Server offline'));
            }

            try {
                var f_ret = ResponseEnvelop.decode(body);
            } catch (e) {
                if (e.decoded) { // Truncated
                    console.warn(e);
                    f_ret = e.decoded; // Decoded message with missing required fields
                }
            }

            return callback(null, f_ret);
        });

    }

    self.init = function(username, password, location, provider, callback) {
        if (provider !== 'ptc' && provider !== 'google') {
            return callback(new Error('Invalid provider'));
        }
        // set provider
        self.playerInfo.provider = provider;
        // Updating location
        self.SetLocation(location, function(err, loc) {
            if (err) {
                return callback(err);
            }
            // Getting access token
            self.GetAccessToken(username, password, function(err, token) {
                if (err) {
                    return callback(err);
                }
                // Getting api endpoint
                self.GetApiEndpoint(function(err, api_endpoint) {
                    if (err) {
                        return callback(err);
                    }
                    callback(null);
                });
            });
        });

    };

    self.GetAccessToken = function(user, pass, callback) {
        self.DebugPrint('[i] Logging with user: ' + user);
        if (self.playerInfo.provider === 'ptc') {
            Logins.PokemonClub(user, pass, self, function(err, token) {
                if (err) {
                    return callback(err);
                }

                self.playerInfo.accessToken = token;
                self.DebugPrint("[i] Received PTC access token!")
                callback(null, token);
            });
        } else {
            Logins.GoogleAccount(user, pass, self, function(err, token) {
                if (err) {
                    return callback(err);
                }

                self.playerInfo.accessToken = token;
                self.DebugPrint("[i] Received Google access token!")
                callback(null, token);
            });
        }
    };

    self.GetApiEndpoint = function(callback) {
        var req = [];
        req.push(
            new RequestEnvelop.Requests(2),
            new RequestEnvelop.Requests(126),
            new RequestEnvelop.Requests(4),
            new RequestEnvelop.Requests(129),
            new RequestEnvelop.Requests(5)
        );

        api_req(api_url, self.playerInfo.accessToken, req, function(err, f_ret) {
            if (err) {
                return callback(err);
            }
            var api_endpoint = 'https://' + f_ret.api_url + '/rpc';
            self.playerInfo.apiEndpoint = api_endpoint;
            self.DebugPrint('[i] Received API Endpoint: ' + api_endpoint);
            callback(null, api_endpoint);
        });
    };

    self.GetProfile = function(callback) {
        var req = new RequestEnvelop.Requests(2);
        api_req(self.playerInfo.apiEndpoint, self.playerInfo.accessToken, req, function(err, f_ret) {
            if (err) {
                return callback(err);
            }
            var profile = ResponseEnvelop.ProfilePayload.decode(f_ret.payload[0]).profile

            if (profile.username) {
                self.DebugPrint('[i] Logged in!');
            }
            callback(null, profile);
        });
    };

    self.Heartbeat = function(callback) {

    };

    self.GetLocation = function(callback) {
        geocoder.reverseGeocode(self.playerInfo.latitude, self.playerInfo.longitude, function(err, data) {
            console.log('[i] lat/long/alt: ' + self.playerInfo.latitude + ' ' + self.playerInfo.longitude + ' ' + self.playerInfo.altitude);
            if (data.status === 'ZERO_RESULTS') {
                return callback(new Error('location not found'));
            }

            callback(null, data.results[0].formatted_address);
        });
    };

    self.GetLocationCoords = function() {
        var coords = {
            latitude: self.playerInfo.latitude,
            longitude: self.playerInfo.longitude,
            altitude: self.playerInfo.altitude,
        };

        return coords;
    };

    self.SetLocation = function(location, callback) {
        if (location.type !== 'name' && location.type !== 'coords') {
            return callback(new Error('Invalid location type'));
        }

        if (location.type === 'name') {
            if (!location.name) {
                return callback(new Error('You should add a location name'));
            }
            var locationName = location.name;
            geocoder.geocode(locationName, function(err, data) {
                if (err || data.status === 'ZERO_RESULTS') {
                    return callback(new Error('location not found'));
                }

                self.playerInfo.latitude = data.results[0].geometry.location.lat;
                self.playerInfo.longitude = data.results[0].geometry.location.lng;
                self.playerInfo.locationName = locationName;

                var coords = {
                    latitude: self.playerInfo.latitude,
                    longitude: self.playerInfo.longitude,
                    altitude: self.playerInfo.altitude,
                };

                callback(null, coords);
            });
        } else if (location.type === 'coords') {
            if (!location.coords) {
                return callback(new Error('Coords object missing'));
            }

            self.playerInfo.latitude = location.coords.latitude ? location.coords.latitude : self.playerInfo.latitude;
            self.playerInfo.longitude = location.coords.longitude ? location.coords.longitude : self.playerInfo.longitude;
            self.playerInfo.altitude = location.coords.altitude ? location.coords.altitude : self.playerInfo.altitude;

            var coords = {
                latitude: self.playerInfo.latitude,
                longitude: self.playerInfo.longitude,
                altitude: self.playerInfo.altitude,
            };

            geocoder.reverseGeocode(self.playerInfo.latitude, self.playerInfo.longitude, function(err, data) {
                if (data.status !== 'ZERO_RESULTS') {
                    self.playerInfo.locationName = data.results[0].formatted_address;
                }
                callback(null, coords);
            });
        }
    };
}

module.exports = new Pokeio();
module.exports.Pokeio = Pokeio;
<|endoftext|>