1# frozen_string_literal: true
2
3require "ruby-bandwidth-iris"
4Faraday.default_adapter = :em_synchrony
5
6require "cbor"
7require "countries"
8
9require_relative "area_code_repo"
10require_relative "form_template"
11
12class TelSelections
13 THIRTY_DAYS = 60 * 60 * 24 * 30
14
15 def initialize(redis: REDIS, db: DB, memcache: MEMCACHE)
16 @redis = redis
17 @memcache = memcache
18 @db = db
19 end
20
21 def set(jid, tel)
22 @redis.setex("pending_tel_for-#{jid}", THIRTY_DAYS, tel)
23 end
24
25 def delete(jid)
26 @redis.del("pending_tel_for-#{jid}")
27 end
28
29 def [](jid)
30 @redis.get("pending_tel_for-#{jid}").then do |tel|
31 tel ? HaveTel.new(tel) : ChooseTel.new(db: @db, memcache: @memcache)
32 end
33 end
34
35 class HaveTel
36 def initialize(tel)
37 @tel = tel
38 end
39
40 def choose_tel
41 EMPromise.resolve(@tel)
42 end
43 end
44
45 class ChooseTel
46 def initialize(db: DB, memcache: MEMCACHE)
47 @db = db
48 @memcache = memcache
49 end
50
51 def choose_tel(error: nil)
52 Command.reply { |reply|
53 reply.allowed_actions = [:next]
54 reply.command << FormTemplate.render("tn_search", error: error)
55 }.then do |iq|
56 available = AvailableNumber.for(iq.form, db: @db, memcache: @memcache)
57 next available if available.is_a?(String)
58
59 choose_from_list(available.tns)
60 rescue StandardError
61 choose_tel(error: $!.to_s)
62 end
63 end
64
65 def choose_from_list(tns)
66 raise "No numbers found, try another search." if tns.empty?
67
68 Command.reply { |reply|
69 reply.allowed_actions = [:next, :prev]
70 reply.command << FormTemplate.render("tn_list", tns: tns)
71 }.then { |iq|
72 tel = iq.form.field("tel")&.value
73 next choose_tel if iq.prev? || !tel
74
75 tel.to_s.strip
76 }
77 end
78
79 class AvailableNumber
80 def self.for(form, db: DB, memcache: MEMCACHE)
81 qs = form.field("q")&.value.to_s.strip
82 return qs if qs =~ /\A\+1\d{10}\Z/
83
84 q = Q.for(feelinglucky(qs, form), db: db, memcache: memcache)
85
86 new(
87 q.iris_query
88 .merge(enableTNDetail: true, LCA: false)
89 .merge(Quantity.for(form).iris_query),
90 fallback: q.fallback,
91 memcache: memcache
92 )
93 end
94
95 ACTION_FIELD = "http://jabber.org/protocol/commands#actions"
96
97 def self.feelinglucky(q, form)
98 return q unless q.empty?
99 return q unless form.field(ACTION_FIELD)&.value == "feelinglucky"
100
101 "810"
102 end
103
104 def initialize(iris_query, fallback: [], memcache: MEMCACHE)
105 @iris_query = iris_query
106 @fallback = fallback
107 @memcache = memcache
108 end
109
110 def tns
111 Command.log.debug("BandwidthIris::AvailableNumber.list", @iris_query)
112 unless (result = fetch_cache)
113 result = BandwidthIris::AvailableNumber.list(@iris_query)
114 end
115 return next_fallback if result.empty? && !@fallback.empty?
116
117 result.map { |tn| Tn.new(**tn) }
118 end
119
120 def next_fallback
121 @memcache.set(cache_key, CBOR.encode([]), 43200)
122 self.class.new(
123 @fallback.shift.iris_query.merge(
124 enableTNDetail: true, quantity: @iris_query[:quantity]
125 ),
126 fallback: @fallback,
127 memcache: @memcache
128 ).tns
129 end
130
131 def fetch_cache
132 promise = EMPromise.new
133 @memcache.get(cache_key, &promise.method(:fulfill))
134 result = promise.sync
135 result ? CBOR.decode(result) : nil
136 end
137
138 def cache_key
139 "BandwidthIris_#{@iris_query.to_a.flatten.join(',')}"
140 end
141
142 class Quantity
143 def self.for(form)
144 if form.field(ACTION_FIELD)&.value == "feelinglucky"
145 return Default.new
146 end
147
148 rsm_max = form.find(
149 "ns:set/ns:max",
150 ns: "http://jabber.org/protocol/rsm"
151 ).first
152 return new(rsm_max.content.to_i) if rsm_max
153
154 Default.new
155 end
156
157 def initialize(quantity)
158 @quantity = quantity
159 end
160
161 def iris_query
162 { quantity: @quantity }
163 end
164
165 # NOTE: Gajim sends back the whole list on submit, so big
166 # lists can cause issues
167 class Default
168 def iris_query
169 { quantity: 10 }
170 end
171 end
172 end
173 end
174
175 class Tn
176 attr_reader :tel
177
178 def initialize(full_number:, city:, state:, **)
179 @tel = "+1#{full_number}"
180 @locality = city
181 @region = state
182 end
183
184 def formatted_tel
185 @tel =~ /\A\+1(\d{3})(\d{3})(\d+)\Z/
186 "(#{$1}) #{$2}-#{$3}"
187 end
188
189 def option
190 op = Blather::Stanza::X::Field::Option.new(value: tel, label: to_s)
191 op << reference
192 op
193 end
194
195 def reference
196 Nokogiri::XML::Builder.new { |xml|
197 xml.reference(
198 xmlns: "urn:xmpp:reference:0",
199 begin: 0,
200 end: formatted_tel.length - 1,
201 type: "data",
202 uri: "tel:#{tel}"
203 )
204 }.doc.root
205 end
206
207 def to_s
208 "#{formatted_tel} (#{@locality}, #{@region})"
209 end
210 end
211
212 class Q
213 def self.register(regex, &block)
214 @queries ||= []
215 @queries << [regex, block]
216 end
217
218 def self.for(q, **kwa)
219 q = replace_region_names(q) unless q.start_with?("~")
220
221 @queries.each do |(regex, block)|
222 match_data = (q =~ regex)
223 return block.call($1 || $&, *$~.to_a[2..-1], **kwa) if match_data
224 end
225
226 raise "Format not recognized: #{q}"
227 end
228
229 def self.replace_region_names(query)
230 ISO3166::Country[:US].subdivisions.merge(
231 ISO3166::Country[:CA].subdivisions
232 ).reduce(query) do |q, (code, region)|
233 ([region.name] + Array(region.unofficial_names))
234 .reduce(q) do |r, name|
235 r.sub(/#{name}\s*(?!,)/i, code)
236 end
237 end
238 end
239
240 def initialize(q)
241 @q = q
242 end
243
244 def fallback
245 []
246 end
247
248 {
249 areaCode: [:AreaCode, /\A[2-9][0-9]{2}\Z/],
250 npaNxx: [:NpaNxx, /\A(?:[2-9][0-9]{2}){2}\Z/],
251 npaNxxx: [:NpaNxxx, /\A(?:[2-9][0-9]{2}){2}[0-9]\Z/],
252 zip: [:PostalCode, /\A\d{5}(?:-\d{4})?\Z/],
253 localVanity: [:LocalVanity, /\A~(.+)\Z/]
254 }.each do |k, args|
255 klass = const_set(
256 args[0],
257 Class.new(Q) {
258 define_method(:iris_query) do
259 { k => @q }
260 end
261 }
262 )
263
264 args[1..-1].each do |regex|
265 register(regex) { |q, **| klass.new(q) }
266 end
267 end
268
269 class State
270 Q.register(/\A[a-zA-Z]{2}\Z/, &method(:new))
271
272 STATE_MAP = {
273 "QC" => "PQ"
274 }.freeze
275
276 def initialize(state, **)
277 @state = STATE_MAP.fetch(state.upcase, state.upcase)
278 end
279
280 def fallback
281 []
282 end
283
284 def iris_query
285 { state: @state }
286 end
287
288 def to_s
289 @state
290 end
291 end
292
293 class CityState
294 Q.register(/\A([^,]+)\s*,\s*([a-zA-Z]{2})\Z/, &method(:new))
295
296 CITY_MAP = {
297 "ajax" => "Ajax-Pickering",
298 "kitchener" => "Kitchener-Waterloo",
299 "new york" => "New York City",
300 "pickering" => "Ajax-Pickering",
301 "sault ste marie" => "sault sainte marie",
302 "sault ste. marie" => "sault sainte marie",
303 "south durham" => "Durham",
304 "township of langley" => "Langley",
305 "waterloo" => "Kitchener-Waterloo",
306 "west durham" => "Durham"
307 }.freeze
308
309 def initialize(city, state, db: DB, memcache: MEMCACHE)
310 @city = CITY_MAP.fetch(city.downcase, city)
311 @state = State.new(state)
312 @db = db
313 @memcache = memcache
314 end
315
316 def fallback
317 LazyObject.new do
318 AreaCodeRepo.new(
319 db: @db,
320 geo_code_repo: GeoCodeRepo.new(memcache: @memcache)
321 ).find(to_s).sync.map { |area_code|
322 AreaCode.new(area_code)
323 }
324 end
325 end
326
327 def iris_query
328 @state.iris_query.merge(city: @city)
329 end
330
331 def to_s
332 "#{@city}, #{@state}"
333 end
334 end
335 end
336 end
337end