Class: GrubY::TDLib::Client

Inherits:
Object
  • Object
show all
Includes:
Decorators
Defined in:
lib/gruubY/tdlib/client.rb

Defined Under Namespace

Classes: Handler

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Decorators

#finalizer, #initializer, #on_message

Constructor Details

#initialize(api_id:, api_hash:, database_directory: "storage/tdlib", files_directory: "storage/tdlib/files", phone_number: nil, bot_token: nil, tdjson_path: nil, database_encryption_key: "", use_test_dc: false, system_language_code: "en", device_model: "GrubY", system_version: RUBY_PLATFORM, application_version: "0.2.0", options: {}, workers: 4, queue_size: 1_000, default_handler_timeout: nil, td_verbosity: 1) ⇒ Client

Returns a new instance of Client.



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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
# File 'lib/gruubY/tdlib/client.rb', line 30

def initialize(
  api_id:,
  api_hash:,
  database_directory: "storage/tdlib",
  files_directory: "storage/tdlib/files",
  phone_number: nil,
  bot_token: nil,
  tdjson_path: nil,
  database_encryption_key: "",
  use_test_dc: false,
  system_language_code: "en",
  device_model: "GrubY",
  system_version: RUBY_PLATFORM,
  application_version: "0.2.0",
  options: {},
  workers: 4,
  queue_size: 1_000,
  default_handler_timeout: nil,
  td_verbosity: 1
)
  @api_id = api_id
  @api_hash = api_hash
  @database_directory = database_directory
  @files_directory = files_directory
  @phone_number = phone_number
  @bot_token = bot_token
  @database_encryption_key = database_encryption_key.to_s
  @use_test_dc = use_test_dc
  @system_language_code = system_language_code
  @device_model = device_model
  @system_version = system_version
  @application_version = application_version
  @td_options = options
  @workers = workers
  @queue_size = queue_size
  @default_handler_timeout = default_handler_timeout
  @logger = Logger.new($stdout)
  @logger.level = Logger::INFO

  @handlers = Hash.new { |h, k| h[k] = [] }
  @next_handler_id = 1
  @pending = {}
  @pending_mutex = Mutex.new
  @sequence = 0
  @running = false
  @authorized = false
  @authorization_state = nil
  @updates_thread = nil
  @workers_threads = []
  @queue = Queue.new
  @group_manager = GroupManager.new(self)
  @local_handlers = {
    "updateAuthorizationState" => method(:process_authorization_update),
    "updateOption" => method(:process_update_option)
  }

  @tdjson = TdJson.new(lib_path: tdjson_path, verbosity: td_verbosity)
  @native_client = @tdjson.create_client_id
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, **kwargs, &block) ⇒ Object



289
290
291
292
293
294
295
# File 'lib/gruubY/tdlib/client.rb', line 289

def method_missing(name, *args, **kwargs, &block)
  return super if block
  return super unless args.empty?

  type = self.class.camelize_td_type(name)
  invoke({ "@type": type }.merge(kwargs))
end

Instance Attribute Details

#api_hashObject (readonly)

Returns the value of attribute api_hash.



27
28
29
# File 'lib/gruubY/tdlib/client.rb', line 27

def api_hash
  @api_hash
end

#api_idObject (readonly)

Returns the value of attribute api_id.



27
28
29
# File 'lib/gruubY/tdlib/client.rb', line 27

def api_id
  @api_id
end

#authorization_stateObject (readonly)

Returns the value of attribute authorization_state.



28
29
30
# File 'lib/gruubY/tdlib/client.rb', line 28

def authorization_state
  @authorization_state
end

#database_directoryObject (readonly)

Returns the value of attribute database_directory.



27
28
29
# File 'lib/gruubY/tdlib/client.rb', line 27

def database_directory
  @database_directory
end

#files_directoryObject (readonly)

Returns the value of attribute files_directory.



27
28
29
# File 'lib/gruubY/tdlib/client.rb', line 27

def files_directory
  @files_directory
end

#group_managerObject (readonly)

Returns the value of attribute group_manager.



27
28
29
# File 'lib/gruubY/tdlib/client.rb', line 27

def group_manager
  @group_manager
end

#td_optionsObject (readonly)

Returns the value of attribute td_options.



28
29
30
# File 'lib/gruubY/tdlib/client.rb', line 28

def td_options
  @td_options
end

Class Method Details

.camelize_td_type(name) ⇒ Object



313
314
315
316
# File 'lib/gruubY/tdlib/client.rb', line 313

def self.camelize_td_type(name)
  parts = name.to_s.split("_")
  parts.first + parts[1..].map(&:capitalize).join
end

.compose(*clients, &block) ⇒ Object



305
306
307
308
309
310
311
# File 'lib/gruubY/tdlib/client.rb', line 305

def self.compose(*clients, &block)
  clients.each(&:start)
  block.call if block
  clients.each(&:idle)
ensure
  clients.each(&:stop)
end

Instance Method Details

#add_handler(update_type = nil, filter: nil, position: nil, inner_object: false, timeout: nil, &block) ⇒ Object

Raises:

  • (ArgumentError)


143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/gruubY/tdlib/client.rb', line 143

def add_handler(
  update_type = nil,
  filter: nil,
  position: nil,
  inner_object: false,
  timeout: nil,
  &block
)
  raise ArgumentError, "handler block is required" unless block

  id = @next_handler_id
  @next_handler_id += 1
  type = update_type.to_s
  handler = Handler.new(
    id: id,
    update_type: type,
    block: block,
    filter: filter,
    position: position,
    inner_object: inner_object,
    timeout: timeout
  )
  @handlers[type] << handler
  sort_handlers(type)
  id
end

#authorized?Boolean

Returns:

  • (Boolean)


224
225
226
# File 'lib/gruubY/tdlib/client.rb', line 224

def authorized?
  @authorized
end

#check_authentication_bot_token(token = @bot_token) ⇒ Object Also known as: sign_in_bot



240
241
242
# File 'lib/gruubY/tdlib/client.rb', line 240

def check_authentication_bot_token(token = @bot_token)
  send_query("@type": "checkAuthenticationBotToken", token: token)
end

#check_authentication_code(code) ⇒ Object Also known as: sign_in



228
229
230
# File 'lib/gruubY/tdlib/client.rb', line 228

def check_authentication_code(code)
  send_query("@type": "checkAuthenticationCode", code: code)
end

#check_authentication_password(password) ⇒ Object Also known as: check_password



234
235
236
# File 'lib/gruubY/tdlib/client.rb', line 234

def check_authentication_password(password)
  send_query("@type": "checkAuthenticationPassword", password: password)
end

#execute(query) ⇒ Object



190
191
192
# File 'lib/gruubY/tdlib/client.rb', line 190

def execute(query)
  @tdjson.execute(@native_client, stringify_keys(query))
end

#get_active_sessionsObject



273
274
275
# File 'lib/gruubY/tdlib/client.rb', line 273

def get_active_sessions
  invoke("@type": "getActiveSessions")
end

#idleObject



135
136
137
138
139
140
141
# File 'lib/gruubY/tdlib/client.rb', line 135

def idle
  @idle = true
  trap_signals
  sleep 0.3 while @idle
ensure
  @idle = false
end

#invoke(query, timeout: 30.0, poll_interval: 0.05) ⇒ Object



194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
# File 'lib/gruubY/tdlib/client.rb', line 194

def invoke(query, timeout: 30.0, poll_interval: 0.05)
  tagged = with_extra(query)
  tag = extra_id(tagged["@extra"])
  @pending_mutex.synchronize { @pending[tag] = nil }
  @tdjson.send(@native_client, tagged)

  deadline = Time.now + timeout
  while Time.now < deadline
    consume_once(poll_interval)
    value = @pending_mutex.synchronize { @pending[tag] }
    return value if value
  end
  raise Timeout::Error, "TDLib response timeout for #{query[:@type] || query['@type']}"
ensure
  @pending_mutex.synchronize { @pending.delete(tag) } if tag
end

#log_outObject



269
270
271
# File 'lib/gruubY/tdlib/client.rb', line 269

def log_out
  send_query("@type": "logOut")
end

#native_client_keyObject



301
302
303
# File 'lib/gruubY/tdlib/client.rb', line 301

def native_client_key
  @native_client.to_i
end

#on(update_type = nil, **options, &block) ⇒ Object



170
171
172
# File 'lib/gruubY/tdlib/client.rb', line 170

def on(update_type = nil, **options, &block)
  add_handler(update_type, **options, &block)
end

#raw(query, timeout: 30.0, poll_interval: 0.05) ⇒ Object



211
212
213
# File 'lib/gruubY/tdlib/client.rb', line 211

def raw(query, timeout: 30.0, poll_interval: 0.05)
  invoke(query, timeout: timeout, poll_interval: poll_interval)
end

#raw!(query, timeout: 30.0, poll_interval: 0.05) ⇒ Object



215
216
217
218
219
220
221
222
# File 'lib/gruubY/tdlib/client.rb', line 215

def raw!(query, timeout: 30.0, poll_interval: 0.05)
  result = raw(query, timeout: timeout, poll_interval: poll_interval)
  if result.is_a?(Hash) && result["@type"] == "error"
    message = result["message"] || "unknown TDLib error"
    raise StandardError, "TDLib raw call failed: #{message}"
  end
  result
end

#recover_password(recovery_code, new_password: nil, new_hint: nil) ⇒ Object



260
261
262
263
264
265
266
267
# File 'lib/gruubY/tdlib/client.rb', line 260

def recover_password(recovery_code, new_password: nil, new_hint: nil)
  send_query(
    "@type": "recoverAuthenticationPassword",
    recovery_code: recovery_code,
    new_password: new_password,
    new_hint: new_hint
  )
end

#remove_handler(handler_id = nil, &block) ⇒ Object



174
175
176
177
178
179
180
181
182
183
184
# File 'lib/gruubY/tdlib/client.rb', line 174

def remove_handler(handler_id = nil, &block)
  removed = false
  @handlers.each_key do |type|
    before = @handlers[type].length
    @handlers[type].delete_if do |handler|
      (handler_id && handler.id == handler_id) || (block && handler.block == block)
    end
    removed ||= before != @handlers[type].length
  end
  removed
end

#resend_phone_number_codeObject



252
253
254
# File 'lib/gruubY/tdlib/client.rb', line 252

def resend_phone_number_code
  send_query("@type": "resendAuthenticationCode")
end

#reset_session(session_hash) ⇒ Object



277
278
279
# File 'lib/gruubY/tdlib/client.rb', line 277

def reset_session(session_hash)
  send_query("@type": "terminateSession", session_id: session_hash)
end

#reset_sessionsObject



281
282
283
# File 'lib/gruubY/tdlib/client.rb', line 281

def reset_sessions
  send_query("@type": "terminateAllOtherSessions")
end

#respond_to_missing?(_name, _include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


297
298
299
# File 'lib/gruubY/tdlib/client.rb', line 297

def respond_to_missing?(_name, _include_private = false)
  true
end

#restartObject



124
125
126
127
# File 'lib/gruubY/tdlib/client.rb', line 124

def restart
  stop
  start
end

#runObject



129
130
131
132
133
# File 'lib/gruubY/tdlib/client.rb', line 129

def run
  start
  idle
  stop
end

#send_phone_number_code(phone_number, settings: nil) ⇒ Object



246
247
248
249
250
# File 'lib/gruubY/tdlib/client.rb', line 246

def send_phone_number_code(phone_number, settings: nil)
  payload = { "@type": "setAuthenticationPhoneNumber", phone_number: phone_number }
  payload[:settings] = settings if settings
  send_query(payload)
end

#send_query(query) ⇒ Object



186
187
188
# File 'lib/gruubY/tdlib/client.rb', line 186

def send_query(query)
  @tdjson.send(@native_client, with_extra(query))
end

#send_recovery_codeObject



256
257
258
# File 'lib/gruubY/tdlib/client.rb', line 256

def send_recovery_code
  send_query("@type": "requestAuthenticationPasswordRecovery")
end

#set_log_verbosity(level) ⇒ Object



285
286
287
# File 'lib/gruubY/tdlib/client.rb', line 285

def set_log_verbosity(level)
  Native.td_set_log_verbosity_level(level.to_i)
end

#startObject Also known as: connect, initialize_client



90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/gruubY/tdlib/client.rb', line 90

def start
  return self if @running

  ensure_native_client!
  ensure_storage!
  verify_arguments!
  @running = true
  set_options
  boot_authorization_state
  start_update_loop
  start_workers
  self
end

#stopObject Also known as: disconnect, terminate



106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'lib/gruubY/tdlib/client.rb', line 106

def stop
  return self unless @running

  @running = false
  @updates_thread&.kill
  @updates_thread = nil
  @workers_threads.each(&:kill)
  @workers_threads.clear
  send_query("@type": "close")
  @tdjson.destroy(@native_client) if @native_client
  @native_client = nil
  self
end