telethon 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +96 -0
- data/README.md +103 -8
- data/lib/telethon/cli/commands.rb +25 -20
- data/lib/telethon/client/auth.rb +22 -1
- data/lib/telethon/client/chats.rb +577 -0
- data/lib/telethon/client/dialogs.rb +211 -0
- data/lib/telethon/client/downloads.rb +659 -0
- data/lib/telethon/client/entities.rb +50 -2
- data/lib/telethon/client/files.rb +341 -192
- data/lib/telethon/client/messages.rb +264 -40
- data/lib/telethon/client/updates.rb +407 -0
- data/lib/telethon/client.rb +119 -31
- data/lib/telethon/crypto/rsa.rb +81 -5
- data/lib/telethon/custom/admin_log_event.rb +133 -0
- data/lib/telethon/custom/conversation.rb +358 -0
- data/lib/telethon/custom/dialog.rb +144 -0
- data/lib/telethon/custom/file.rb +130 -0
- data/lib/telethon/custom/forward.rb +63 -0
- data/lib/telethon/custom/getters.rb +152 -0
- data/lib/telethon/custom/participant_permissions.rb +100 -0
- data/lib/telethon/errors.rb +12 -0
- data/lib/telethon/events/album.rb +108 -0
- data/lib/telethon/events/chat_action.rb +212 -0
- data/lib/telethon/events/common.rb +173 -0
- data/lib/telethon/events/message_deleted.rb +119 -0
- data/lib/telethon/events/new_message.rb +176 -0
- data/lib/telethon/events/raw.rb +35 -0
- data/lib/telethon/events/user_update.rb +129 -0
- data/lib/telethon/extensions/html.rb +373 -0
- data/lib/telethon/extensions/markdown.rb +116 -0
- data/lib/telethon/extensions/text.rb +171 -0
- data/lib/telethon/message.rb +423 -0
- data/lib/telethon/mime.rb +1930 -0
- data/lib/telethon/mime_guess.rb +54 -0
- data/lib/telethon/network/authenticator.rb +5 -4
- data/lib/telethon/network/sender.rb +7 -0
- data/lib/telethon/private_files.rb +25 -0
- data/lib/telethon/session.rb +18 -0
- data/lib/telethon/tl/object.rb +4 -0
- data/lib/telethon/updates/message_box.rb +481 -0
- data/lib/telethon/version.rb +1 -1
- data/lib/telethon.rb +25 -0
- metadata +26 -1
|
@@ -0,0 +1,407 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Telethon
|
|
4
|
+
class Client
|
|
5
|
+
# The Updates constructors, the only answers the socket or a request gives that carry updates.
|
|
6
|
+
UPDATES_TYPES = %w[updatesTooLong updateShortMessage updateShortChatMessage updateShort updatesCombined updates
|
|
7
|
+
updateShortSentMessage].freeze
|
|
8
|
+
# Requests answer these with a pts but no update: Telethon passes them on as an updateDeleteMessages
|
|
9
|
+
# with no ids, the least intrusive update with a pts, so a deletion does not look like a gap.
|
|
10
|
+
AFFECTED_TYPES = %w[messages.affectedHistory messages.affectedMessages messages.affectedFoundMessages].freeze
|
|
11
|
+
KEEPALIVE = 60
|
|
12
|
+
POLL_SLICE = 0.5
|
|
13
|
+
|
|
14
|
+
# Registers a handler for an event builder (Events::Raw when none), with the block as the handler:
|
|
15
|
+
#
|
|
16
|
+
# client.on(Telethon::Events::NewMessage.new(incoming: true)) { |event| event.reply("got it") }
|
|
17
|
+
#
|
|
18
|
+
# Answers the handler, to remove it later.
|
|
19
|
+
def on(builder = nil, &handler)
|
|
20
|
+
add_event_handler(handler, builder)
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
def add_event_handler(handler, builder = nil)
|
|
24
|
+
@event_builders << [builder || Events::Raw.new, handler]
|
|
25
|
+
handler
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
# Removes a handler: from every builder, or only from the builders of kind (e.g. "NewMessage", or
|
|
29
|
+
# a builder whose kind it takes). Answers how many were removed.
|
|
30
|
+
def remove_event_handler(handler, kind = nil)
|
|
31
|
+
kind = kind.kind if kind.is_a?(Events::Builder)
|
|
32
|
+
before = @event_builders.size
|
|
33
|
+
@event_builders = @event_builders.reject { |pair| pair[1] == handler && (kind.nil? || pair[0].kind == kind) }
|
|
34
|
+
before - @event_builders.size
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
# [handler, builder] pairs, in the order they run.
|
|
38
|
+
def list_event_handlers
|
|
39
|
+
@event_builders.map { |pair| [pair[1], pair[0]] }
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
# Fetches what was missed: while offline (with catch_up: true, the state saved last time) or now.
|
|
43
|
+
def catch_up
|
|
44
|
+
start_updates
|
|
45
|
+
@update_queue << [TL.make("updatesTooLong"), false]
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
# Stops or restarts updates. While stopped, the update state is not kept.
|
|
49
|
+
def set_receive_updates(receive)
|
|
50
|
+
@no_updates = !receive
|
|
51
|
+
call(TL.make("updates.getState")) if receive
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
# Runs the update loop until disconnect is called (from a handler, say) or Ctrl-C.
|
|
55
|
+
def run_until_disconnected
|
|
56
|
+
start_updates
|
|
57
|
+
call(TL.make("updates.getState")) # tells Telegram this connection wants updates
|
|
58
|
+
step_updates while connected?
|
|
59
|
+
rescue Interrupt
|
|
60
|
+
nil
|
|
61
|
+
ensure
|
|
62
|
+
disconnect
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
# One turn of Telethon's _update_loop: hand one update to the handlers, or fetch a pending
|
|
66
|
+
# difference, or wait up to the nearest deadline for updates and apply them. run_until_disconnected
|
|
67
|
+
# calls it over and over; a program with a loop of its own can call it instead, waiting at most
|
|
68
|
+
# max_wait seconds for the socket.
|
|
69
|
+
def step_updates(max_wait = nil)
|
|
70
|
+
start_updates
|
|
71
|
+
unless @dispatch_queue.empty?
|
|
72
|
+
item = @dispatch_queue.shift
|
|
73
|
+
dispatch_update(item[0], item[1])
|
|
74
|
+
return
|
|
75
|
+
end
|
|
76
|
+
return if fetch_difference
|
|
77
|
+
return if fetch_channel_difference
|
|
78
|
+
|
|
79
|
+
deadline = @message_box.check_deadlines
|
|
80
|
+
album = deliver_albums
|
|
81
|
+
deadline = album if album && album < deadline
|
|
82
|
+
delay = deadline - @clock.now
|
|
83
|
+
delay = max_wait if max_wait && max_wait < delay
|
|
84
|
+
return if delay <= 0
|
|
85
|
+
|
|
86
|
+
item = next_updates(delay)
|
|
87
|
+
return unless item
|
|
88
|
+
|
|
89
|
+
processed = []
|
|
90
|
+
begin
|
|
91
|
+
users, chats = @message_box.process_updates(item[0], item[1], processed)
|
|
92
|
+
rescue Updates::GapError
|
|
93
|
+
return # get_difference or get_channel_difference now has a request to make
|
|
94
|
+
end
|
|
95
|
+
queue_dispatch(processed, users, chats)
|
|
96
|
+
end
|
|
97
|
+
|
|
98
|
+
# The message box: the update state, for inspecting it.
|
|
99
|
+
attr_reader :message_box
|
|
100
|
+
|
|
101
|
+
private
|
|
102
|
+
|
|
103
|
+
def setup_updates(catch_up)
|
|
104
|
+
@catch_up = catch_up
|
|
105
|
+
@clock = Updates::Clock.new
|
|
106
|
+
@message_box = Updates::MessageBox.new(@clock)
|
|
107
|
+
@event_builders = []
|
|
108
|
+
@update_queue = []
|
|
109
|
+
@dispatch_queue = []
|
|
110
|
+
@albums = {}
|
|
111
|
+
@conversation_builders = nil
|
|
112
|
+
@updates_started = false
|
|
113
|
+
@no_updates = false
|
|
114
|
+
@last_keepalive = nil
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
# Telethon's connect and _on_login for updates: the saved state with catch_up, else the account's
|
|
118
|
+
# state now (updates.getState, then the difference to it, since getState may give an old qts).
|
|
119
|
+
def start_updates
|
|
120
|
+
return if @updates_started
|
|
121
|
+
|
|
122
|
+
@updates_started = true
|
|
123
|
+
connect
|
|
124
|
+
get_me if @session.user_id.nil? # events tell incoming from outgoing by it
|
|
125
|
+
@last_keepalive = @clock.now
|
|
126
|
+
saved = @session.update_state
|
|
127
|
+
if @catch_up && saved
|
|
128
|
+
channels = {}
|
|
129
|
+
@session.channel_pts.each do |id, pts|
|
|
130
|
+
channels[id] = pts if @session.entity(-(CHANNEL_BASE + id))
|
|
131
|
+
end
|
|
132
|
+
@message_box.load(saved["pts"], saved["qts"], saved["date"], saved["seq"], channels)
|
|
133
|
+
end
|
|
134
|
+
if @message_box.empty?
|
|
135
|
+
state = call(TL.make("updates.getState"))
|
|
136
|
+
difference = call(TL.make("updates.getDifference", "pts" => state["pts"], "date" => state["date"],
|
|
137
|
+
"qts" => state["qts"]))
|
|
138
|
+
case difference.name
|
|
139
|
+
when "updates.difference" then state = difference["state"]
|
|
140
|
+
when "updates.differenceSlice" then state = difference["intermediate_state"]
|
|
141
|
+
when "updates.differenceTooLong" then state["pts"] = difference["pts"]
|
|
142
|
+
end
|
|
143
|
+
@message_box.load(state["pts"], state["qts"], state["date"], state["seq"], {})
|
|
144
|
+
end
|
|
145
|
+
@update_queue << [TL.make("updatesTooLong"), false] if @catch_up
|
|
146
|
+
end
|
|
147
|
+
|
|
148
|
+
# After every answer: what the socket brought meanwhile, then the answer's own updates, which
|
|
149
|
+
# update the state but are not dispatched (Telethon v1 never dispatched a client's own updates).
|
|
150
|
+
def take_updates(request, result)
|
|
151
|
+
return unless @updates_started && !@no_updates
|
|
152
|
+
|
|
153
|
+
@sender.take_updates.each { |u| @update_queue << [u, false] if u.is_a?(TL::Object) && UPDATES_TYPES.include?(u.name) }
|
|
154
|
+
store_own_updates(request, result)
|
|
155
|
+
end
|
|
156
|
+
|
|
157
|
+
def store_own_updates(request, result)
|
|
158
|
+
return unless result.is_a?(TL::Object)
|
|
159
|
+
|
|
160
|
+
if UPDATES_TYPES.include?(result.name) && !result.is?("updatesTooLong")
|
|
161
|
+
@update_queue << [result, true]
|
|
162
|
+
elsif AFFECTED_TYPES.include?(result.name)
|
|
163
|
+
# Telethon makes this an account-wide update even for channels.deleteMessages, whose pts is the
|
|
164
|
+
# channel's; this gives a channel's to the channel.
|
|
165
|
+
channel = request["channel"]
|
|
166
|
+
update = if channel.is_a?(TL::Object) && channel.is?("inputChannel")
|
|
167
|
+
TL.make("updateDeleteChannelMessages", "channel_id" => channel["channel_id"], "messages" => [],
|
|
168
|
+
"pts" => result["pts"], "pts_count" => result["pts_count"])
|
|
169
|
+
else
|
|
170
|
+
TL.make("updateDeleteMessages", "messages" => [], "pts" => result["pts"],
|
|
171
|
+
"pts_count" => result["pts_count"])
|
|
172
|
+
end
|
|
173
|
+
@update_queue << [TL.make("updateShort", "update" => update, "date" => 0), true]
|
|
174
|
+
elsif result.is?("messages.invitedUsers")
|
|
175
|
+
@update_queue << [result["updates"], true]
|
|
176
|
+
end
|
|
177
|
+
end
|
|
178
|
+
|
|
179
|
+
# The next Updates value: queued, or read from the socket for up to delay seconds. Pings and saves
|
|
180
|
+
# the state once a minute, as Telethon's keepalive loop does.
|
|
181
|
+
def next_updates(delay)
|
|
182
|
+
return @update_queue.shift unless @update_queue.empty?
|
|
183
|
+
|
|
184
|
+
if @clock.now - @last_keepalive >= KEEPALIVE
|
|
185
|
+
keepalive
|
|
186
|
+
return @update_queue.shift unless @update_queue.empty?
|
|
187
|
+
end
|
|
188
|
+
wait = [delay, KEEPALIVE - (@clock.now - @last_keepalive)].min
|
|
189
|
+
wait = 0.0 if wait.negative?
|
|
190
|
+
begin
|
|
191
|
+
# In slices, letting go of the connection between them for a call from another thread.
|
|
192
|
+
loop do
|
|
193
|
+
slice = wait < POLL_SLICE ? wait : POLL_SLICE
|
|
194
|
+
got = locked { @sender.poll(slice) }
|
|
195
|
+
got.each { |u| @update_queue << [u, false] if u.is_a?(TL::Object) && UPDATES_TYPES.include?(u.name) }
|
|
196
|
+
wait -= slice
|
|
197
|
+
break if !@update_queue.empty? || wait <= 0
|
|
198
|
+
end
|
|
199
|
+
rescue TransportError, IOError, SystemCallError => e
|
|
200
|
+
@on_updates_error&.call(e)
|
|
201
|
+
disconnect
|
|
202
|
+
raise
|
|
203
|
+
end
|
|
204
|
+
@update_queue.shift
|
|
205
|
+
end
|
|
206
|
+
|
|
207
|
+
def keepalive
|
|
208
|
+
@last_keepalive = @clock.now
|
|
209
|
+
call(TL.make("ping", "ping_id" => random_long))
|
|
210
|
+
save_update_state
|
|
211
|
+
@session.save
|
|
212
|
+
end
|
|
213
|
+
|
|
214
|
+
def save_update_state
|
|
215
|
+
return unless @updates_started
|
|
216
|
+
|
|
217
|
+
account, channels = @message_box.session_state
|
|
218
|
+
@session.update_state = account
|
|
219
|
+
@session.channel_pts = channels
|
|
220
|
+
end
|
|
221
|
+
|
|
222
|
+
# The account's difference, if the message box wants it. Answers whether it was fetched (or tried).
|
|
223
|
+
def fetch_difference
|
|
224
|
+
request = @message_box.get_difference
|
|
225
|
+
return false unless request
|
|
226
|
+
|
|
227
|
+
begin
|
|
228
|
+
diff = call(request)
|
|
229
|
+
rescue RPCError => e
|
|
230
|
+
@message_box.end_difference
|
|
231
|
+
if e.code == 401
|
|
232
|
+
disconnect
|
|
233
|
+
raise
|
|
234
|
+
end
|
|
235
|
+
return true # Telegram is having issues: try again on the next gap or deadline
|
|
236
|
+
rescue TransportError, IOError, SystemCallError
|
|
237
|
+
sleep(5)
|
|
238
|
+
return true
|
|
239
|
+
end
|
|
240
|
+
queue_dispatch(*@message_box.apply_difference(diff))
|
|
241
|
+
true
|
|
242
|
+
end
|
|
243
|
+
|
|
244
|
+
def fetch_channel_difference
|
|
245
|
+
channel_id = @message_box.channel_needing_difference
|
|
246
|
+
return false unless channel_id
|
|
247
|
+
|
|
248
|
+
cached = @session.entity(-(CHANNEL_BASE + channel_id))
|
|
249
|
+
unless cached
|
|
250
|
+
@message_box.forget_channel(channel_id)
|
|
251
|
+
return true
|
|
252
|
+
end
|
|
253
|
+
request = @message_box.get_channel_difference(channel_id, cached[0], false)
|
|
254
|
+
begin
|
|
255
|
+
diff = call(request)
|
|
256
|
+
rescue RPCError => e
|
|
257
|
+
if e.code == 401
|
|
258
|
+
@message_box.end_channel_difference(channel_id, :temporary)
|
|
259
|
+
disconnect
|
|
260
|
+
raise
|
|
261
|
+
end
|
|
262
|
+
# Banned since: stop following the channel. Anything else (server trouble, an outdated pts):
|
|
263
|
+
# end for now, without moving the pts, and retry on the next gap or deadline.
|
|
264
|
+
banned = %w[CHANNEL_PRIVATE CHANNEL_INVALID].include?(e.name)
|
|
265
|
+
@message_box.end_channel_difference(channel_id, banned ? :banned : :temporary)
|
|
266
|
+
return true
|
|
267
|
+
rescue TransportError, IOError, SystemCallError
|
|
268
|
+
sleep(5)
|
|
269
|
+
return true
|
|
270
|
+
end
|
|
271
|
+
queue_dispatch(*@message_box.apply_channel_difference(channel_id, diff))
|
|
272
|
+
true
|
|
273
|
+
end
|
|
274
|
+
|
|
275
|
+
# Telethon's _preprocess_updates: remembers the users and chats, and gives every update them.
|
|
276
|
+
def queue_dispatch(updates, users, chats)
|
|
277
|
+
entities = {}
|
|
278
|
+
users.each do |user|
|
|
279
|
+
remember(user)
|
|
280
|
+
entities[Client.peer_id(user)] = user
|
|
281
|
+
end
|
|
282
|
+
chats.each do |chat|
|
|
283
|
+
remember(chat)
|
|
284
|
+
entities[Client.peer_id(chat)] = chat
|
|
285
|
+
end
|
|
286
|
+
updates.each { |u| @dispatch_queue << [u, entities] }
|
|
287
|
+
end
|
|
288
|
+
|
|
289
|
+
# Runs the handlers whose builders take the update. Each kind of event is built once per update and
|
|
290
|
+
# shared by its handlers. A handler's error is reported and the next handler still runs;
|
|
291
|
+
# Events::StopPropagation stops the rest.
|
|
292
|
+
def dispatch_update(update, entities)
|
|
293
|
+
built = {}
|
|
294
|
+
feed_conversations(built, update, entities) unless @conversations.empty?
|
|
295
|
+
@event_builders.each do |pair|
|
|
296
|
+
builder = pair[0]
|
|
297
|
+
kind = builder.kind
|
|
298
|
+
built[kind] = build_event(builder, update, entities) unless built.key?(kind)
|
|
299
|
+
event = built[kind]
|
|
300
|
+
next unless event
|
|
301
|
+
|
|
302
|
+
builder.resolve(self) unless builder.resolved?
|
|
303
|
+
next unless builder.filter(event)
|
|
304
|
+
break unless run_handler(pair[1], event)
|
|
305
|
+
end
|
|
306
|
+
end
|
|
307
|
+
|
|
308
|
+
# Telethon's _dispatch_update for conversations: each open one sees the new messages, edits and
|
|
309
|
+
# reads, and the events its wait_event builders take.
|
|
310
|
+
def feed_conversations(built, update, entities)
|
|
311
|
+
@conversation_builders ||= [Events::NewMessage.new, Events::MessageEdited.new, Events::MessageRead.new]
|
|
312
|
+
@conversation_builders.each do |builder|
|
|
313
|
+
built[builder.kind] = build_event(builder, update, entities) unless built.key?(builder.kind)
|
|
314
|
+
end
|
|
315
|
+
@conversations.values.flatten.each do |conv|
|
|
316
|
+
new_message = built["NewMessage"]
|
|
317
|
+
conv.on_new_message(new_message) if new_message
|
|
318
|
+
edited = built["MessageEdited"]
|
|
319
|
+
conv.on_edit(edited) if edited
|
|
320
|
+
read = built["MessageRead"]
|
|
321
|
+
conv.on_read(read) if read
|
|
322
|
+
conv.custom_builders.each do |builder|
|
|
323
|
+
built[builder.kind] = build_event(builder, update, entities) unless built.key?(builder.kind)
|
|
324
|
+
end
|
|
325
|
+
conv.check_custom(built)
|
|
326
|
+
end
|
|
327
|
+
end
|
|
328
|
+
|
|
329
|
+
def build_event(builder, update, entities)
|
|
330
|
+
event = builder.build(update, @session.user_id)
|
|
331
|
+
return event unless event.is_a?(Events::Common)
|
|
332
|
+
|
|
333
|
+
event.attach(self, update, entities)
|
|
334
|
+
collect_album(event) if event.is_a?(Events::Album::Event) && event.size == 1
|
|
335
|
+
event
|
|
336
|
+
end
|
|
337
|
+
|
|
338
|
+
# Answers false when the handler stopped propagation.
|
|
339
|
+
def run_handler(handler, event)
|
|
340
|
+
handler.call(event)
|
|
341
|
+
true
|
|
342
|
+
rescue Events::StopPropagation
|
|
343
|
+
false
|
|
344
|
+
rescue StandardError => e
|
|
345
|
+
report_handler_error(handler, e)
|
|
346
|
+
true
|
|
347
|
+
end
|
|
348
|
+
|
|
349
|
+
def report_handler_error(_handler, error)
|
|
350
|
+
if @on_handler_error
|
|
351
|
+
@on_handler_error.call(error)
|
|
352
|
+
else
|
|
353
|
+
warn "Unhandled exception in an event handler: #{error.class}: #{error.message}"
|
|
354
|
+
end
|
|
355
|
+
end
|
|
356
|
+
|
|
357
|
+
public
|
|
358
|
+
|
|
359
|
+
# Called with a handler's exception instead of printing it.
|
|
360
|
+
attr_accessor :on_handler_error, :on_updates_error
|
|
361
|
+
attr_reader :clock
|
|
362
|
+
|
|
363
|
+
# The clock the update deadlines run on (tests replace it).
|
|
364
|
+
def clock=(clock)
|
|
365
|
+
@clock = clock
|
|
366
|
+
@message_box.clock = clock
|
|
367
|
+
end
|
|
368
|
+
|
|
369
|
+
private
|
|
370
|
+
|
|
371
|
+
# Telethon's AlbumHack: one album's parts come as separate updates, so they are held until
|
|
372
|
+
# Album::DELAY passes with no new part.
|
|
373
|
+
def collect_album(event)
|
|
374
|
+
held = @albums[event.grouped_id]
|
|
375
|
+
if held
|
|
376
|
+
held[1].extend_with(event)
|
|
377
|
+
held[0] = @clock.now + Events::Album::DELAY
|
|
378
|
+
else
|
|
379
|
+
@albums[event.grouped_id] = [@clock.now + Events::Album::DELAY, event]
|
|
380
|
+
end
|
|
381
|
+
end
|
|
382
|
+
|
|
383
|
+
# Hands the albums whose time came to the Album handlers. Answers the next album deadline, or nil.
|
|
384
|
+
def deliver_albums
|
|
385
|
+
return nil if @albums.empty?
|
|
386
|
+
|
|
387
|
+
now = @clock.now
|
|
388
|
+
due = []
|
|
389
|
+
@albums.each { |id, held| due << id if held[0] <= now }
|
|
390
|
+
due.each { |id| dispatch_album(@albums.delete(id)[1]) }
|
|
391
|
+
nearest = nil
|
|
392
|
+
@albums.each_value { |held| nearest = held[0] if nearest.nil? || held[0] < nearest }
|
|
393
|
+
nearest
|
|
394
|
+
end
|
|
395
|
+
|
|
396
|
+
def dispatch_album(event)
|
|
397
|
+
@event_builders.each do |pair|
|
|
398
|
+
builder = pair[0]
|
|
399
|
+
next unless builder.kind == "Album"
|
|
400
|
+
|
|
401
|
+
builder.resolve(self) unless builder.resolved?
|
|
402
|
+
next unless builder.filter(event)
|
|
403
|
+
break unless run_handler(pair[1], event)
|
|
404
|
+
end
|
|
405
|
+
end
|
|
406
|
+
end
|
|
407
|
+
end
|
data/lib/telethon/client.rb
CHANGED
|
@@ -10,9 +10,15 @@ module Telethon
|
|
|
10
10
|
|
|
11
11
|
attr_reader :session, :api_id, :api_hash
|
|
12
12
|
attr_accessor :flood_sleep_threshold, :on_flood_wait
|
|
13
|
+
# A Proc that answers count random bytes, for tests that need the same ids every run.
|
|
14
|
+
attr_writer :random_source
|
|
13
15
|
|
|
16
|
+
# parse_mode: how send_message and edit_message read text, and how Message#text writes it:
|
|
17
|
+
# "markdown" (Telethon's default), "html", or nil for plain text.
|
|
18
|
+
# catch_up: on the first update loop, fetch what was missed since the state saved last time
|
|
19
|
+
# (Telethon's catch_up), instead of starting from now.
|
|
14
20
|
def initialize(session, api_id:, api_hash:, device_model: nil, system_version: nil, app_version: VERSION,
|
|
15
|
-
lang_code: "en")
|
|
21
|
+
lang_code: "en", catch_up: false, parse_mode: "markdown")
|
|
16
22
|
@session = session
|
|
17
23
|
@api_id = api_id
|
|
18
24
|
@api_hash = api_hash
|
|
@@ -23,8 +29,18 @@ module Telethon
|
|
|
23
29
|
@sender = nil
|
|
24
30
|
@dc_options = nil
|
|
25
31
|
@exported = {}
|
|
32
|
+
@cdn_senders = {}
|
|
33
|
+
@call_lock = Mutex.new
|
|
34
|
+
@megagroup_cache = {}
|
|
35
|
+
@conversations = {}
|
|
36
|
+
@kick_sleep = ->(seconds) { sleep(seconds) }
|
|
37
|
+
@random_source = nil
|
|
26
38
|
@flood_sleep_threshold = FLOOD_SLEEP_THRESHOLD
|
|
27
39
|
@on_flood_wait = nil
|
|
40
|
+
@on_handler_error = nil
|
|
41
|
+
@on_updates_error = nil
|
|
42
|
+
@parse_mode = Client.parse_mode_name(parse_mode)
|
|
43
|
+
setup_updates(catch_up)
|
|
28
44
|
end
|
|
29
45
|
|
|
30
46
|
def connect
|
|
@@ -37,9 +53,14 @@ module Telethon
|
|
|
37
53
|
self
|
|
38
54
|
end
|
|
39
55
|
|
|
40
|
-
# Replaces the connection, for tests that script Telegram's answers
|
|
41
|
-
|
|
42
|
-
|
|
56
|
+
# Replaces the connection, for tests that script Telegram's answers: the home data center's, or
|
|
57
|
+
# with dc_id the one call_on uses for that data center.
|
|
58
|
+
def use_sender(sender, dc_id = nil)
|
|
59
|
+
if dc_id
|
|
60
|
+
@exported[dc_id] = sender
|
|
61
|
+
else
|
|
62
|
+
@sender = sender
|
|
63
|
+
end
|
|
43
64
|
end
|
|
44
65
|
|
|
45
66
|
def connected?
|
|
@@ -47,39 +68,34 @@ module Telethon
|
|
|
47
68
|
end
|
|
48
69
|
|
|
49
70
|
def disconnect
|
|
71
|
+
if @updates_started && @sender
|
|
72
|
+
save_update_state
|
|
73
|
+
@session.save
|
|
74
|
+
end
|
|
50
75
|
@session.save_entities if @session.entities_changed?
|
|
51
76
|
@sender&.transport&.close
|
|
52
77
|
@sender = nil
|
|
53
78
|
@exported.each_value { |sender| sender.transport.close }
|
|
54
79
|
@exported = {}
|
|
80
|
+
@cdn_senders.each_value { |sender| sender.transport.close }
|
|
81
|
+
@cdn_senders = {}
|
|
55
82
|
end
|
|
56
83
|
|
|
57
84
|
# Calls a TL function on the home data center.
|
|
58
85
|
def call(request)
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
begin
|
|
62
|
-
result = @sender.call(request)
|
|
63
|
-
if result.is_a?(Array)
|
|
64
|
-
result.each { |item| remember(item) }
|
|
65
|
-
else
|
|
66
|
-
remember_entities(result)
|
|
67
|
-
end
|
|
68
|
-
result
|
|
69
|
-
rescue RPCError => e
|
|
70
|
-
attempts += 1
|
|
71
|
-
raise if attempts > 5
|
|
86
|
+
locked { call_unlocked(request) }
|
|
87
|
+
end
|
|
72
88
|
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
89
|
+
# One call or read on the connection at a time: a typing action's thread (Client#action) calls
|
|
90
|
+
# while the program does. The lock is the caller's again inside (a call during a call).
|
|
91
|
+
def locked
|
|
92
|
+
return yield if @call_lock.owned?
|
|
93
|
+
|
|
94
|
+
@call_lock.lock
|
|
95
|
+
begin
|
|
96
|
+
yield
|
|
97
|
+
ensure
|
|
98
|
+
@call_lock.unlock
|
|
83
99
|
end
|
|
84
100
|
end
|
|
85
101
|
|
|
@@ -87,14 +103,32 @@ module Telethon
|
|
|
87
103
|
def call_on(dc_id, request)
|
|
88
104
|
return call(request) if dc_id == @session.dc_id
|
|
89
105
|
|
|
90
|
-
|
|
91
|
-
|
|
106
|
+
locked do
|
|
107
|
+
@exported[dc_id] ||= exported_sender(dc_id)
|
|
108
|
+
@exported[dc_id].call(request)
|
|
109
|
+
end
|
|
110
|
+
end
|
|
111
|
+
|
|
112
|
+
# Calls a TL function on a CDN data center, over a connection with its own auth key: CDNs know no
|
|
113
|
+
# accounts, and take only upload.getCdnFile.
|
|
114
|
+
def call_cdn(dc_id, request)
|
|
115
|
+
locked do
|
|
116
|
+
@cdn_senders[dc_id] ||= cdn_sender(dc_id)
|
|
117
|
+
@cdn_senders[dc_id].call(request)
|
|
118
|
+
end
|
|
119
|
+
end
|
|
120
|
+
|
|
121
|
+
# Replaces a CDN data center's connection, for tests that script Telegram's answers.
|
|
122
|
+
def use_cdn_sender(sender, dc_id)
|
|
123
|
+
@cdn_senders[dc_id] = sender
|
|
92
124
|
end
|
|
93
125
|
|
|
94
126
|
# Reads what the server pushes (updates) for up to timeout seconds.
|
|
95
127
|
def poll_updates(timeout)
|
|
96
|
-
|
|
97
|
-
|
|
128
|
+
locked do
|
|
129
|
+
connect unless @sender
|
|
130
|
+
@sender.poll(timeout)
|
|
131
|
+
end
|
|
98
132
|
end
|
|
99
133
|
|
|
100
134
|
def authorized?
|
|
@@ -129,6 +163,35 @@ module Telethon
|
|
|
129
163
|
|
|
130
164
|
private
|
|
131
165
|
|
|
166
|
+
def call_unlocked(request)
|
|
167
|
+
connect unless @sender
|
|
168
|
+
attempts = 0
|
|
169
|
+
begin
|
|
170
|
+
result = @sender.call(request)
|
|
171
|
+
take_updates(request, result)
|
|
172
|
+
if result.is_a?(Array)
|
|
173
|
+
result.each { |item| remember(item) }
|
|
174
|
+
else
|
|
175
|
+
remember_entities(result)
|
|
176
|
+
end
|
|
177
|
+
result
|
|
178
|
+
rescue RPCError => e
|
|
179
|
+
attempts += 1
|
|
180
|
+
raise if attempts > 5
|
|
181
|
+
|
|
182
|
+
if e.migrate? && MIGRATING.include?(e.name)
|
|
183
|
+
switch_dc(e.value)
|
|
184
|
+
retry
|
|
185
|
+
end
|
|
186
|
+
if e.flood_wait? && e.value <= @flood_sleep_threshold
|
|
187
|
+
@on_flood_wait&.call(e.value)
|
|
188
|
+
sleep(e.value + 1)
|
|
189
|
+
retry
|
|
190
|
+
end
|
|
191
|
+
raise
|
|
192
|
+
end
|
|
193
|
+
end
|
|
194
|
+
|
|
132
195
|
def fetch_dc_options
|
|
133
196
|
@dc_options = @sender ? call(TL.make("help.getConfig"))["dc_options"] : []
|
|
134
197
|
rescue RPCError
|
|
@@ -149,6 +212,31 @@ module Telethon
|
|
|
149
212
|
sender
|
|
150
213
|
end
|
|
151
214
|
|
|
215
|
+
# A CDN connection: an auth key made with the CDN's RSA keys (help.getCdnConfig), then
|
|
216
|
+
# initConnection as on any other, and no authorization imported.
|
|
217
|
+
def cdn_sender(dc_id)
|
|
218
|
+
keys = []
|
|
219
|
+
call_unlocked(TL.make("help.getCdnConfig"))["public_keys"].each do |key|
|
|
220
|
+
keys << Crypto::RSA.parse_pem(key["public_key"]) if key["dc_id"] == dc_id
|
|
221
|
+
end
|
|
222
|
+
raise Error, "Telegram gave no RSA key for CDN data center #{dc_id}" if keys.empty?
|
|
223
|
+
|
|
224
|
+
@dc_options = nil
|
|
225
|
+
options = fetch_dc_options_unlocked
|
|
226
|
+
found = options.find { |o| o["id"] == dc_id && o["cdn"] && !o["ipv6"] }
|
|
227
|
+
raise Error, "no address for CDN data center #{dc_id}" unless found
|
|
228
|
+
|
|
229
|
+
transport = Network::Transport.new(found["ip_address"], found["port"]).connect
|
|
230
|
+
key, offset = Network::Authenticator.run(transport, keys)
|
|
231
|
+
sender = Network::Sender.new(transport, Network::State.new(key, offset))
|
|
232
|
+
sender.wrap_first { |query| init_connection(query) }
|
|
233
|
+
sender
|
|
234
|
+
end
|
|
235
|
+
|
|
236
|
+
def fetch_dc_options_unlocked
|
|
237
|
+
@dc_options = call_unlocked(TL.make("help.getConfig"))["dc_options"]
|
|
238
|
+
end
|
|
239
|
+
|
|
152
240
|
def exported_sender(dc_id)
|
|
153
241
|
exported = call(TL.make("auth.exportAuthorization", "dc_id" => dc_id))
|
|
154
242
|
address, port = dc_address(dc_id)
|