telethon 0.1.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.
@@ -0,0 +1,149 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Telethon
4
+ class Client
5
+ # Where Telegram sent a login code, in words, by auth.SentCodeType. It is rarely an SMS.
6
+ CODE_DELIVERY = {
7
+ "auth.sentCodeTypeApp" => 'the "Telegram" service chat on a device already logged into the account',
8
+ "auth.sentCodeTypeSms" => "SMS",
9
+ "auth.sentCodeTypeCall" => "a phone call",
10
+ "auth.sentCodeTypeFlashCall" => "a missed call (the code is the last digits of the number)",
11
+ "auth.sentCodeTypeEmailCode" => "the account's login email",
12
+ "auth.sentCodeTypeFragmentSms" => "an SMS through Fragment",
13
+ "auth.sentCodeTypeFirebaseSms" => "SMS"
14
+ }.freeze
15
+
16
+ # The tg://login URL of a QR login token: base64url without padding. Not with the base64 library,
17
+ # which is no default gem since Ruby 3.4.
18
+ def self.login_url(token)
19
+ "tg://login?token=#{[token].pack("m0").tr("+/", "-_").delete("=")}"
20
+ end
21
+
22
+ def self.code_delivery(sent_code)
23
+ type = sent_code["type"]
24
+ CODE_DELIVERY.fetch(type.name, type.name)
25
+ end
26
+
27
+ # Answers auth.sentCode; phone_code_hash is in it.
28
+ def send_code(phone)
29
+ call(TL.make("auth.sendCode", "phone_number" => phone, "api_id" => @api_id, "api_hash" => @api_hash,
30
+ "settings" => TL.make("codeSettings")))
31
+ end
32
+
33
+ def resend_code(phone, phone_code_hash)
34
+ call(TL.make("auth.resendCode", "phone_number" => phone, "phone_code_hash" => phone_code_hash))
35
+ end
36
+
37
+ # Answers the user. Raises RPCError SESSION_PASSWORD_NEEDED when the account has 2FA: then call
38
+ # check_password.
39
+ def sign_in(phone, code, phone_code_hash)
40
+ logged_in(call(TL.make("auth.signIn", "phone_number" => phone, "phone_code_hash" => phone_code_hash,
41
+ "phone_code" => code)))
42
+ end
43
+
44
+ def check_password(password)
45
+ info = call(TL.make("account.getPassword"))
46
+ algo = info["current_algo"]
47
+ raise Error, "the account has no 2FA password" unless algo
48
+
49
+ a, m1 = Crypto::SRP.compute(salt1: algo["salt1"], salt2: algo["salt2"], g: algo["g"], p: algo["p"],
50
+ srp_b: info["srp_B"], password: password)
51
+ srp = TL.make("inputCheckPasswordSRP", "srp_id" => info["srp_id"], "A" => a, "M1" => m1)
52
+ logged_in(call(TL.make("auth.checkPassword", "password" => srp)))
53
+ end
54
+
55
+ # Starts a QR login: show qr.url as a QR code, then qr.wait.
56
+ def qr_login(except_ids = [])
57
+ QRLogin.new(self, except_ids).recreate
58
+ end
59
+
60
+ def get_me
61
+ call(TL.make("users.getUsers", "id" => [TL.make("inputUserSelf")]))[0]
62
+ end
63
+
64
+ # An auth.authorization, as signIn, checkPassword and a QR login answer: remembers the user.
65
+ def logged_in(authorization)
66
+ if authorization.is?("auth.authorizationSignUpRequired")
67
+ raise Error, "this phone number has no Telegram account"
68
+ end
69
+
70
+ user = authorization["user"]
71
+ @session.user_id = user["id"]
72
+ @session.save
73
+ user
74
+ end
75
+
76
+ # Telethon's QRLogin: the token to show, and the wait for another device to accept it.
77
+ class QRLogin
78
+ attr_reader :response
79
+
80
+ def initialize(client, except_ids)
81
+ @client = client
82
+ @except_ids = except_ids
83
+ @response = nil
84
+ end
85
+
86
+ def recreate
87
+ @response = @client.call(export_request)
88
+ self
89
+ end
90
+
91
+ def url
92
+ Client.login_url(@response["token"])
93
+ end
94
+
95
+ def expires
96
+ @response["expires"]
97
+ end
98
+
99
+ # Waits up to timeout seconds for the token to be accepted. Answers the user, or nil on timeout.
100
+ # Raises RPCError SESSION_PASSWORD_NEEDED for an account with 2FA.
101
+ def wait(timeout)
102
+ deadline = Time.now.to_f + timeout
103
+ loop do
104
+ left = deadline - Time.now.to_f
105
+ return nil if left <= 0
106
+
107
+ break if @client.poll_updates([left, 1.0].min).any? { |update| login_token?(update) }
108
+ end
109
+ finish(@client.call(export_request))
110
+ end
111
+
112
+ private
113
+
114
+ def export_request
115
+ TL.make("auth.exportLoginToken", "api_id" => @client.api_id, "api_hash" => @client.api_hash,
116
+ "except_ids" => @except_ids)
117
+ end
118
+
119
+ def finish(answer)
120
+ if answer.is?("auth.loginTokenMigrateTo")
121
+ @client.switch_dc(answer["dc_id"])
122
+ answer = @client.call(TL.make("auth.importLoginToken", "token" => answer["token"]))
123
+ end
124
+ raise Error, "unexpected answer to a QR login: #{answer.name}" unless answer.is?("auth.loginTokenSuccess")
125
+
126
+ @client.logged_in(answer["authorization"])
127
+ end
128
+
129
+ def login_token?(update)
130
+ return false unless update.is_a?(TL::Object)
131
+ return true if update.is?("updateLoginToken")
132
+ return login_token?(update["update"]) if update.is?("updateShort")
133
+
134
+ update.is?("updates") && update["updates"].any? { |u| login_token?(u) }
135
+ end
136
+ end
137
+ end
138
+ end
139
+
140
+ module Telethon
141
+ class Client
142
+ # Creates the account for a phone number that has none (auth.authorizationSignUpRequired), which
143
+ # only the test data centers' numbers are expected to need here.
144
+ def sign_up(phone, phone_code_hash, first_name, last_name = "")
145
+ logged_in(call(TL.make("auth.signUp", "phone_number" => phone, "phone_code_hash" => phone_code_hash,
146
+ "first_name" => first_name, "last_name" => last_name)))
147
+ end
148
+ end
149
+ end
@@ -0,0 +1,153 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Telethon
4
+ class Client
5
+ CHANNEL_BASE = 1_000_000_000_000
6
+
7
+ # Telethon's marked peer id: users as they are, basic groups negative, channels -100… .
8
+ def self.peer_id(object)
9
+ case object.name
10
+ when "user", "userEmpty", "peerUser", "inputPeerUser" then object["user_id"] || object["id"]
11
+ when "chat", "chatForbidden", "chatEmpty", "peerChat", "inputPeerChat" then -(object["chat_id"] || object["id"])
12
+ when "channel", "channelForbidden", "peerChannel", "inputPeerChannel"
13
+ -(CHANNEL_BASE + (object["channel_id"] || object["id"]))
14
+ else raise Error, "#{object.name} has no peer id"
15
+ end
16
+ end
17
+
18
+ def self.display_name(entity)
19
+ return nil if entity.nil?
20
+
21
+ if entity.name.start_with?("user")
22
+ full = [entity["first_name"], entity["last_name"]].compact.reject(&:empty?).join(" ")
23
+ full.empty? ? nil : full
24
+ else
25
+ entity["title"]
26
+ end
27
+ end
28
+
29
+ # The input peer for a marked id, from the entity cache. nil when it was never seen.
30
+ def input_peer(id)
31
+ return TL.make("inputPeerSelf") if id == @session.user_id
32
+
33
+ if id.positive?
34
+ cached = @session.entity(id)
35
+ cached && TL.make("inputPeerUser", "user_id" => id, "access_hash" => cached[0])
36
+ elsif id <= -CHANNEL_BASE
37
+ cached = @session.entity(id)
38
+ cached && TL.make("inputPeerChannel", "channel_id" => -id - CHANNEL_BASE, "access_hash" => cached[0])
39
+ else
40
+ TL.make("inputPeerChat", "chat_id" => -id)
41
+ end
42
+ end
43
+
44
+ def input_peer_for(entity)
45
+ id = Client.peer_id(entity)
46
+ return TL.make("inputPeerSelf") if entity.name == "user" && entity["self"]
47
+
48
+ remember(entity)
49
+ input_peer(id)
50
+ end
51
+
52
+ def input_channel(peer)
53
+ TL.make("inputChannel", "channel_id" => peer["channel_id"], "access_hash" => peer["access_hash"])
54
+ end
55
+
56
+ def channel?(peer)
57
+ peer.is?("inputPeerChannel")
58
+ end
59
+
60
+ # Remembers the users and chats of an answer, as Telethon does with every result.
61
+ def remember_entities(result)
62
+ return unless result.is_a?(TL::Object)
63
+
64
+ users = result["users"]
65
+ users&.each { |user| remember(user) }
66
+ chats = result["chats"]
67
+ chats&.each { |chat| remember(chat) }
68
+ end
69
+
70
+ def remember(entity)
71
+ return unless entity.is_a?(TL::Object)
72
+ return if entity["min"] && @session.entity(Client.peer_id(entity)) # a min entity's hash is not usable
73
+
74
+ case entity.name
75
+ when "user", "channel"
76
+ return if entity["access_hash"].nil?
77
+
78
+ @session.remember(Client.peer_id(entity), entity["access_hash"], entity["username"], Client.display_name(entity))
79
+ when "chat"
80
+ @session.remember(Client.peer_id(entity), 0, nil, entity["title"])
81
+ end
82
+ end
83
+
84
+ # The user, chat or channel for a CLI reference: "me", a marked id, or a @username. A numeric id
85
+ # the session has not seen yet loads the dialog list once, as tg.py did.
86
+ def get_entity(reference)
87
+ ref = reference.to_s.strip
88
+ return get_me if %w[me self].include?(ref)
89
+
90
+ if ref.match?(/\A-?\d+\z/)
91
+ id = ref.to_i
92
+ found = fetch_entity(id)
93
+ return found if found
94
+
95
+ load_dialogs
96
+ found = fetch_entity(id)
97
+ raise Error, "no chat or user #{id} among this account's dialogs" unless found
98
+
99
+ return found
100
+ end
101
+
102
+ username = ref.delete_prefix("@").sub(%r{\Ahttps?://t\.me/}, "")
103
+ resolved = call(TL.make("contacts.resolveUsername", "username" => username))
104
+ peer_id = Client.peer_id(resolved["peer"])
105
+ (resolved["users"] + resolved["chats"]).find { |e| Client.peer_id(e) == peer_id } ||
106
+ raise(Error, "@#{username} did not resolve")
107
+ end
108
+
109
+ # Every dialog, paged, which fills the entity cache with what this account can see.
110
+ def load_dialogs
111
+ offset_date = 0
112
+ offset_id = 0
113
+ offset_peer = TL.make("inputPeerEmpty")
114
+ seen = 0
115
+ loop do
116
+ page = call(TL.make("messages.getDialogs", "offset_date" => offset_date, "offset_id" => offset_id,
117
+ "offset_peer" => offset_peer, "limit" => 100, "hash" => 0))
118
+ dialogs = page["dialogs"] || []
119
+ seen += dialogs.size
120
+ break if dialogs.empty? || page.is?("messages.dialogs") || seen >= page["count"].to_i
121
+
122
+ last = dialogs[-1]
123
+ last_peer = Client.peer_id(last["peer"])
124
+ message = page["messages"].find { |m| m["id"] == last["top_message"] && Client.peer_id(m["peer_id"]) == last_peer }
125
+ break unless message
126
+
127
+ offset_date = message["date"]
128
+ offset_id = message["id"]
129
+ offset_peer = input_peer(last_peer) || TL.make("inputPeerEmpty")
130
+ end
131
+ @session.save_entities
132
+ seen
133
+ end
134
+
135
+ private
136
+
137
+ def fetch_entity(id)
138
+ peer = input_peer(id)
139
+ return nil unless peer
140
+
141
+ case peer.name
142
+ when "inputPeerSelf" then get_me
143
+ when "inputPeerUser"
144
+ call(TL.make("users.getUsers", "id" => [TL.make("inputUser", "user_id" => peer["user_id"],
145
+ "access_hash" => peer["access_hash"])]))[0]
146
+ when "inputPeerChat"
147
+ call(TL.make("messages.getChats", "id" => [peer["chat_id"]]))["chats"][0]
148
+ else
149
+ call(TL.make("channels.getChannels", "id" => [input_channel(peer)]))["chats"][0]
150
+ end
151
+ end
152
+ end
153
+ end
@@ -0,0 +1,236 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+
5
+ module Telethon
6
+ class Client
7
+ PART_SIZE = 512 * 1024
8
+ BIG_FILE = 10 * 1024 * 1024
9
+ DOWNLOAD_CHUNK = 512 * 1024
10
+ 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
28
+
29
+ def self.mime_type(path)
30
+ MIME.fetch(File.extname(path).delete_prefix(".").downcase, "application/octet-stream")
31
+ end
32
+
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
52
+ 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 : "")
84
+ 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
+ end
90
+ ids
91
+ end
92
+
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
99
+
100
+ plan = download_plan(media, message["date"])
101
+ return nil unless plan
102
+
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
107
+ end
108
+
109
+ private
110
+
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)
114
+
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))])
119
+ end
120
+
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"]))
126
+ 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"]))
130
+ end
131
+ end
132
+
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"])
142
+ end
143
+ 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"
187
+ end
188
+ end
189
+ [kind, names]
190
+ end
191
+
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)
198
+ 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
207
+ end
208
+ path
209
+ end
210
+
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)
224
+ 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
+ end
233
+ out
234
+ end
235
+ end
236
+ end