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,373 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Telethon
4
+ # Telethon's extensions/html.py: <b>/<strong>, <i>/<em>, <u>, <s>/<del>, <blockquote [expandable]>,
5
+ # <code>, <pre> (with <code class="language-x"> inside for the language), <a href>, and
6
+ # <tg-emoji emoji-id>. Telethon reads the markup with Python's HTMLParser; HTML::Tokenizer here does
7
+ # the part of it these tags need.
8
+ module HTML
9
+ # Python's html.escape: &, <, >, " and '.
10
+ def self.escape(text)
11
+ text.gsub("&", "&amp;").gsub("<", "&lt;").gsub(">", "&gt;").gsub('"', "&quot;").gsub("'", "&#x27;")
12
+ end
13
+
14
+ def self.escape_units(units)
15
+ Text.units(escape(Text.string(units)))
16
+ end
17
+
18
+ # Answers [text, entities] for the HTML message.
19
+ def self.parse(html)
20
+ return [html, []] if html.nil? || html.empty?
21
+
22
+ parser = Parser.new
23
+ Tokenizer.new(Text.units(html), parser).run
24
+ text = Text.strip(parser.text, parser.entities)
25
+ entities = parser.entities.reverse
26
+ sorted = []
27
+ entities.each do |e|
28
+ k = sorted.size
29
+ k -= 1 while k.positive? && sorted[k - 1].offset > e.offset
30
+ sorted.insert(k, e)
31
+ end
32
+ [Text.string(text), sorted.map(&:to_tl)]
33
+ end
34
+
35
+ # Telethon's HTMLToTelegramParser: builds the text and the entities from the tags.
36
+ class Parser
37
+ attr_reader :text, :entities
38
+
39
+ def initialize
40
+ @text = []
41
+ @entities = []
42
+ @building = {}
43
+ @building_order = []
44
+ @open_tags = []
45
+ @open_meta = []
46
+ end
47
+
48
+ def start_tag(tag, attrs, raw)
49
+ @open_tags.unshift(tag)
50
+ @open_meta.unshift(nil)
51
+ name = nil
52
+ field = nil
53
+ value = nil
54
+ case tag
55
+ when "strong", "b" then name = "messageEntityBold"
56
+ when "em", "i" then name = "messageEntityItalic"
57
+ when "u" then name = "messageEntityUnderline"
58
+ when "del", "s" then name = "messageEntityStrike"
59
+ when "blockquote"
60
+ name = "messageEntityBlockquote"
61
+ if attrs.key?("expandable")
62
+ field = "collapsed"
63
+ value = true
64
+ end
65
+ when "code"
66
+ pre = @building["pre"]
67
+ if pre
68
+ klass = attrs["class"]
69
+ pre.value = klass[9..] || "" if klass
70
+ else
71
+ name = "messageEntityCode"
72
+ end
73
+ when "pre"
74
+ name = "messageEntityPre"
75
+ field = "language"
76
+ value = ""
77
+ when "a"
78
+ return unless attrs.key?("href")
79
+
80
+ url = attrs["href"] || ""
81
+ if url.start_with?("mailto:")
82
+ url = url[7..]
83
+ name = "messageEntityEmail"
84
+ elsif raw == url
85
+ name = "messageEntityUrl"
86
+ else
87
+ name = "messageEntityTextUrl"
88
+ field = "url"
89
+ value = url
90
+ url = nil
91
+ end
92
+ @open_meta[0] = url
93
+ when "tg-emoji"
94
+ id = attrs["emoji-id"]
95
+ return unless id && id.match?(/\A\s*[-+]?\d+(_\d+)*\s*\z/)
96
+
97
+ name = "messageEntityCustomEmoji"
98
+ field = "document_id"
99
+ value = id.delete("_").to_i
100
+ end
101
+ return unless name && !@building.key?(tag)
102
+
103
+ @building[tag] = Text::Entity.new(name, @text.size, 0, field, value)
104
+ @building_order << tag
105
+ end
106
+
107
+ def data(units)
108
+ if @open_tags[0] == "a"
109
+ url = @open_meta[0]
110
+ units = Text.units(url) if url
111
+ end
112
+ @building_order.each { |tag| @building[tag].length += units.size }
113
+ @text.concat(units)
114
+ end
115
+
116
+ def end_tag(tag)
117
+ @open_tags.shift
118
+ @open_meta.shift
119
+ entity = @building.delete(tag)
120
+ return unless entity
121
+
122
+ @building_order.delete(tag)
123
+ @entities << entity
124
+ end
125
+ end
126
+
127
+ # The part of Python's HTMLParser (convert_charrefs=True) Telethon's parser relies on: start, end
128
+ # and self-closing tags with their attributes, text with character references resolved, comments
129
+ # and declarations skipped, and <script>/<style> content read as raw text.
130
+ class Tokenizer
131
+ LT = 0x3C
132
+ GT = 0x3E
133
+ SLASH = 0x2F
134
+ BANG = 0x21
135
+ QUESTION = 0x3F
136
+ AMP = 0x26
137
+ EQUALS = 0x3D
138
+ QUOTE = 0x22
139
+ APOSTROPHE = 0x27
140
+ WHITESPACE = [0x20, 0x09, 0x0A, 0x0D, 0x0C].freeze
141
+ NAME_END = [0x20, 0x09, 0x0A, 0x0D, 0x0C, 0x2F, 0x3E, 0x00].freeze
142
+
143
+ def initialize(units, parser)
144
+ @s = units
145
+ @parser = parser
146
+ @cdata = nil
147
+ end
148
+
149
+ def run
150
+ i = 0
151
+ text_start = 0
152
+ while i < @s.size
153
+ if @cdata
154
+ close = cdata_end(i)
155
+ flush_raw(i, close)
156
+ i = close
157
+ text_start = i
158
+ @cdata = nil
159
+ next
160
+ end
161
+ unless @s[i] == LT
162
+ i += 1
163
+ next
164
+ end
165
+ flush(text_start, i)
166
+ text_start = i
167
+ finish = markup_end(i)
168
+ if finish
169
+ i = finish
170
+ text_start = i
171
+ else
172
+ i += 1
173
+ end
174
+ end
175
+ flush(text_start, @s.size)
176
+ end
177
+
178
+ private
179
+
180
+ def letter?(unit)
181
+ unit && ((unit >= 0x41 && unit <= 0x5A) || (unit >= 0x61 && unit <= 0x7A))
182
+ end
183
+
184
+ def space?(unit)
185
+ WHITESPACE.include?(unit)
186
+ end
187
+
188
+ def lower(units)
189
+ Text.string(units).downcase
190
+ end
191
+
192
+ def flush(from, to)
193
+ return if to <= from
194
+
195
+ @parser.data(unescape(@s[from...to]))
196
+ end
197
+
198
+ def flush_raw(from, to)
199
+ @parser.data(@s[from...to]) if to > from
200
+ end
201
+
202
+ # Where the markup that starts with the "<" at i ends, having handed it to the parser; nil when
203
+ # it is no markup, which leaves the "<" as text.
204
+ def markup_end(i)
205
+ nxt = @s[i + 1]
206
+ if letter?(nxt)
207
+ start_tag(i)
208
+ elsif nxt == SLASH
209
+ end_tag(i)
210
+ elsif nxt == BANG || nxt == QUESTION
211
+ skip_to_gt(i)
212
+ end
213
+ end
214
+
215
+ def skip_to_gt(i)
216
+ if Text.starts_at?(@s, i, Text.units("<!--"))
217
+ close = Text.find(@s, Text.units("-->"), i + 4)
218
+ return close ? close + 3 : nil
219
+ end
220
+ close = gt_from(i + 2)
221
+ close ? close + 1 : nil
222
+ end
223
+
224
+ def gt_from(k)
225
+ k += 1 while k < @s.size && @s[k] != GT
226
+ k < @s.size ? k : nil
227
+ end
228
+
229
+ def start_tag(i)
230
+ j = i + 1
231
+ j += 1 while j < @s.size && !NAME_END.include?(@s[j])
232
+ tag = lower(@s[i + 1...j])
233
+ attrs = {}
234
+ loop do
235
+ j += 1 while j < @s.size && (space?(@s[j]) || (@s[j] == SLASH && @s[j + 1] != GT))
236
+ return nil if j >= @s.size
237
+ break if @s[j] == GT || (@s[j] == SLASH && @s[j + 1] == GT)
238
+
239
+ k = j + 1
240
+ k += 1 while k < @s.size && !space?(@s[k]) && ![SLASH, EQUALS, GT].include?(@s[k])
241
+ name = lower(@s[j...k])
242
+ value = nil
243
+ m = k
244
+ m += 1 while m < @s.size && space?(@s[m])
245
+ if @s[m] == EQUALS
246
+ m += 1 while m < @s.size && @s[m] == EQUALS
247
+ m += 1 while m < @s.size && space?(@s[m])
248
+ if @s[m] == QUOTE || @s[m] == APOSTROPHE
249
+ quote = @s[m]
250
+ close = m + 1
251
+ close += 1 while close < @s.size && @s[close] != quote
252
+ return nil if close >= @s.size
253
+
254
+ value = Text.string(unescape(@s[m + 1...close]))
255
+ k = close + 1
256
+ else
257
+ close = m
258
+ close += 1 while close < @s.size && @s[close] != GT && !space?(@s[close])
259
+ value = Text.string(unescape(@s[m...close]))
260
+ k = close
261
+ end
262
+ end
263
+ attrs[name] = value unless attrs.key?(name)
264
+ j = k
265
+ end
266
+ self_closing = @s[j] == SLASH
267
+ finish = self_closing ? j + 2 : j + 1
268
+ @parser.start_tag(tag, attrs, Text.string(@s[i...finish]))
269
+ if self_closing
270
+ @parser.end_tag(tag)
271
+ elsif %w[script style].include?(tag)
272
+ @cdata = tag
273
+ end
274
+ finish
275
+ end
276
+
277
+ def end_tag(i)
278
+ close = gt_from(i + 2)
279
+ return nil unless close
280
+ return close + 1 unless letter?(@s[i + 2])
281
+
282
+ j = i + 2
283
+ j += 1 while j < close && !NAME_END.include?(@s[j])
284
+ @parser.end_tag(lower(@s[i + 2...j]))
285
+ close + 1
286
+ end
287
+
288
+ # Where the raw text of a <script> or <style> ends: at its closing tag, or the end of input.
289
+ def cdata_end(i)
290
+ found = Text.find(@lower ||= @s.map { |u| u >= 0x41 && u <= 0x5A ? u + 32 : u }, Text.units("</#{@cdata}"), i)
291
+ found || @s.size
292
+ end
293
+
294
+ # Python's html.unescape for the references messages use: numeric ones and the common names.
295
+ NAMED = { "amp" => 0x26, "lt" => 0x3C, "gt" => 0x3E, "quot" => 0x22, "apos" => 0x27, "nbsp" => 0xA0 }.freeze
296
+ CP1252 = { 0x80 => 0x20AC, 0x82 => 0x201A, 0x83 => 0x0192, 0x84 => 0x201E, 0x85 => 0x2026, 0x86 => 0x2020,
297
+ 0x87 => 0x2021, 0x88 => 0x02C6, 0x89 => 0x2030, 0x8A => 0x0160, 0x8B => 0x2039, 0x8C => 0x0152,
298
+ 0x8E => 0x017D, 0x91 => 0x2018, 0x92 => 0x2019, 0x93 => 0x201C, 0x94 => 0x201D, 0x95 => 0x2022,
299
+ 0x96 => 0x2013, 0x97 => 0x2014, 0x98 => 0x02DC, 0x99 => 0x2122, 0x9A => 0x0161, 0x9B => 0x203A,
300
+ 0x9C => 0x0153, 0x9E => 0x017E, 0x9F => 0x0178 }.freeze
301
+
302
+ def unescape(units)
303
+ return units unless units.include?(AMP)
304
+
305
+ text = Text.string(units)
306
+ out = text.gsub(/&(#[0-9]+;?|#[xX][0-9a-fA-F]+;?|[a-zA-Z]+;?)/) do |ref|
307
+ body = ref[1..].delete_suffix(";")
308
+ if body.start_with?("#")
309
+ code = body[1] == "x" || body[1] == "X" ? body[2..].to_i(16) : body[1..].to_i
310
+ code = CP1252[code] || code
311
+ code = 0xFFFD if code.zero? || code > 0x10FFFF || (code >= 0xD800 && code <= 0xDFFF)
312
+ [code].pack("U")
313
+ elsif NAMED.key?(body) && (ref.end_with?(";") || body != "apos")
314
+ [NAMED[body]].pack("U")
315
+ else
316
+ ref
317
+ end
318
+ end
319
+ Text.units(out)
320
+ end
321
+ end
322
+
323
+ FORMATTERS = { "messageEntityBold" => %w[<strong> </strong>], "messageEntityItalic" => %w[<em> </em>],
324
+ "messageEntityCode" => %w[<code> </code>], "messageEntityUnderline" => %w[<u> </u>],
325
+ "messageEntityStrike" => %w[<del> </del>] }.freeze
326
+
327
+ # The HTML for text with these TL entities, the reverse of parse.
328
+ def self.unparse(text, entities)
329
+ return text if text.nil? || text.empty?
330
+ return escape(text) if entities.nil? || entities.empty?
331
+
332
+ units = Text.units(text)
333
+ insert_at = []
334
+ entities.each_with_index do |entity, i|
335
+ s = entity["offset"]
336
+ e = s + entity["length"]
337
+ pair = formatter(entity, Text.string(units[s...e] || []))
338
+ next unless pair
339
+
340
+ insert_at << [s, i, pair[0]]
341
+ insert_at << [e, -i, pair[1]]
342
+ end
343
+ insert_at = Text.sorted_insertions(insert_at)
344
+ bound = units.size
345
+ until insert_at.empty?
346
+ at, _, what = insert_at.pop
347
+ at += 1 while Text.within_surrogate?(units, at)
348
+ units = units[0, at] + Text.units(what) + escape_units(units[at...bound] || []) + Text.from(units, bound)
349
+ bound = at
350
+ end
351
+ Text.string(escape_units(units[0, bound]) + Text.from(units, bound))
352
+ end
353
+
354
+ def self.formatter(entity, inner)
355
+ pair = FORMATTERS[entity.name]
356
+ return pair if pair
357
+
358
+ case entity.name
359
+ when "messageEntityBlockquote"
360
+ [entity["collapsed"] ? "<blockquote expandable>" : "<blockquote>", "</blockquote>"]
361
+ when "messageEntityPre"
362
+ # Telethon's closing half is "{}\n </code>\n</pre>", a format string never formatted; the
363
+ # port leaves the "{}" out (DEVELOPING.md).
364
+ ["<pre>\n <code class='language-#{entity['language']}'>\n ", "\n </code>\n</pre>"]
365
+ when "messageEntityEmail" then ["<a href=\"mailto:#{inner}\">", "</a>"]
366
+ when "messageEntityUrl" then ["<a href=\"#{inner}\">", "</a>"]
367
+ when "messageEntityTextUrl" then ["<a href=\"#{escape(entity['url'])}\">", "</a>"]
368
+ when "messageEntityMentionName" then ["<a href=\"tg://user?id=#{entity['user_id']}\">", "</a>"]
369
+ when "messageEntityCustomEmoji" then ["<tg-emoji emoji-id=\"#{entity['document_id']}\">", "</tg-emoji>"]
370
+ end
371
+ end
372
+ end
373
+ end
@@ -0,0 +1,116 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Telethon
4
+ # Telethon's extensions/markdown.py: its own small markdown, without nesting. **bold**, __italic__,
5
+ # ~~strike~~, `code`, ```pre``` and [text](url); a tg://user?id=N url mentions that user.
6
+ module Markdown
7
+ # Longest first, as Telethon tries them: ``` is not read as three code delimiters.
8
+ DEFAULT_DELIMITERS = [["```", "messageEntityPre"], ["**", "messageEntityBold"], ["__", "messageEntityItalic"],
9
+ ["~~", "messageEntityStrike"], ["`", "messageEntityCode"]].freeze
10
+
11
+ OPEN_BRACKET = 0x5B
12
+ CLOSE_BRACKET = 0x5D
13
+ OPEN_PAREN = 0x28
14
+ CLOSE_PAREN = 0x29
15
+
16
+ # Answers [text, entities]: the text without the markup, and the TL entities it stood for.
17
+ # delimiters is a list of [delimiter, entity name] pairs, tried in order; an empty one parses nothing.
18
+ def self.parse(message, delimiters = nil)
19
+ return [message, []] if message.nil? || message.empty?
20
+ return [message, []] if delimiters && delimiters.empty?
21
+
22
+ delims = []
23
+ (delimiters || DEFAULT_DELIMITERS).each do |d|
24
+ at = delims.size
25
+ at -= 1 while at.positive? && delims[at - 1][0].size < d[0].size
26
+ delims.insert(at, [Text.units(d[0]), d[1]])
27
+ end
28
+ text = Text.units(message)
29
+ result = []
30
+ i = 0
31
+ while i < text.size
32
+ delim = delims.find { |d| Text.starts_at?(text, i, d[0]) }
33
+ if delim
34
+ size = delim[0].size
35
+ finish = Text.find(text, delim[0], i + size + 1)
36
+ if finish
37
+ text = text[0, i] + text[i + size...finish] + Text.from(text, finish + size)
38
+ result.each do |ent|
39
+ next unless ent.offset + ent.length > i
40
+
41
+ ent.length -= ent.offset <= i && ent.offset + ent.length >= finish + size ? size * 2 : size
42
+ end
43
+ name = delim[1]
44
+ result << if name == "messageEntityPre"
45
+ Text::Entity.new(name, i, finish - i - size, "language", "")
46
+ else
47
+ Text::Entity.new(name, i, finish - i - size)
48
+ end
49
+ i = finish - size if %w[messageEntityCode messageEntityPre].include?(name)
50
+ next
51
+ end
52
+ else
53
+ link = url_at(text, i)
54
+ if link
55
+ inner = text[i + 1...link[0]]
56
+ url = text[link[0] + 2...link[1]]
57
+ text = text[0, i] + inner + Text.from(text, link[1] + 1)
58
+ removed = link[1] + 1 - i - inner.size
59
+ result.each { |ent| ent.length -= removed if ent.offset + ent.length > i }
60
+ result << Text::Entity.new("messageEntityTextUrl", i, inner.size, "url", Text.string(url))
61
+ i += inner.size
62
+ next
63
+ end
64
+ end
65
+ i += 1
66
+ end
67
+ text = Text.strip(text, result)
68
+ [Text.string(text), result.map(&:to_tl)]
69
+ end
70
+
71
+ # Telethon's [text](url) regexp, \[([^]]*?)\]\(([\s\S]*?)\), matched at i: answers the indexes of
72
+ # the "]" and of the closing ")", or nil.
73
+ def self.url_at(text, i)
74
+ return nil unless text[i] == OPEN_BRACKET
75
+
76
+ close = i + 1
77
+ close += 1 while close < text.size && text[close] != CLOSE_BRACKET
78
+ return nil unless close + 1 < text.size && text[close + 1] == OPEN_PAREN
79
+
80
+ paren = close + 2
81
+ paren += 1 while paren < text.size && text[paren] != CLOSE_PAREN
82
+ paren < text.size ? [close, paren] : nil
83
+ end
84
+
85
+ # The markdown for text with these TL entities, the reverse of parse.
86
+ def self.unparse(text, entities, delimiters = nil)
87
+ return text if text.nil? || text.empty? || entities.nil? || entities.empty?
88
+ return text if delimiters && delimiters.empty?
89
+
90
+ by_name = {}
91
+ (delimiters || DEFAULT_DELIMITERS).each { |d| by_name[d[1]] = d[0] }
92
+ units = Text.units(text)
93
+ insert_at = []
94
+ entities.each_with_index do |entity, i|
95
+ s = entity["offset"]
96
+ e = s + entity["length"]
97
+ delimiter = by_name[entity.name]
98
+ if delimiter
99
+ insert_at << [s, i, delimiter]
100
+ insert_at << [e, -i, delimiter]
101
+ else
102
+ url = if entity.is?("messageEntityTextUrl")
103
+ entity["url"]
104
+ elsif entity.is?("messageEntityMentionName")
105
+ "tg://user?id=#{entity['user_id']}"
106
+ end
107
+ if url
108
+ insert_at << [s, i, "["]
109
+ insert_at << [e, -i, "](#{url})"]
110
+ end
111
+ end
112
+ end
113
+ Text.insert_all(units, Text.sorted_insertions(insert_at))
114
+ end
115
+ end
116
+ end
@@ -0,0 +1,171 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Telethon
4
+ # Telethon's text helpers (helpers.py): Telegram counts entity offsets and lengths in UTF-16 code
5
+ # units, so the parse modes work on a String's UTF-16 units, an Array of Integers, as Telethon works
6
+ # on its "surrogated" str.
7
+ module Text
8
+ # What Python's str.isspace calls whitespace, which str.strip removes.
9
+ SPACE = [0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x85, 0xA0, 0x1680,
10
+ 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A,
11
+ 0x2028, 0x2029, 0x202F, 0x205F, 0x3000].freeze
12
+
13
+ # An entity while a parser builds it: a TL name, offset, length and the one extra field it has.
14
+ class Entity
15
+ attr_accessor :name, :offset, :length, :field, :value
16
+
17
+ def initialize(name, offset, length, field = nil, value = nil)
18
+ @name = name
19
+ @offset = offset
20
+ @length = length
21
+ @field = field
22
+ @value = value
23
+ end
24
+
25
+ def to_tl
26
+ fields = { "offset" => @offset, "length" => @length }
27
+ fields[@field] = @value if @field
28
+ TL.make(@name, fields)
29
+ end
30
+ end
31
+
32
+ # Telethon's add_surrogate: the UTF-16 code units of text.
33
+ def self.units(text)
34
+ out = []
35
+ text.codepoints.each do |c|
36
+ if c >= 0x10000
37
+ c -= 0x10000
38
+ out << (0xD800 + (c >> 10))
39
+ out << (0xDC00 + (c & 0x3FF))
40
+ else
41
+ out << c
42
+ end
43
+ end
44
+ out
45
+ end
46
+
47
+ # Telethon's del_surrogate: the String of UTF-16 code units (a lone surrogate becomes U+FFFD).
48
+ def self.string(units)
49
+ codepoints = []
50
+ i = 0
51
+ while i < units.size
52
+ c = units[i]
53
+ if c >= 0xD800 && c <= 0xDBFF && i + 1 < units.size && units[i + 1] >= 0xDC00 && units[i + 1] <= 0xDFFF
54
+ codepoints << (((c - 0xD800) << 10) + (units[i + 1] - 0xDC00) + 0x10000)
55
+ i += 2
56
+ else
57
+ codepoints << (c >= 0xD800 && c <= 0xDFFF ? 0xFFFD : c)
58
+ i += 1
59
+ end
60
+ end
61
+ codepoints.pack("U*")
62
+ end
63
+
64
+ # The UTF-16 length of text, as Telegram counts it.
65
+ def self.length(text)
66
+ n = 0
67
+ text.codepoints.each { |c| n += c >= 0x10000 ? 2 : 1 }
68
+ n
69
+ end
70
+
71
+ # Telethon's within_surrogate: index falls between the halves of a surrogate pair.
72
+ def self.within_surrogate?(units, index)
73
+ index > 1 && index < units.size && units[index - 1] >= 0xD800 && units[index - 1] <= 0xDBFF &&
74
+ units[index] >= 0xD800 && units[index] <= 0xDFFF
75
+ end
76
+
77
+ def self.space?(unit)
78
+ SPACE.include?(unit)
79
+ end
80
+
81
+ # The units of units from start (Python's units[start:], empty past the end).
82
+ def self.from(units, start)
83
+ start >= units.size ? [] : units[start..]
84
+ end
85
+
86
+ # The index of needle in units at or after start, or nil (Python's str.find).
87
+ def self.find(units, needle, start)
88
+ last = units.size - needle.size
89
+ i = start
90
+ while i <= last
91
+ return i if starts_at?(units, i, needle)
92
+
93
+ i += 1
94
+ end
95
+ nil
96
+ end
97
+
98
+ def self.starts_at?(units, i, needle)
99
+ return false if i + needle.size > units.size
100
+
101
+ needle.each_with_index { |u, k| return false unless units[i + k] == u }
102
+ true
103
+ end
104
+
105
+ # Telethon's strip_text: strips whitespace from both ends, moving the entities with the text and
106
+ # dropping those left empty. Answers the stripped units; entities are changed in place.
107
+ def self.strip(units, entities)
108
+ left = 0
109
+ left += 1 while left < units.size && space?(units[left])
110
+ right = units.size
111
+ right -= 1 while right > left && space?(units[right - 1])
112
+ stripped = units[left...right]
113
+ return stripped if entities.empty?
114
+
115
+ final = stripped.size
116
+ i = entities.size - 1
117
+ while i >= 0
118
+ e = entities[i]
119
+ if e.length.zero?
120
+ entities.delete_at(i)
121
+ elsif e.offset + e.length > left
122
+ if e.offset >= left
123
+ e.offset -= left
124
+ else
125
+ e.length = e.offset + e.length - left
126
+ e.offset = 0
127
+ end
128
+ if e.offset + e.length > final
129
+ if e.offset >= final
130
+ entities.delete_at(i)
131
+ else
132
+ e.length = final - e.offset
133
+ end
134
+ end
135
+ else
136
+ entities.delete_at(i)
137
+ end
138
+ i -= 1
139
+ end
140
+ stripped
141
+ end
142
+
143
+ # The [at, i, markup] insertions of an unparse, sorted by (at, i) and stable as Python's sort.
144
+ def self.sorted_insertions(list)
145
+ out = []
146
+ list.each do |t|
147
+ k = out.size
148
+ k -= 1 while k.positive? && (out[k - 1][0] > t[0] || (out[k - 1][0] == t[0] && out[k - 1][1] > t[1]))
149
+ out.insert(k, t)
150
+ end
151
+ out
152
+ end
153
+
154
+ # Puts each markup into units, last first, as Telethon's unparse does; answers the String.
155
+ def self.insert_all(units, insertions)
156
+ until insertions.empty?
157
+ t = insertions.pop
158
+ at = t[0]
159
+ at += 1 while within_surrogate?(units, at)
160
+ units = units[0, at] + units(t[2]) + from(units, at)
161
+ end
162
+ string(units)
163
+ end
164
+
165
+ # Telethon's utils.get_inner_text: the text each entity covers.
166
+ def self.inner_text(text, entities)
167
+ units = units(text)
168
+ entities.map { |e| string(units[e["offset"], e["length"]] || []) }
169
+ end
170
+ end
171
+ end