<commit_before>const EventEmitter = require('eventemitter3');
const Request = require('request-promise');

const Telegram = EventEmitter => class extends EventEmitter {
  constructor(token) {
    super();
    if (token === undefined) {
      throw new Error('Please provide a Telegram bot token when instantiating');
    }
    this._token = token;
  }

  _request(method, params, formData) {
    if (arguments.length === 0 || typeof arguments[0] !== 'string') {
      throw new Error('Please provide method as a string');
    }

    // the 2nd, 3rd or 4th argument could be a callback
    let callback;
    if (typeof arguments[3] == 'function') {
      callback = arguments[3];
    } else if (typeof arguments[2] == 'function') {
      callback = arguments[2];
      formData = null;
    } else if (typeof arguments[1] == 'function') {
      callback = arguments[1];
      params = null;
    }

    let options = {
      uri: 'https://api.telegram.org/bot' + this._token + '/' + method,
      qs: params,
      formData: formData,
      simple: false,
      resolveWithFullResponse: true,
      forever: true
    };

    return Request(options)
    .then(resp => {
      if (resp.statusCode !== 200) {
        throw new Error(resp.statusCode + ':\n'+ resp.body);
      }

      let updates = JSON.parse(resp.body);

      if (updates.ok) {
        callback && callback(null, updates);

        return updates;
      }
    })
    .catch(error => {
      if (callback) {
        callback(error);
      }
      else {
        throw error;
      }
    });
  }

  getMe(callback) {
    return this._request('getMe', callback);
  }

  getUpdates(offset, callback) {
    let params = {
      offset: offset,
      timeout: 10
    };

    return this._request('getUpdates', params, callback);
  }

  setWebhook(url, optionalParams, callback) {
    return this._request('setWebhook', url, optionalParams, callback);
  }

  deleteWebhook(callback) {
    return this._request('deleteWebhook', callback);
  }

  getWebhookInfo(callback) {
    return this._request('getWebhookInfo', callback);
  }

  sendMessage(chatId, text, optionalParams, callback) {
    let params = {
      chat_id: chatId,
      text: text
    };

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams, callback);
    }

    return this._request('sendMessage', params, callback);
  }

  answerCallbackQuery(callbackQueryId, optionalParams, callback) {
    let params = {
      callback_query_id: callbackQueryId
    };

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('answerCallbackQuery', params, callback);
  }

  editMessageText(chatId, messageId, text, optionalParams, callback) {
    let params = {
      chat_id: chatId,
      message_id: messageId,
      text: text
    };

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('editMessageText', params, callback);
  }

  editInlineMessageText(inlineMessageId, text, optionalParams, callback) {
    let params = {
      inline_message_id: inlineMessageId,
      text: text
    };

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('editMessageText', params, callback);
  }

  editMessageCaption(chatId, messageId, caption, optionalParams, callback) {
    let params = {
      chat_id: chatId,
      message_id: messageId,
      caption: caption
    };

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('editMessageCaption', params, callback);
  }

  editInlineMessageCaption(inlineMessagId, caption, optionalParams, callback) {
    let params = {
      inline_message_id: inlineMessageId,
      caption: caption
    };

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('editMessageCaption', params, callback);
  }

  editMessageReplyMarkup(chatId, messageId, replyMarkup, callback) {
    let params = {
      chat_id: chatId,
      message_id: messageId,
      reply_markup: replyMarkup
    }

    return this._request('editMessageReplyMarkup', params, callback);
  }

  editInlineMessageReplyMarkup(inlineMessageId, replyMarkup, callback) {
    let params = {
      inline_message_id: inlineMessageId,
      reply_markup: replyMarkup
    }

    return this._request('editMessageReplyMarkup', params, callback);
  }

  deleteMessage(chatId, messageId) {
    let params = {
      chat_id: chatId,
      message_id: messageId
    }

    return this._request('deleteMessage', params, callback);
  }

  answerInlineQuery(inlineQueryId, results, optionalParams, callback) {
    let params = {
      inline_query_id: inlineQueryId,
      results: results
    };

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('answerInlineQuery', params, callback);
  }

  forwardMessage(chatId, fromChatId, messageId, optionalParams, callback) {
    let params = {
      chat_id: chatId,
      from_chat_id: fromChatId,
      message_id: messageId
    }

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('forwardMessage', params, callback);
  }

  sendPhoto(chatId, photo, optionalParams, callback) {
    let params = {
      chat_id: chatId,
      photo: photo
    };

    let formData = {
      photo: photo
    };

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('sendPhoto', params, formData, callback);
  }

  sendAudio(chatId, audio, optionalParams, callback) {
    let params = {
      chat_id: chatId,
      audio: audio
    };

    let formData = {
      audio: audio
    };

    // write test for file size limit

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('sendAudio', params, formData, callback);
  }

  sendDocument(chatId, document, optionalParams, callback) {
    let params = {
      chat_id: chatId,
      document: document
    };

    let formData = {
      document: document
    };

    // write test for file size limit

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('sendDocument', params, formData, callback);
  }

  sendSticker(chatId, sticker, optionalParams, callback) {
    let params = {
      chat_id: chatId,
      sticker: sticker
    };

    let formData = {
      sticker: sticker
    };

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('sendSticker', params, formData, callback);
  }

  sendVideo(chatId, video, optionalParams, callback) {
    let params = {
      chat_id: chatId,
      video: video
    };

    let formData = {
      video: video
    };

    // write test for file size limit
    // write test for file size type (only .mp4)

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('sendVideo', params, callback);
  }

  sendVoice(chatId, voice, optionalParams, callback) {
    let params = {
      chat_id: chatId,
      voice: voice
    };

    let formData = {
      voice: voice
    };

    // write test for file size limit
    // write test for file size type (only .ogg encoded in OPUS)

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('sendVoice', params, callback);
  }

  sendVideoNote(chatId, videoNote, optionalParams, callback) {
    let params = {
      chat_id: chatId,
      video_note: videoNote
    };

    let formData = {
      video_note: videoNote
    };

    // write test for file size limit
    // write test for file size type (only .ogg encoded in OPUS)

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('sendVideoNote', params, callback);
  }

  sendLocation(chatId, lat, lon, optionalParams, callback) {
    let params = {
      chat_id: chatId,
      latitude: lat,
      longitude: lon
    };

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('sendLocation', params, callback);
  }

  sendVenue(chatId, lat, lon, title, address, optionalParams, callback) {
    let params = {
      chat_id: chatId,
      latitude: lat,
      longitude: lon,
      title: title,
      address: address
    }

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('sendVenue', params, callback);
  }

  sendContact(chatId, phoneNumber, firstName, optionalParams, callback) {
    let params = {
      chat_id: chatId,
      phone_number: phoneNumber,
      first_name: firstName
    }

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('sendContact', params, callback);
  }

  sendChatAction(chatId, action, callback) {
    if (typeof action !== 'string') {
      throw new Error('sendChatAction method needs a string input');
    }

    let params = {
      chat_id: chatId,
      action: action
    };

    return this._request('sendChatAction', params, callback);
  }

  getUserProfilePhotos(userId, optionalParams, callback) {
    let params = {
      user_id: userId,
    };

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('getUserProfilePhotos', params, callback);
  }

  getFile(fileId, callback) {
    let params = {
      file_id: fileId
    };

    return this._request('getFile', params, callback);
  }

  kickChatMember(chatId, userId, optionalParams, callback) {
    let params = {
      chat_id: chatId,
      user_id: userId
    };

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('kickChatMember', params, callback);
  }

  leaveChat(chatId, callback) {
    let params = {
      chat_id: chatId
    };

    return this._request('leaveChat', params, callback);
  }

  unbanChatMember(chatId, userId, callback) {
    let params = {
      chat_id: chatId,
      user_id: userId
    };

    return this._request('unbanChatMember', params, callback);
  }

  restrictChatMember(chatId, userId, optionalParams, callback) {
    let params = {
      chat_id: chatId,
      user_id: userId
    }

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('restrictChatMember', params, callback);
  }

  promoteChatMember(chatId, userId, optionalParams, callback) {
    let params = {
      chat_id: chatId,
      user_id: userId
    }

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('promoteChatMember', params, callback);
  }

  exportChatInviteLink(chatId, callback) {
    let params = {
      chat_id: chatId
    }

    return this._request('exportChatInviteLink', params, callback);
  }

  setChatPhoto(chatId, photo, callback) {
    let params = {
      chat_id: chatId,
      photo: photo
    };

    let formData = {
      photo: photo
    };

    return this._request('setChatPhoto', params, formData, callback);
  }

  deleteChatPhoto(chatId, callback) {
    let params = {
      chat_id: chatId
    }

    return this._request('deleteChatPhoto', params, callback);
  }

  setChatTitle(chatId, title, callback) {
    let params = {
      chat_id: chatId,
      title: title
    }

    return this._request('setChatTitle', params, callback);
  }

  setChatDescription(chatId, description, callback) {
    let params = {
      chat_id: chatId,
      description: description
    }

    return this._request('setChatDescription', params, callback);
  }

  pinChatMessage(chatId, messageId, optionalParams, callback) {
    let params = {
      chat_id: chatId,
      message: messageId
    }

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('pinChatMessage', params, callback);
  }

  unpinChatMessage(chatId, callback) {
    let params = {
      chat_id: chatId
    }

    return this._request('unpinChatMessage', params, callback);
  }

  getChat(chatId, callback) {
    let params = {
      chat_id: chatId
    };

    return this._request('getChat', params, callback);
  }

  getChatAdministrators(chatId, callback) {
    let params = {
      chat_id: chatId
    };

    return this._request('getChatAdministrators', params, callback);
  }

  getChatMembersCount(chatId, callback) {
    let params = {
      chat_id: chatId
    };

    return this._request('getChatMembersCount', params, callback);
  }

  getChatMember(chatId, userId, callback) {
    let params = {
      chat_id: chatId,
      user_id: userId
    };

    return this._request('getChatMember', params, callback);
  }

  // Payment

  sendInvoice(chatId, title, description, payload, providerToken, startParameter, currency, prices, optionalParams, callback) {
    let params = {
      chat_id: chatId,
      title: title,
      description: description,
      payload: payload,
      provider_token: providerToken,
      start_parameter: startParameter,
      currency: currency,
      prices: prices
    };

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('sendInvoice', params, callback);
  }

  answerShippingQuery(shippingQueryId, ok) {
    let params = {
      shipping_query_id: shippingQueryId,
      ok: ok
    };

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('answerShippingQuery', params, callback);
  }

  answerPreCheckoutQuery(preCheckoutQueryId, ok, errorMessage) {
    let params = {
      pre_checkout_query_id: preCheckoutQueryId,
      ok: ok,
      error_message: errorMessage
    };

    return this._request('answerShippingQuery', params, callback);
  }

  // Games

  sendGame(chatId, gameShortName, optionalParams, callback) {
    let params = {
      chat_id: chatId,
      game_short_name: gameShortName
    };

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('sendGame', params, callback);
  }

  setGameScore(userId, score, optionalParams, callback) {
    let params = {
      user_id: userId,
      score: score
    }

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('setGameScore', params, callback);
  }

  getGameHighScores(userId, optionalParams, callback) {
    let params = {
      user_id: userId
    };

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('getGameHighScores', params, callback);
  }
}

module.exports = Telegram;
<commit_msg>Added getStickerSet method<commit_after>const EventEmitter = require('eventemitter3');
const Request = require('request-promise');

const Telegram = EventEmitter => class extends EventEmitter {
  constructor(token) {
    super();
    if (token === undefined) {
      throw new Error('Please provide a Telegram bot token when instantiating');
    }
    this._token = token;
  }

  _request(method, params, formData) {
    if (arguments.length === 0 || typeof arguments[0] !== 'string') {
      throw new Error('Please provide method as a string');
    }

    // the 2nd, 3rd or 4th argument could be a callback
    let callback;
    if (typeof arguments[3] == 'function') {
      callback = arguments[3];
    } else if (typeof arguments[2] == 'function') {
      callback = arguments[2];
      formData = null;
    } else if (typeof arguments[1] == 'function') {
      callback = arguments[1];
      params = null;
    }

    let options = {
      uri: 'https://api.telegram.org/bot' + this._token + '/' + method,
      qs: params,
      formData: formData,
      simple: false,
      resolveWithFullResponse: true,
      forever: true
    };

    return Request(options)
    .then(resp => {
      if (resp.statusCode !== 200) {
        throw new Error(resp.statusCode + ':\n'+ resp.body);
      }

      let updates = JSON.parse(resp.body);

      if (updates.ok) {
        callback && callback(null, updates);

        return updates;
      }
    })
    .catch(error => {
      if (callback) {
        callback(error);
      }
      else {
        throw error;
      }
    });
  }

  getMe(callback) {
    return this._request('getMe', callback);
  }

  getUpdates(offset, callback) {
    let params = {
      offset: offset,
      timeout: 10
    };

    return this._request('getUpdates', params, callback);
  }

  setWebhook(url, optionalParams, callback) {
    return this._request('setWebhook', url, optionalParams, callback);
  }

  deleteWebhook(callback) {
    return this._request('deleteWebhook', callback);
  }

  getWebhookInfo(callback) {
    return this._request('getWebhookInfo', callback);
  }

  sendMessage(chatId, text, optionalParams, callback) {
    let params = {
      chat_id: chatId,
      text: text
    };

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams, callback);
    }

    return this._request('sendMessage', params, callback);
  }

  answerCallbackQuery(callbackQueryId, optionalParams, callback) {
    let params = {
      callback_query_id: callbackQueryId
    };

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('answerCallbackQuery', params, callback);
  }

  editMessageText(chatId, messageId, text, optionalParams, callback) {
    let params = {
      chat_id: chatId,
      message_id: messageId,
      text: text
    };

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('editMessageText', params, callback);
  }

  editInlineMessageText(inlineMessageId, text, optionalParams, callback) {
    let params = {
      inline_message_id: inlineMessageId,
      text: text
    };

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('editMessageText', params, callback);
  }

  editMessageCaption(chatId, messageId, caption, optionalParams, callback) {
    let params = {
      chat_id: chatId,
      message_id: messageId,
      caption: caption
    };

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('editMessageCaption', params, callback);
  }

  editInlineMessageCaption(inlineMessagId, caption, optionalParams, callback) {
    let params = {
      inline_message_id: inlineMessageId,
      caption: caption
    };

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('editMessageCaption', params, callback);
  }

  editMessageReplyMarkup(chatId, messageId, replyMarkup, callback) {
    let params = {
      chat_id: chatId,
      message_id: messageId,
      reply_markup: replyMarkup
    }

    return this._request('editMessageReplyMarkup', params, callback);
  }

  editInlineMessageReplyMarkup(inlineMessageId, replyMarkup, callback) {
    let params = {
      inline_message_id: inlineMessageId,
      reply_markup: replyMarkup
    }

    return this._request('editMessageReplyMarkup', params, callback);
  }

  deleteMessage(chatId, messageId) {
    let params = {
      chat_id: chatId,
      message_id: messageId
    }

    return this._request('deleteMessage', params, callback);
  }

  answerInlineQuery(inlineQueryId, results, optionalParams, callback) {
    let params = {
      inline_query_id: inlineQueryId,
      results: results
    };

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('answerInlineQuery', params, callback);
  }

  forwardMessage(chatId, fromChatId, messageId, optionalParams, callback) {
    let params = {
      chat_id: chatId,
      from_chat_id: fromChatId,
      message_id: messageId
    }

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('forwardMessage', params, callback);
  }

  sendPhoto(chatId, photo, optionalParams, callback) {
    let params = {
      chat_id: chatId,
      photo: photo
    };

    let formData = {
      photo: photo
    };

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('sendPhoto', params, formData, callback);
  }

  sendAudio(chatId, audio, optionalParams, callback) {
    let params = {
      chat_id: chatId,
      audio: audio
    };

    let formData = {
      audio: audio
    };

    // write test for file size limit

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('sendAudio', params, formData, callback);
  }

  sendDocument(chatId, document, optionalParams, callback) {
    let params = {
      chat_id: chatId,
      document: document
    };

    let formData = {
      document: document
    };

    // write test for file size limit

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('sendDocument', params, formData, callback);
  }

  // Stickers

  sendSticker(chatId, sticker, optionalParams, callback) {
    let params = {
      chat_id: chatId,
      sticker: sticker
    };

    let formData = {
      sticker: sticker
    };

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('sendSticker', params, formData, callback);
  }

  getStickerSet(name, callback) {
    let params = {
      name: name
    }

    return this._request('getStickerSet', params, callback);
  }

  sendVideo(chatId, video, optionalParams, callback) {
    let params = {
      chat_id: chatId,
      video: video
    };

    let formData = {
      video: video
    };

    // write test for file size limit
    // write test for file size type (only .mp4)

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('sendVideo', params, callback);
  }

  sendVoice(chatId, voice, optionalParams, callback) {
    let params = {
      chat_id: chatId,
      voice: voice
    };

    let formData = {
      voice: voice
    };

    // write test for file size limit
    // write test for file size type (only .ogg encoded in OPUS)

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('sendVoice', params, callback);
  }

  sendVideoNote(chatId, videoNote, optionalParams, callback) {
    let params = {
      chat_id: chatId,
      video_note: videoNote
    };

    let formData = {
      video_note: videoNote
    };

    // write test for file size limit
    // write test for file size type (only .ogg encoded in OPUS)

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('sendVideoNote', params, callback);
  }

  sendLocation(chatId, lat, lon, optionalParams, callback) {
    let params = {
      chat_id: chatId,
      latitude: lat,
      longitude: lon
    };

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('sendLocation', params, callback);
  }

  sendVenue(chatId, lat, lon, title, address, optionalParams, callback) {
    let params = {
      chat_id: chatId,
      latitude: lat,
      longitude: lon,
      title: title,
      address: address
    }

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('sendVenue', params, callback);
  }

  sendContact(chatId, phoneNumber, firstName, optionalParams, callback) {
    let params = {
      chat_id: chatId,
      phone_number: phoneNumber,
      first_name: firstName
    }

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('sendContact', params, callback);
  }

  sendChatAction(chatId, action, callback) {
    if (typeof action !== 'string') {
      throw new Error('sendChatAction method needs a string input');
    }

    let params = {
      chat_id: chatId,
      action: action
    };

    return this._request('sendChatAction', params, callback);
  }

  getUserProfilePhotos(userId, optionalParams, callback) {
    let params = {
      user_id: userId,
    };

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('getUserProfilePhotos', params, callback);
  }

  getFile(fileId, callback) {
    let params = {
      file_id: fileId
    };

    return this._request('getFile', params, callback);
  }

  kickChatMember(chatId, userId, optionalParams, callback) {
    let params = {
      chat_id: chatId,
      user_id: userId
    };

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('kickChatMember', params, callback);
  }

  leaveChat(chatId, callback) {
    let params = {
      chat_id: chatId
    };

    return this._request('leaveChat', params, callback);
  }

  unbanChatMember(chatId, userId, callback) {
    let params = {
      chat_id: chatId,
      user_id: userId
    };

    return this._request('unbanChatMember', params, callback);
  }

  restrictChatMember(chatId, userId, optionalParams, callback) {
    let params = {
      chat_id: chatId,
      user_id: userId
    }

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('restrictChatMember', params, callback);
  }

  promoteChatMember(chatId, userId, optionalParams, callback) {
    let params = {
      chat_id: chatId,
      user_id: userId
    }

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('promoteChatMember', params, callback);
  }

  exportChatInviteLink(chatId, callback) {
    let params = {
      chat_id: chatId
    }

    return this._request('exportChatInviteLink', params, callback);
  }

  setChatPhoto(chatId, photo, callback) {
    let params = {
      chat_id: chatId,
      photo: photo
    };

    let formData = {
      photo: photo
    };

    return this._request('setChatPhoto', params, formData, callback);
  }

  deleteChatPhoto(chatId, callback) {
    let params = {
      chat_id: chatId
    }

    return this._request('deleteChatPhoto', params, callback);
  }

  setChatTitle(chatId, title, callback) {
    let params = {
      chat_id: chatId,
      title: title
    }

    return this._request('setChatTitle', params, callback);
  }

  setChatDescription(chatId, description, callback) {
    let params = {
      chat_id: chatId,
      description: description
    }

    return this._request('setChatDescription', params, callback);
  }

  pinChatMessage(chatId, messageId, optionalParams, callback) {
    let params = {
      chat_id: chatId,
      message: messageId
    }

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('pinChatMessage', params, callback);
  }

  unpinChatMessage(chatId, callback) {
    let params = {
      chat_id: chatId
    }

    return this._request('unpinChatMessage', params, callback);
  }

  getChat(chatId, callback) {
    let params = {
      chat_id: chatId
    };

    return this._request('getChat', params, callback);
  }

  getChatAdministrators(chatId, callback) {
    let params = {
      chat_id: chatId
    };

    return this._request('getChatAdministrators', params, callback);
  }

  getChatMembersCount(chatId, callback) {
    let params = {
      chat_id: chatId
    };

    return this._request('getChatMembersCount', params, callback);
  }

  getChatMember(chatId, userId, callback) {
    let params = {
      chat_id: chatId,
      user_id: userId
    };

    return this._request('getChatMember', params, callback);
  }

  // Payment

  sendInvoice(chatId, title, description, payload, providerToken, startParameter, currency, prices, optionalParams, callback) {
    let params = {
      chat_id: chatId,
      title: title,
      description: description,
      payload: payload,
      provider_token: providerToken,
      start_parameter: startParameter,
      currency: currency,
      prices: prices
    };

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('sendInvoice', params, callback);
  }

  answerShippingQuery(shippingQueryId, ok) {
    let params = {
      shipping_query_id: shippingQueryId,
      ok: ok
    };

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('answerShippingQuery', params, callback);
  }

  answerPreCheckoutQuery(preCheckoutQueryId, ok, errorMessage) {
    let params = {
      pre_checkout_query_id: preCheckoutQueryId,
      ok: ok,
      error_message: errorMessage
    };

    return this._request('answerShippingQuery', params, callback);
  }

  // Games

  sendGame(chatId, gameShortName, optionalParams, callback) {
    let params = {
      chat_id: chatId,
      game_short_name: gameShortName
    };

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('sendGame', params, callback);
  }

  setGameScore(userId, score, optionalParams, callback) {
    let params = {
      user_id: userId,
      score: score
    }

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('setGameScore', params, callback);
  }

  getGameHighScores(userId, optionalParams, callback) {
    let params = {
      user_id: userId
    };

    if (typeof optionalParams == 'function') {
      callback = optionalParams;
    } else {
      Object.assign(params, optionalParams);
    }

    return this._request('getGameHighScores', params, callback);
  }
}

module.exports = Telegram;
<|endoftext|>


<commit_before>const Evaluator = require('./evaluator');
const FilterManager = require('./filter-manager');
const Hash = require('./data.hash');
const QueueHash = require('./data.queueHash');
const parser = require('./parser');

class PrefetchManager {
  /**
   * @param {Hash} templates
   */
  constructor(templates) {
    this._jobList = [];
    this._templates = templates;
  }

  /**
   * @param {string[]} sourceList
   * @param {function} callback
   */
  add(sourceList, callback) {
    this._jobList.push({
      sourceList: sourceList,
      callback: callback,
    });
  }

  notifyFetched() {
    const undone = [];
    const finished = [];

    this._jobList.forEach((job) => {
      const unacquired = job.sourceList.filter((source) => {
        return !this._templates.has(source);
      });

      if (unacquired.length > 0) {
        undone.push(job);
      } else {
        finished.push(job);
      }
    });

    this._jobList = undone;

    finished.forEach((job) => {
      if (typeof job.callback === 'function') {
        job.callback();
      }
    });
  }
}

const template = () => {
  const that = {};

  const _filterManager = new FilterManager();

  const _evaluator = new Evaluator(_filterManager);

  const _templates = new Hash();

  const _parser = parser.init();

  const _remoteQueue = new QueueHash();

  const _prefetchManager = new PrefetchManager(_templates);

  /**
   * @param {string} source
   * @return {boolean}
   */
  const _isRemoteFile = (source) => {
    return (/\.html$/).test(source);
  };

  /**
   * @param {string} source
   * @param {string} content
   */
  const _register = (source, content) => {
    _templates.add(source, _parser.parse(content, source));
  };

  const _registerFromRemote = (() => {
    const _fetching = new Hash();

    return (source, checkCallback) => {
      if (_fetching.has(source)) {
        return;
      }

      _fetching.add(source, true);

      const req = new XMLHttpRequest();
      req.open('GET', source, true);
      req.onreadystatechange = () => {
        if (req.readyState !== 4 || req.status !== 200) {
          return;
        }

        let queue;

        if (typeof checkCallback === 'function') {
          checkCallback(source);
        }

        _register(source, req.responseText);
        _fetching.remove(source);
        _prefetchManager.notifyFetched();

        while (_remoteQueue.sizeOf(source) > 0) {
          queue = _remoteQueue.getFrom(source);
          queue.callback(_evaluate(source, queue.bindParams));
        }
      };
      req.send();
    };
  })();

  /**
   * @param {string} source
   * @param {Object} bindParams
   * @param {function} [callback]
   */
  const _execute = (source, bindParams, callback) => {
    if (_templates.has(source)) {
      if (typeof callback === 'function') {
        callback(_evaluate(source, bindParams));
      } else {
        return _evaluate(source, bindParams);
      }
    } else if (_isRemoteFile(source)) {
      if (typeof callback === 'function') {
        _registerFromRemote(source);
        _remoteQueue.addTo(source, {
          bindParams: bindParams,
          callback: callback,
        });
      }
    }
  };

  /**
   * @param {string} source
   * @param {Object} bindParams
   * @return {string}
   */
  const _evaluate = (source, bindParams) => {
    try {
      return _evaluator.evaluate(_templates.get(source), [bindParams]);
    } catch (e) {
      throw new Error('template - ' + e.message + ' in source ' + source);
    }
  };

  /**
   * @param {string} name
   * @param {function} func
   */
  that.addFilter = (name, func) => {
    _filterManager.register(name, func);
  };

  /**
   * @param {string} source
   * @param {Object} param
   */
  that.render = (source, param) => {
    return _execute(source, param);
  };

  /**
   * @param {string} source
   * @param {Object} param
   * @param {function} callback
   */
  that.renderAsync = (source, param, callback) => {
    _execute(source, param, callback);
  };

  /**
   * @param {string|string[]} target
   * @param {function} callback Called once when all sources fetched.
   * @param {function} [checkCallback] Called every time when a source fetched.
   */
  that.prefetch = (target, callback, checkCallback) => {
    const sourceList = (typeof target === 'string') ? [].concat(target) : target;

    if (Array.isArray(sourceList)) {
      sourceList.forEach((source) => {
        if (_isRemoteFile(source)) {
          _registerFromRemote(source, checkCallback);
        }
      });

      _prefetchManager.add(sourceList, callback);
    }
  };

  that.clearTemplateCache = () => {
    _templates.clear();
  };

  registerPredefinedFilters(_filterManager);

  return that;
};

/**
 * @param {FilterManager} filterManager
 */
const registerPredefinedFilters = (filterManager) => {
  filterManager.register('h', (() => {
    const list = {
      '<': '<',
      '>': '>',
      '&': '&',
      '"': '"',
      "'": ''', // eslint-disable-line quotes
    };

    return (value) => {
      return value.replace(/[<>&"']/g, (matched) => {
        return list[matched];
      });
    };
  })());

  filterManager.register('default', (value, defaultValue) => {
    return value.length === 0 ? defaultValue : value;
  });

  filterManager.register('upper', (value) => {
    return value.toLocaleUpperCase();
  });

  filterManager.register('lower', (value) => {
    return value.toLocaleLowerCase();
  });

  filterManager.register('plus', (value, plus) => {
    if (isFinite(value) && typeof plus === 'number' && isFinite(plus)) {
      return (+(value) + plus).toString();
    } else {
      return value;
    }
  });
};

module.exports.init = () => {
  return template();
};
<commit_msg>Remove unnecessary code from _execute()<commit_after>const Evaluator = require('./evaluator');
const FilterManager = require('./filter-manager');
const Hash = require('./data.hash');
const QueueHash = require('./data.queueHash');
const parser = require('./parser');

class PrefetchManager {
  /**
   * @param {Hash} templates
   */
  constructor(templates) {
    this._jobList = [];
    this._templates = templates;
  }

  /**
   * @param {string[]} sourceList
   * @param {function} callback
   */
  add(sourceList, callback) {
    this._jobList.push({
      sourceList: sourceList,
      callback: callback,
    });
  }

  notifyFetched() {
    const undone = [];
    const finished = [];

    this._jobList.forEach((job) => {
      const unacquired = job.sourceList.filter((source) => {
        return !this._templates.has(source);
      });

      if (unacquired.length > 0) {
        undone.push(job);
      } else {
        finished.push(job);
      }
    });

    this._jobList = undone;

    finished.forEach((job) => {
      if (typeof job.callback === 'function') {
        job.callback();
      }
    });
  }
}

const template = () => {
  const that = {};

  const _filterManager = new FilterManager();

  const _evaluator = new Evaluator(_filterManager);

  const _templates = new Hash();

  const _parser = parser.init();

  const _remoteQueue = new QueueHash();

  const _prefetchManager = new PrefetchManager(_templates);

  /**
   * @param {string} source
   * @return {boolean}
   */
  const _isRemoteFile = (source) => {
    return (/\.html$/).test(source);
  };

  /**
   * @param {string} source
   * @param {string} content
   */
  const _register = (source, content) => {
    _templates.add(source, _parser.parse(content, source));
  };

  const _registerFromRemote = (() => {
    const _fetching = new Hash();

    return (source, checkCallback) => {
      if (_fetching.has(source)) {
        return;
      }

      _fetching.add(source, true);

      const req = new XMLHttpRequest();
      req.open('GET', source, true);
      req.onreadystatechange = () => {
        if (req.readyState !== 4 || req.status !== 200) {
          return;
        }

        let queue;

        if (typeof checkCallback === 'function') {
          checkCallback(source);
        }

        _register(source, req.responseText);
        _fetching.remove(source);
        _prefetchManager.notifyFetched();

        while (_remoteQueue.sizeOf(source) > 0) {
          queue = _remoteQueue.getFrom(source);
          queue.callback(_evaluate(source, queue.bindParams));
        }
      };
      req.send();
    };
  })();

  /**
   * @param {string} source
   * @param {Object} bindParams
   * @param {function} [callback]
   */
  const _execute = (source, bindParams, callback) => {
    if (_templates.has(source)) {
      return _evaluate(source, bindParams);
    } else if (_isRemoteFile(source)) {
      if (typeof callback === 'function') {
        _registerFromRemote(source);
        _remoteQueue.addTo(source, {
          bindParams: bindParams,
          callback: callback,
        });
      }
    }
  };

  /**
   * @param {string} source
   * @param {Object} bindParams
   * @return {string}
   */
  const _evaluate = (source, bindParams) => {
    try {
      return _evaluator.evaluate(_templates.get(source), [bindParams]);
    } catch (e) {
      throw new Error('template - ' + e.message + ' in source ' + source);
    }
  };

  /**
   * @param {string} name
   * @param {function} func
   */
  that.addFilter = (name, func) => {
    _filterManager.register(name, func);
  };

  /**
   * @param {string} source
   * @param {Object} param
   */
  that.render = (source, param) => {
    return _execute(source, param);
  };

  /**
   * @param {string} source
   * @param {Object} param
   * @param {function} callback
   */
  that.renderAsync = (source, param, callback) => {
    _execute(source, param, callback);
  };

  /**
   * @param {string|string[]} target
   * @param {function} callback Called once when all sources fetched.
   * @param {function} [checkCallback] Called every time when a source fetched.
   */
  that.prefetch = (target, callback, checkCallback) => {
    const sourceList = (typeof target === 'string') ? [].concat(target) : target;

    if (Array.isArray(sourceList)) {
      sourceList.forEach((source) => {
        if (_isRemoteFile(source)) {
          _registerFromRemote(source, checkCallback);
        }
      });

      _prefetchManager.add(sourceList, callback);
    }
  };

  that.clearTemplateCache = () => {
    _templates.clear();
  };

  registerPredefinedFilters(_filterManager);

  return that;
};

/**
 * @param {FilterManager} filterManager
 */
const registerPredefinedFilters = (filterManager) => {
  filterManager.register('h', (() => {
    const list = {
      '<': '<',
      '>': '>',
      '&': '&',
      '"': '"',
      "'": ''', // eslint-disable-line quotes
    };

    return (value) => {
      return value.replace(/[<>&"']/g, (matched) => {
        return list[matched];
      });
    };
  })());

  filterManager.register('default', (value, defaultValue) => {
    return value.length === 0 ? defaultValue : value;
  });

  filterManager.register('upper', (value) => {
    return value.toLocaleUpperCase();
  });

  filterManager.register('lower', (value) => {
    return value.toLocaleLowerCase();
  });

  filterManager.register('plus', (value, plus) => {
    if (isFinite(value) && typeof plus === 'number' && isFinite(plus)) {
      return (+(value) + plus).toString();
    } else {
      return value;
    }
  });
};

module.exports.init = () => {
  return template();
};
<|endoftext|>


<commit_before>'use strict';

import Sprite from './sprite';

class TiledObject {
	constructor(layer, objectData) {
		this.id = objectData.id;
		this.name = objectData.name;
		this.type = objectData.type;
		this.visible = objectData.visible;
		this.sprite = new Sprite(objectData.width, objectData.height, null);
		this.sprite.setRotation(objectData.rotation);
		this.sprite.setPosition(objectData.x, objectData.y);
	}
}

export default class TiledMap {
	constructor(graphics, content) {
		this.graphics = graphics;
		this.content = content;
		this.sprite = new Sprite(0, 0, null);
		this.textures = {};
		this.objects = {};
		this.animationTime = 0;
		this.createObjects();
	}
	createObjects() {
		for (let layer of this.content.layers) {
			if (layer.type === 'objectgroup') {
				this.createObjectsFromLayer(layer);
			}
		}
	}
	createObjectsFromLayer(layer) {
		for (let objectData of layer.objects) {
			this.objects[objectData.id] = new TiledObject(layer, objectData);
		}
	}
	update(deltaTime) {
		this.animationTime += deltaTime * 1000;
	}
	draw() {
		for (let layer of this.content.layers) {
			if (layer.type === 'tilelayer') {
				this.drawTileLayer(layer);
			} else if (layer.type === 'objectgroup') {
				this.drawObjectGroup(layer);
			}
		}
	}
	drawTileLayer(layer) {
		if (!layer.visible) return;
		this.sprite.setColor(1.0, 1.0, 1.0, layer.opacity);
		for (let x = 0; x < layer.width; ++x) {
			for (let y = 0; y < layer.height; ++y) {
				let gid = layer.data[y * layer.width + x];
				this.drawTile(gid, x, y);
			}
		}
	}
	drawTile(gid, tileX, tileY) {
		if (gid === 0) return;

		for (let tileset of this.content.tilesets) {
			if (gid >= tileset.firstgid && gid <= tileset.firstgid + tileset.tilecount) {
				this.sprite.texture = this.textures[tileset.image];
				this.sprite.width = tileset.tilewidth;
				this.sprite.height = tileset.tileheight;
				this.sprite.setPosition(
					this.content.tilewidth * tileX,
					this.content.tileheight * tileY
				);

				let tileId = this.getEffectiveTileId(tileset, gid);
				let tilesetX = tileId % tileset.columns;
				let tilesetY = Math.floor(tileId / tileset.columns);

				let textureX = tilesetX * tileset.tilewidth;
				let textureY = tilesetY * tileset.tileheight;
				this.sprite.setTextureCoordinates(
					textureX / tileset.imagewidth,
					textureY / tileset.imageheight,
					(textureX + tileset.tilewidth) / tileset.imagewidth,
					(textureY + tileset.tileheight) / tileset.imageheight
				);

				this.graphics.draw(this.sprite);
			}
		}
	}
	drawObjectGroup(layer) {
		if (!layer.visible) return;
		for (let objectData of layer.objects) {
			this.drawObject(this.objects[objectData.id], objectData);
		}
	}
	drawObject(object, objectData) {
		if (!object || objectData.gid === 0 || !object.visible) return;
		let gid = objectData.gid;
		for (let tileset of this.content.tilesets) {
			if (gid >= tileset.firstgid && gid <= tileset.firstgid + tileset.tilecount) {
				object.sprite.texture = this.textures[tileset.image];

				let tileId = this.getEffectiveTileId(tileset, gid);
				let tilesetX = tileId % tileset.columns;
				let tilesetY = Math.floor(tileId / tileset.columns);

				let textureX = tilesetX * tileset.tilewidth;
				let textureY = tilesetY * tileset.tileheight;
				object.sprite.setTextureCoordinates(
					textureX / tileset.imagewidth,
					textureY / tileset.imageheight,
					(textureX + tileset.tilewidth) / tileset.imagewidth,
					(textureY + tileset.tileheight) / tileset.imageheight
				);

				this.graphics.draw(object.sprite);
			}
		}
	}
	getEffectiveTileId(tileset, gid) {
		let tileId = gid - tileset.firstgid;
		if (tileset.tiles) {
			let tiledata = tileset.tiles[tileId];
			if (tiledata) {
				let animation = tiledata.animation;
				if (animation) {
					let totalTime = 0;
					for (let frame of animation) {
						totalTime += frame.duration;
					}
					let currentTime = Math.floor(this.animationTime) % totalTime;
					totalTime = 0;
					for (let frame of animation) {
						totalTime += frame.duration;
						if (totalTime >= currentTime) {
							return frame.tileid;
						}
					}
				}
			}
		}
		return tileId;
	}
	registerTexture(name, texture) {
		this.textures[name] = texture;
	}
}
<commit_msg>Change the Tiled object origin to be consistent<commit_after>'use strict';

import Sprite from './sprite';

class TiledObject {
	constructor(layer, objectData) {
		this.id = objectData.id;
		this.name = objectData.name;
		this.type = objectData.type;
		this.visible = objectData.visible;
		this.sprite = new Sprite(objectData.width, objectData.height, null);
		this.sprite.setOrigin(0, objectData.height);
		this.sprite.setRotation(objectData.rotation);
		this.sprite.setPosition(objectData.x, objectData.y - objectData.height);
	}
}

export default class TiledMap {
	constructor(graphics, content) {
		this.graphics = graphics;
		this.content = content;
		this.sprite = new Sprite(0, 0, null);
		this.textures = {};
		this.objects = {};
		this.animationTime = 0;
		this.createObjects();
	}
	createObjects() {
		for (let layer of this.content.layers) {
			if (layer.type === 'objectgroup') {
				this.createObjectsFromLayer(layer);
			}
		}
	}
	createObjectsFromLayer(layer) {
		for (let objectData of layer.objects) {
			this.objects[objectData.id] = new TiledObject(layer, objectData);
		}
	}
	update(deltaTime) {
		this.animationTime += deltaTime * 1000;
	}
	draw() {
		for (let layer of this.content.layers) {
			if (layer.type === 'tilelayer') {
				this.drawTileLayer(layer);
			} else if (layer.type === 'objectgroup') {
				this.drawObjectGroup(layer);
			}
		}
	}
	drawTileLayer(layer) {
		if (!layer.visible) return;
		this.sprite.setColor(1.0, 1.0, 1.0, layer.opacity);
		for (let x = 0; x < layer.width; ++x) {
			for (let y = 0; y < layer.height; ++y) {
				let gid = layer.data[y * layer.width + x];
				this.drawTile(gid, x, y);
			}
		}
	}
	drawTile(gid, tileX, tileY) {
		if (gid === 0) return;

		for (let tileset of this.content.tilesets) {
			if (gid >= tileset.firstgid && gid <= tileset.firstgid + tileset.tilecount) {
				this.sprite.texture = this.textures[tileset.image];
				this.sprite.width = tileset.tilewidth;
				this.sprite.height = tileset.tileheight;
				this.sprite.setPosition(
					this.content.tilewidth * tileX,
					this.content.tileheight * tileY
				);

				let tileId = this.getEffectiveTileId(tileset, gid);
				let tilesetX = tileId % tileset.columns;
				let tilesetY = Math.floor(tileId / tileset.columns);

				let textureX = tilesetX * tileset.tilewidth;
				let textureY = tilesetY * tileset.tileheight;
				this.sprite.setTextureCoordinates(
					textureX / tileset.imagewidth,
					textureY / tileset.imageheight,
					(textureX + tileset.tilewidth) / tileset.imagewidth,
					(textureY + tileset.tileheight) / tileset.imageheight
				);

				this.graphics.draw(this.sprite);
			}
		}
	}
	drawObjectGroup(layer) {
		if (!layer.visible) return;
		for (let objectData of layer.objects) {
			this.drawObject(this.objects[objectData.id], objectData);
		}
	}
	drawObject(object, objectData) {
		if (!object || objectData.gid === 0 || !object.visible) return;
		let gid = objectData.gid;
		for (let tileset of this.content.tilesets) {
			if (gid >= tileset.firstgid && gid <= tileset.firstgid + tileset.tilecount) {
				object.sprite.texture = this.textures[tileset.image];

				let tileId = this.getEffectiveTileId(tileset, gid);
				let tilesetX = tileId % tileset.columns;
				let tilesetY = Math.floor(tileId / tileset.columns);

				let textureX = tilesetX * tileset.tilewidth;
				let textureY = tilesetY * tileset.tileheight;
				object.sprite.setTextureCoordinates(
					textureX / tileset.imagewidth,
					textureY / tileset.imageheight,
					(textureX + tileset.tilewidth) / tileset.imagewidth,
					(textureY + tileset.tileheight) / tileset.imageheight
				);

				this.graphics.draw(object.sprite);
			}
		}
	}
	getEffectiveTileId(tileset, gid) {
		let tileId = gid - tileset.firstgid;
		if (tileset.tiles) {
			let tiledata = tileset.tiles[tileId];
			if (tiledata) {
				let animation = tiledata.animation;
				if (animation) {
					let totalTime = 0;
					for (let frame of animation) {
						totalTime += frame.duration;
					}
					let currentTime = Math.floor(this.animationTime) % totalTime;
					totalTime = 0;
					for (let frame of animation) {
						totalTime += frame.duration;
						if (totalTime >= currentTime) {
							return frame.tileid;
						}
					}
				}
			}
		}
		return tileId;
	}
	registerTexture(name, texture) {
		this.textures[name] = texture;
	}
}
<|endoftext|>


<commit_before>/**
 * class-component-initializer.js v2.2.0
 * author: Yoshiya Hinosawa ( https://github.com/kt3k )
 * license: MIT
 */

(function ($, Promise) {

    var reSpaces = / +/;

    /**
     * Initialized the all class components of the given names and returns of the promise of all initialization.
     *
     * @param {String[]} arguments
     * @return {Promise}
     */
    $.CC.init = function (classNames, elem) {

        if (typeof classNames === 'string') {

            classNames = classNames.split(reSpaces);

        }

        return Promise.all(classNames.map(function (className) {

            return initOne(className, elem);

        })).then(function (elemGroups) {

            var x = [];

            return x.concat.apply(x, elemGroups);

        });
    };

    /**
     * Initializes one kind of class components of the given name and returns the promise of all initialization.
     *
     * @param {String} className The class name to initialize
     * @return {Promise}
     */
    initOne = function (className, elem) {

        return new Promise(function (resolve) {

            var elements = $.CC.initClassComponent(className, elem);

            Promise.all(elements.map(function (elem) {

                return $(elem).classComponentReady(className);

            })).then(function () {

                resolve(elements);

            });

        });

    };

    $.fn.spawn = function (url, classNames, options) {

        var elem = this;

        options = options || {};

        return Promise.resolve($.ajax(url, options)).then(function (data) {

            elem.append($(data));

            return $.CC.init(classNames, elem);

        });

    };

}(jQuery, Promise));
<commit_msg>Add doc and prepend option<commit_after>/**
 * class-component-initializer.js v2.2.0
 * author: Yoshiya Hinosawa ( https://github.com/kt3k )
 * license: MIT
 */

(function ($, Promise) {

    var reSpaces = / +/;

    /**
     * Initialized the all class components of the given names and returns of the promise of all initialization.
     *
     * @param {String[]} arguments
     * @return {Promise}
     */
    $.CC.init = function (classNames, elem) {

        if (typeof classNames === 'string') {

            classNames = classNames.split(reSpaces);

        }

        return Promise.all(classNames.map(function (className) {

            return initOne(className, elem);

        })).then(function (elemGroups) {

            var x = [];

            return x.concat.apply(x, elemGroups);

        });
    };

    /**
     * Initializes one kind of class components of the given name and returns the promise of all initialization.
     *
     * @param {String} className The class name to initialize
     * @return {Promise}
     */
    initOne = function (className, elem) {

        return new Promise(function (resolve) {

            var elements = $.CC.initClassComponent(className, elem);

            Promise.all(elements.map(function (elem) {

                return $(elem).classComponentReady(className);

            })).then(function () {

                resolve(elements);

            });

        });

    };

    /**
     * Spawns the class components from the given url's html contents.
     *
     * @param {String} url The url
     * @param {String|Array<String>} classNames The class names
     * @param {Object} options This options is passed to $.ajax method call
     * @param {Boolean} [options.prepend] if true then prepends the spawned components in the element otherwise appends
     * @return {Promise}
     */
    $.fn.spawn = function (url, classNames, options) {

        var elem = this;

        options = options || {};

        return Promise.resolve($.ajax(url, options)).then(function (data) {

            if (options.prepend) {

                elem.prepend($(data));

            } else {

                elem.append($(data));

            }

            return $.CC.init(classNames, elem);

        });

    };

}(jQuery, Promise));
<|endoftext|>


<commit_before>import React from 'React';
import {Link} from 'react-router';
var debug = require('react-debug');
import {hideElement} from '../util'

export default class NavChatItem extends React.Component {
    constructor(props) {
        super(props);
        this.state={
          online:false
        }
    }

    handleClick(e){
      e.preventDefault();
      this.props.switchUser(this.props.data._id);
    }

    render() {
        return (

this.handleClick(e)}>

                    <Link to={"profile/"+this.props.data._id}>

                    </Link>

                          {this.props.data.fullname}

                      {this.props.lastmessage===undefined?"":this.props.lastmessage.text}
                      New

        )
    }

}
<commit_msg>improve chat message shown<commit_after>import React from 'React';
import {Link} from 'react-router';
import {hideElement} from '../util'
// var debug = require('react-debug');

export default class NavChatItem extends React.Component {
    constructor(props) {
        super(props);
        this.state={
          online:false
        }
    }

    handleClick(e){
      e.preventDefault();
      this.props.switchUser(this.props.data._id);
    }

    render() {
        return (

this.handleClick(e)}>

                    <Link to={"profile/"+this.props.data._id}>

                    </Link>

                          {this.props.data.fullname}

                      {this.props.lastmessage===undefined?"":
                        (this.props.lastmessage.text.length>35?this.props.lastmessage.text.substring(0,35)+"...":this.props.lastmessage.text)}
                      New

        )
    }

}
<|endoftext|>


<commit_before>const {extend} = require('../modules/utilities')
const {mergeArraysByKey} = require('../modules/auxiliaries')

module.exports = function follows(state = [], action = {type: ''}) {
    if(action.type === 'LIST_FOLLOWS_SUCCESS') {
        const follows = mergeArraysByKey(
            state,
            action.follows,
            'id'
        )
        follows.forEach((follow, i) => {
            extend(follow.entity, action.entities[i])
        })
        return follows
    }
    if(action.type === 'ASK_FOLLOW_SUCCESS') {
        if (action.follows.length === 0) { return }
        const follow = action.follows[0]
        const follows = state
        const index = follows.findIndex((f) =>
            f.entity.id === action.entityID)
        if (index > -1) {
            follows[index] = follow
        } else {
            follows.push(follow)
        }
        return follows
        // TODO-3 will this cause a bug with mergeArraysByKey later?
    }
    if(action.type === 'FOLLOW_SUCCESS') {
        const follows = state
        follows.push(action.follow)
        return follows
        // TODO-3 will this cause a bug with mergeArraysByKey later?
    }
    if(action.type === 'UNFOLLOW_SUCCESS') {
        const follows = state
        const i = follows.findIndex((follow) =>
            follow.id === action.id)
        follows.splice(i, 1)
        return follows
    }
    return state
}
<commit_msg>Fix for list follows<commit_after>const {extend} = require('../modules/utilities')
const {mergeArraysByKey} = require('../modules/auxiliaries')

module.exports = function follows(state = [], action = {type: ''}) {
    if(action.type === 'LIST_FOLLOWS_SUCCESS') {
        const follows = mergeArraysByKey(
            state,
            action.follows,
            'id'
        )
        follows.forEach((follow, i) => {
            const entity = action.entities[i]
            if (entity) { extend(follow.entity, entity) }
        })
        return follows
    }
    if(action.type === 'ASK_FOLLOW_SUCCESS') {
        if (action.follows.length === 0) { return }
        const follow = action.follows[0]
        const follows = state
        const index = follows.findIndex((f) =>
            f.entity.id === action.entityID)
        if (index > -1) {
            follows[index] = follow
        } else {
            follows.push(follow)
        }
        return follows
        // TODO-3 will this cause a bug with mergeArraysByKey later?
    }
    if(action.type === 'FOLLOW_SUCCESS') {
        const follows = state
        follows.push(action.follow)
        return follows
        // TODO-3 will this cause a bug with mergeArraysByKey later?
    }
    if(action.type === 'UNFOLLOW_SUCCESS') {
        const follows = state
        const i = follows.findIndex((follow) =>
            follow.id === action.id)
        follows.splice(i, 1)
        return follows
    }
    return state
}
<|endoftext|>


<commit_before>import React from 'react';
import timeUtils from './calendar/timeUtils';
import classNames from 'classnames';
import _ from 'lodash';

class EventList extends React.Component {

  static propTypes = {
    onEventClick: React.PropTypes.func,
    onHeaderClick: React.PropTypes.func,
    events: React.PropTypes.array.isRequired
  }

  state = {
    groupedEvents: {}
  }

  componentWillReceiveProps(nextProps) {
    this.state.groupedEvents = this._groupEvents(nextProps.events);
  }

  componentWillUnmount() {
    if (this.state.animationFrame) {
      cancelAnimationFrame(this.state.animationFrame);
    }
  }

  /*
   * Get the group for a date
   */

  _getGroupForDate(date) {
    return timeUtils.prettyFormatDate(date);
  }

  /*
   * Group events by date
   */

  _groupEvents(events) {
    const groups = {};
    const now = new Date();

    // if no events, return only an empty today
    if (!events.length) {
      return {
        [this._getGroupForDate(now)]: []
      };
    }

    let last = now;
    events.forEach(e => {
      const d = new Date(e.start.dateTime || e.start.date);
      d.setHours(0, 0, 0, 0);

      const format = this._getGroupForDate(d);

      // there's no events for today, so create one
      if (last < now && d > now) {
        groups[this._getGroupForDate(now)] = [];
      }

      if (!groups[format]) {
        groups[format] = [e];
      } else {
        groups[format].push(e);
      }

      last = d;
    });

    return groups;
  }

  /*
   * Scroll to a date
   */

  scrollToDate(date) {
    const group = this._getGroupForDate(date);

    const el = this.refs[group];
    if (el) {
      if (this.state.animationFrame) {
        cancelAnimationFrame(this.state.animationFrame);
      }
      this._animateContainer(el.offsetParent, el);
    }
  }

  /*
   * Smoothly animate a container to an element
   */

  _animateContainer(container, el) {
    function easeInOutQuad(t, b, c, d) {
      t /= d / 2;
      if (t < 1) return c / 2 * t * t + b;
      t--;
      return -c / 2 * (t * (t - 2) - 1) + b;
    }

    const target = el.offsetTop - 10;
    const start = container.scrollTop;
    const time = 250;
    let elapsed = 0;
    let last = new Date().getTime();

    const anim = () => {
      const req = requestAnimationFrame(() => {
        const now = new Date().getTime();
        const delta = now - last;
        elapsed += delta;
        const val = easeInOutQuad(Math.min(elapsed, time), start, target - start, time);
        container.scrollTop = val;
        last = now;
        if (val !== target) {
          anim();
        } else {
          this.state.animationFrame = null;
        }
      });
      this.state.animationFrame = req;
    };
    anim();
  }

  /*
   *  Handle when an event is clicked on
   */

  _handleEventClick(event) {
    if (this.props.onEventClick) {
      this.props.onEventClick(event);
    }
  }

  /*
   * Handle when a group header is clicked on
   */

  _handleHeaderClick(group) {
    if (this.props.onHeaderClick) {
      const d = new Date(group.substr(group.indexOf(' ') + 1));
      this.props.onHeaderClick(d);
    }
  }

  /*
   * Render the individual event item
   */

  _renderEvent(event, idx) {
    let name = event.summary;
    const start = new Date(event.start.dateTime || event.start.date);
    const end = new Date(event.end.dateTime || event.start.date);
    let timeRange = `${timeUtils.formatTime(start, 'ampm')} - ${timeUtils.formatTime(end, 'ampm')}`;
    const now = new Date();
    const isPast = end < now;
    const isCurrent = now >= start && now <= end;

    const eventClasses = classNames({
      event: true,
      past: isPast,
      current: isCurrent
    });

    return (

          {name}

            {event.location}

{timeRange}

    );
  }

  /*
   * Render the list of events
   */

  render() {
    const items = _.map(this.state.groupedEvents, (subItems, key) => {
      const header = (

{key}

      );
      const els = subItems.map((e, i) => (
        this._renderEvent(e, i)
      ));

      if (!els.length && key.indexOf('Today') === 0) {
        els.push(

No events today!

        );
      }
      return [header].concat(els);
    });

    return (

{items}

    );
  }
}

export default EventList;
<commit_msg>Fix typo for end date<commit_after>import React from 'react';
import timeUtils from './calendar/timeUtils';
import classNames from 'classnames';
import _ from 'lodash';

class EventList extends React.Component {

  static propTypes = {
    onEventClick: React.PropTypes.func,
    onHeaderClick: React.PropTypes.func,
    events: React.PropTypes.array.isRequired
  }

  state = {
    groupedEvents: {}
  }

  componentWillReceiveProps(nextProps) {
    this.state.groupedEvents = this._groupEvents(nextProps.events);
  }

  componentWillUnmount() {
    if (this.state.animationFrame) {
      cancelAnimationFrame(this.state.animationFrame);
    }
  }

  /*
   * Get the group for a date
   */

  _getGroupForDate(date) {
    return timeUtils.prettyFormatDate(date);
  }

  /*
   * Group events by date
   */

  _groupEvents(events) {
    const groups = {};
    const now = new Date();

    // if no events, return only an empty today
    if (!events.length) {
      return {
        [this._getGroupForDate(now)]: []
      };
    }

    let last = now;
    events.forEach(e => {
      const d = new Date(e.start.dateTime || e.start.date);
      d.setHours(0, 0, 0, 0);

      const format = this._getGroupForDate(d);

      // there's no events for today, so create one
      if (last < now && d > now) {
        groups[this._getGroupForDate(now)] = [];
      }

      if (!groups[format]) {
        groups[format] = [e];
      } else {
        groups[format].push(e);
      }

      last = d;
    });

    return groups;
  }

  /*
   * Scroll to a date
   */

  scrollToDate(date) {
    const group = this._getGroupForDate(date);

    const el = this.refs[group];
    if (el) {
      if (this.state.animationFrame) {
        cancelAnimationFrame(this.state.animationFrame);
      }
      this._animateContainer(el.offsetParent, el);
    }
  }

  /*
   * Smoothly animate a container to an element
   */

  _animateContainer(container, el) {
    function easeInOutQuad(t, b, c, d) {
      t /= d / 2;
      if (t < 1) return c / 2 * t * t + b;
      t--;
      return -c / 2 * (t * (t - 2) - 1) + b;
    }

    const target = el.offsetTop - 10;
    const start = container.scrollTop;
    const time = 250;
    let elapsed = 0;
    let last = new Date().getTime();

    const anim = () => {
      const req = requestAnimationFrame(() => {
        const now = new Date().getTime();
        const delta = now - last;
        elapsed += delta;
        const val = easeInOutQuad(Math.min(elapsed, time), start, target - start, time);
        container.scrollTop = val;
        last = now;
        if (val !== target) {
          anim();
        } else {
          this.state.animationFrame = null;
        }
      });
      this.state.animationFrame = req;
    };
    anim();
  }

  /*
   *  Handle when an event is clicked on
   */

  _handleEventClick(event) {
    if (this.props.onEventClick) {
      this.props.onEventClick(event);
    }
  }

  /*
   * Handle when a group header is clicked on
   */

  _handleHeaderClick(group) {
    if (this.props.onHeaderClick) {
      const d = new Date(group.substr(group.indexOf(' ') + 1));
      this.props.onHeaderClick(d);
    }
  }

  /*
   * Render the individual event item
   */

  _renderEvent(event, idx) {
    let name = event.summary;
    const start = new Date(event.start.dateTime || event.start.date);
    const end = new Date(event.end.dateTime || event.end.date);
    let timeRange = `${timeUtils.formatTime(start, 'ampm')} - ${timeUtils.formatTime(end, 'ampm')}`;
    const now = new Date();
    const isPast = end < now;
    const isCurrent = now >= start && now <= end;

    const eventClasses = classNames({
      event: true,
      past: isPast,
      current: isCurrent
    });

    return (

          {name}

            {event.location}

{timeRange}

    );
  }

  /*
   * Render the list of events
   */

  render() {
    const items = _.map(this.state.groupedEvents, (subItems, key) => {
      const header = (

{key}

      );
      const els = subItems.map((e, i) => (
        this._renderEvent(e, i)
      ));

      if (!els.length && key.indexOf('Today') === 0) {
        els.push(

No events today!

        );
      }
      return [header].concat(els);
    });

    return (

{items}

    );
  }
}

export default EventList;
<|endoftext|>


<commit_before>angular.module('domegis')
.controller('QueryCtrl', [
  '$scope',
  'Content',
  'esriService',
  function($scope, Content, Esri) {

    $scope.helpers({
      synced: () => Contents.find({})
    });

    $scope.sort = {
      syncedAt: -1
    };

    $scope.subscribe('synced', () => {
      return [
        {
          sort: $scope.getReactively('sort')
        }
      ]
    });

    $scope.syncItem = (item) => {
      Contents.insert(angular.copy(item));
    };

    $scope.unsyncItem = (item) => {
      Contents.remove({_id: item._id});
    };

    $scope.content = Content.data;

    $scope.search = '';
    $scope.query = {
      type: ''
    };
    $scope.params = {};

    $scope.sort = 'numviews';

    $scope.availableTypes = Esri.getContentTypes();

    $scope.doQuery = function() {
      $scope.doSort();
      Esri.getContent(
        $scope.search,
        $scope.query,
        $scope.params
      ).then(function(data) {
        $scope.content = data.data;
      });
    };

    $scope.$watchGroup(['search', 'query'], _.debounce(function() {
      $scope.doQuery();
    }, 500), true);

    $scope.doSort = function() {
      $scope.params = _.extend($scope.params, {
        sortField: $scope.sort,
        sortOrder: getSortOrder($scope.sort)
      });
    };

    function getSortOrder(sort) {
      if(sort == 'title' || sort == 'owner') {
        return 'asc';
      } else {
        return 'desc';
      }
    }

  }
]);
<commit_msg>use sync method<commit_after>angular.module('domegis')
.controller('QueryCtrl', [
  '$scope',
  'Content',
  'esriService',
  function($scope, Content, Esri) {

    $scope.helpers({
      synced: () => Contents.find({})
    });

    $scope.sort = {
      syncedAt: -1
    };

    $scope.subscribe('synced', () => {
      return [
        {
          sort: $scope.getReactively('sort')
        }
      ]
    });

    $scope.syncItem = (item) => {
      Meteor.call('syncContent', angular.copy(item));
    };

    $scope.unsyncItem = (item) => {
      Contents.remove({_id: item._id});
    };

    $scope.content = Content.data;

    $scope.search = '';
    $scope.query = {
      type: ''
    };
    $scope.params = {};

    $scope.sort = 'numviews';

    $scope.availableTypes = Esri.getContentTypes();

    $scope.doQuery = function() {
      $scope.doSort();
      Esri.getContent(
        $scope.search,
        $scope.query,
        $scope.params
      ).then(function(data) {
        $scope.content = data.data;
      });
    };

    $scope.$watchGroup(['search', 'query'], _.debounce(function() {
      $scope.doQuery();
    }, 500), true);

    $scope.doSort = function() {
      $scope.params = _.extend($scope.params, {
        sortField: $scope.sort,
        sortOrder: getSortOrder($scope.sort)
      });
    };

    function getSortOrder(sort) {
      if(sort == 'title' || sort == 'owner') {
        return 'asc';
      } else {
        return 'desc';
      }
    }

  }
]);
<|endoftext|>


<commit_before>import { isString, isEmpty, map, isNaN } from 'lodash';
import {
    identifiedBy,
} from 'mobx-decorated-models';

@identifiedBy('date-range')
export default class DateRange {

    constructor(range) {
        if (isString(range) && !isEmpty(range)) {
            [this.start, this.end] = map(range.split('...'), d => new Date(d));
        } else if (range) {
            this.start = range.start;
            this.end = range.end;
        }
    }

    toJSON() {
        if (this.start && this.end && !isNaN(this.start) && !isNaN(this.end)) {
            // this strange format is what PG user and is therefore what active record expects
            return `[${this.start.toISOString()},${this.end.toISOString()})`;
        }
        return '';
    }

    static serialize(range) {
        return (range ? range.toJSON() : '');
    }

}
<commit_msg>add isCurrent<commit_after>import moment from 'moment';
import { observable, computed } from 'mobx';
import { isString, isEmpty, map, isNaN } from 'lodash';
import {
    identifiedBy,
} from 'mobx-decorated-models';

@identifiedBy('date-range')
export default class DateRange {

    @observable start;
    @observable end;

    constructor(range) {
        if (isString(range) && !isEmpty(range)) {
            [this.start, this.end] = map(range.split('...'), d => new Date(d));
        } else if (range) {
            this.start = range.start;
            this.end = range.end;
        }
    }

    toJSON() {
        if (this.start && this.end && !isNaN(this.start) && !isNaN(this.end)) {
            // this strange format is what PG user and is therefore what active record expects
            return `[${this.start.toISOString()},${this.end.toISOString()})`;
        }
        return '';
    }

    static serialize(range) {
        return (range ? range.toJSON() : '');
    }

    @computed get isCurrent() {
        return moment(this.end).isAfter() && moment(this.start).isBefore();
    }

}
<|endoftext|>


<commit_before>// Get my id, update lobby state
function handleMe(response) {
    player.id = response.me.id;
    handleLobbyUpdate(response.lobby);
}

// Change UI [lobby, game, leaderboard]
function handleLobbyUpdate(response) {
    // Only worry about response once we get our id
    if (!player.id) {
        return;
    }

    // Update state
    state = response.state;

    UIHideAll();
    if (state === STATE_LOBBY) {
        $("#lobby").show();
        UIUpdateLobbyPlayers(response.players);
    } else if (state === STATE_GAME) {
        $("#game").show();
    } else if (state === STATE_GAME_OVER) {
        $("#leaderboard").show();
    }
}

// Role is a enum (see roles.js)
function handlePlayerRole(role) {
    console.log("My role is: " + role);
    player.role = role;

    switch(player.role){
        case ROLE_APE:
            updateLevelStart();
            break;
        case ROLE_JAILER:
            ape.anchor.setTo(0.5, 1);
            ape.body.move = false;
            layer2.visible = true;
            apeName = game.add.text(0, 0, "", { font: "12px Arial", fill: "#000000", align: "center" });
            break;
    }
}

// A new level started
function handleLevelStart(response) {
    console.log("The level is: " + response);
}

var lastUpdate = new Date();
//Ape position updated by server
function handleGameState(state){
    // Latency checking
    var currentUpdate = new Date();
    //console.log("Last update "+(currentUpdate - lastUpdate) + "ms ago");
    lastUpdate = currentUpdate;

    if (window.player.role === ROLE_JAILER){
        for(var player in state.players){
            switch(state.players[player].role){
                case ROLE_APE:
                    var xPos = state.players[player].state.x;
                    var yPos = state.players[player].state.y;
                    var scale = state.players[player].state.scale;

                    if(apeName){
                        apeName.text = state.players[player].name;
                        var nameXPos = Math.floor(xPos + ape.width / 2) - ((scale.x === 1) ? ape.width : 0);
                        apeName.x = nameXPos;
                        apeName.y = yPos - 65;
                    }
                    ape.x = xPos;
                    ape.y = yPos;
                    ape.scale = scale;
                    ape.frame = state.players[player].state.frame;
                    break;
                case ROLE_JAILER:
                    break;
            }
        }
    }
}

// Find out who I am
socket.on("me", handleMe);

// Lobby update
socket.on("lobby_state", handleLobbyUpdate);

// Find out what role I am
socket.on("player_role", handlePlayerRole);

// Find out a new level has started
socket.on("level_start", handleLevelStart);

// Find out the game's state
socket.on("game_state", handleGameState);<commit_msg>30ms interpolation<commit_after>// Get my id, update lobby state
function handleMe(response) {
    player.id = response.me.id;
    handleLobbyUpdate(response.lobby);
}

// Change UI [lobby, game, leaderboard]
function handleLobbyUpdate(response) {
    // Only worry about response once we get our id
    if (!player.id) {
        return;
    }

    // Update state
    state = response.state;

    UIHideAll();
    if (state === STATE_LOBBY) {
        $("#lobby").show();
        UIUpdateLobbyPlayers(response.players);
    } else if (state === STATE_GAME) {
        $("#game").show();
    } else if (state === STATE_GAME_OVER) {
        $("#leaderboard").show();
    }
}

// Role is a enum (see roles.js)
function handlePlayerRole(role) {
    console.log("My role is: " + role);
    player.role = role;

    switch(player.role){
        case ROLE_APE:
            updateLevelStart();
            break;
        case ROLE_JAILER:
            ape.anchor.setTo(0.5, 1);
            ape.body.move = false;
            layer2.visible = true;
            apeName = game.add.text(0, 0, "", { font: "12px Arial", fill: "#000000", align: "center" });
            break;
    }
}

// A new level started
function handleLevelStart(response) {
    console.log("The level is: " + response);
}

var lastUpdate = new Date();
//Ape position updated by server
function handleGameState(state){
    // Latency checking
    var currentUpdate = new Date();
    //console.log("Last update "+(currentUpdate - lastUpdate) + "ms ago");
    lastUpdate = currentUpdate;

    if (window.player.role === ROLE_JAILER){
        for(var player in state.players){
            switch(state.players[player].role){
                case ROLE_APE:
                    var xPos = state.players[player].state.x;
                    var yPos = state.players[player].state.y;
                    var scale = state.players[player].state.scale;

                    if(apeName){
                        apeName.text = state.players[player].name;
                        var nameXPos = Math.floor(xPos + ape.width / 2) - ((scale.x === 1) ? ape.width : 0);
                        apeName.x = nameXPos;
                        apeName.y = yPos - 65;
                    }

                    //TWEEN DAT
                    game.add.tween(ape).to({
                        x: [xPos],
                        y: [yPos]
                    },30).interpolation(Phaser.Math.bezierInterpolation).start();

                    ape.scale = scale;
                    ape.frame = state.players[player].state.frame;
                    break;
                case ROLE_JAILER:
                    break;
            }
        }
    }
}

// Find out who I am
socket.on("me", handleMe);

// Lobby update
socket.on("lobby_state", handleLobbyUpdate);

// Find out what role I am
socket.on("player_role", handlePlayerRole);

// Find out a new level has started
socket.on("level_start", handleLevelStart);

// Find out the game's state
socket.on("game_state", handleGameState);<|endoftext|>


<commit_before>import alt from '../alt';
import ScaleActions from '../actions/ScaleActions';

export default alt.createStore(class ScaleStore {
  constructor () {
    this.scales = {
      major: [0, 2, 4, 5, 7, 9, 11, 12],
      minor: [0, 2, 3, 5, 7, 8, 10, 12],
      pentatonic: [0, 3, 5, 7, 10, 12],
      phrygian: [0, 1, 3, 5, 7, 8, 10, 12],
      'phrygian dominant': [0, 1, 4, 5, 7, 8, 10, 12],
      wholetone: [0, 2, 4, 6, 8, 10, 12],
    };

    this.scaleName = 'major';

    this.bindListeners({
      handleUpdateScale: ScaleActions.UPDATE_SCALE,
    });
  }

  handleUpdateScale (item) {
    this.scaleName = item;
  }
}, 'ScaleStore');
<commit_msg>add harmonic minor scale<commit_after>import alt from '../alt';
import ScaleActions from '../actions/ScaleActions';

export default alt.createStore(class ScaleStore {
  constructor () {
    this.scales = {
      'harmonic minor': [0, 2, 3, 5, 7, 8, 11, 12],
      major: [0, 2, 4, 5, 7, 9, 11, 12],
      minor: [0, 2, 3, 5, 7, 8, 10, 12],
      pentatonic: [0, 3, 5, 7, 10, 12],
      phrygian: [0, 1, 3, 5, 7, 8, 10, 12],
      'phrygian dominant': [0, 1, 4, 5, 7, 8, 10, 12],
      wholetone: [0, 2, 4, 6, 8, 10, 12],
    };

    this.scaleName = 'major';

    this.bindListeners({
      handleUpdateScale: ScaleActions.UPDATE_SCALE,
    });
  }

  handleUpdateScale (item) {
    this.scaleName = item;
  }
}, 'ScaleStore');
<|endoftext|>


<commit_before>app.RoomCreateForm = React.createClass({
  handleSubmit: function(e) {
    e.preventDefault();

    var roomName = this.refs.name.getDOMNode();

    app.RoomActions.create(roomName.value.trim());
    roomName.value = '';
    return;
  },

  render: function(){
    return (
      <form className="pure-form pure-g" ref="form" onSubmit={this.handleSubmit}>
        <input className="pure-input-1" type="text" ref="name" placeholder="Room" />
        <button className="button-small pure-button pure-button-primary" type="submit" ref="submit" >Create Room</button>
      </form>
    );
  }
});
<commit_msg>Remove className from button.<commit_after>app.RoomCreateForm = React.createClass({
  handleSubmit: function(e) {
    e.preventDefault();

    var roomName = this.refs.name.getDOMNode();

    app.RoomActions.create(roomName.value.trim());
    roomName.value = '';
    return;
  },

  render: function(){
    return (
      <form className="pure-form pure-g" ref="form" onSubmit={this.handleSubmit}>
        <input type="text" ref="name" placeholder="Room" />
        <button className="button-small pure-button pure-button-primary" type="submit" ref="submit" >Create Room</button>
      </form>
    );
  }
});
<|endoftext|>


<commit_before>import fetch from 'isomorphic-fetch';

import { API_ROOT } from './common';

export function loadRecentListings() {
  return function (dispatch, getState) {
    dispatch({
      type: 'RECENT_LISTINGS_REQUEST',
    });

    fetch(`${API_ROOT}/listings`)
      .then(response => response.json())
      .then(json => dispatch({
        json,
        type: 'RECENT_LISTINGS_SUCCESS',
      }))
      .catch(error => dispatch({
        error,
        type: 'RECENT_LISTINGS_FAILURE',
      }));
  };
}

export function searchListings(query) {
  return function (dispatch, getState) {
    dispatch({
      type: 'SEARCH_LISTINGS_REQUEST',
    });
    fetch(`${API_ROOT}/listings?q=${encodeURIComponent(query)}`)
      .then(response => response.json())
      .then(json => dispatch({
        json,
        type: 'SEARCH_LISTINGS_SUCCESS',
      }))
      .catch(error => dispatch({
        error,
        type: 'SEARCH_LISTINGS_FAILURE',
      }));
  };
}

export function setCurrentListingsQuery(query) {
  return ({
    type: 'SET_CURRENT_LISTINGS_QUERY',
    query,
  });
}

export function postListing(listing) {
  return function (dispatch, getState) {
    dispatch({
      type: 'POST_LISTING_REQUEST',
    });

    fetch(`${API_ROOT}/listings`, {
      credentials: 'include',
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(listing),
    })
    .then((json) => {
      dispatch({
        json,
        type: 'POST_LISTING_SUCCESS',
      });
      dispatch(loadRecentListings());
    })
    .catch(error => dispatch({
      error,
      type: 'POST_LISTING_FAILURE',
    }));
  };
}
<commit_msg>send as query= not q=<commit_after>import fetch from 'isomorphic-fetch';

import { API_ROOT } from './common';

export function loadRecentListings() {
  return function (dispatch, getState) {
    dispatch({
      type: 'RECENT_LISTINGS_REQUEST',
    });

    fetch(`${API_ROOT}/listings`)
      .then(response => response.json())
      .then(json => dispatch({
        json,
        type: 'RECENT_LISTINGS_SUCCESS',
      }))
      .catch(error => dispatch({
        error,
        type: 'RECENT_LISTINGS_FAILURE',
      }));
  };
}

export function searchListings(query) {
  return function (dispatch, getState) {
    dispatch({
      type: 'SEARCH_LISTINGS_REQUEST',
    });
    fetch(`${API_ROOT}/listings?query=${encodeURIComponent(query)}`)
      .then(response => response.json())
      .then(json => dispatch({
        json,
        type: 'SEARCH_LISTINGS_SUCCESS',
      }))
      .catch(error => dispatch({
        error,
        type: 'SEARCH_LISTINGS_FAILURE',
      }));
    /*
    fetch(`${API_ROOT}/search/${encodeURIComponent(query)}`)
      .then(response => response.json())
      .then(json => dispatch({
        json,
        type: 'SEARCH_LISTINGS_SUCCESS',
      }))
      .catch(error => dispatch({
        error,
        type: 'SEARCH_LISTINGS_FAILURE',
      }));
      */
  };
}

export function setCurrentListingsQuery(query) {
  return ({
    type: 'SET_CURRENT_LISTINGS_QUERY',
    query,
  });
}

export function postListing(listing) {
  return function (dispatch, getState) {
    dispatch({
      type: 'POST_LISTING_REQUEST',
    });

    fetch(`${API_ROOT}/listings`, {
      credentials: 'include',
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(listing),
    })
    .then((json) => {
      dispatch({
        json,
        type: 'POST_LISTING_SUCCESS',
      });
      dispatch(loadRecentListings());
    })
    .catch(error => dispatch({
      error,
      type: 'POST_LISTING_FAILURE',
    }));
  };
}
<|endoftext|>