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.
Files changed (44) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +96 -0
  3. data/README.md +103 -8
  4. data/lib/telethon/cli/commands.rb +25 -20
  5. data/lib/telethon/client/auth.rb +22 -1
  6. data/lib/telethon/client/chats.rb +577 -0
  7. data/lib/telethon/client/dialogs.rb +211 -0
  8. data/lib/telethon/client/downloads.rb +659 -0
  9. data/lib/telethon/client/entities.rb +50 -2
  10. data/lib/telethon/client/files.rb +341 -192
  11. data/lib/telethon/client/messages.rb +264 -40
  12. data/lib/telethon/client/updates.rb +407 -0
  13. data/lib/telethon/client.rb +119 -31
  14. data/lib/telethon/crypto/rsa.rb +81 -5
  15. data/lib/telethon/custom/admin_log_event.rb +133 -0
  16. data/lib/telethon/custom/conversation.rb +358 -0
  17. data/lib/telethon/custom/dialog.rb +144 -0
  18. data/lib/telethon/custom/file.rb +130 -0
  19. data/lib/telethon/custom/forward.rb +63 -0
  20. data/lib/telethon/custom/getters.rb +152 -0
  21. data/lib/telethon/custom/participant_permissions.rb +100 -0
  22. data/lib/telethon/errors.rb +12 -0
  23. data/lib/telethon/events/album.rb +108 -0
  24. data/lib/telethon/events/chat_action.rb +212 -0
  25. data/lib/telethon/events/common.rb +173 -0
  26. data/lib/telethon/events/message_deleted.rb +119 -0
  27. data/lib/telethon/events/new_message.rb +176 -0
  28. data/lib/telethon/events/raw.rb +35 -0
  29. data/lib/telethon/events/user_update.rb +129 -0
  30. data/lib/telethon/extensions/html.rb +373 -0
  31. data/lib/telethon/extensions/markdown.rb +116 -0
  32. data/lib/telethon/extensions/text.rb +171 -0
  33. data/lib/telethon/message.rb +423 -0
  34. data/lib/telethon/mime.rb +1930 -0
  35. data/lib/telethon/mime_guess.rb +54 -0
  36. data/lib/telethon/network/authenticator.rb +5 -4
  37. data/lib/telethon/network/sender.rb +7 -0
  38. data/lib/telethon/private_files.rb +25 -0
  39. data/lib/telethon/session.rb +18 -0
  40. data/lib/telethon/tl/object.rb +4 -0
  41. data/lib/telethon/updates/message_box.rb +481 -0
  42. data/lib/telethon/version.rb +1 -1
  43. data/lib/telethon.rb +25 -0
  44. metadata +26 -1
@@ -0,0 +1,659 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Telethon
4
+ class Client
5
+ # Telethon's client/downloads.py.
6
+ MIN_CHUNK_SIZE = 4096
7
+ MAX_CHUNK_SIZE = 512 * 1024
8
+ TIMED_OUT_SLEEP = 1
9
+ # utils.stripped_photo_to_jpg's JPEG header; bytes 164 and 166 take the stripped photo's size.
10
+ STRIPPED_HEADER = [
11
+ "ffd8ffe000104a46494600010100000100010000ffdb004300281c1e231e19282321232d2b28303c64413c37373c7b58" \
12
+ "5d4964918099968f808c8aa0b4e6c3a0aadaad8a8cc8ffcbdaeef5ffffff9bc1fffffffaffe6fdfff8ffdb0043012b2d" \
13
+ "2d3c353c76414176f8a58ca5f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8" \
14
+ "f8f8f8f8f8f8f8f8f8f8f8f8f8f8ffc00011080000000003012200021101031101ffc4001f0000010501010101010100" \
15
+ "000000000000000102030405060708090a0bffc400b5100002010303020403050504040000017d010203000411051221" \
16
+ "31410613516107227114328191a1082342b1c11552d1f02433627282090a161718191a25262728292a3435363738393a" \
17
+ "434445464748494a535455565758595a636465666768696a737475767778797a838485868788898a9293949596979899" \
18
+ "9aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae1e2e3e4e5e6e7e8e9eaf1" \
19
+ "f2f3f4f5f6f7f8f9faffc4001f0100030101010101010101010000000000000102030405060708090a0bffc400b51100" \
20
+ "020102040403040705040400010277000102031104052131061241510761711322328108144291a1b1c109233352f015" \
21
+ "6272d10a162434e125f11718191a262728292a35363738393a434445464748494a535455565758595a63646566676869" \
22
+ "6a737475767778797a82838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4" \
23
+ "c5c6c7c8c9cad2d3d4d5d6d7d8d9dae2e3e4e5e6e7e8e9eaf2f3f4f5f6f7f8f9faffda000c03010002110311003f00"
24
+ ].pack("H*").freeze
25
+ STRIPPED_FOOTER = ["ffd9"].pack("H*").freeze
26
+ # What download_profile_photo takes as an entity (by TL type), and what it looks up first.
27
+ PROFILE_ENTITY_TYPES = %w[User Chat ChatFull UserFull].freeze
28
+ PROFILE_INPUT_TYPES = %w[InputPeer InputUser InputChannel].freeze
29
+
30
+ attr_writer :download_sleep
31
+
32
+ # Telethon's utils.stripped_photo_to_jpg: the JPEG a photoStrippedSize stands for.
33
+ def self.stripped_photo_to_jpg(stripped)
34
+ bytes = stripped.b
35
+ head = bytes.unpack("C3")
36
+ return bytes if bytes.bytesize < 3 || head[0] != 1
37
+
38
+ header = STRIPPED_HEADER.unpack("C*")
39
+ header[164] = head[1]
40
+ header[166] = head[2]
41
+ header.pack("C*") + bytes.byteslice(3, bytes.bytesize - 3) + STRIPPED_FOOTER
42
+ end
43
+
44
+ # utils._photo_size_byte_count.
45
+ def self.photo_size_byte_count(size)
46
+ case size.name
47
+ when "photoSize" then size["size"]
48
+ when "photoStrippedSize"
49
+ bytes = size["bytes"]
50
+ bytes.bytesize < 3 || bytes.getbyte(0) != 1 ? bytes.bytesize : bytes.bytesize + 622
51
+ when "photoCachedSize" then size["bytes"].bytesize
52
+ when "photoSizeEmpty" then 0
53
+ when "photoSizeProgressive" then size["sizes"].max
54
+ end
55
+ end
56
+
57
+ # utils.get_appropriated_part_size, in KB.
58
+ def self.appropriated_part_size(file_size)
59
+ return 128 if file_size <= 104_857_600
60
+ return 256 if file_size <= 786_432_000
61
+
62
+ 512
63
+ end
64
+
65
+ # utils.get_extension of a photo or document (with its dot), "" when there is none.
66
+ def self.media_extension(media)
67
+ media = media["document"] if media.is?("messageMediaDocument")
68
+ return ".jpg" if %w[photo messageMediaPhoto userProfilePhoto chatPhoto].include?(media.name)
69
+ return "" unless %w[document webDocument webDocumentNoProxy].include?(media.name)
70
+ return "" if media["mime_type"] == "application/octet-stream"
71
+
72
+ Mime.guess_extension(media["mime_type"]) || ""
73
+ end
74
+
75
+ # Telethon's _get_kind_and_names: "audio" or "voice" for those, else "document"; and the names the
76
+ # file may be saved under, its own file name first.
77
+ def self.kind_and_names(attributes)
78
+ kind = "document"
79
+ names = []
80
+ attributes.each do |attr|
81
+ if attr.is?("documentAttributeFilename")
82
+ names.unshift(attr["file_name"])
83
+ elsif attr.is?("documentAttributeAudio")
84
+ kind = "audio"
85
+ performer = attr["performer"]
86
+ title = attr["title"]
87
+ if present?(performer) && present?(title)
88
+ names << "#{performer} - #{title}"
89
+ elsif present?(performer)
90
+ names << performer
91
+ elsif present?(title)
92
+ names << title
93
+ elsif attr["voice"]
94
+ kind = "voice"
95
+ end
96
+ end
97
+ end
98
+ [kind, names]
99
+ end
100
+
101
+ def self.present?(text)
102
+ !text.nil? && !text.empty?
103
+ end
104
+
105
+ # Telethon's _get_thumb: the photo size thumb names among thumbs, sorted smallest first (videos
106
+ # after pictures). nil takes the largest, an Integer indexes, a String is a size's type.
107
+ def self.get_thumb(thumbs, thumb)
108
+ return nil if thumbs.nil? || thumbs.empty?
109
+
110
+ order = []
111
+ thumbs.size.times { |i| order << i }
112
+ order = order.sort do |a, b|
113
+ ka = thumb_key(thumbs[a])
114
+ kb = thumb_key(thumbs[b])
115
+ c = ka[0] <=> kb[0]
116
+ c = ka[1] <=> kb[1] if c.zero?
117
+ c = a <=> b if c.zero? # Python's sort is stable
118
+ c
119
+ end
120
+ sorted = []
121
+ order.each { |i| sorted << thumbs[i] unless thumbs[i].is?("photoPathSize") }
122
+ return sorted[-1] if thumb.nil?
123
+ return sorted.fetch(thumb) if thumb.is_a?(Integer)
124
+ return sorted.find { |t| t["type"] == thumb } if thumb.is_a?(String)
125
+ return thumb if %w[photoSize photoCachedSize photoStrippedSize videoSize].include?(thumb.name)
126
+
127
+ nil
128
+ end
129
+
130
+ def self.thumb_key(thumb)
131
+ case thumb.name
132
+ when "photoStrippedSize", "photoCachedSize" then [1, thumb["bytes"].bytesize]
133
+ when "photoSize" then [1, thumb["size"]]
134
+ when "photoSizeProgressive" then [1, thumb["sizes"].max]
135
+ when "videoSize" then [2, thumb["size"]]
136
+ else [0, 0]
137
+ end
138
+ end
139
+
140
+ # utils._get_file_info: [input file location, data center or nil, size or nil] of a location, a
141
+ # message, its media, or a photo or document.
142
+ def self.file_info(file)
143
+ raise ArgumentError, "Cannot cast #{file.class} to any kind of InputFileLocation." unless file.is_a?(TL::Object) || file.is_a?(Message)
144
+
145
+ file = file.raw if file.is_a?(Message)
146
+ return [file, nil, nil] if TL.schema.named(file.name).result == "InputFileLocation"
147
+
148
+ file = file["media"] if file.is?("message")
149
+ if file && file.is?("messageMediaDocument")
150
+ file = file["document"]
151
+ elsif file && file.is?("messageMediaPhoto")
152
+ file = file["photo"]
153
+ end
154
+ if file && file.is?("document")
155
+ location = TL.make("inputDocumentFileLocation", "id" => file["id"], "access_hash" => file["access_hash"],
156
+ "file_reference" => file["file_reference"], "thumb_size" => "")
157
+ return [location, file["dc_id"], file["size"]]
158
+ end
159
+ if file && file.is?("photo")
160
+ last = file["sizes"][-1]
161
+ location = TL.make("inputPhotoFileLocation", "id" => file["id"], "access_hash" => file["access_hash"],
162
+ "file_reference" => file["file_reference"], "thumb_size" => last["type"])
163
+ return [location, file["dc_id"], photo_size_byte_count(last)]
164
+ end
165
+ raise ArgumentError, "Cannot cast #{file ? file.name : 'nil'} to any kind of InputFileLocation."
166
+ end
167
+
168
+ # Python's os.path.basename, os.path.split and os.path.join, which name downloads in Telethon.
169
+ def self.py_basename(path)
170
+ slash = path.rindex("/")
171
+ slash ? path[(slash + 1)..] : path
172
+ end
173
+
174
+ def self.py_split(path)
175
+ slash = path.rindex("/")
176
+ return ["", path] unless slash
177
+
178
+ head = path[0, slash + 1]
179
+ stripped = head.sub(%r{/+\z}, "")
180
+ [stripped.empty? ? head : stripped, path[(slash + 1)..]]
181
+ end
182
+
183
+ def self.py_join(dir, name)
184
+ return name if dir.empty? || name.start_with?("/")
185
+
186
+ dir.end_with?("/") ? dir + name : "#{dir}/#{name}"
187
+ end
188
+
189
+ # Telethon's _get_proper_filename. file is nil (the current directory), a directory, a file path
190
+ # (taken as it is, and overwritten), :bytes or an IO (given back as they are). In a directory the
191
+ # file takes the first possible name, else kind_YYYY-MM-DD_HH-MM-SS of date (a Unix time, in UTC;
192
+ # local now without one); ext when the name has none; " (1)" and on when the name is taken. A name
193
+ # of "." or ".." counts as none, so a download never leaves the directory.
194
+ def self.proper_filename(file, kind, extension, date = nil, names = nil)
195
+ return file unless file.nil? || file.is_a?(String)
196
+
197
+ file = "" if file.nil?
198
+ return file if !file.empty? && File.file?(file)
199
+
200
+ if file.empty? || File.directory?(file)
201
+ name = nil
202
+ if names
203
+ first = names.find { |n| present?(n) }
204
+ name = first && py_basename(first)
205
+ name = nil if name == "." || name == ".."
206
+ end
207
+ if name.nil? || name.empty?
208
+ t = date ? Time.at(date).utc : Time.now
209
+ name = format("%s_%d-%02d-%02d_%02d-%02d-%02d", kind, t.year, t.month, t.day, t.hour, t.min, t.sec)
210
+ end
211
+ file = py_join(file, name)
212
+ end
213
+ dir, base = py_split(file)
214
+ root, ext = Mime.splitext(base)
215
+ ext = extension if ext.empty?
216
+ result = py_join(dir, root + ext)
217
+ i = 1
218
+ while File.exist?(result)
219
+ result = py_join(dir, "#{root} (#{i})#{ext}")
220
+ i += 1
221
+ end
222
+ result
223
+ end
224
+
225
+ # Saves a message's media (or the media, photo or document given) and answers where it went: the
226
+ # path, the bytes for file :bytes, the IO given, or nil for media that is not a file. file is as
227
+ # proper_filename takes it. thumb picks a thumbnail instead (see get_thumb). progress_callback is
228
+ # called with the bytes so far and the total. Contacts save as a vCard; link previews save their
229
+ # document or photo; a chat photo change saves the new photo.
230
+ def download_media(message, file = nil, thumb: nil, progress_callback: nil)
231
+ msg_data = nil
232
+ date = nil
233
+ wrapped = nil
234
+ if message.is_a?(Message)
235
+ wrapped = message
236
+ elsif message.is_a?(TL::Object) && (message.is?("message") || message.is?("messageService"))
237
+ wrapped = Message.new(message, self)
238
+ end
239
+ if wrapped && wrapped.raw.is?("message")
240
+ date = wrapped.date
241
+ media = wrapped.media
242
+ chat = wrapped.input_chat
243
+ msg_data = [chat, wrapped.id] if chat
244
+ elsif wrapped
245
+ action = wrapped.action
246
+ media = action && action.is?("messageActionChatEditPhoto") ? action["photo"] : nil
247
+ else
248
+ raise ArgumentError, "bot API file ids are not supported" if message.is_a?(String)
249
+
250
+ media = message
251
+ end
252
+ return nil if media.nil?
253
+
254
+ if media.is?("messageMediaWebPage") && media["webpage"] && media["webpage"].is?("webPage")
255
+ page = media["webpage"]
256
+ media = page["document"] || page["photo"]
257
+ return nil if media.nil?
258
+ end
259
+ if media.is?("messageMediaPhoto") || media.is?("photo")
260
+ download_photo(media, file, date, thumb, progress_callback)
261
+ elsif media.is?("messageMediaDocument") || media.is?("document")
262
+ download_document(media, file, date, thumb, progress_callback, msg_data)
263
+ elsif media.is?("messageMediaContact") && thumb.nil?
264
+ download_contact(media, file)
265
+ elsif (media.is?("webDocument") || media.is?("webDocumentNoProxy")) && thumb.nil?
266
+ raise Error, "web documents are fetched over HTTP, which telethon.rb does not do"
267
+ end
268
+ end
269
+
270
+ # Downloads a file location (or what file_info takes) into file: nil or :bytes answer the bytes, a
271
+ # path is written owner-only (and nil answered), an IO is written to. part_size_kb is the request
272
+ # size, from file_size when not given. key and iv decrypt each part with AES-IGE, as Telethon does.
273
+ def download_file(input_location, file = nil, part_size_kb: nil, file_size: nil, progress_callback: nil,
274
+ dc_id: nil, key: nil, iv: nil)
275
+ download_file_from(input_location, file, part_size_kb, file_size, progress_callback, dc_id, key, iv, nil)
276
+ end
277
+
278
+ # Telethon's iter_download: yields the file's chunks (or answers them all without a block). offset,
279
+ # stride and chunk_size select which bytes; limit is how many chunks; request_size how much each
280
+ # request asks for (4 KB to 512 KB).
281
+ def iter_download(file, offset: 0, stride: nil, limit: nil, chunk_size: nil, request_size: MAX_CHUNK_SIZE,
282
+ file_size: nil, dc_id: nil)
283
+ chunks = []
284
+ download_chunks(file, offset, stride, limit, chunk_size, request_size, file_size, dc_id, nil) do |chunk|
285
+ if block_given?
286
+ yield chunk
287
+ else
288
+ chunks << chunk
289
+ end
290
+ end
291
+ block_given? ? nil : chunks
292
+ end
293
+
294
+ # Saves a user's, chat's or channel's profile photo (big, unless download_big is false) and answers
295
+ # where it went, as download_media; nil without one. A channel whose photo location is no longer
296
+ # valid gets its full chat's photo instead.
297
+ def download_profile_photo(entity, file = nil, download_big: true)
298
+ type = entity.is_a?(TL::Object) ? TL.schema.named(entity.name).result : nil
299
+ if type.nil? || PROFILE_INPUT_TYPES.include?(type)
300
+ entity = get_entity(entity)
301
+ type = TL.schema.named(entity.name).result
302
+ end
303
+ thumb = download_big ? -1 : 0
304
+ names = []
305
+ if PROFILE_ENTITY_TYPES.include?(type)
306
+ unless Client.tl_field?(entity, "photo")
307
+ return nil unless Client.tl_field?(entity, "chat_photo")
308
+
309
+ return download_photo(entity["chat_photo"], file, nil, thumb, nil)
310
+ end
311
+ %w[username first_name title].each { |field| names << (Client.tl_field?(entity, field) ? entity[field] : nil) }
312
+ photo = entity["photo"]
313
+ else
314
+ photo = entity
315
+ end
316
+ return nil unless photo && (photo.is?("userProfilePhoto") || photo.is?("chatPhoto"))
317
+
318
+ dc_id = photo["dc_id"]
319
+ peer = Custom.input_peer_of(self, entity)
320
+ raise ArgumentError, "Cannot cast #{entity.name} to any kind of InputPeer." unless peer
321
+
322
+ location = TL.make("inputPeerPhotoFileLocation", "peer" => peer,
323
+ "photo_id" => photo["photo_id"], "big" => download_big)
324
+ file = Client.proper_filename(file, "profile_photo", ".jpg", nil, names)
325
+ begin
326
+ result = download_file_from(location, file, nil, nil, nil, dc_id, nil, nil, nil)
327
+ file == :bytes ? result : file
328
+ rescue RPCError => e
329
+ raise unless e.name == "LOCATION_INVALID"
330
+
331
+ peer = get_input_entity(entity)
332
+ return nil unless peer.is?("inputPeerChannel")
333
+
334
+ full = call(TL.make("channels.getFullChannel", "channel" => input_channel(peer)))
335
+ download_photo(full["full_chat"]["chat_photo"], file, nil, thumb, nil)
336
+ end
337
+ end
338
+
339
+ # Whether the constructor has the field (Python's hasattr on a TL object).
340
+ def self.tl_field?(object, field)
341
+ TL.schema.named(object.name).params.any? { |p| p.name == field }
342
+ end
343
+
344
+ private
345
+
346
+ def download_photo(photo, file, date, thumb, progress_callback)
347
+ photo = photo["photo"] if photo && photo.is?("messageMediaPhoto")
348
+ return nil unless photo && photo.is?("photo")
349
+
350
+ size = Client.get_thumb(photo["sizes"] + (photo["video_sizes"] || []), thumb)
351
+ return nil if size.nil? || size.is?("photoSizeEmpty")
352
+
353
+ file = if size.is?("videoSize")
354
+ Client.proper_filename(file, "video", ".mp4", date)
355
+ else
356
+ Client.proper_filename(file, "photo", ".jpg", date)
357
+ end
358
+ return save_cached_size(size, file) if size.is?("photoCachedSize") || size.is?("photoStrippedSize")
359
+
360
+ file_size = size.is?("photoSizeProgressive") ? size["sizes"].max : size["size"]
361
+ location = TL.make("inputPhotoFileLocation", "id" => photo["id"], "access_hash" => photo["access_hash"],
362
+ "file_reference" => photo["file_reference"], "thumb_size" => size["type"])
363
+ result = download_file_from(location, file, nil, file_size, progress_callback, nil, nil, nil, nil)
364
+ file == :bytes ? result : file
365
+ end
366
+
367
+ def download_document(document, file, date, thumb, progress_callback, msg_data)
368
+ document = document["document"] if document.is?("messageMediaDocument")
369
+ return nil unless document && document.is?("document")
370
+
371
+ size = nil
372
+ if thumb.nil?
373
+ kind, names = Client.kind_and_names(document["attributes"])
374
+ file = Client.proper_filename(file, kind, Client.media_extension(document), date, names)
375
+ else
376
+ file = Client.proper_filename(file, "photo", ".jpg", date)
377
+ size = Client.get_thumb(document["thumbs"], thumb)
378
+ return nil if size.nil? || size.is?("photoSizeEmpty")
379
+ return save_cached_size(size, file) if size.is?("photoCachedSize") || size.is?("photoStrippedSize")
380
+ end
381
+ location = TL.make("inputDocumentFileLocation", "id" => document["id"], "access_hash" => document["access_hash"],
382
+ "file_reference" => document["file_reference"],
383
+ "thumb_size" => size ? size["type"] : "")
384
+ result = download_file_from(location, file, nil, size ? size["size"] : document["size"], progress_callback, nil,
385
+ nil, nil, msg_data)
386
+ file == :bytes ? result : file
387
+ end
388
+
389
+ def save_cached_size(size, file)
390
+ data = size.is?("photoStrippedSize") ? Client.stripped_photo_to_jpg(size["bytes"]) : size["bytes"]
391
+ return data if file == :bytes
392
+
393
+ write_whole(file, data)
394
+ file
395
+ end
396
+
397
+ # Telethon's _download_contact: a vCard 4.0 of the contact.
398
+ def download_contact(media, file)
399
+ first = media["first_name"].delete(";")
400
+ last = (media["last_name"] || "").delete(";")
401
+ phone = media["phone_number"]
402
+ card = "BEGIN:VCARD\nVERSION:4.0\nN:#{first};#{last};;;\nFN:#{first} #{last}\n" \
403
+ "TEL;TYPE=cell;VALUE=uri:tel:+#{phone}\nEND:VCARD\n"
404
+ result = card.b
405
+ file = Client.proper_filename(file, "contact", ".vcard", nil, [first, phone, last])
406
+ return result if file == :bytes
407
+
408
+ write_whole(file, result)
409
+ file
410
+ end
411
+
412
+ def write_whole(file, data)
413
+ if file.is_a?(String)
414
+ PrivateFiles.stream(file) { |f| f.write(data) }
415
+ else
416
+ file.write(data)
417
+ end
418
+ end
419
+
420
+ def download_file_from(location, file, part_size_kb, file_size, progress_callback, dc_id, key, iv, msg_data)
421
+ if part_size_kb.nil? || part_size_kb.zero?
422
+ part_size_kb = file_size.nil? || file_size.zero? ? 64 : Client.appropriated_part_size(file_size)
423
+ end
424
+ part_size = (part_size_kb * 1024).to_i
425
+ raise ArgumentError, "The part size must be evenly divisible by 4096." unless (part_size % MIN_CHUNK_SIZE).zero?
426
+
427
+ if file.nil? || file == :bytes
428
+ out = +"".b
429
+ download_chunks(location, 0, nil, nil, nil, part_size, nil, dc_id, msg_data) do |chunk|
430
+ chunk = Crypto.ige_decrypt(chunk, key, iv) if key && iv
431
+ out << chunk
432
+ progress_callback&.call(out.bytesize, file_size)
433
+ end
434
+ return out
435
+ end
436
+ if file.is_a?(String)
437
+ written = 0
438
+ PrivateFiles.stream(file) do |f|
439
+ download_chunks(location, 0, nil, nil, nil, part_size, nil, dc_id, msg_data) do |chunk|
440
+ chunk = Crypto.ige_decrypt(chunk, key, iv) if key && iv
441
+ f.write(chunk)
442
+ written += chunk.bytesize
443
+ progress_callback&.call(written, file_size)
444
+ end
445
+ end
446
+ return nil
447
+ end
448
+ download_chunks(location, 0, nil, nil, nil, part_size, nil, dc_id, msg_data) do |chunk|
449
+ chunk = Crypto.ige_decrypt(chunk, key, iv) if key && iv
450
+ file.write(chunk)
451
+ progress_callback&.call(file.pos, file_size)
452
+ end
453
+ nil
454
+ end
455
+
456
+ # Telethon's _iter_download: picks the direct download (whole requests, aligned) or the generic one,
457
+ # then yields the chunks.
458
+ def download_chunks(file, offset, stride, limit, chunk_size, request_size, file_size, dc_id, msg_data, &block)
459
+ location, info_dc, info_size = Client.file_info(file)
460
+ dc_id = info_dc if info_dc
461
+ file_size = info_size if file_size.nil?
462
+ chunk_size ||= request_size
463
+ limit = (file_size + chunk_size - 1) / chunk_size if limit.nil? && file_size
464
+ if stride.nil?
465
+ stride = chunk_size
466
+ elsif stride < chunk_size
467
+ raise ArgumentError, "stride must be >= chunk_size"
468
+ end
469
+ request_size -= request_size % MIN_CHUNK_SIZE
470
+ request_size = MIN_CHUNK_SIZE if request_size < MIN_CHUNK_SIZE
471
+ request_size = MAX_CHUNK_SIZE if request_size > MAX_CHUNK_SIZE
472
+ # Telethon divides by limit here, and fails on an empty file; the port downloads nothing.
473
+ return if limit&.zero?
474
+
475
+ direct = chunk_size == request_size && (offset % MIN_CHUNK_SIZE).zero? && (stride % MIN_CHUNK_SIZE).zero? &&
476
+ (limit.nil? || (offset % limit).zero?)
477
+ download = FileDownload.new(self, location, dc_id, offset, request_size, stride, chunk_size, msg_data,
478
+ @download_sleep || ->(seconds) { sleep(seconds) })
479
+ download.each(limit, direct, &block)
480
+ end
481
+ end
482
+
483
+ # One download's requests: Telethon's _DirectDownloadIter and _GenericDownloadIter.
484
+ class FileDownload
485
+ def initialize(client, location, dc_id, offset, request_size, stride, chunk_size, msg_data, sleeper)
486
+ @client = client
487
+ @location = location
488
+ @dc_id = dc_id
489
+ @offset = offset
490
+ @limit = request_size
491
+ @stride = stride
492
+ @chunk_size = chunk_size
493
+ @msg_data = msg_data
494
+ @sleeper = sleeper
495
+ @timed_out = false
496
+ @last_part = nil
497
+ @cdn = nil
498
+ @master_dc = nil
499
+ @hashes = {}
500
+ end
501
+
502
+ # RequestIter: yields up to limit chunks (all without one), loading them a request (or several) at a
503
+ # time.
504
+ def each(limit, direct)
505
+ left = limit
506
+ buffer = []
507
+ index = 0
508
+ loop do
509
+ break if left && left <= 0
510
+
511
+ if index == buffer.size
512
+ index = 0
513
+ buffer = []
514
+ done = direct ? load_direct(buffer) : load_generic(buffer)
515
+ left = buffer.size if done
516
+ end
517
+ break if buffer.empty?
518
+
519
+ yield buffer[index]
520
+ index += 1
521
+ left -= 1 if left
522
+ end
523
+ end
524
+
525
+ private
526
+
527
+ def load_direct(buffer)
528
+ current = fetch
529
+ buffer << current
530
+ return true if current.bytesize < @limit
531
+
532
+ @offset += @stride
533
+ false
534
+ end
535
+
536
+ def load_generic(buffer)
537
+ data = +"".b
538
+ bad = @offset % @limit
539
+ before = @offset
540
+ @offset -= bad
541
+ done = false
542
+ while !done && data.bytesize - bad < @chunk_size
543
+ current = fetch
544
+ @offset += @limit
545
+ data << current
546
+ done = current.bytesize < @limit
547
+ end
548
+ @offset = before
549
+ i = bad
550
+ while i < data.bytesize
551
+ buffer << data.byteslice(i, @chunk_size)
552
+ @offset += @stride
553
+ i += @stride
554
+ end
555
+ return true if done
556
+
557
+ if !buffer.empty? && buffer[-1].bytesize != @chunk_size
558
+ @last_part = buffer.pop
559
+ @offset -= @stride
560
+ end
561
+ false
562
+ end
563
+
564
+ # One upload.getFile, following the file to its data center (or CDN) and refreshing an expired
565
+ # reference.
566
+ def fetch
567
+ return fetch_cdn if @cdn
568
+
569
+ request = TL.make("upload.getFile", "location" => @location, "offset" => @offset, "limit" => @limit)
570
+ result = @dc_id ? @client.call_on(@dc_id, request) : @client.call(request)
571
+ @timed_out = false
572
+ if result.is?("upload.fileCdnRedirect")
573
+ if @client.session.bot
574
+ raise Error, "FileCdnRedirect but the GetCdnFileRequest API access for bot users is restricted. Try to " \
575
+ "change api_id to avoid FileCdnRedirect"
576
+ end
577
+
578
+ @cdn = result
579
+ @master_dc = @dc_id
580
+ add_hashes(result["file_hashes"])
581
+ return fetch_cdn
582
+ end
583
+
584
+ result["bytes"]
585
+ rescue RPCError => e
586
+ if e.code == -503
587
+ raise if @timed_out
588
+
589
+ @timed_out = true
590
+ @sleeper.call(Client::TIMED_OUT_SLEEP)
591
+ return fetch
592
+ end
593
+ if e.name == "FILE_MIGRATE"
594
+ @dc_id = e.value
595
+ return fetch
596
+ end
597
+ raise unless %w[FILEREF_UPGRADE_NEEDED FILE_REFERENCE_EXPIRED].include?(e.name)
598
+ raise unless @msg_data && @location.is?("inputDocumentFileLocation") && @location["thumb_size"] == ""
599
+
600
+ message = @client.get_messages(@msg_data[0], [@msg_data[1]])[0]
601
+ media = message && message.media
602
+ raise unless media && media.is?("messageMediaDocument")
603
+
604
+ document = media["document"]
605
+ raise unless document["id"] == @location["id"]
606
+
607
+ @location = TL.make("inputDocumentFileLocation", "id" => @location["id"], "access_hash" => @location["access_hash"],
608
+ "file_reference" => document["file_reference"], "thumb_size" => "")
609
+ fetch
610
+ end
611
+
612
+ # https://core.telegram.org/cdn: the part from the CDN, decrypted with AES-256-CTR (the iv's last
613
+ # four bytes are the offset in 16-byte blocks) and checked against the hashes the file's own data
614
+ # center gives. A CDN that does not have the file yet has it reuploaded first. (Telethon asks the
615
+ # CDN with the account's own auth key and decrypts with IGE, which cannot work.)
616
+ def fetch_cdn
617
+ token = @cdn["file_token"]
618
+ request = TL.make("upload.getCdnFile", "file_token" => token, "offset" => @offset, "limit" => @limit)
619
+ result = @client.call_cdn(@cdn["dc_id"], request)
620
+ if result.is?("upload.cdnFileReuploadNeeded")
621
+ add_hashes(master(TL.make("upload.reuploadCdnFile", "file_token" => token,
622
+ "request_token" => result["request_token"])))
623
+ result = @client.call_cdn(@cdn["dc_id"], request)
624
+ raise Error, "the CDN still does not have the file after its reupload" unless result.is?("upload.cdnFile")
625
+ end
626
+ iv = @cdn["encryption_iv"].byteslice(0, 12) + [@offset / 16].pack("N")
627
+ data = Crypto::Ctr.new(@cdn["encryption_key"], iv).update(result["bytes"])
628
+ verify(@offset, data)
629
+ data
630
+ end
631
+
632
+ def master(request)
633
+ @master_dc ? @client.call_on(@master_dc, request) : @client.call(request)
634
+ end
635
+
636
+ def add_hashes(hashes)
637
+ hashes.each { |h| @hashes[h["offset"]] = h }
638
+ end
639
+
640
+ # Every hashed part of data must match its sha256; Telegram hashes files in parts (of 128 KB), so
641
+ # a CDN download goes in whole parts.
642
+ def verify(offset, data)
643
+ pos = 0
644
+ while pos < data.bytesize
645
+ at = offset + pos
646
+ unless @hashes[at]
647
+ add_hashes(master(TL.make("upload.getCdnFileHashes", "file_token" => @cdn["file_token"], "offset" => at)))
648
+ end
649
+ hash = @hashes[at]
650
+ raise Error, "Telegram gave no hash for the CDN file at offset #{at} (CDN downloads go in whole parts)" unless hash
651
+
652
+ part = data.byteslice(pos, hash["limit"])
653
+ raise Error, "the CDN file was tampered with at offset #{at}" unless Crypto.sha256(part) == hash["hash"]
654
+
655
+ pos += hash["limit"]
656
+ end
657
+ end
658
+ end
659
+ end