phonomenal_client 0.10.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.
data/README.md ADDED
@@ -0,0 +1,532 @@
1
+ # Phonomenal Client
2
+
3
+ A Ruby client library for the Phonomenal API by Voiz Works. Provides a clean interface for managing campaigns, sessions, members, calls, leads, SIP configurations, voice messages, and reference data (languages/voices).
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'phonomenal_client'
11
+ ```
12
+
13
+ Then run:
14
+
15
+ ```
16
+ bundle install
17
+ ```
18
+
19
+ ## Quick Start
20
+
21
+ The client operates in one of two contexts: campaign or account. You must choose one when initializing.
22
+
23
+ ```ruby
24
+ # Campaign context
25
+ client = Phonomenal::Client.for_campaign("your_campaign_key")
26
+
27
+ # Account context
28
+ client = Phonomenal::Client.for_account("your_account_key")
29
+ ```
30
+
31
+ ## Authentication
32
+
33
+ All requests are authenticated via request headers:
34
+
35
+ - Campaign context: `X-Phonomenal-Campaign-Key`
36
+ - Account context: `X-Phonomenal-Account-Key`
37
+
38
+ ## Configuration
39
+
40
+ ### Base URL
41
+
42
+ The default base URL is `https://phonomenal.voizworks.com`. You can override it:
43
+
44
+ ```ruby
45
+ client = Phonomenal::Client.for_campaign("key", base_url: "https://staging.example.com")
46
+ ```
47
+
48
+ ### Block Syntax
49
+
50
+ Both factory methods have a `with_*` variant that yields the client to a block:
51
+
52
+ ```ruby
53
+ Phonomenal::Client.with_campaign("key") do |client|
54
+ client.sessions.list
55
+ end
56
+
57
+ Phonomenal::Client.with_account("key") do |client|
58
+ client.campaigns.list
59
+ end
60
+ ```
61
+
62
+ ### Request bodies and root keys
63
+
64
+ Most resources are thin wrappers around Rails controllers that call `params.require(:some_key)`,
65
+ so the hash you pass to `create`/`update` must be wrapped under that key — the client does **not**
66
+ add it for you. `leads` is the one exception: its `create`/`update` methods wrap the hash in `lead:`
67
+ internally, so you pass the fields directly. Each section below shows the exact shape expected.
68
+
69
+ ## Campaign Context
70
+
71
+ Use `Phonomenal::Client.for_campaign` to operate within a specific campaign.
72
+
73
+ ### Campaign
74
+
75
+ ```ruby
76
+ # Show campaign details
77
+ client.campaign.show
78
+
79
+ # Update campaign (body must be wrapped in `campaign:`)
80
+ client.campaign.update({ campaign: { name: "New Name" } })
81
+
82
+ # Clear all webhooks
83
+ client.campaign.clear_webhooks
84
+ ```
85
+
86
+ `campaign` update accepts any of the following keys (all optional):
87
+
88
+ | Key | Type | Notes |
89
+ |---|---|---|
90
+ | `name` | string | |
91
+ | `campaign_type` | string | one of `outbound`, `inbound`, `blended`, `streaming`, `predictive`, `automated_calling` |
92
+ | `retry_count` | integer | 0–8 |
93
+ | `dial_member_into_conference` | boolean | |
94
+ | `streaming_url` | string | must be a valid `ws://`/`wss://` URL |
95
+ | `outbound_start_url` | string | |
96
+ | `outbound_connect_url` | string | |
97
+ | `outbound_disconnect_url` | string | |
98
+ | `outbound_disposed_url` | string | |
99
+ | `outbound_end_url` | string | |
100
+ | `inbound_start_url` | string | |
101
+ | `inbound_connect_url` | string | |
102
+ | `inbound_disconnect_url` | string | |
103
+ | `inbound_disposed_url` | string | |
104
+ | `inbound_end_url` | string | |
105
+ | `leg_1_connect_url` | string | |
106
+ | `leg_1_failed_url` | string | |
107
+ | `leg_2_connect_url` | string | |
108
+ | `leg_2_failed_url` | string | |
109
+ | `member_conference_join_url` | string | |
110
+ | `member_conference_leave_url` | string | |
111
+ | `member_status_webhook_url` | string | |
112
+ | `allow_inbound` | boolean | |
113
+ | `route_inbound_to_number` | string | `+91XXXXXXXXXX` format |
114
+ | `play_ivr_menu` | boolean | |
115
+ | `ivr_welcome_message` | string | |
116
+ | `voice_message_requires_input` | boolean | whether the automated voice message waits for a DTMF response |
117
+ | `user_inputs` | string | digit-to-disposition mapping, one per line: `1 = Confirm` |
118
+ | `pacing_ratio` | decimal | 1–5 |
119
+ | `predictive_max_retries` | integer | 1–100 |
120
+ | `paused` | boolean | |
121
+ | `use_sticky_agents` | boolean | |
122
+ | `use_fresh_rnr_ratio` | boolean | |
123
+ | `fresh_lead_priority` | decimal | 0.0–1.0 |
124
+
125
+ `client.campaign.show` and `client.campaign.update` both target `/api/v1/campaign` under the
126
+ campaign key currently in use.
127
+
128
+ ### Sessions
129
+
130
+ ```ruby
131
+ # List active sessions
132
+ client.sessions.list
133
+
134
+ # Create/reuse a session for a member (top-level fields, no root key)
135
+ client.sessions.create({ username: "1001", password: "secret" })
136
+ # or, using an extension explicitly:
137
+ client.sessions.create({ extension: "1001", password: "secret" })
138
+
139
+ # Delete (end) a session
140
+ client.sessions.destroy(session_id)
141
+
142
+ # Session actions
143
+ client.sessions.start_break(session_id)
144
+ client.sessions.end_break(session_id)
145
+ client.sessions.switch_to_manual(session_id)
146
+ client.sessions.switch_to_auto(session_id)
147
+
148
+ # Dispose the member's current call
149
+ client.sessions.dispose_call(session_id, {
150
+ disposition: "sale",
151
+ sub_disposition: "confirmed",
152
+ follow_up_at: "2026-04-01T10:00:00Z" # optional
153
+ })
154
+ ```
155
+
156
+ `create` looks up the member by `username`/`extension` + `password` and returns their existing
157
+ active session if one is already open, otherwise creates a new one.
158
+
159
+ > **Note:** `client.sessions.update(session_id, { ... })` exists on the client but the server's
160
+ > `SessionsController#update` does not currently look up or modify the session — it's a no-op.
161
+ > Don't rely on it to change session state.
162
+
163
+ ### Members
164
+
165
+ ```ruby
166
+ client.members.list
167
+ client.members.show(member_id)
168
+ client.members.create({ member: { full_name: "Agent Name", email: "agent@example.com", phone: "1234567890", password: "secret", member_group_id: 3 } })
169
+ client.members.update(member_id, { member: { full_name: "New Name" } })
170
+ client.members.activate(member_id)
171
+ client.members.deactivate(member_id)
172
+ ```
173
+
174
+ `member` accepts `full_name`, `email`, `phone`, `password`, `member_group_id`. `extension` is
175
+ assigned automatically and cannot be set.
176
+
177
+ ### SIP Configurations
178
+
179
+ ```ruby
180
+ client.sip_configs.list
181
+ client.sip_configs.show(sip_config_id)
182
+ client.sip_configs.create({ sip_config: { host: "sip.example.com", username: "user", password: "pass", did: "1234567890", use_did_as_user: false, dial_prefix: "0" } })
183
+ client.sip_configs.update(sip_config_id, { sip_config: { host: "sip2.example.com" } })
184
+ client.sip_configs.destroy(sip_config_id)
185
+ client.sip_configs.activate(sip_config_id)
186
+ client.sip_configs.deactivate(sip_config_id)
187
+
188
+ # Borrow a free global DID and turn it into a SIP config for this campaign.
189
+ # Note the explicit `nil` — `borrow` is a collection action, not a member action,
190
+ # so the first positional argument (normally an id) must be left blank.
191
+ client.sip_configs.borrow
192
+ client.sip_configs.borrow(nil, { did: "0791234567" }) # borrow a specific DID
193
+ ```
194
+
195
+ `sip_config` accepts `host`, `username`, `password`, `did`, `use_did_as_user`, `dial_prefix`.
196
+ `update` is rejected with an error if the SIP config was borrowed from the global DID pool.
197
+
198
+ ### Global DIDs
199
+
200
+ ```ruby
201
+ client.global_dids.list
202
+ client.global_dids.list(start_with: "079")
203
+ client.global_dids.list(end_with: "99")
204
+ ```
205
+
206
+ Lists free (unborrowed, non-retired) DIDs. Both filters are optional and can be combined.
207
+
208
+ ### Member Groups
209
+
210
+ ```ruby
211
+ client.member_groups.list
212
+ client.member_groups.show(group_id)
213
+ client.member_groups.create({ member_group: { label: "Team A", digit: 1 } })
214
+ client.member_groups.update(group_id, { member_group: { label: "Team B" } })
215
+ client.member_groups.destroy(group_id)
216
+ ```
217
+
218
+ `member_group` accepts `label` (unique per campaign) and `digit` (the IVR keypad digit routed to
219
+ this group, unique per campaign).
220
+
221
+ > **Note:** as currently implemented server-side, `MemberGroupsController#create` saves the
222
+ > record against the campaign's *members* association instead of its *member_groups* association,
223
+ > so `create` will error against a real server. `update`/`destroy`/`index`/`show` are unaffected.
224
+
225
+ ### Blacklist Phones
226
+
227
+ ```ruby
228
+ client.black_list_phones.list
229
+ client.black_list_phones.show(id)
230
+ client.black_list_phones.create({ black_list_phone: { phone: "1234567890", reason: "Repeated complaints" } })
231
+ client.black_list_phones.update(id, { black_list_phone: { reason: "Updated reason" } })
232
+ client.black_list_phones.destroy(id)
233
+ ```
234
+
235
+ `black_list_phone` accepts `phone` (unique per campaign) and `reason`.
236
+
237
+ ### Holidays
238
+
239
+ ```ruby
240
+ client.holidays.list
241
+ client.holidays.show(holiday_id)
242
+ client.holidays.create({ holiday: { year: 2026, holiday_date: "2026-01-01", reason: "New Year" } })
243
+ client.holidays.update(holiday_id, { holiday: { reason: "Updated reason" } })
244
+ client.holidays.destroy(holiday_id)
245
+ ```
246
+
247
+ `holiday` accepts `year`, `holiday_date` (unique per campaign), `reason`.
248
+
249
+ ### Inbound Schedule Entries
250
+
251
+ ```ruby
252
+ client.inbound_schedule_entries.list
253
+ client.inbound_schedule_entries.show(entry_id)
254
+ client.inbound_schedule_entries.create({ inbound_schedule_entry: { day: "monday", start_hour: 9, start_minutes: 0, end_hour: 18, end_minutes: 0, is_holiday: false } })
255
+ client.inbound_schedule_entries.update(entry_id, { inbound_schedule_entry: { end_hour: 20 } })
256
+ client.inbound_schedule_entries.destroy(entry_id)
257
+ ```
258
+
259
+ `inbound_schedule_entry` accepts:
260
+
261
+ | Key | Type | Notes |
262
+ |---|---|---|
263
+ | `day` | string | one of `global`, `sunday`, `monday`, `tuesday`, `wednesday`, `thursday`, `friday`, `saturday`; unique per campaign |
264
+ | `start_hour` | integer | |
265
+ | `start_minutes` | integer | |
266
+ | `end_hour` | integer | |
267
+ | `end_minutes` | integer | |
268
+ | `is_holiday` | boolean | marks this entry as covering holiday hours |
269
+
270
+ ### Voice Messages
271
+
272
+ Per-language automated voice messages for a campaign (`is_default` marks the fallback message
273
+ used when a lead's language doesn't match any configured message; setting it unsets any other
274
+ default for the same campaign).
275
+
276
+ ```ruby
277
+ client.voice_messages.list
278
+ client.voice_messages.create({ voice_message: { language_name: "en", message_text: "Hello, this is a reminder.", is_default: true } })
279
+ client.voice_messages.update(voice_message_id, { voice_message: { message_text: "Updated message." } })
280
+ ```
281
+
282
+ `voice_message` accepts:
283
+
284
+ | Key | Type | Notes |
285
+ |---|---|---|
286
+ | `language_name` | string | ISO 639-1 code (see [Languages](#languages)), required |
287
+ | `message_text` | string | required; supports `{{full_name}}` and `{{custom_data['EMI']}}` personalization tokens, with defaults for blank values: `{{ full_name \| default: "there" }}` |
288
+ | `is_default` | boolean | |
289
+ | `voice_id` | string | a voice `id` from [Voices](#voices); blank picks a female Indian voice for the language |
290
+
291
+ Saving a message generates its audio in the background — the message itself, or a sample read
292
+ with the default values when it's personalized. Each message reports `audio_status`
293
+ (`pending`, `generating`, `ready`, `failed`), `audio_error`, `audio_duration_seconds` and
294
+ `audio_generated_at`, and the campaign's `voice_message_webhook_url` (see Campaign) is POSTed
295
+ when generation finishes:
296
+
297
+ ```json
298
+ { "event": "voice_message.audio_generated", "campaign_token": "...", "voice_message": { "id": 1, "audio_status": "ready", "...": "..." } }
299
+ ```
300
+
301
+ The audio itself:
302
+
303
+ ```ruby
304
+ audio = client.voice_messages.audio(voice_message_id) # the generated audio (404 until ready)
305
+ audio = client.voice_messages.preview(voice_message_id, lead: { full_name: "Asha", custom_data: { "EMI" => "Rs. 500" } })
306
+
307
+ audio.success? # => true
308
+ audio.content_type # => "audio/wav"
309
+ audio.body # => the WAV's bytes
310
+ audio.text # => "Hi Asha, your EMI of Rs. 500 is due" (previews)
311
+ ```
312
+
313
+ The campaign's own voice message (what calls fall back to without a matching or
314
+ default voice message) has audio too. Its state is in `client.campaign.show`'s
315
+ `voice_message_audio`, and the webhook gets `event: "campaign.voice_message_audio_generated"`.
316
+
317
+ ```ruby
318
+ audio = client.campaign.voice_message_audio # 404 until ready
319
+ audio = client.campaign.voice_message_preview(lead: { full_name: "Asha" })
320
+ ```
321
+
322
+ > **Note:** the client also exposes `client.voice_messages.show(id)` and
323
+ > `client.voice_messages.destroy(id)`, but the server currently only routes
324
+ > `index`/`create`/`update` for this resource — `show` and `destroy` will 404.
325
+
326
+ ### IVR menus
327
+
328
+ The campaign's IVR goes three levels deep: main menu > sub menu > sub sub menu. A
329
+ digit routes to a member tag or group, or opens a deeper menu. In a sub menu callers
330
+ press `*` for the previous menu and `0` for the main menu (on the main menu, `0`
331
+ repeats it). Digits the main menu already gives member groups and tags are listed
332
+ in `taken_digits`.
333
+
334
+ ```ruby
335
+ client.campaign.ivr.json["ivr"] # play_ivr_menu, welcome_message, taken_digits, options, menus
336
+
337
+ client.campaign.update_ivr(
338
+ play_ivr_menu: true,
339
+ welcome_message: "Welcome to Acme.",
340
+ options: [{ digit: 2, member_tag_id: 7 }],
341
+ menus: [
342
+ { digit: 3, label: "Support", message: "Support.",
343
+ options: [{ digit: 1, member_tag_id: 8 }],
344
+ menus: [{ digit: 2, label: "Billing", options: [{ digit: 1, member_group_id: 4 }] }] }
345
+ ]
346
+ )
347
+ # Replaces the whole tree; nothing changes if any part is invalid (422, "errors")
348
+ ```
349
+
350
+ ### Calls
351
+
352
+ ```ruby
353
+ # Create a call
354
+ client.calls.create({
355
+ to: "1234567890",
356
+ from: "0987654321", # only used when there's no session context
357
+ start_url: "https://example.com/start",
358
+ connect_url: "https://example.com/connect",
359
+ disconnect_url: "https://example.com/disconnect",
360
+ end_url: "https://example.com/end",
361
+ timeout: 30,
362
+ custom_id: "external-ref-123"
363
+ })
364
+
365
+ # Create a call within a specific session (dials the member's softphone/conference instead)
366
+ client.calls.create({ to: "1234567890" }, session_id: 42)
367
+ ```
368
+
369
+ All body fields are optional except `to`. When `session_id` is passed, the call is placed to the
370
+ member's extension (or into the conference, if the campaign has
371
+ `dial_member_into_conference` set) rather than to `from`.
372
+
373
+ ### Leads
374
+
375
+ ```ruby
376
+ # List leads (supports pagination and filtering)
377
+ client.leads.list
378
+ client.leads.list(filter: "blocked") # one of: blocked, follow_up, bumped
379
+
380
+ # Create and update (fields are passed directly; the client wraps them in `lead:` for you)
381
+ client.leads.create({ full_name: "Jane Doe", phone: "1234567890", custom_unique_reference: "ext-1", email: "jane@example.com", custom_data: { plan: "gold" } })
382
+ client.leads.update(lead_id, { full_name: "Jane Smith" })
383
+
384
+ # State changes
385
+ client.leads.block(lead_id)
386
+ client.leads.restore(lead_id) # `unblock` is an alias of this
387
+ client.leads.unbump(lead_id)
388
+ client.leads.unset_follow_up(lead_id)
389
+
390
+ # Prioritise a lead in the dialling queue
391
+ client.leads.bump(lead_id) # due immediately
392
+ client.leads.bump(lead_id, bump_at: "2026-04-01T10:00:00Z") # due at that time
393
+
394
+ # Assignment and scheduling
395
+ client.leads.assign(lead_id, "agent@example.com")
396
+ client.leads.unassign(lead_id)
397
+ client.leads.unassign_all("agent@example.com") # clears that agent's whole book
398
+ client.leads.set_follow_up(lead_id, "2026-04-01T10:00:00Z")
399
+ ```
400
+
401
+ `unassign_all` is a collection call: it takes an agent's email rather than a lead id and
402
+ clears `member` on every lead that agent currently holds. It returns a count instead of a
403
+ lead, and 404s if no member in the campaign has that email:
404
+
405
+ ```ruby
406
+ response = client.leads.unassign_all("agent@example.com")
407
+ response.success? # => true
408
+ response.body["unassigned_count"] # => 37, or 0 if they held nothing
409
+ ```
410
+
411
+ Reach for it when an agent leaves or moves queue. Deactivating a member already releases
412
+ their leads; this clears them without deactivating. On a campaign using sticky agents the
413
+ released leads become unowned and return to the pool every free agent can draw from.
414
+
415
+ `bump_at` is when the lead becomes *due* for priority rather than a record of when the bump
416
+ was made, so a future time schedules the bump instead of applying it now. Omit it to bump
417
+ from the current time.
418
+
419
+ `lead` accepts `custom_unique_reference`, `full_name`, `email`, `phone`, `member_email`,
420
+ `follow_up_at`, `custom_data` (a free-form hash).
421
+
422
+ > **Changed in 0.6.0:** `unblock` and `set_follow_up` used to POST to `/leads/:id/unblock`
423
+ > and `/leads/:id/set_follow_up`, neither of which is a route on the server, so both always
424
+ > 404'd. They now reach `restore` and `follow_up` respectively. `reset` has been removed —
425
+ > the server has never had a `reset` route.
426
+ >
427
+ > The server also exposes bulk endpoints (`POST /leads/bulk/create`, `PATCH /leads/bulk/update`,
428
+ > `DELETE /leads/bulk/remove`) that the client does not currently wrap.
429
+
430
+ ## Account Context
431
+
432
+ Use `Phonomenal::Client.for_account` to manage resources at the account level.
433
+
434
+ ### Campaigns
435
+
436
+ ```ruby
437
+ client.campaigns.list
438
+ client.campaigns.show(campaign_id)
439
+ client.campaigns.create({ campaign: { name: "New Campaign", campaign_type: "outbound" } })
440
+ client.campaigns.update(campaign_id, { campaign: { name: "Updated Name" } })
441
+ client.campaigns.destroy(campaign_id)
442
+ ```
443
+
444
+ `campaign` accepts the same fields as [Campaign](#campaign) above, plus `name` and
445
+ `campaign_type` are required on `create`.
446
+
447
+ > The server also supports `POST /campaigns/:id/activate` and `.../deactivate`, but the client
448
+ > doesn't currently expose `activate`/`deactivate` for the account-level `campaigns` resource
449
+ > (unlike `members` and `sip_configs`, which do).
450
+
451
+ ### Languages
452
+
453
+ ```ruby
454
+ client.languages.list
455
+ ```
456
+
457
+ Read-only reference list of all supported languages (no parameters). Each entry has:
458
+
459
+ | Key | Notes |
460
+ |---|---|
461
+ | `iso_639_1` | 2-letter code, e.g. `"en"` — this is the value to use for `language_name` on voice messages |
462
+ | `iso_639_2` | 3-letter code |
463
+ | `name` | English name, e.g. `"English"` |
464
+ | `native_name` | Name in the language itself |
465
+ | `family` | Language family, e.g. `"Indo-European"` |
466
+ | `label` | Same as `name`; kept for display convenience |
467
+
468
+ ### Voices
469
+
470
+ ```ruby
471
+ client.voices.list
472
+ ```
473
+
474
+ Read-only reference list of available text-to-speech voices (no parameters). Each entry has:
475
+
476
+ | Key | Notes |
477
+ |---|---|
478
+ | `id` | Opaque identifier (`locale:gender:name`) usable wherever a voice id is expected |
479
+ | `name` | Voice name, e.g. `"Neerja"` |
480
+ | `gender` | `"Male"` or `"Female"` |
481
+ | `locale` | e.g. `"en-IN"` |
482
+ | `short_name` | Azure short name, e.g. `"en-IN-NeerjaNeural"` |
483
+ | `label` | Human-readable summary, e.g. `"Neerja (Female, en-IN)"` |
484
+
485
+ ## Response Object
486
+
487
+ All API calls return a `Phonomenal::Response` object.
488
+
489
+ ```ruby
490
+ response = client.sessions.list
491
+
492
+ # Access parsed JSON body
493
+ response.json
494
+
495
+ # Check if request succeeded (HTTP 200 and success: true in body)
496
+ response.success?
497
+
498
+ # Access the underlying HTTParty response for anything else (status code, headers, etc.)
499
+ response.http_response
500
+ response.http_response.code
501
+ response.http_response.headers
502
+ ```
503
+
504
+ > **Note:** `Phonomenal::Response` attempts to delegate unknown methods (like `.code` or
505
+ > `.headers` called directly on the response) to `http_response` via `method_missing`, but the
506
+ > method is currently misspelled (`method_messing`), so that delegation never fires. Call
507
+ > `.http_response.code` / `.http_response.headers` explicitly, as shown above, rather than
508
+ > `.code` / `.headers` directly on the response.
509
+
510
+ ## Error Handling
511
+
512
+ ```ruby
513
+ begin
514
+ client = Phonomenal::Client.new(campaign_key: "a", account_key: "b")
515
+ rescue ArgumentError => e
516
+ puts e.message # "Provide either campaign_key or account_key, not both"
517
+ end
518
+
519
+ response = client.leads.create({ ... })
520
+ unless response.success?
521
+ puts "Request failed: #{response.json}"
522
+ end
523
+ ```
524
+
525
+ ## Requirements
526
+
527
+ - Ruby >= 3.0.0
528
+ - [httparty](https://github.com/jnunemaker/httparty)
529
+
530
+ ## License
531
+
532
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Phonomenal
4
+ # :nodoc:
5
+ module AccountContext
6
+ def campaigns
7
+ @campaigns ||= Phonomenal::ApiHandler.new(
8
+ client: self,
9
+ path: "campaigns",
10
+ allowed_methods: %i[index create update destroy show],
11
+ singular: false
12
+ )
13
+ end
14
+
15
+ def languages
16
+ @languages ||= Phonomenal::ApiHandler.new(
17
+ client: self,
18
+ path: "languages",
19
+ allowed_methods: %i[index],
20
+ singular: false
21
+ )
22
+ end
23
+
24
+ def voices
25
+ @voices ||= Phonomenal::ApiHandler.new(
26
+ client: self,
27
+ path: "voices",
28
+ allowed_methods: %i[index],
29
+ singular: false
30
+ )
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,90 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "phonomenal/response"
4
+ require "phonomenal/audio_response"
5
+
6
+ module Phonomenal
7
+ class ApiHandler # rubocop:disable Style/Documentation
8
+ attr_reader :client, :path, :allowed_methods, :singular
9
+
10
+ def initialize(client:, path:, allowed_methods:, singular:)
11
+ @client = client
12
+ @path = path
13
+ @allowed_methods = Set.new(allowed_methods)
14
+ @singular = singular
15
+
16
+ prepare_methods!
17
+ end
18
+
19
+ def url_for(...)
20
+ client.url_for(...)
21
+ end
22
+
23
+ def prepare_response(http_response)
24
+ Phonomenal::Response.new(http_response)
25
+ end
26
+
27
+ # Just assume all the methods are on members
28
+ def add_method!(method_name:, method: :post, url_path: nil)
29
+ singleton_class.define_method(method_name) do |id = nil, data = nil|
30
+ args = if data.nil?
31
+ {}
32
+ else
33
+ method == :post ? { body: data.to_json } : { query: data }
34
+ end
35
+
36
+ # URL
37
+ url = url_for([path, (singular ? nil : id), url_path || method_name].compact.join("/"))
38
+
39
+ prepare_response client.send(method, url, **args)
40
+ end
41
+ end
42
+
43
+ def prepare_methods! # rubocop:disable Metrics/AbcSize,Metrics/CyclomaticComplexity,Metrics/MethodLength,Metrics/PerceivedComplexity
44
+ if allowed_methods.include?(:index)
45
+ singleton_class.define_method(:list) do |**args|
46
+ prepare_response client.get(url_for(path), query: args)
47
+ end
48
+ end
49
+
50
+ if allowed_methods.include?(:create)
51
+ singleton_class.define_method(:create) do |body|
52
+ prepare_response client.post(url_for(path), body: body.to_json)
53
+ end
54
+ end
55
+
56
+ if allowed_methods.include?(:update)
57
+ singleton_class.define_method(:update) do |*args|
58
+ body = singular ? args.first : args.last
59
+ url = singular ? path : "#{path}/#{args.first}"
60
+
61
+ prepare_response client.patch(url_for(url), body: body.to_json)
62
+ end
63
+ end
64
+
65
+ if allowed_methods.include?(:destroy)
66
+ singleton_class.define_method(:destroy) do |id|
67
+ prepare_response client.delete(url_for("#{path}/#{id}"))
68
+ end
69
+ end
70
+
71
+ if allowed_methods.include?(:activate)
72
+ singleton_class.define_method(:activate) do |id|
73
+ prepare_response client.post(url_for("#{path}/#{id}/activate"))
74
+ end
75
+ end
76
+
77
+ if allowed_methods.include?(:deactivate)
78
+ singleton_class.define_method(:deactivate) do |id|
79
+ prepare_response client.post(url_for("#{path}/#{id}/deactivate"))
80
+ end
81
+ end
82
+
83
+ return unless allowed_methods.include?(:show)
84
+
85
+ singleton_class.define_method(:show) do |*args|
86
+ prepare_response client.get(url_for(singular ? path : "#{path}/#{args.first}"))
87
+ end
88
+ end
89
+ end
90
+ end
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Phonomenal
4
+ # An endpoint that answers with audio rather than JSON (voice message audio
5
+ # and previews). On success `body` is the file's bytes; on failure `json` has
6
+ # the server's error.
7
+ AudioResponse = Struct.new(:http_response) do
8
+ def success?
9
+ http_response.code == 200 && content_type.to_s.start_with?("audio/")
10
+ end
11
+
12
+ def body
13
+ http_response.body
14
+ end
15
+
16
+ def content_type
17
+ http_response.headers["content-type"].to_s.split(";").first
18
+ end
19
+
20
+ # The text the audio reads, for previews
21
+ def text
22
+ value = http_response.headers["x-voice-message-text"]
23
+ value && URI.decode_www_form_component(value)
24
+ end
25
+
26
+ def json
27
+ JSON.parse(body.to_s)
28
+ rescue JSON::ParserError
29
+ {}
30
+ end
31
+ end
32
+ end