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,154 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Telethon
4
+ class Client
5
+ MAX_CHUNK = 100
6
+
7
+ # Telethon's message.sender_id: from_id, else the chat itself for channel posts and for incoming
8
+ # messages in a private chat (which no longer carry from_id).
9
+ def self.sender_id(message)
10
+ return peer_id(message["from_id"]) if message["from_id"]
11
+
12
+ peer = message["peer_id"]
13
+ return peer_id(peer) if message["post"] || (!message["out"] && peer.is?("peerUser"))
14
+
15
+ nil
16
+ end
17
+
18
+ # Telethon's message.file.name: a document's file name attribute, nil for anything else.
19
+ def self.file_name(message)
20
+ media = message["media"]
21
+ return nil unless media && media.is?("messageMediaDocument") && media["document"]&.is?("document")
22
+
23
+ attribute = media["document"]["attributes"].find { |a| a.is?("documentAttributeFilename") }
24
+ attribute && attribute["file_name"]
25
+ end
26
+
27
+ # Yields the chat's messages newest first, with each one's sender (a user or chat, or nil):
28
+ # history, or one forum topic's with reply_to. limit nil means all of them.
29
+ def iter_messages(entity, limit: nil, reply_to: nil, offset_id: 0)
30
+ peer = input_peer_for(entity)
31
+ left = limit
32
+ offset = offset_id
33
+ loop do
34
+ chunk = left ? [left, MAX_CHUNK].min : MAX_CHUNK
35
+ request = if reply_to
36
+ TL.make("messages.getReplies", "peer" => peer, "msg_id" => reply_to, "offset_id" => offset,
37
+ "offset_date" => 0, "add_offset" => 0, "limit" => chunk,
38
+ "max_id" => 0, "min_id" => 0, "hash" => 0)
39
+ else
40
+ TL.make("messages.getHistory", "peer" => peer, "offset_id" => offset, "offset_date" => 0,
41
+ "add_offset" => 0, "limit" => chunk, "max_id" => 0, "min_id" => 0,
42
+ "hash" => 0)
43
+ end
44
+ page = call(request)
45
+ senders = entity_map(page)
46
+ messages = page["messages"]
47
+ last = nil
48
+ messages.each do |message|
49
+ next if message.is?("messageEmpty")
50
+
51
+ sender = senders[Client.sender_id(message)]
52
+ yield message, sender
53
+ last = message
54
+ if left
55
+ left -= 1
56
+ return if left.zero?
57
+ end
58
+ end
59
+ # As Telethon: a non-slice answer is everything; an empty one, or one reaching id <= limit, the end.
60
+ break if page.is?("messages.messages") || messages.empty? || messages[0]["id"] <= chunk || last.nil?
61
+
62
+ offset = last["id"]
63
+ end
64
+ end
65
+
66
+ # The messages with these ids, in the order asked, nil for those that do not exist; with senders.
67
+ def get_messages(entity, ids)
68
+ peer = input_peer_for(entity)
69
+ inputs = ids.map { |id| TL.make("inputMessageID", "id" => id) }
70
+ page = if channel?(peer)
71
+ call(TL.make("channels.getMessages", "channel" => input_channel(peer), "id" => inputs))
72
+ else
73
+ call(TL.make("messages.getMessages", "id" => inputs))
74
+ end
75
+ senders = entity_map(page)
76
+ by_id = {}
77
+ page["messages"].each { |m| by_id[m["id"]] = m unless m.is?("messageEmpty") }
78
+ ids.map do |id|
79
+ message = by_id[id]
80
+ message && [message, senders[Client.sender_id(message)]]
81
+ end
82
+ end
83
+
84
+ def forum_topics(entity, limit: 100)
85
+ call(TL.make("messages.getForumTopics", "peer" => input_peer_for(entity), "offset_date" => 0, "offset_id" => 0,
86
+ "offset_topic" => 0, "limit" => limit))["topics"]
87
+ end
88
+
89
+ # Deletes for everyone (revoke), as Telethon's delete_messages does by default.
90
+ def delete_messages(entity, ids, revoke: true)
91
+ peer = input_peer_for(entity)
92
+ if channel?(peer)
93
+ call(TL.make("channels.deleteMessages", "channel" => input_channel(peer), "id" => ids))
94
+ else
95
+ call(TL.make("messages.deleteMessages", "id" => ids, "revoke" => revoke))
96
+ end
97
+ end
98
+
99
+ # Answers the sent message's id. reply_to is a message id, or a forum topic's.
100
+ def send_message(entity, text, reply_to: nil)
101
+ peer = input_peer_for(entity)
102
+ random_id = random_long
103
+ fields = { "peer" => peer, "message" => text, "random_id" => random_id }
104
+ fields["reply_to"] = TL.make("inputReplyToMessage", "reply_to_msg_id" => reply_to) if reply_to
105
+ result = call(TL.make("messages.sendMessage", fields))
106
+ return result["id"] if result.is?("updateShortSentMessage")
107
+
108
+ sent_ids(result, [random_id])[0]
109
+ end
110
+
111
+ def edit_message(entity, id, text)
112
+ result = call(TL.make("messages.editMessage", "peer" => input_peer_for(entity), "id" => id, "message" => text))
113
+ edited = updates_of(result).find { |u| u.name.start_with?("updateEdit") && u["message"]["id"] == id }
114
+ edited ? edited["message"]["id"] : id
115
+ end
116
+
117
+ # Forwards without the "Forwarded from" header when drop_author. Answers the new ids, in order.
118
+ def forward_messages(to_entity, ids, from_entity, drop_author: false)
119
+ random_ids = Array.new(ids.size) { random_long }
120
+ result = call(TL.make("messages.forwardMessages", "from_peer" => input_peer_for(from_entity), "id" => ids,
121
+ "to_peer" => input_peer_for(to_entity), "random_id" => random_ids,
122
+ "drop_author" => drop_author))
123
+ sent_ids(result, random_ids)
124
+ end
125
+
126
+ private
127
+
128
+ def entity_map(page)
129
+ map = {}
130
+ (page["users"] || []).each { |u| map[Client.peer_id(u)] = u }
131
+ (page["chats"] || []).each { |c| map[Client.peer_id(c)] = c }
132
+ map
133
+ end
134
+
135
+ def updates_of(result)
136
+ case result.name
137
+ when "updates", "updatesCombined" then result["updates"]
138
+ when "updateShort" then [result["update"]]
139
+ else []
140
+ end
141
+ end
142
+
143
+ # The message ids an Updates answer gave each random_id (updateMessageID), in the order of random_ids.
144
+ def sent_ids(result, random_ids)
145
+ by_random = {}
146
+ updates_of(result).each { |u| by_random[u["random_id"]] = u["id"] if u.is?("updateMessageID") }
147
+ random_ids.map { |r| by_random[r] }
148
+ end
149
+
150
+ def random_long
151
+ Crypto.random_bytes(8).unpack1("q<")
152
+ end
153
+ end
154
+ end
@@ -0,0 +1,174 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Telethon
4
+ # A Telegram user client, after Telethon's TelegramClient. Connects to the session's data center
5
+ # (creating an auth key the first time), follows *_MIGRATE errors to the account's home DC, sleeps
6
+ # through short FLOOD_WAITs, and opens extra connections to other DCs for files kept there.
7
+ class Client
8
+ FLOOD_SLEEP_THRESHOLD = 60
9
+ MIGRATING = %w[PHONE_MIGRATE NETWORK_MIGRATE USER_MIGRATE].freeze
10
+
11
+ attr_reader :session, :api_id, :api_hash
12
+ attr_accessor :flood_sleep_threshold, :on_flood_wait
13
+
14
+ def initialize(session, api_id:, api_hash:, device_model: nil, system_version: nil, app_version: VERSION,
15
+ lang_code: "en")
16
+ @session = session
17
+ @api_id = api_id
18
+ @api_hash = api_hash
19
+ @device_model = device_model || default_device_model
20
+ @system_version = system_version || "1.0"
21
+ @app_version = app_version
22
+ @lang_code = lang_code
23
+ @sender = nil
24
+ @dc_options = nil
25
+ @exported = {}
26
+ @flood_sleep_threshold = FLOOD_SLEEP_THRESHOLD
27
+ @on_flood_wait = nil
28
+ end
29
+
30
+ def connect
31
+ return self if @sender
32
+
33
+ @sender = open_sender(@session.address, @session.port, @session.auth_key) do |key|
34
+ @session.auth_key = key.key
35
+ @session.save
36
+ end
37
+ self
38
+ end
39
+
40
+ # Replaces the connection, for tests that script Telegram's answers.
41
+ def use_sender(sender)
42
+ @sender = sender
43
+ end
44
+
45
+ def connected?
46
+ !@sender.nil?
47
+ end
48
+
49
+ def disconnect
50
+ @session.save_entities if @session.entities_changed?
51
+ @sender&.transport&.close
52
+ @sender = nil
53
+ @exported.each_value { |sender| sender.transport.close }
54
+ @exported = {}
55
+ end
56
+
57
+ # Calls a TL function on the home data center.
58
+ def call(request)
59
+ connect unless @sender
60
+ attempts = 0
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
72
+
73
+ if e.migrate? && MIGRATING.include?(e.name)
74
+ switch_dc(e.value)
75
+ retry
76
+ end
77
+ if e.flood_wait? && e.value <= @flood_sleep_threshold
78
+ @on_flood_wait&.call(e.value)
79
+ sleep(e.value + 1)
80
+ retry
81
+ end
82
+ raise
83
+ end
84
+ end
85
+
86
+ # Calls a TL function on another data center, with this account's authorization exported to it.
87
+ def call_on(dc_id, request)
88
+ return call(request) if dc_id == @session.dc_id
89
+
90
+ @exported[dc_id] ||= exported_sender(dc_id)
91
+ @exported[dc_id].call(request)
92
+ end
93
+
94
+ # Reads what the server pushes (updates) for up to timeout seconds.
95
+ def poll_updates(timeout)
96
+ connect unless @sender
97
+ @sender.poll(timeout)
98
+ end
99
+
100
+ def authorized?
101
+ call(TL.make("updates.getState"))
102
+ true
103
+ rescue RPCError => e
104
+ raise unless e.code == 401
105
+
106
+ false
107
+ end
108
+
109
+ # Permanently moves the session to another data center: its auth key does not carry over.
110
+ def switch_dc(dc_id)
111
+ address, port = dc_address(dc_id)
112
+ disconnect
113
+ @session.set_dc(dc_id, address, port)
114
+ @session.save
115
+ connect
116
+ end
117
+
118
+ def dc_address(dc_id)
119
+ options = @dc_options || fetch_dc_options
120
+ found = options.find { |o| o["id"] == dc_id && !o["ipv6"] && !o["cdn"] && !o["media_only"] } ||
121
+ options.find { |o| o["id"] == dc_id && !o["ipv6"] && !o["cdn"] }
122
+ return [found["ip_address"], found["port"]] if found
123
+
124
+ address = @session.default_address(dc_id)
125
+ raise Error, "no address for data center #{dc_id}" unless address
126
+
127
+ [address, 443]
128
+ end
129
+
130
+ private
131
+
132
+ def fetch_dc_options
133
+ @dc_options = @sender ? call(TL.make("help.getConfig"))["dc_options"] : []
134
+ rescue RPCError
135
+ @dc_options = []
136
+ end
137
+
138
+ def open_sender(address, port, auth_key)
139
+ transport = Network::Transport.new(address, port).connect
140
+ if auth_key
141
+ key = Network::AuthKey.new(auth_key)
142
+ offset = 0
143
+ else
144
+ key, offset = Network::Authenticator.run(transport)
145
+ yield key if block_given?
146
+ end
147
+ sender = Network::Sender.new(transport, Network::State.new(key, offset))
148
+ sender.wrap_first { |query| init_connection(query) }
149
+ sender
150
+ end
151
+
152
+ def exported_sender(dc_id)
153
+ exported = call(TL.make("auth.exportAuthorization", "dc_id" => dc_id))
154
+ address, port = dc_address(dc_id)
155
+ sender = open_sender(address, port, nil)
156
+ sender.call(TL.make("auth.importAuthorization", "id" => exported["id"], "bytes" => exported["bytes"]))
157
+ sender
158
+ end
159
+
160
+ # invokeWithLayer(initConnection(query)), as the first request of every connection.
161
+ def init_connection(query)
162
+ TL.encode(TL.make("invokeWithLayer", "layer" => TL::LAYER, "query" => TL.make(
163
+ "initConnection", "api_id" => @api_id, "device_model" => @device_model,
164
+ "system_version" => @system_version, "app_version" => @app_version,
165
+ "system_lang_code" => @lang_code, "lang_pack" => "", "lang_code" => @lang_code,
166
+ "query" => query
167
+ )))
168
+ end
169
+
170
+ def default_device_model
171
+ "telethon.rb"
172
+ end
173
+ end
174
+ end
@@ -0,0 +1,105 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "openssl" unless RUBY_ENGINE == "spinel"
4
+
5
+ module Telethon
6
+ module Crypto
7
+ module_function
8
+
9
+ # AES-256-IGE, which MTProto encrypts every message with. iv is 32 bytes.
10
+ def ige_encrypt(data, key, iv)
11
+ ige(data, key, iv, true)
12
+ end
13
+
14
+ def ige_decrypt(data, key, iv)
15
+ ige(data, key, iv, false)
16
+ end
17
+
18
+ def ige(data, key, iv, encrypt)
19
+ raise ArgumentError, "IGE data must be a multiple of 16 bytes" unless (data.bytesize % 16).zero?
20
+
21
+ if RUBY_ENGINE == "spinel"
22
+ out = Buffers.blank(data.bytesize)
23
+ TelethonNative.tn_aes_ige(out, Buffers.of(data), data.bytesize, Buffers.of(key), Buffers.of(iv),
24
+ encrypt ? 1 : 0)
25
+ Buffers.read(out, data.bytesize)
26
+ else
27
+ ige_openssl(data, key, iv, encrypt)
28
+ end
29
+ end
30
+
31
+ def ige_openssl(data, key, iv, encrypt)
32
+ cipher = OpenSSL::Cipher.new("aes-256-ecb")
33
+ encrypt ? cipher.encrypt : cipher.decrypt
34
+ cipher.key = key
35
+ cipher.padding = 0
36
+ c_prev = iv.byteslice(0, 16)
37
+ p_prev = iv.byteslice(16, 16)
38
+ out = +"".b
39
+ offset = 0
40
+ while offset < data.bytesize
41
+ block = data.byteslice(offset, 16)
42
+ if encrypt
43
+ y = xor(cipher.update(xor(block, c_prev)), p_prev)
44
+ p_prev = block
45
+ c_prev = y
46
+ else
47
+ y = xor(cipher.update(xor(block, p_prev)), c_prev)
48
+ c_prev = block
49
+ p_prev = y
50
+ end
51
+ out << y
52
+ offset += 16
53
+ end
54
+ out
55
+ end
56
+
57
+ def xor(left, right)
58
+ a = left.unpack("Q>Q>")
59
+ b = right.unpack("Q>Q>")
60
+ [a[0] ^ b[0], a[1] ^ b[1]].pack("Q>Q>")
61
+ end
62
+
63
+ # One raw AES-256 block, for the FIPS-197 test vector.
64
+ def aes_block(block, key)
65
+ if RUBY_ENGINE == "spinel"
66
+ out = Buffers.blank(16)
67
+ TelethonNative.tn_aes_block(out, Buffers.of(block), Buffers.of(key))
68
+ Buffers.read(out, 16)
69
+ else
70
+ cipher = OpenSSL::Cipher.new("aes-256-ecb")
71
+ cipher.encrypt
72
+ cipher.key = key
73
+ cipher.padding = 0
74
+ cipher.update(block).b
75
+ end
76
+ end
77
+
78
+ # AES-256-CTR as a stream, for the obfuscated transport: one per direction, kept for the connection.
79
+ class Ctr
80
+ def initialize(key, iv)
81
+ @key = key.b
82
+ if RUBY_ENGINE == "spinel"
83
+ @state = Buffers.of(iv.b + ("\0" * 16).b + [16].pack("C"))
84
+ else
85
+ @cipher = OpenSSL::Cipher.new("aes-256-ctr")
86
+ @cipher.encrypt
87
+ @cipher.key = key
88
+ @cipher.iv = iv
89
+ end
90
+ end
91
+
92
+ def update(data)
93
+ return "".b if data.empty?
94
+
95
+ if RUBY_ENGINE == "spinel"
96
+ out = Buffers.blank(data.bytesize)
97
+ TelethonNative.tn_aes_ctr(out, Buffers.of(data), data.bytesize, Buffers.of(@key), @state)
98
+ Buffers.read(out, data.bytesize)
99
+ else
100
+ @cipher.update(data).b
101
+ end
102
+ end
103
+ end
104
+ end
105
+ end
@@ -0,0 +1,45 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+ require "securerandom"
5
+ require "openssl" unless RUBY_ENGINE == "spinel"
6
+
7
+ module Telethon
8
+ module Crypto
9
+ module_function
10
+
11
+ def sha1(data)
12
+ Digest::SHA1.digest(data).b
13
+ end
14
+
15
+ def sha256(data)
16
+ Digest::SHA256.digest(data).b
17
+ end
18
+
19
+ def sha512(data)
20
+ if RUBY_ENGINE == "spinel"
21
+ out = Buffers.blank(64)
22
+ TelethonNative.tn_sha512(out, Buffers.of(data), data.bytesize)
23
+ Buffers.read(out, 64)
24
+ else
25
+ OpenSSL::Digest.digest("SHA512", data).b
26
+ end
27
+ end
28
+
29
+ def pbkdf2_sha512(password, salt, iterations, length)
30
+ if RUBY_ENGINE == "spinel"
31
+ out = Buffers.blank(length)
32
+ TelethonNative.tn_pbkdf2_sha512(out, length, Buffers.of(password), password.bytesize,
33
+ Buffers.of(salt), salt.bytesize, iterations)
34
+ Buffers.read(out, length)
35
+ else
36
+ OpenSSL::KDF.pbkdf2_hmac(password, salt: salt, iterations: iterations, length: length,
37
+ hash: "SHA512").b
38
+ end
39
+ end
40
+
41
+ def random_bytes(count)
42
+ SecureRandom.random_bytes(count).b
43
+ end
44
+ end
45
+ end
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The C in native/, bound for the Spinel build. CRuby never loads this module's functions: every caller
4
+ # checks RUBY_ENGINE first, and Spinel drops the branch that rules it out before analysis.
5
+ if RUBY_ENGINE == "spinel"
6
+ module TelethonNative
7
+ ffi_func :tn_aes_ige, %i[ptr ptr long ptr ptr long], :long
8
+ ffi_func :tn_aes_ctr, %i[ptr ptr long ptr ptr], :long
9
+ ffi_func :tn_aes_block, %i[ptr ptr ptr], :long
10
+ ffi_func :tn_sha512, %i[ptr ptr long], :long
11
+ ffi_func :tn_pbkdf2_sha512, %i[ptr long ptr long ptr long long], :long
12
+ ffi_func :tn_bn_mod, %i[ptr ptr long ptr long], :long
13
+ ffi_func :tn_bn_mul, %i[ptr ptr long ptr long], :long
14
+ ffi_func :tn_bn_add, %i[ptr ptr long ptr long], :long
15
+ ffi_func :tn_bn_sub, %i[ptr ptr ptr long], :long
16
+ ffi_func :tn_bn_modpow, %i[ptr ptr long ptr long ptr long], :long
17
+ ffi_func :tn_pq_factor, %i[long], :long
18
+ end
19
+ end
20
+
21
+ module Telethon
22
+ module Crypto
23
+ # Byte strings in and out of IO::Buffers, which is how the Spinel build hands memory to C.
24
+ module Buffers
25
+ module_function
26
+
27
+ def of(bytes)
28
+ buffer = IO::Buffer.new(bytes.bytesize.positive? ? bytes.bytesize : 1)
29
+ buffer.set_string(bytes) if bytes.bytesize.positive?
30
+ buffer
31
+ end
32
+
33
+ def blank(size)
34
+ IO::Buffer.new(size.positive? ? size : 1)
35
+ end
36
+
37
+ def read(buffer, size)
38
+ return "".b if size.zero?
39
+
40
+ buffer.get_string(0, size).b
41
+ end
42
+ end
43
+ end
44
+ end