Class: TD::Client

Inherits:
Object
  • Object
show all
Includes:
Concurrent, ClientMethods
Defined in:
lib/tdlib/client.rb

Overview

Simple client for TDLib.

Constant Summary collapse

TIMEOUT =
20

Class Method Summary collapse

Instance Method Summary collapse

Methods included from ClientMethods

#accept_call, #accept_terms_of_service, #add_chat_member, #add_chat_members, #add_contact, #add_custom_server_language_pack, #add_favorite_sticker, #add_local_message, #add_log_message, #add_network_statistics, #add_proxy, #add_recent_sticker, #add_recently_found_chat, #add_saved_animation, #add_sticker_to_set, #answer_callback_query, #answer_custom_query, #answer_inline_query, #answer_pre_checkout_query, #answer_shipping_query, #block_user, #can_transfer_ownership, #cancel_download_file, #cancel_upload_file, #change_imported_contacts, #change_phone_number, #change_sticker_set, #check_authentication_bot_token, #check_authentication_code, #check_authentication_password, #check_change_phone_number_code, #check_chat_invite_link, #check_chat_username, #check_created_public_chats_limit, #check_database_encryption_key, #check_email_address_verification_code, #check_phone_number_confirmation_code, #check_phone_number_verification_code, #check_recovery_email_address_code, #clean_file_name, #clear_all_draft_messages, #clear_imported_contacts, #clear_recent_stickers, #clear_recently_found_chats, #close, #close_chat, #close_secret_chat, #confirm_qr_code_authentication, #create_basic_group_chat, #create_call, #create_new_basic_group_chat, #create_new_secret_chat, #create_new_sticker_set, #create_new_supergroup_chat, #create_private_chat, #create_secret_chat, #create_supergroup_chat, #create_temporary_password, #delete_account, #delete_chat_history, #delete_chat_messages_from_user, #delete_chat_reply_markup, #delete_file, #delete_language_pack, #delete_messages, #delete_passport_element, #delete_profile_photo, #delete_saved_credentials, #delete_saved_order_info, #delete_supergroup, #destroy, #disable_proxy, #discard_call, #disconnect_all_websites, #disconnect_website, #download_file, #edit_custom_language_pack_info, #edit_inline_message_caption, #edit_inline_message_live_location, #edit_inline_message_media, #edit_inline_message_reply_markup, #edit_inline_message_text, #edit_message_caption, #edit_message_live_location, #edit_message_media, #edit_message_reply_markup, #edit_message_scheduling_state, #edit_message_text, #edit_proxy, #enable_proxy, #finish_file_generation, #forward_messages, #generate_chat_invite_link, #get_account_ttl, #get_active_live_location_messages, #get_active_sessions, #get_all_passport_elements, #get_application_config, #get_archived_sticker_sets, #get_attached_sticker_sets, #get_authorization_state, #get_auto_download_settings_presets, #get_background_url, #get_backgrounds, #get_basic_group, #get_basic_group_full_info, #get_blocked_users, #get_callback_query_answer, #get_chat, #get_chat_administrators, #get_chat_event_log, #get_chat_history, #get_chat_member, #get_chat_message_by_date, #get_chat_message_count, #get_chat_notification_settings_exceptions, #get_chat_pinned_message, #get_chat_scheduled_messages, #get_chat_statistics_url, #get_chats, #get_connected_websites, #get_contacts, #get_country_code, #get_created_public_chats, #get_current_state, #get_database_statistics, #get_deep_link_info, #get_emoji_suggestions_url, #get_favorite_stickers, #get_file, #get_file_downloaded_prefix_size, #get_file_extension, #get_file_mime_type, #get_game_high_scores, #get_groups_in_common, #get_imported_contact_count, #get_inactive_supergroup_chats, #get_inline_game_high_scores, #get_inline_query_results, #get_installed_sticker_sets, #get_invite_text, #get_json_string, #get_json_value, #get_language_pack_info, #get_language_pack_string, #get_language_pack_strings, #get_localization_target_info, #get_log_stream, #get_log_tag_verbosity_level, #get_log_tags, #get_log_verbosity_level, #get_login_url, #get_login_url_info, #get_map_thumbnail_file, #get_me, #get_message, #get_message_link, #get_message_link_info, #get_message_locally, #get_messages, #get_network_statistics, #get_option, #get_passport_authorization_form, #get_passport_authorization_form_available_elements, #get_passport_element, #get_password_state, #get_payment_form, #get_payment_receipt, #get_preferred_country_language, #get_proxies, #get_proxy_link, #get_public_message_link, #get_push_receiver_id, #get_recent_inline_bots, #get_recent_stickers, #get_recently_visited_t_me_urls, #get_recovery_email_address, #get_remote_file, #get_replied_message, #get_saved_animations, #get_saved_order_info, #get_scope_notification_settings, #get_secret_chat, #get_sticker_emojis, #get_sticker_set, #get_stickers, #get_storage_statistics, #get_storage_statistics_fast, #get_suitable_discussion_chats, #get_supergroup, #get_supergroup_full_info, #get_supergroup_members, #get_support_user, #get_temporary_password_state, #get_text_entities, #get_ton_wallet_password_salt, #get_top_chats, #get_trending_sticker_sets, #get_user, #get_user_full_info, #get_user_privacy_setting_rules, #get_user_profile_photos, #get_web_page_instant_view, #get_web_page_preview, #import_contacts, #join_chat, #join_chat_by_invite_link, #leave_chat, #log_out, #open_chat, #open_message_content, #optimize_storage, #parse_text_entities, #pin_chat_message, #ping_proxy, #process_push_notification, #read_all_chat_mentions, #read_file_part, #recover_authentication_password, #recover_password, #register_device, #register_user, #remove_background, #remove_chat_action_bar, #remove_contacts, #remove_favorite_sticker, #remove_notification, #remove_notification_group, #remove_proxy, #remove_recent_hashtag, #remove_recent_sticker, #remove_recently_found_chat, #remove_saved_animation, #remove_sticker_from_set, #remove_top_chat, #reorder_installed_sticker_sets, #report_chat, #report_supergroup_spam, #request_authentication_password_recovery, #request_password_recovery, #request_qr_code_authentication, #resend_authentication_code, #resend_change_phone_number_code, #resend_email_address_verification_code, #resend_messages, #resend_phone_number_confirmation_code, #resend_phone_number_verification_code, #resend_recovery_email_address_code, #reset_all_notification_settings, #reset_backgrounds, #reset_network_statistics, #save_application_log_event, #search_background, #search_call_messages, #search_chat_members, #search_chat_messages, #search_chat_recent_location_messages, #search_chats, #search_chats_nearby, #search_chats_on_server, #search_contacts, #search_emojis, #search_hashtags, #search_installed_sticker_sets, #search_messages, #search_public_chat, #search_public_chats, #search_secret_messages, #search_sticker_set, #search_sticker_sets, #search_stickers, #send_bot_start_message, #send_call_debug_information, #send_call_rating, #send_chat_action, #send_chat_screenshot_taken_notification, #send_chat_set_ttl_message, #send_custom_request, #send_email_address_verification_code, #send_inline_query_result_message, #send_message, #send_message_album, #send_passport_authorization_form, #send_payment_form, #send_phone_number_confirmation_code, #send_phone_number_verification_code, #send_ton_lite_server_request, #set_account_ttl, #set_alarm, #set_authentication_phone_number, #set_auto_download_settings, #set_background, #set_bio, #set_bot_updates_status, #set_chat_chat_list, #set_chat_client_data, #set_chat_description, #set_chat_discussion_group, #set_chat_draft_message, #set_chat_location, #set_chat_member_status, #set_chat_notification_settings, #set_chat_permissions, #set_chat_photo, #set_chat_slow_mode_delay, #set_chat_title, #set_custom_language_pack, #set_custom_language_pack_string, #set_database_encryption_key, #set_file_generation_progress, #set_game_score, #set_inline_game_score, #set_log_stream, #set_log_tag_verbosity_level, #set_log_verbosity_level, #set_name, #set_network_type, #set_option, #set_passport_element, #set_passport_element_errors, #set_password, #set_pinned_chats, #set_poll_answer, #set_profile_photo, #set_recovery_email_address, #set_scope_notification_settings, #set_sticker_position_in_set, #set_supergroup_sticker_set, #set_supergroup_username, #set_tdlib_parameters, #set_user_privacy_setting_rules, #set_username, #share_phone_number, #stop_poll, #synchronize_language_pack, #terminate_all_other_sessions, #terminate_session, #toggle_chat_default_disable_notification, #toggle_chat_is_marked_as_unread, #toggle_chat_is_pinned, #toggle_supergroup_is_all_history_available, #toggle_supergroup_sign_messages, #transfer_chat_ownership, #unblock_user, #unpin_chat_message, #upgrade_basic_group_chat_to_supergroup_chat, #upload_file, #upload_sticker_file, #validate_order_info, #view_messages, #view_trending_sticker_sets, #write_generated_file_part

Constructor Details

#initialize(td_client = TD::Api.client_create, update_manager = TD::UpdateManager.new(td_client), timeout: TIMEOUT, **extra_config) ⇒ Client

Returns a new instance of Client.

Parameters:

  • td_client (FFI::Pointer) (defaults to: TD::Api.client_create)
  • update_manager (TD::UpdateManager) (defaults to: TD::UpdateManager.new(td_client))
  • timeout (Numeric) (defaults to: TIMEOUT)
  • extra_config (Hash)

    optional configuration hash that will be merged into tdlib client configuration



18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/tdlib/client.rb', line 18

def initialize(td_client = TD::Api.client_create,
               update_manager = TD::UpdateManager.new(td_client),
               timeout: TIMEOUT,
               **extra_config)
  @td_client = td_client
  @ready = false
  @alive = true
  @update_manager = update_manager
  @timeout = timeout
  @config = TD.config.client.to_h.merge(extra_config)
  @ready_condition_mutex = Mutex.new
  @ready_condition = ConditionVariable.new
end

Class Method Details

.ready(*args) ⇒ Object



10
11
12
# File 'lib/tdlib/client.rb', line 10

def self.ready(*args)
  new(*args).connect
end

Instance Method Details

#alive?Boolean

Returns:

  • (Boolean)


155
156
157
# File 'lib/tdlib/client.rb', line 155

def alive?
  @alive
end

#broadcast(query) ⇒ Concurrent::Promises::Future

Sends asynchronous request to the TDLib client and returns Promise object

Examples:

client.broadcast(some_query).then { |result| puts result }.rescue { |error| puts [error.code, error.message] }

Parameters:

  • query (Hash)

Returns:

  • (Concurrent::Promises::Future)

See Also:



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/tdlib/client.rb', line 64

def broadcast(query)
  return dead_client_promise if dead?

  Promises.future do
    condition = ConditionVariable.new
    extra = SecureRandom.uuid
    result = nil
    mutex = Mutex.new

    @update_manager << TD::UpdateHandler.new(TD::Types::Base, extra, disposable: true) do |update|
      mutex.synchronize do
        result = update
        condition.signal
      end
    end

    query['@extra'] = extra

    mutex.synchronize do
      send_to_td_client(query)
      condition.wait(mutex, @timeout)
      error = nil
      error = result if result.is_a?(TD::Types::Error)
      error = timeout_error if result.nil?
      raise TD::Error.new(error) if error
      result
    end
  end
end

#connectConcurrent::Promises::Future

Adds initial authorization state handler and runs update manager Returns future that will be fulfilled when client is ready

Returns:

  • (Concurrent::Promises::Future)


35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/tdlib/client.rb', line 35

def connect
  on TD::Types::Update::AuthorizationState do |update|
    case update.authorization_state
    when TD::Types::AuthorizationState::WaitTdlibParameters
      set_tdlib_parameters(TD::Types::TdlibParameters.new(**@config))
    when TD::Types::AuthorizationState::WaitEncryptionKey
      check_database_encryption_key(TD.config.encryption_key).then do
        @ready_condition_mutex.synchronize do
          @ready = true
          @ready_condition.broadcast
        end
      end
    else
      # do nothing
    end
  end

  @update_manager.run(callback: method(:handle_update))
  ready
end

#dead?Boolean

Returns:

  • (Boolean)


159
160
161
# File 'lib/tdlib/client.rb', line 159

def dead?
  !alive?
end

#disposeObject

Stops update manager and destroys TDLib client



150
151
152
153
# File 'lib/tdlib/client.rb', line 150

def dispose
  return if dead?
  close.then { get_authorization_state }
end

#execute(query) ⇒ Object

Synchronously executes TDLib request Only a few requests can be executed synchronously

Parameters:

  • query (Hash)


106
107
108
109
# File 'lib/tdlib/client.rb', line 106

def execute(query)
  return dead_client_error if dead?
  TD::Api.client_execute(@td_client, query)
end

#fetch(query) ⇒ Hash Also known as: broadcast_and_receive

Sends asynchronous request to the TDLib client and returns received update synchronously

Parameters:

  • query (Hash)

Returns:

  • (Hash)


97
98
99
# File 'lib/tdlib/client.rb', line 97

def fetch(query)
  broadcast(query).value!
end

#on(update_type) {|update| ... } ⇒ Object

Binds passed block as a handler for updates with type of update_type

Parameters:

  • update_type (String, Class)

Yields:

  • (update)

    yields update to the block as soon as it's received



114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/tdlib/client.rb', line 114

def on(update_type, &action)
  if update_type.is_a?(String)
    if (type_const = TD::Types::LOOKUP_TABLE[update_type])
      update_type = TD::Types.const_get("TD::Types::#{type_const}")
    else
      raise ArgumentError.new("Can't find class for #{update_type}")
    end
  end

  unless update_type < TD::Types::Base
    raise ArgumentError.new("Wrong type specified (#{update_type}). Should be of kind TD::Types::Base")
  end

  @update_manager << TD::UpdateHandler.new(update_type, &action)
end

#on_ready(&action) ⇒ Object

Deprecated.


145
146
147
# File 'lib/tdlib/client.rb', line 145

def on_ready(&action)
  ready.then(&action).value!
end

#readyConcurrent::Promises::Future

returns future that will be fulfilled when client is ready

Returns:

  • (Concurrent::Promises::Future)


132
133
134
135
136
137
138
139
140
141
142
# File 'lib/tdlib/client.rb', line 132

def ready
  return dead_client_promise if dead?
  return Promises.fulfilled_future(self) if ready?

  Promises.future do
    @ready_condition_mutex.synchronize do
      next self if @ready || (@ready_condition.wait(@ready_condition_mutex, @timeout) && @ready)
      raise TD::Error.new(timeout_error)
    end
  end
end

#ready?Boolean

Returns:

  • (Boolean)


163
164
165
# File 'lib/tdlib/client.rb', line 163

def ready?
  @ready
end