<commit_before># Copyright (C) 2012-2015 Zammad Foundation, http://zammad-foundation.org/

class Telegram

  attr_accessor :client

=begin

check token and return bot attributes of token

  bot = Telegram.check_token('token')

=end

  def self.check_token(token)
    api = TelegramAPI.new(token)
    begin
      bot = api.getMe()
    rescue
      raise 'invalid api token'
    end
    bot
  end

=begin

set webhool for bot

  success = Telegram.set_webhook('token', callback_url)

returns

  true|false

=end

  def self.set_webhook(token, callback_url)
    if callback_url =~ %r{^http://}i
      raise 'webhook url need to start with https://, you use http://'
    end
    api = TelegramAPI.new(token)
    begin
      api.setWebhook(callback_url)
    rescue
      raise 'Unable to set webhook at Telegram, seems to be a invalid url.'
    end
    true
  end

=begin

create or update channel, store bot attributes and verify token

  channel = Telegram.create_or_update_channel('token', params)

returns

  channel # instance of Channel

=end

  def self.create_or_update_channel(token, params, channel = nil)

    # verify token
    bot = Telegram.check_token(token)

    if !channel
      if Telegram.bot_duplicate?(bot['id'])
        raise 'Bot already exists!'
      end
    end

    if params[:group_id].blank?
      raise 'Group needed!'
    end
    group = Group.find_by(id: params[:group_id])
    if !group
      raise 'Group invalid!'
    end

    # generate randam callback token
    callback_token = SecureRandom.urlsafe_base64(10)

    # set webhook / callback url for this bot @ telegram
    callback_url = "#{Setting.get('http_type')}://#{Setting.get('fqdn')}/api/v1/channels_telegram_webhook/#{callback_token}?bid=#{bot['id']}"
    Telegram.set_webhook(token, callback_url)

    if !channel
      channel = Telegram.bot_by_bot_id(bot['id'])
      if !channel
        channel = Channel.new
      end
    end
    channel.area = 'Telegram::Bot'
    channel.options = {
      bot: {
        id: bot['id'],
        username: bot['username'],
        first_name: bot['first_name'],
        last_name: bot['last_name'],
      },
      callback_token: callback_token,
      callback_url: callback_url,
      api_token: token,
      welcome: params[:welcome],
    }
    channel.group_id = group.id
    channel.active = true
    channel.save!
    channel
  end

=begin

check if bot already exists as channel

  success = Telegram.bot_duplicate?(bot_id)

returns

  channel # instance of Channel

=end

  def self.bot_duplicate?(bot_id, channel_id = nil)
    Channel.where(area: 'Telegram::Bot').each { |channel|
      next if !channel.options
      next if !channel.options[:bot]
      next if !channel.options[:bot][:id]
      next if channel.options[:bot][:id] != bot_id
      next if channel.id.to_s == channel_id.to_s
      return true
    }
    false
  end

=begin

get channel by bot_id

  channel = Telegram.bot_by_bot_id(bot_id)

returns

  true|false

=end

  def self.bot_by_bot_id(bot_id)
    Channel.where(area: 'Telegram::Bot').each { |channel|
      next if !channel.options
      next if !channel.options[:bot]
      next if !channel.options[:bot][:id]
      return channel if channel.options[:bot][:id].to_s == bot_id.to_s
    }
    nil
  end

=begin

generate message_id for message

  message_id = Telegram.message_id(message)

returns

  message_id # 123456@telegram

=end

  def self.message_id(params)
    message_id = nil
    [:message, :edited_message].each { |key|
      next if !params[key]
      next if !params[key][:message_id]
      message_id = params[key][:message_id]
      break
    }
    if !message_id
      message_id = params[:update_id]
    end
    "#{message_id}@telegram"
  end

=begin

  client = Telegram.new('token')

=end

  def initialize(token)
    @token = token
    @api = TelegramAPI.new(token)
  end

=begin

  client.message(chat_id, 'some message')

=end

  def message(chat_id, message)
    return if Rails.env.test?
    @api.sendMessage(chat_id, message)
  end

  def user(params)
    {
      id:         params[:message][:from][:id],
      username:   params[:message][:from][:username],
      first_name: params[:message][:from][:first_name],
      last_name:  params[:message][:from][:last_name]
    }
  end

  def to_user(params)
    Rails.logger.debug 'Create user from message...'
    Rails.logger.debug params.inspect

    # do message_user lookup
    message_user = user(params)

    auth = Authorization.find_by(uid: message_user[:id], provider: 'telegram')

    # create or update user
    user_data = {
      login: message_user[:username],
      firstname: message_user[:first_name],
      lastname: message_user[:last_name],
    }
    if auth
      user = User.find(auth.user_id)
      user.update_attributes(user_data)
    else
      user_data[:note]     = "Telegram @#{message_user[:username]}"
      user_data[:active]   = true
      user_data[:role_ids] = Role.signup_role_ids
      user                 = User.create(user_data)
    end

    # create or update authorization
    auth_data = {
      uid:      message_user[:id],
      username: message_user[:username],
      user_id:  user.id,
      provider: 'telegram'
    }
    if auth
      auth.update_attributes(auth_data)
    else
      Authorization.create(auth_data)
    end

    user
  end
<commit_msg>Also support telegram users without username.<commit_after># Copyright (C) 2012-2015 Zammad Foundation, http://zammad-foundation.org/

class Telegram

  attr_accessor :client

=begin

check token and return bot attributes of token

  bot = Telegram.check_token('token')

=end

  def self.check_token(token)
    api = TelegramAPI.new(token)
    begin
      bot = api.getMe()
    rescue
      raise 'invalid api token'
    end
    bot
  end

=begin

set webhool for bot

  success = Telegram.set_webhook('token', callback_url)

returns

  true|false

=end

  def self.set_webhook(token, callback_url)
    if callback_url =~ %r{^http://}i
      raise 'webhook url need to start with https://, you use http://'
    end
    api = TelegramAPI.new(token)
    begin
      api.setWebhook(callback_url)
    rescue
      raise 'Unable to set webhook at Telegram, seems to be a invalid url.'
    end
    true
  end

=begin

create or update channel, store bot attributes and verify token

  channel = Telegram.create_or_update_channel('token', params)

returns

  channel # instance of Channel

=end

  def self.create_or_update_channel(token, params, channel = nil)

    # verify token
    bot = Telegram.check_token(token)

    if !channel
      if Telegram.bot_duplicate?(bot['id'])
        raise 'Bot already exists!'
      end
    end

    if params[:group_id].blank?
      raise 'Group needed!'
    end
    group = Group.find_by(id: params[:group_id])
    if !group
      raise 'Group invalid!'
    end

    # generate randam callback token
    callback_token = SecureRandom.urlsafe_base64(10)

    # set webhook / callback url for this bot @ telegram
    callback_url = "#{Setting.get('http_type')}://#{Setting.get('fqdn')}/api/v1/channels_telegram_webhook/#{callback_token}?bid=#{bot['id']}"
    Telegram.set_webhook(token, callback_url)

    if !channel
      channel = Telegram.bot_by_bot_id(bot['id'])
      if !channel
        channel = Channel.new
      end
    end
    channel.area = 'Telegram::Bot'
    channel.options = {
      bot: {
        id: bot['id'],
        username: bot['username'],
        first_name: bot['first_name'],
        last_name: bot['last_name'],
      },
      callback_token: callback_token,
      callback_url: callback_url,
      api_token: token,
      welcome: params[:welcome],
    }
    channel.group_id = group.id
    channel.active = true
    channel.save!
    channel
  end

=begin

check if bot already exists as channel

  success = Telegram.bot_duplicate?(bot_id)

returns

  channel # instance of Channel

=end

  def self.bot_duplicate?(bot_id, channel_id = nil)
    Channel.where(area: 'Telegram::Bot').each { |channel|
      next if !channel.options
      next if !channel.options[:bot]
      next if !channel.options[:bot][:id]
      next if channel.options[:bot][:id] != bot_id
      next if channel.id.to_s == channel_id.to_s
      return true
    }
    false
  end

=begin

get channel by bot_id

  channel = Telegram.bot_by_bot_id(bot_id)

returns

  true|false

=end

  def self.bot_by_bot_id(bot_id)
    Channel.where(area: 'Telegram::Bot').each { |channel|
      next if !channel.options
      next if !channel.options[:bot]
      next if !channel.options[:bot][:id]
      return channel if channel.options[:bot][:id].to_s == bot_id.to_s
    }
    nil
  end

=begin

generate message_id for message

  message_id = Telegram.message_id(message)

returns

  message_id # 123456@telegram

=end

  def self.message_id(params)
    message_id = nil
    [:message, :edited_message].each { |key|
      next if !params[key]
      next if !params[key][:message_id]
      message_id = params[key][:message_id]
      break
    }
    if !message_id
      message_id = params[:update_id]
    end
    "#{message_id}@telegram"
  end

=begin

  client = Telegram.new('token')

=end

  def initialize(token)
    @token = token
    @api = TelegramAPI.new(token)
  end

=begin

  client.message(chat_id, 'some message')

=end

  def message(chat_id, message)
    return if Rails.env.test?
    @api.sendMessage(chat_id, message)
  end

  def user(params)
    {
      id:         params[:message][:from][:id],
      username:   params[:message][:from][:username],
      first_name: params[:message][:from][:first_name],
      last_name:  params[:message][:from][:last_name]
    }
  end

  def to_user(params)
    Rails.logger.debug 'Create user from message...'
    Rails.logger.debug params.inspect

    # do message_user lookup
    message_user = user(params)

    auth = Authorization.find_by(uid: message_user[:id], provider: 'telegram')

    # create or update user
    login = message_user[:username] || message_user[:id]
    user_data = {
      login: login,
      firstname: message_user[:first_name],
      lastname: message_user[:last_name],
    }
    if auth
      user = User.find(auth.user_id)
      user.update_attributes(user_data)
    else
      if message_user[:username]
        user_data[:note] = "Telegram @#{message_user[:username]}"
      end
      user_data[:active]   = true
      user_data[:role_ids] = Role.signup_role_ids
      user                 = User.create(user_data)
    end

    # create or update authorization
    auth_data = {
      uid:      message_user[:id],
      username: login,
      user_id:  user.id,
      provider: 'telegram'
    }
    if auth
      auth.update_attributes(auth_data)
    else
      Authorization.create(auth_data)
    end

    user
  end

{'fraction_non_alphanumeric': 0.11091516614070912, 'fraction_numerical': 0.0035270094672359385, 'mean_word_length': 2.855098389982111, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1823395', 'n_tokens_mistral': 3620, 'n_tokens_neox': 3528, 'n_words': 829}