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
@@ -4,233 +4,382 @@ require "digest"
4
4
 
5
5
  module Telethon
6
6
  class Client
7
- PART_SIZE = 512 * 1024
7
+ # Telethon's client/uploads.py and the utils it uses (get_attributes, get_input_media, is_image...).
8
8
  BIG_FILE = 10 * 1024 * 1024
9
- DOWNLOAD_CHUNK = 512 * 1024
10
9
  ALBUM_MAX = 10
11
- IMAGE = /\.(png|jpe?g)\z/i
12
- MIME = {
13
- "pdf" => "application/pdf", "txt" => "text/plain", "md" => "text/markdown", "csv" => "text/csv",
14
- "json" => "application/json", "html" => "text/html", "xml" => "application/xml",
15
- "zip" => "application/zip", "gz" => "application/gzip", "tar" => "application/x-tar",
16
- "png" => "image/png", "jpg" => "image/jpeg", "jpeg" => "image/jpeg", "gif" => "image/gif",
17
- "webp" => "image/webp", "svg" => "image/svg+xml", "mp4" => "video/mp4", "mov" => "video/quicktime",
18
- "webm" => "video/webm", "mp3" => "audio/mpeg", "ogg" => "audio/ogg", "m4a" => "audio/mp4",
19
- "wav" => "audio/x-wav", "doc" => "application/msword",
20
- "docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
21
- "xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
22
- "pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation"
23
- }.freeze
24
- EXTENSION = { "image/jpeg" => ".jpg", "image/png" => ".png", "image/gif" => ".gif", "image/webp" => ".webp",
25
- "video/mp4" => ".mp4", "audio/mpeg" => ".mp3", "audio/ogg" => ".oga", "application/pdf" => ".pdf",
26
- "text/plain" => ".txt", "application/zip" => ".zip", "application/x-tgsticker" => ".tgs",
27
- "video/quicktime" => ".mov", "video/webm" => ".webm" }.freeze
10
+ PART_READ = 512 * 1024
11
+ IMAGE_EXTENSION = /\A\.(png|jpe?g)/i
28
12
 
13
+ # The mime type Telethon sends a file as: Python's guess from the name, else application/octet-stream.
29
14
  def self.mime_type(path)
30
- MIME.fetch(File.extname(path).delete_prefix(".").downcase, "application/octet-stream")
15
+ Mime.guess_type(path)[0] || "application/octet-stream"
31
16
  end
32
17
 
33
- # Uploads a file in parts (saveBigFilePart past 10 MB) and answers the inputFile for it.
34
- def upload_file(path)
35
- size = File.size(path)
36
- big = size > BIG_FILE
37
- file_id = random_long
38
- parts = [(size + PART_SIZE - 1) / PART_SIZE, 1].max
39
- md5 = Digest::MD5.new unless big
40
- File.open(path, "rb") do |file|
41
- parts.times do |part|
42
- chunk = file.read(PART_SIZE) || "".b
43
- md5&.update(chunk)
44
- request = if big
45
- TL.make("upload.saveBigFilePart", "file_id" => file_id, "file_part" => part,
46
- "file_total_parts" => parts, "bytes" => chunk)
47
- else
48
- TL.make("upload.saveFilePart", "file_id" => file_id, "file_part" => part, "bytes" => chunk)
49
- end
50
- raise Error, "Telegram refused part #{part} of #{path}" unless call(request) == true
51
- end
18
+ # The name a file goes by: a path itself, an IO's name (or its path), an uploaded file's name.
19
+ def self.file_name_of(file)
20
+ return file if file.is_a?(String)
21
+ return file["name"] if file.is_a?(TL::Object) && (file.is?("inputFile") || file.is?("inputFileBig"))
22
+ return nil if file.is_a?(TL::Object) || file.is_a?(Message)
23
+ return file.name if file.respond_to?(:name)
24
+ return File.basename(file.path) if file.respond_to?(:path)
25
+
26
+ nil
27
+ end
28
+
29
+ # utils._get_extension: the extension of the file's name (with its dot), else of its media.
30
+ def self.file_extension(file)
31
+ name = file_name_of(file)
32
+ return Mime.splitext(name)[1] if name
33
+ return media_extension(file) if file.is_a?(TL::Object)
34
+
35
+ ""
36
+ end
37
+
38
+ # utils.is_image: an extension that starts with .png, .jpg or .jpeg.
39
+ def self.image?(file)
40
+ file_extension(file).match?(IMAGE_EXTENSION)
41
+ end
42
+
43
+ # utils.is_video, by the extension's mime type (Telethon reads no metadata either without hachoir;
44
+ # is_audio only decides whether to read it).
45
+ def self.video?(file) = major_type?(file, "video/")
46
+
47
+ def self.major_type?(file, major)
48
+ ext = file_extension(file)
49
+ return false if ext.empty?
50
+
51
+ (Mime.guess_type("a#{ext}")[0] || "").start_with?(major)
52
+ end
53
+
54
+ # utils.get_attributes: [document attributes, mime type] for a file sent as a document. The
55
+ # attributes given replace those of their kind, in place.
56
+ def self.get_attributes(file, attributes: nil, mime_type: nil, force_document: false, voice_note: false,
57
+ video_note: false, supports_streaming: false)
58
+ name = file_name_of(file) || "unnamed"
59
+ mime_type ||= Mime.guess_type(name)[0]
60
+ kinds = ["documentAttributeFilename"]
61
+ values = [TL.make("documentAttributeFilename", "file_name" => py_basename(name))]
62
+ if !force_document && video?(file)
63
+ kinds << "documentAttributeVideo"
64
+ values << TL.make("documentAttributeVideo", "duration" => 0.0, "w" => 1, "h" => 1, "round_message" => video_note,
65
+ "supports_streaming" => supports_streaming)
52
66
  end
53
- name = File.basename(path)
54
- if big
55
- TL.make("inputFileBig", "id" => file_id, "parts" => parts, "name" => name)
56
- else
57
- TL.make("inputFile", "id" => file_id, "parts" => parts, "name" => name, "md5_checksum" => md5.hexdigest)
58
- end
59
- end
60
-
61
- # Sends files as one message (an album past one file; ten per album, as Telegram allows), the caption
62
- # on the first. Images go as photos unless force_document. Answers the new message ids.
63
- def send_file(entity, paths, caption: "", reply_to: nil, force_document: false)
64
- peer = input_peer_for(entity)
65
- list = paths.is_a?(Array) ? paths : [paths]
66
- reply = reply_to && TL.make("inputReplyToMessage", "reply_to_msg_id" => reply_to)
67
- if list.size == 1
68
- random_id = random_long
69
- fields = { "peer" => peer, "media" => uploaded_media(list[0], force_document), "message" => caption.to_s,
70
- "random_id" => random_id }
71
- fields["reply_to"] = reply if reply
72
- return sent_ids(call(TL.make("messages.sendMedia", fields)), [random_id])
73
- end
74
-
75
- ids = []
76
- start = 0
77
- while start < list.size
78
- singles = []
79
- list[start, ALBUM_MAX].each do |path|
80
- uploaded = call(TL.make("messages.uploadMedia", "peer" => peer, "media" => uploaded_media(path, force_document)))
81
- first = start.zero? && singles.empty?
82
- singles << TL.make("inputSingleMedia", "media" => stored_media(uploaded), "random_id" => random_long,
83
- "message" => first ? caption.to_s : "")
67
+ if voice_note
68
+ kinds << "documentAttributeAudio"
69
+ values << TL.make("documentAttributeAudio", "duration" => 0, "voice" => true)
70
+ end
71
+ attributes&.each do |attr|
72
+ at = kinds.index(attr.name)
73
+ if at
74
+ values[at] = attr
75
+ else
76
+ kinds << attr.name
77
+ values << attr
84
78
  end
85
- start += ALBUM_MAX
86
- fields = { "peer" => peer, "multi_media" => singles }
87
- fields["reply_to"] = reply if reply
88
- ids.concat(sent_ids(call(TL.make("messages.sendMultiMedia", fields)), singles.map { |s| s["random_id"] }))
89
79
  end
90
- ids
80
+ [values, mime_type || "application/octet-stream"]
91
81
  end
92
82
 
93
- # Saves a message's photo or document into directory (owner-only) and answers the path, or nil for
94
- # media that is not a file. Names it as Telethon does: the file's own name, else kind_date.ext,
95
- # with " (1)" and on added rather than overwriting.
96
- def download_media(message, directory)
97
- media = message["media"]
98
- return nil unless media
83
+ # utils.get_input_media for media that already exists (sent before, or a message's): the InputMedia
84
+ # that sends it again. Raises ArgumentError for what cannot be sent so.
85
+ def self.input_media_of(media, ttl: nil)
86
+ media = media.raw if media.is_a?(Message)
87
+ raise ArgumentError, "Cannot cast #{media.class} to any kind of InputMedia." unless media.is_a?(TL::Object)
99
88
 
100
- plan = download_plan(media, message["date"])
101
- return nil unless plan
89
+ type = TL.schema.named(media.name).result
90
+ return media if type == "InputMedia"
91
+ return TL.make("inputMediaPhoto", "id" => media, "ttl_seconds" => ttl) if type == "InputPhoto"
92
+ return TL.make("inputMediaDocument", "id" => media, "ttl_seconds" => ttl) if type == "InputDocument"
102
93
 
103
- location, dc_id, kind, extension, names, date, inline = plan
104
- path = proper_filename(directory, kind, extension, date, names)
105
- PrivateFiles.write(path, inline || fetch_file(location, dc_id))
106
- path
94
+ case media.name
95
+ when "messageMediaPhoto"
96
+ TL.make("inputMediaPhoto", "id" => input_photo(media["photo"]), "spoiler" => media["spoiler"],
97
+ "ttl_seconds" => ttl || media["ttl_seconds"])
98
+ when "photo", "photoEmpty" then TL.make("inputMediaPhoto", "id" => input_photo(media), "ttl_seconds" => ttl)
99
+ when "messageMediaDocument"
100
+ TL.make("inputMediaDocument", "id" => input_document(media["document"]), "spoiler" => media["spoiler"],
101
+ "ttl_seconds" => ttl || media["ttl_seconds"])
102
+ when "document", "documentEmpty"
103
+ TL.make("inputMediaDocument", "id" => input_document(media), "ttl_seconds" => ttl)
104
+ when "messageMediaContact"
105
+ TL.make("inputMediaContact", "phone_number" => media["phone_number"], "first_name" => media["first_name"],
106
+ "last_name" => media["last_name"], "vcard" => "")
107
+ when "messageMediaGeo" then TL.make("inputMediaGeoPoint", "geo_point" => input_geo(media["geo"]))
108
+ when "messageMediaDice" then TL.make("inputMediaDice", "emoticon" => media["emoticon"])
109
+ when "messageMediaEmpty", "messageMediaUnsupported", "chatPhotoEmpty", "userProfilePhotoEmpty", "chatPhoto",
110
+ "userProfilePhoto"
111
+ TL.make("inputMediaEmpty")
112
+ when "message" then input_media_of(media["media"], ttl: ttl)
113
+ else raise ArgumentError, "Cannot cast #{media.name} to any kind of InputMedia."
114
+ end
107
115
  end
108
116
 
109
- private
117
+ def self.input_photo(photo)
118
+ return TL.make("inputPhotoEmpty") if photo.nil? || photo.is?("photoEmpty")
119
+
120
+ TL.make("inputPhoto", "id" => photo["id"], "access_hash" => photo["access_hash"],
121
+ "file_reference" => photo["file_reference"])
122
+ end
123
+
124
+ def self.input_document(document)
125
+ return TL.make("inputDocumentEmpty") if document.nil? || document.is?("documentEmpty")
126
+
127
+ TL.make("inputDocument", "id" => document["id"], "access_hash" => document["access_hash"],
128
+ "file_reference" => document["file_reference"])
129
+ end
110
130
 
111
- def uploaded_media(path, force_document)
112
- file = upload_file(path)
113
- return TL.make("inputMediaUploadedPhoto", "file" => file) if !force_document && path.match?(IMAGE)
131
+ def self.input_geo(geo)
132
+ return TL.make("inputGeoPointEmpty") if geo.nil? || geo.is?("geoPointEmpty")
114
133
 
115
- TL.make("inputMediaUploadedDocument", "file" => file, "mime_type" => Client.mime_type(path),
116
- "force_file" => force_document,
117
- "attributes" => [TL.make("documentAttributeFilename",
118
- "file_name" => File.basename(path))])
134
+ TL.make("inputGeoPoint", "lat" => geo["lat"], "long" => geo["long"], "accuracy_radius" => geo["accuracy_radius"])
119
135
  end
120
136
 
121
- def stored_media(uploaded)
122
- if uploaded.is?("messageMediaPhoto")
123
- photo = uploaded["photo"]
124
- TL.make("inputMediaPhoto", "id" => TL.make("inputPhoto", "id" => photo["id"], "access_hash" => photo["access_hash"],
125
- "file_reference" => photo["file_reference"]))
137
+ # Uploads a file in parts (saveBigFilePart past 10 MB) and answers the inputFile (or inputFileBig)
138
+ # for it. file is a path, or an IO (readpartial; name or path when it has one). part_size_kb
139
+ # is from the size unless given (at most 512). key and iv encrypt each part with AES-IGE, as Telethon
140
+ # does. An inputFile given is answered as it is.
141
+ def upload_file(file, part_size_kb: nil, file_size: nil, file_name: nil, progress_callback: nil, key: nil,
142
+ iv: nil)
143
+ return file if file.is_a?(TL::Object) && (file.is?("inputFile") || file.is?("inputFileBig"))
144
+
145
+ if file.is_a?(String)
146
+ return upload_stream(file, nil, File.basename(file), File.size(file), part_size_kb, file_name,
147
+ progress_callback, key, iv)
148
+ end
149
+ # Any other IO is read whole first (Telethon streams one it can seek in), up to file_size when
150
+ # given, through readpartial: under Spinel, read(n) on an object of unknown class would also
151
+ # dispatch to IO::Buffer#read, which answers an Integer (DEVELOPING.md).
152
+ data = +"".b
153
+ loop do
154
+ begin
155
+ data << file.readpartial(PART_READ)
156
+ rescue EOFError
157
+ break
158
+ end
159
+ break if file_size && data.bytesize >= file_size
160
+ end
161
+ upload_stream(nil, data, Client.file_name_of(file), file_size || data.bytesize, part_size_kb, file_name,
162
+ progress_callback, key, iv)
163
+ end
164
+
165
+ # Sends a file (path, http(s) URL, IO, uploaded inputFile, or media sent before) with caption in
166
+ # parse_mode, or several as albums of ten (caption then a list, one per file). Images go as photos
167
+ # unless force_document; other files as documents with Telethon's attributes (file name; video for
168
+ # video names unless force_document; voice for voice_note; round for video_note), replaced by
169
+ # attributes of the same kind. Answers the sent Message, or the Messages for a list.
170
+ def send_file(entity, file, caption: nil, force_document: false, mime_type: nil, file_size: nil,
171
+ clear_draft: false, progress_callback: nil, reply_to: nil, attributes: nil, thumb: nil,
172
+ parse_mode: :default, formatting_entities: nil, voice_note: false, video_note: false,
173
+ silent: nil, background: nil, supports_streaming: false, schedule: nil, ttl: nil,
174
+ nosound_video: nil, send_as: nil, message_effect_id: nil)
175
+ raise ArgumentError, "Cannot use #{file.inspect} as file" if file.nil? || (file.is_a?(Array) && file.empty?)
176
+
177
+ caption = "" if caption.nil? || (caption.is_a?(Array) && caption.empty?)
178
+ formatting_entities ||= []
179
+ peer = get_input_entity(entity)
180
+ reply_to = reply_to.id if reply_to.is_a?(Message)
181
+ schedule = schedule.to_i if schedule.is_a?(Time)
182
+ sender = send_as && get_input_entity(send_as)
183
+ if file.is_a?(Array)
184
+ return send_albums(peer, file, caption, formatting_entities, progress_callback, reply_to, parse_mode, silent,
185
+ schedule, supports_streaming, clear_draft, force_document, background, sender,
186
+ message_effect_id)
187
+ end
188
+
189
+ if formatting_entities.empty?
190
+ caption, entities = parse_message_text(caption, parse_mode)
126
191
  else
127
- doc = uploaded["document"]
128
- TL.make("inputMediaDocument", "id" => TL.make("inputDocument", "id" => doc["id"], "access_hash" => doc["access_hash"],
129
- "file_reference" => doc["file_reference"]))
192
+ entities = formatting_entities
130
193
  end
194
+ media = file_to_media(file, force_document, file_size, progress_callback, attributes, thumb, voice_note,
195
+ video_note, supports_streaming, mime_type, ttl, nosound_video)
196
+ raise ArgumentError, "Cannot use #{file.inspect} as file" unless media
197
+
198
+ fields = { "peer" => peer, "media" => media, "message" => caption, "entities" => entities, "silent" => silent,
199
+ "schedule_date" => schedule, "clear_draft" => clear_draft, "background" => background,
200
+ "send_as" => sender, "effect" => message_effect_id, "random_id" => random_id }
201
+ fields["reply_to"] = TL.make("inputReplyToMessage", "reply_to_msg_id" => reply_to) if reply_to
202
+ request = TL.make("messages.sendMedia", fields)
203
+ response_message(request, call(request), peer)
131
204
  end
132
205
 
133
- # [location, dc_id, kind, extension, possible names, date, inline bytes or nil] for downloadable media.
134
- def download_plan(media, date)
135
- # As Telethon: a link preview downloads its page's document, else its photo.
136
- if media.is?("messageMediaWebPage") && media["webpage"]&.is?("webPage")
137
- page = media["webpage"]
138
- if page["document"]
139
- media = TL.make("messageMediaDocument", "document" => page["document"])
140
- elsif page["photo"]
141
- media = TL.make("messageMediaPhoto", "photo" => page["photo"])
206
+ private
207
+
208
+ # Uploads the file at path (read a part at a time), or data when path is nil.
209
+ def upload_stream(io, data, name, file_size, part_size_kb, file_name, progress_callback, key, iv)
210
+ part_size_kb = Client.appropriated_part_size(file_size) if part_size_kb.nil? || part_size_kb.zero?
211
+ raise ArgumentError, "The part size must be less or equal to 512KB" if part_size_kb > 512
212
+
213
+ part_size = (part_size_kb * 1024).to_i
214
+ raise ArgumentError, "The part size must be evenly divisible by 1024" unless (part_size % 1024).zero?
215
+
216
+ file_id = random_long
217
+ if file_name.nil? || file_name.empty?
218
+ file_name = name.nil? || name.empty? ? file_id.to_s : name
219
+ end
220
+ if Mime.splitext(file_name)[1].empty? && name
221
+ file_name += Mime.splitext(name)[1]
222
+ end
223
+ big = file_size > BIG_FILE
224
+ md5 = Digest::MD5.new
225
+ part_count = (file_size + part_size - 1) / part_size
226
+ pos = 0
227
+ part_count.times do |index|
228
+ part = if io
229
+ File.binread(io, part_size, pos) || "".b
230
+ else
231
+ data.byteslice(pos, part_size) || "".b
232
+ end
233
+ if part.bytesize != part_size && index < part_count - 1
234
+ raise ArgumentError, "read less than #{part_size} before reaching the end; either `file_size` or `read` are wrong"
142
235
  end
236
+
237
+ pos += part.bytesize
238
+ part = Crypto.ige_encrypt(pad_to_block(part), key, iv) if key && iv
239
+ md5.update(part) unless big
240
+ request = if big
241
+ TL.make("upload.saveBigFilePart", "file_id" => file_id, "file_part" => index,
242
+ "file_total_parts" => part_count, "bytes" => part)
243
+ else
244
+ TL.make("upload.saveFilePart", "file_id" => file_id, "file_part" => index, "bytes" => part)
245
+ end
246
+ raise Error, "Failed to upload file part #{index}." unless call(request)
247
+
248
+ progress_callback&.call(pos, file_size)
143
249
  end
144
- if media.is?("messageMediaPhoto") && media["photo"]&.is?("photo")
145
- photo = media["photo"]
146
- size = photo["sizes"].max_by { |s| photo_size_bytes(s) }
147
- return nil unless size
148
-
149
- inline = %w[photoCachedSize photoStrippedSize].include?(size.name) ? size["bytes"] : nil
150
- location = TL.make("inputPhotoFileLocation", "id" => photo["id"], "access_hash" => photo["access_hash"],
151
- "file_reference" => photo["file_reference"], "thumb_size" => size["type"])
152
- return [location, photo["dc_id"], "photo", ".jpg", [], date, inline]
153
- end
154
- return nil unless media.is?("messageMediaDocument") && media["document"]&.is?("document")
155
-
156
- doc = media["document"]
157
- kind, names = kind_and_names(doc["attributes"])
158
- location = TL.make("inputDocumentFileLocation", "id" => doc["id"], "access_hash" => doc["access_hash"],
159
- "file_reference" => doc["file_reference"], "thumb_size" => "")
160
- [location, doc["dc_id"], kind, EXTENSION.fetch(doc["mime_type"], ""), names, date, nil]
161
- end
162
-
163
- def photo_size_bytes(size)
164
- case size.name
165
- when "photoSize" then size["size"]
166
- when "photoSizeProgressive" then size["sizes"].max
167
- when "photoCachedSize", "photoStrippedSize" then size["bytes"].bytesize
168
- else 0
169
- end
170
- end
171
-
172
- # Telethon's _get_kind_and_names.
173
- def kind_and_names(attributes)
174
- kind = "document"
175
- names = []
176
- attributes.each do |attr|
177
- case attr.name
178
- when "documentAttributeFilename" then names.unshift(attr["file_name"])
179
- when "documentAttributeAudio"
180
- kind = attr["voice"] ? "voice" : "audio"
181
- names << "#{attr['performer']} - #{attr['title']}" if attr["performer"] && attr["title"]
182
- names << attr["performer"] if attr["performer"]
183
- names << attr["title"] if attr["title"]
184
- when "documentAttributeVideo" then kind = "video"
185
- when "documentAttributeSticker" then kind = "sticker"
186
- when "documentAttributeAnimated" then kind = "animation"
250
+ if big
251
+ TL.make("inputFileBig", "id" => file_id, "parts" => part_count, "name" => file_name)
252
+ else
253
+ TL.make("inputFile", "id" => file_id, "parts" => part_count, "name" => file_name,
254
+ "md5_checksum" => md5.hexdigest)
255
+ end
256
+ end
257
+
258
+ # AES.encrypt_ige's padding: random bytes up to a whole block.
259
+ def pad_to_block(data)
260
+ extra = data.bytesize % 16
261
+ extra.zero? ? data : data + random_bytes(16 - extra)
262
+ end
263
+
264
+ # Telethon's _file_to_media: the InputMedia for a file, uploading it when it is one; nil when it
265
+ # cannot be sent.
266
+ def file_to_media(file, force_document, file_size, progress_callback, attributes, thumb, voice_note, video_note,
267
+ supports_streaming, mime_type, ttl, nosound_video)
268
+ return nil if file.nil?
269
+
270
+ is_image = Client.image?(file)
271
+ as_image = is_image && !force_document
272
+ uploaded = file.is_a?(TL::Object) && (file.is?("inputFile") || file.is?("inputFileBig"))
273
+ if !file.is_a?(String) && !uploaded && (file.is_a?(TL::Object) || file.is_a?(Message) || !file.respond_to?(:readpartial))
274
+ begin
275
+ return Client.input_media_of(file, ttl: ttl)
276
+ rescue ArgumentError
277
+ return nil
187
278
  end
188
279
  end
189
- [kind, names]
280
+ handle = nil
281
+ media = nil
282
+ if uploaded
283
+ handle = file
284
+ elsif !file.is_a?(String) || File.file?(file)
285
+ handle = upload_file(file, file_size: file_size, progress_callback: progress_callback)
286
+ elsif file.match?(%r{\Ahttps?://})
287
+ media = if as_image
288
+ TL.make("inputMediaPhotoExternal", "url" => file, "ttl_seconds" => ttl)
289
+ else
290
+ TL.make("inputMediaDocumentExternal", "url" => file, "ttl_seconds" => ttl)
291
+ end
292
+ end
293
+ return media if media
294
+ unless handle
295
+ raise ArgumentError, "Failed to convert #{file} to media. Not an existing file, an HTTP URL or a valid " \
296
+ "bot-API-like file ID"
297
+ end
298
+ return TL.make("inputMediaUploadedPhoto", "file" => handle, "ttl_seconds" => ttl) if as_image
299
+
300
+ attrs, mime = Client.get_attributes(file, attributes: attributes, mime_type: mime_type,
301
+ force_document: force_document && !is_image, voice_note: voice_note,
302
+ video_note: video_note, supports_streaming: supports_streaming)
303
+ thumb_file = thumb ? upload_file(thumb, file_size: file_size) : nil
304
+ TL.make("inputMediaUploadedDocument", "file" => handle, "mime_type" => mime, "attributes" => attrs,
305
+ "thumb" => thumb_file, "force_file" => force_document && !is_image,
306
+ "ttl_seconds" => ttl,
307
+ "nosound_video" => mime.split("/")[0] == "video" ? nosound_video : nil)
190
308
  end
191
309
 
192
- # Telethon's _get_proper_filename for a directory: never a path outside it, never an overwrite.
193
- def proper_filename(directory, kind, extension, date, names)
194
- name = names.map { |n| File.basename(n.to_s) }.find { |n| !n.empty? && n != "." && n != ".." }
195
- unless name
196
- t = Time.at(date || Time.now.to_i).utc
197
- name = format("%s_%04d-%02d-%02d_%02d-%02d-%02d", kind, t.year, t.month, t.day, t.hour, t.min, t.sec)
310
+ # send_file for a list: albums of ten. progress_callback hears files done (a fraction for the one
311
+ # uploading) out of the files left.
312
+ def send_albums(peer, files, caption, formatting_entities, progress_callback, reply_to, parse_mode, silent,
313
+ schedule, supports_streaming, clear_draft, force_document, background, sender, effect)
314
+ captions = caption.is_a?(Array) ? caption : [caption]
315
+ entity_lists = if formatting_entities.all? { |e| e.is_a?(Array) }
316
+ formatting_entities
317
+ else
318
+ [formatting_entities]
319
+ end
320
+ sent_count = 0
321
+ used = nil
322
+ if progress_callback
323
+ used = ->(done, _total) { progress_callback.call(sent_count + done, files.size) }
198
324
  end
199
- ext = File.extname(name)
200
- base = ext.empty? ? name : name[0, name.size - ext.size]
201
- ext = extension if ext.empty?
202
- path = File.join(directory, base + ext)
203
- i = 1
204
- while File.exist?(path)
205
- path = File.join(directory, "#{base} (#{i})#{ext}")
206
- i += 1
325
+ sent = []
326
+ until files.empty?
327
+ sent.concat(send_album(peer, files[0, ALBUM_MAX], captions[0, ALBUM_MAX] || [],
328
+ entity_lists[0, ALBUM_MAX] || [], used, reply_to, parse_mode, silent, schedule,
329
+ supports_streaming, clear_draft, force_document, background, sender, effect))
330
+ files = files[ALBUM_MAX..] || []
331
+ captions = captions[ALBUM_MAX..] || []
332
+ entity_lists = entity_lists[ALBUM_MAX..] || []
333
+ sent_count += ALBUM_MAX
207
334
  end
208
- path
335
+ sent
209
336
  end
210
337
 
211
- # The file's bytes, from the data center that stores it.
212
- def fetch_file(location, dc_id)
213
- out = +"".b
214
- offset = 0
215
- loop do
216
- request = TL.make("upload.getFile", "location" => location, "offset" => offset, "limit" => DOWNLOAD_CHUNK)
217
- part = begin
218
- call_on(dc_id, request)
219
- rescue RPCError => e
220
- raise unless e.name == "FILE_MIGRATE"
221
-
222
- dc_id = e.value
223
- call_on(dc_id, request)
338
+ # Telethon's _send_album: each file uploaded as media first, then one sendMultiMedia.
339
+ def send_album(peer, files, captions, entity_lists, progress_callback, reply_to, parse_mode, silent, schedule,
340
+ supports_streaming, clear_draft, force_document, background, sender, effect)
341
+ pending = []
342
+ if entity_lists.empty?
343
+ captions.reverse_each { |c| pending << parse_message_text(c || "", parse_mode) }
344
+ else
345
+ reversed_captions = captions.reverse
346
+ reversed_lists = entity_lists.reverse
347
+ [reversed_captions.size, reversed_lists.size].max.times do |i|
348
+ pending << [reversed_captions[i], reversed_lists[i]]
224
349
  end
225
- raise Error, "the file is on a CDN, which this client does not support" unless part.is?("upload.file")
226
-
227
- bytes = part["bytes"]
228
- out << bytes
229
- break if bytes.bytesize < DOWNLOAD_CHUNK
230
-
231
- offset += DOWNLOAD_CHUNK
232
350
  end
233
- out
351
+ sent_count = 0
352
+ used = nil
353
+ if progress_callback
354
+ used = lambda do |done, total|
355
+ progress_callback.call(done == total ? sent_count + 1 : sent_count + (done.to_f / total), files.size)
356
+ end
357
+ end
358
+ singles = []
359
+ files.each_with_index do |file, index|
360
+ sent_count = index
361
+ media = file_to_media(file, force_document, nil, used, nil, nil, false, false, supports_streaming, nil, nil,
362
+ true)
363
+ if media && (media.is?("inputMediaUploadedPhoto") || media.is?("inputMediaPhotoExternal"))
364
+ uploaded = call(TL.make("messages.uploadMedia", "peer" => peer, "media" => media))
365
+ media = Client.input_media_of(uploaded["photo"])
366
+ elsif media && (media.is?("inputMediaUploadedDocument") || media.is?("inputMediaDocumentExternal"))
367
+ uploaded = call(TL.make("messages.uploadMedia", "peer" => peer, "media" => media))
368
+ media = Client.input_media_of(uploaded["document"])
369
+ end
370
+ text, entities = pending.empty? ? ["", nil] : pending.pop
371
+ singles << TL.make("inputSingleMedia", "media" => media, "message" => text, "entities" => entities,
372
+ "random_id" => random_id)
373
+ end
374
+ fields = { "peer" => peer, "multi_media" => singles, "silent" => silent, "schedule_date" => schedule,
375
+ "clear_draft" => clear_draft, "background" => background, "send_as" => sender, "effect" => effect }
376
+ fields["reply_to"] = TL.make("inputReplyToMessage", "reply_to_msg_id" => reply_to) if reply_to
377
+ request = TL.make("messages.sendMultiMedia", fields)
378
+ found = response_parts(request, call(request), peer)
379
+ singles.map do |single|
380
+ id = found[0][single["random_id"]]
381
+ id && found[1][id]
382
+ end
234
383
  end
235
384
  end
236
385
  end