-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathclient.rb
More file actions
1250 lines (1089 loc) · 51.1 KB
/
client.rb
File metadata and controls
1250 lines (1089 loc) · 51.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# typed: strict
# frozen_string_literal: true
require 'open-uri'
require 'faraday'
require 'faraday/multipart'
require 'faraday/net_http_persistent'
require 'jwt'
require 'time'
require 'date'
require 'sorbet-runtime'
require 'stream-chat/channel'
require 'stream-chat/campaign'
require 'stream-chat/errors'
require 'stream-chat/stream_response'
require 'stream-chat/version'
require 'stream-chat/util'
require 'stream-chat/types'
require 'stream-chat/moderation'
require 'stream-chat/channel_batch_updater'
module StreamChat
DEFAULT_BLOCKLIST = 'profanity_en_2020_v1'
SOFT_DELETE = 'soft'
HARD_DELETE = 'hard'
class Client
extend T::Sig
DEFAULT_BASE_URL = 'https://chat.stream-io-api.com'
DEFAULT_TIMEOUT = 6.0
sig { returns(String) }
attr_reader :api_key
sig { returns(String) }
attr_reader :api_secret
sig { returns(Faraday::Connection) }
attr_reader :conn
sig { returns(Moderation) }
attr_reader :moderation
# initializes a Stream Chat API Client
#
# @param [string] api_key your application api_key
# @param [string] api_secret your application secret
# @param [float] timeout the timeout for the http requests
# @param [Hash] options extra options such as base_url
#
# @example initialized the client with a timeout setting
# StreamChat::Client.new('my_key', 'my_secret', 3.0)
#
sig { params(api_key: String, api_secret: String, timeout: T.nilable(T.any(Float, String)), options: T.untyped).void }
def initialize(api_key, api_secret, timeout = nil, **options)
raise ArgumentError, 'api_key and api_secret are required' if api_key.to_s.empty? || api_secret.to_s.empty?
@api_key = api_key
@api_secret = api_secret
@timeout = T.let(timeout&.to_f || DEFAULT_TIMEOUT, Float)
@auth_token = T.let(JWT.encode({ server: true }, @api_secret, 'HS256'), String)
@base_url = T.let(options[:base_url] || DEFAULT_BASE_URL, String)
conn = Faraday.new(@base_url) do |faraday|
faraday.options[:open_timeout] = @timeout
faraday.options[:timeout] = @timeout
faraday.request :multipart
faraday.adapter :net_http_persistent, pool_size: 5 do |http|
# AWS load balancer idle timeout is 60 secs, so let's make it 59
http.idle_timeout = 59
end
end
@conn = T.let(conn, Faraday::Connection)
@moderation = T.let(Moderation.new(self), Moderation)
end
# initializes a Stream Chat API Client from STREAM_KEY and STREAM_SECRET
# environmental variables. STREAM_CHAT_TIMEOUT and STREAM_CHAT_URL
# variables are optional.
# @param [StringKeyHash] options extra options
sig { params(options: T.untyped).returns(Client) }
def self.from_env(**options)
Client.new(ENV.fetch('STREAM_KEY'),
ENV.fetch('STREAM_SECRET'),
ENV.fetch('STREAM_CHAT_TIMEOUT', DEFAULT_TIMEOUT),
base_url: ENV.fetch('STREAM_CHAT_URL', DEFAULT_BASE_URL),
**options)
end
# Sets the underlying Faraday http client.
#
# @param [client] an instance of Faraday::Connection
sig { params(client: Faraday::Connection).void }
def set_http_client(client)
@conn = client
end
# Creates a JWT for a user.
#
# Stream uses JWT (JSON Web Tokens) to authenticate chat users, enabling them to login.
# Knowing whether a user is authorized to perform certain actions is managed
# separately via a role based permissions system.
# You can set an `exp` (expires at) or `iat` (issued at) claim as well.
sig { params(user_id: String, exp: T.nilable(Integer), iat: T.nilable(Integer)).returns(String) }
def create_token(user_id, exp = nil, iat = nil)
payload = { user_id: user_id }
payload['exp'] = exp unless exp.nil?
payload['iat'] = iat unless iat.nil?
JWT.encode(payload, @api_secret, 'HS256')
end
# Updates application settings.
sig { params(settings: T.untyped).returns(StreamChat::StreamResponse) }
def update_app_settings(**settings)
patch('app', data: settings)
end
# Returns application settings.
sig { returns(StreamChat::StreamResponse) }
def get_app_settings
get('app')
end
# Flags a message.
#
# Any user is allowed to flag a message. This triggers the message.flagged
# webhook event and adds the message to the inbox of your
# Stream Dashboard Chat Moderation view.
sig { params(id: String, options: T.untyped).returns(StreamChat::StreamResponse) }
def flag_message(id, **options)
payload = { target_message_id: id }.merge(options)
post('moderation/flag', data: payload)
end
# Unflags a message.
sig { params(id: String, options: T.untyped).returns(StreamChat::StreamResponse) }
def unflag_message(id, **options)
payload = { target_message_id: id }.merge(options)
post('moderation/unflag', data: payload)
end
# Queries message flags.
#
# If you prefer to build your own in app moderation dashboard, rather than use the Stream
# dashboard, then the query message flags endpoint lets you get flagged messages. Similar
# to other queries in Stream Chat, you can filter the flags using query operators.
sig { params(filter_conditions: StringKeyHash, options: T.untyped).returns(StreamChat::StreamResponse) }
def query_message_flags(filter_conditions, **options)
params = options.merge({
filter_conditions: filter_conditions
})
get('moderation/flags/message', params: { payload: params.to_json })
end
# Flags a user.
sig { params(id: String, options: T.untyped).returns(StreamChat::StreamResponse) }
def flag_user(id, **options)
payload = { target_user_id: id }.merge(options)
post('moderation/flag', data: payload)
end
# Unflags a user.
sig { params(id: String, options: T.untyped).returns(StreamChat::StreamResponse) }
def unflag_user(id, **options)
payload = { target_user_id: id }.merge(options)
post('moderation/unflag', data: payload)
end
# Queries flag reports.
sig { params(options: T.untyped).returns(StreamChat::StreamResponse) }
def query_flag_reports(**options)
data = { filter_conditions: options }
post('moderation/reports', data: data)
end
# Sends a flag report review.
sig { params(report_id: String, review_result: String, user_id: String, details: T.untyped).returns(StreamChat::StreamResponse) }
def review_flag_report(report_id, review_result, user_id, **details)
data = {
review_result: review_result,
user_id: user_id,
review_details: details
}
patch("moderation/reports/#{report_id}", data: data)
end
# Returns a message.
sig { params(id: String, options: T.untyped).returns(StreamChat::StreamResponse) }
def get_message(id, **options)
get("messages/#{id}", params: options)
end
# Searches for messages.
#
# You can enable and/or disable the search indexing on a per channel basis
# type through the Stream Dashboard.
sig { params(filter_conditions: StringKeyHash, query: T.any(String, StringKeyHash), sort: T.nilable(T::Hash[String, Integer]), options: T.untyped).returns(StreamChat::StreamResponse) }
def search(filter_conditions, query, sort: nil, **options)
offset = T.cast(options[:offset], T.nilable(Integer))
next_value = options[:next]
raise ArgumentError, 'cannot use offset with next or sort parameters' if offset&.positive? && (next_value || (!sort.nil? && !sort.empty?))
to_merge = {
filter_conditions: filter_conditions,
sort: StreamChat.get_sort_fields(sort)
}
if query.is_a? String
to_merge[:query] = query
else
to_merge[:message_filter_conditions] = query
end
get('search', params: { payload: options.merge(to_merge).to_json })
end
# @deprecated Use {#upsert_users} instead.
sig { params(users: T::Array[StringKeyHash]).returns(StreamChat::StreamResponse) }
def update_users(users)
warn '[DEPRECATION] `update_users` is deprecated. Please use `upsert_users` instead.'
upsert_users(users)
end
# @deprecated Use {#upsert_user} instead.
sig { params(user: StringKeyHash).returns(StreamChat::StreamResponse) }
def update_user(user)
warn '[DEPRECATION] `update_user` is deprecated. Please use `upsert_user` instead.'
upsert_user(user)
end
# Creates or updates users.
sig { params(users: T::Array[StringKeyHash]).returns(StreamChat::StreamResponse) }
def upsert_users(users)
payload = {}
users.each do |user|
id = user[:id] || user['id']
raise ArgumentError, 'user must have an id' unless id
payload[id] = user
end
post('users', data: { users: payload })
end
# Creates or updates a user.
sig { params(user: StringKeyHash).returns(StreamChat::StreamResponse) }
def upsert_user(user)
upsert_users([user])
end
# Updates multiple users partially.
sig { params(updates: T::Array[StringKeyHash]).returns(StreamChat::StreamResponse) }
def update_users_partial(updates)
patch('users', data: { users: updates })
end
# Updates a single user partially.
sig { params(update: StringKeyHash).returns(StreamChat::StreamResponse) }
def update_user_partial(update)
update_users_partial([update])
end
# Deletes a user synchronously.
sig { params(user_id: String, options: T.untyped).returns(StreamChat::StreamResponse) }
def delete_user(user_id, **options)
delete("users/#{user_id}", params: options)
end
# Restores a user synchronously.
sig { params(user_id: String).returns(StreamChat::StreamResponse) }
def restore_user(user_id)
post('users/restore', data: { user_ids: [user_id] })
end
# Restores users synchronously.
sig { params(user_ids: T::Array[String]).returns(StreamChat::StreamResponse) }
def restore_users(user_ids)
post('users/restore', data: { user_ids: user_ids })
end
# Deactivates a user.
# Deactivated users cannot connect to Stream Chat, and can't send or receive messages.
# To reactivate a user, use `reactivate_user` method.
sig { params(user_id: String, options: T.untyped).returns(StreamChat::StreamResponse) }
def deactivate_user(user_id, **options)
post("users/#{user_id}/deactivate", params: options)
end
# Deactivates a users
sig { params(user_ids: T::Array[String], options: T.untyped).returns(StreamChat::StreamResponse) }
def deactivate_users(user_ids, **options)
raise ArgumentError, 'user_ids should not be empty' if user_ids.empty?
post('users/deactivate', data: { user_ids: user_ids, **options })
end
# Reactivates a deactivated user. Use deactivate_user to deactivate a user.
sig { params(user_id: String, options: T.untyped).returns(StreamChat::StreamResponse) }
def reactivate_user(user_id, **options)
post("users/#{user_id}/reactivate", params: options)
end
# Exports a user. It exports a user and returns an object
# containing all of it's data.
sig { params(user_id: String, options: T.untyped).returns(StreamChat::StreamResponse) }
def export_user(user_id, **options)
get("users/#{user_id}/export", params: options)
end
# Bans a user. Users can be banned from an app entirely or from a channel.
# When a user is banned, they will not be allowed to post messages until the
# ban is removed or expired but will be able to connect to Chat and to channels as before.
# To unban a user, use `unban_user` method.
sig { params(target_id: String, options: T.untyped).returns(StreamChat::StreamResponse) }
def ban_user(target_id, **options)
payload = { target_user_id: target_id }.merge(options)
post('moderation/ban', data: payload)
end
# Unbans a user.
# To ban a user, use `ban_user` method.
sig { params(target_id: String, options: T.untyped).returns(StreamChat::StreamResponse) }
def unban_user(target_id, **options)
params = { target_user_id: target_id }.merge(options)
delete('moderation/ban', params: params)
end
# Shadow ban a user.
# When a user is shadow banned, they will still be allowed to post messages,
# but any message sent during the will only be visible to the messages author
# and invisible to other users of the App.
# To remove a shadow ban, use `remove_shadow_ban` method.
sig { params(target_id: String, options: T.untyped).returns(StreamChat::StreamResponse) }
def shadow_ban(target_id, **options)
payload = { target_user_id: target_id, shadow: true }.merge(options)
post('moderation/ban', data: payload)
end
# Removes a shadow ban of a user.
# To shadow ban a user, use `shadow_ban` method.
sig { params(target_id: String, options: T.untyped).returns(StreamChat::StreamResponse) }
def remove_shadow_ban(target_id, **options)
params = { target_user_id: target_id, shadow: true }.merge(options)
delete('moderation/ban', params: params)
end
# Mutes a user.
sig { params(target_id: String, user_id: String).returns(StreamChat::StreamResponse) }
def mute_user(target_id, user_id)
payload = { target_id: target_id, user_id: user_id }
post('moderation/mute', data: payload)
end
# Unmutes a user.
sig { params(target_id: String, user_id: String).returns(StreamChat::StreamResponse) }
def unmute_user(target_id, user_id)
payload = { target_id: target_id, user_id: user_id }
post('moderation/unmute', data: payload)
end
# Marks all messages as read for a user.
sig { params(user_id: String).returns(StreamChat::StreamResponse) }
def mark_all_read(user_id)
payload = { user: { id: user_id } }
post('channels/read', data: payload)
end
# Get unread count for a user.
sig { params(user_id: String).returns(StreamChat::StreamResponse) }
def unread_counts(user_id)
get('/unread', params: { user_id: user_id })
end
# Get unread counts for a batch of users.
sig { params(user_ids: T::Array[String]).returns(StreamChat::StreamResponse) }
def unread_counts_batch(user_ids)
post('/unread_batch', data: { user_ids: user_ids })
end
# Pins a message.
#
# Pinned messages allow users to highlight important messages, make announcements, or temporarily
# promote content. Pinning a message is, by default, restricted to certain user roles,
# but this is flexible. Each channel can have multiple pinned messages and these can be created
# or updated with or without an expiration.
sig { params(message_id: String, user_id: String, expiration: T.nilable(String)).returns(StreamChat::StreamResponse) }
def pin_message(message_id, user_id, expiration: nil)
updates = {
set: {
pinned: true,
pin_expires: expiration
}
}
update_message_partial(message_id, updates, user_id: user_id)
end
# Unpins a message.
sig { params(message_id: String, user_id: String).returns(StreamChat::StreamResponse) }
def unpin_message(message_id, user_id)
updates = {
set: {
pinned: false
}
}
update_message_partial(message_id, updates, user_id: user_id)
end
# commits a message.
sig { params(message_id: String).returns(StreamChat::StreamResponse) }
def commit_message(message_id)
post("messages/#{message_id}/commit")
end
# Updates a message. Fully overwrites a message.
# For partial update, use `update_message_partial` method.
sig { params(message: StringKeyHash).returns(StreamChat::StreamResponse) }
def update_message(message)
raise ArgumentError, 'message must have an id' unless message.key? 'id'
post("messages/#{message['id']}", data: { message: message })
end
# Updates a message partially.
# A partial update can be used to set and unset specific fields when
# it is necessary to retain additional data fields on the object. AKA a patch style update.
sig { params(message_id: String, updates: StringKeyHash, user_id: T.nilable(String), options: T.untyped).returns(StreamChat::StreamResponse) }
def update_message_partial(message_id, updates, user_id: nil, **options)
params = updates.merge(options)
params['user'] = { id: user_id } if user_id
put("messages/#{message_id}", data: params)
end
# Deletes a message.
sig { params(message_id: String, options: T.untyped).returns(StreamChat::StreamResponse) }
def delete_message(message_id, **options)
delete("messages/#{message_id}", params: options)
end
# Deletes a message with hard delete option.
sig { params(message_id: String).returns(StreamChat::StreamResponse) }
def hard_delete_message(message_id)
delete_message(message_id, hard: true)
end
# Deletes a message with delete_for_me option.
sig { params(message_id: String, user_id: String).returns(StreamChat::StreamResponse) }
def delete_message_for_me(message_id, user_id)
raise ArgumentError, 'user_id must not be empty for delete_for_me functionality' if user_id.to_s.empty?
delete_message(message_id, delete_for_me: true, deleted_by: user_id)
end
# Deletes a message with advanced options.
sig { params(message_id: String, hard: T.nilable(T::Boolean), delete_for_me: T.nilable(T::Boolean), user_id: T.nilable(String)).returns(StreamChat::StreamResponse) }
def delete_message_with_options(message_id, hard: nil, delete_for_me: nil, user_id: nil)
options = {}
options[:hard] = true if hard
if delete_for_me
raise ArgumentError, 'user_id must not be empty for delete_for_me functionality' if user_id.to_s.empty?
options[:delete_for_me] = true
options[:deleted_by] = user_id
end
delete_message(message_id, **options)
end
# Un-deletes a message.
sig { params(message_id: String, undeleted_by: String, options: T.untyped).returns(StreamChat::StreamResponse) }
def undelete_message(message_id, undeleted_by, **options)
payload = { undeleted_by: undeleted_by }.merge(options)
post("messages/#{message_id}/undelete", data: payload)
end
# Queries banned users.
#
# Banned users can be retrieved in different ways:
# 1) Using the dedicated query bans endpoint
# 2) User Search: you can add the banned:true condition to your search. Please note that
# this will only return users that were banned at the app-level and not the ones
# that were banned only on channels.
sig { params(filter_conditions: StringKeyHash, sort: T.nilable(T::Hash[String, Integer]), options: T.untyped).returns(StreamChat::StreamResponse) }
def query_banned_users(filter_conditions, sort: nil, **options)
params = options.merge({
filter_conditions: filter_conditions,
sort: StreamChat.get_sort_fields(sort)
})
get('query_banned_users', params: { payload: params.to_json })
end
# Queries future channel bans.
#
# Future channel bans are automatically applied when a user creates a new channel
# or adds a member to an existing channel.
sig { params(options: T.untyped).returns(StreamChat::StreamResponse) }
def query_future_channel_bans(**options)
get('query_future_channel_bans', params: { payload: options.to_json })
end
# Allows you to search for users and see if they are online/offline.
# You can filter and sort on the custom fields you've set for your user, the user id, and when the user was last active.
sig { params(filter_conditions: StringKeyHash, sort: T.nilable(T::Hash[String, Integer]), options: T.untyped).returns(StreamChat::StreamResponse) }
def query_users(filter_conditions, sort: nil, **options)
params = options.merge({
filter_conditions: filter_conditions,
sort: StreamChat.get_sort_fields(sort)
})
get('users', params: { payload: params.to_json })
end
# Queries channels.
#
# You can query channels based on built-in fields as well as any custom field you add to channels.
# Multiple filters can be combined using AND, OR logical operators, each filter can use its
# comparison (equality, inequality, greater than, greater or equal, etc.).
# You can find the complete list of supported operators in the query syntax section of the docs.
sig { params(filter_conditions: StringKeyHash, sort: T.nilable(T::Hash[String, Integer]), options: T.untyped).returns(StreamChat::StreamResponse) }
def query_channels(filter_conditions, sort: nil, **options)
data = { state: true, watch: false, presence: false }
data = data.merge(options).merge({
filter_conditions: filter_conditions,
sort: StreamChat.get_sort_fields(sort)
})
post('channels', data: data)
end
# Creates a new channel type.
sig { params(data: StringKeyHash).returns(StreamChat::StreamResponse) }
def create_channel_type(data)
data['commands'] = ['all'] unless data.key?('commands') || data['commands'].nil? || data['commands'].empty?
post('channeltypes', data: data)
end
# Returns a channel types.
sig { params(channel_type: String).returns(StreamChat::StreamResponse) }
def get_channel_type(channel_type)
get("channeltypes/#{channel_type}")
end
# Returns a list of channel types.
sig { returns(StreamChat::StreamResponse) }
def list_channel_types
get('channeltypes')
end
# Updates a channel type.
sig { params(channel_type: String, options: T.untyped).returns(StreamChat::StreamResponse) }
def update_channel_type(channel_type, **options)
put("channeltypes/#{channel_type}", data: options)
end
# Deletes a channel type.
sig { params(channel_type: String).returns(StreamChat::StreamResponse) }
def delete_channel_type(channel_type)
delete("channeltypes/#{channel_type}")
end
# Creates a channel instance
#
# @param [string] channel_type the channel type
# @param [string] channel_id the channel identifier
# @param [StringKeyHash] data additional channel data
#
# @return [StreamChat::Channel]
#
sig { params(channel_type: String, channel_id: T.nilable(String), data: T.nilable(StringKeyHash)).returns(StreamChat::Channel) }
def channel(channel_type, channel_id: nil, data: nil)
StreamChat::Channel.new(self, channel_type, channel_id, data)
end
# Creates a campaign instance
#
# @param [String, nil] campaign_id the campaign identifier
# @param [StringKeyHash, nil] data additional campaign data
#
# @return [StreamChat::Campaign]
#
sig { params(campaign_id: T.nilable(String), data: T.nilable(StringKeyHash)).returns(StreamChat::Campaign) }
def campaign(campaign_id: nil, data: nil)
StreamChat::Campaign.new(self, campaign_id, data)
end
# Creates a campaign.
#
# @param [String, nil] campaign_id Optional campaign ID
# @param [StringKeyHash, nil] data Campaign data including message_template, sender_id, segment_ids or user_ids, etc.
# @return [StreamChat::StreamResponse] API response
sig { params(campaign_id: T.nilable(String), data: T.nilable(StringKeyHash)).returns(StreamChat::StreamResponse) }
def create_campaign(campaign_id: nil, data: nil)
payload = {}
payload['id'] = campaign_id if campaign_id
payload.merge!(data) if data
post('campaigns', data: payload)
end
# Gets a campaign by ID.
#
# @param [String] campaign_id The campaign ID
# @return [StreamChat::StreamResponse] API response
sig { params(campaign_id: String).returns(StreamChat::StreamResponse) }
def get_campaign(campaign_id)
get("campaigns/#{campaign_id}")
end
# Updates a campaign.
#
# @param [String] campaign_id The campaign ID
# @param [StringKeyHash] data Campaign data to update
# @return [StreamChat::StreamResponse] API response
sig { params(campaign_id: String, data: StringKeyHash).returns(StreamChat::StreamResponse) }
def update_campaign(campaign_id, data)
put("campaigns/#{campaign_id}", data: data)
end
# Deletes a campaign.
#
# @param [String] campaign_id The campaign ID
# @param [Hash] options Optional deletion options (e.g., gdpr: true)
# @return [StreamChat::StreamResponse] API response
sig { params(campaign_id: String, options: T.untyped).returns(StreamChat::StreamResponse) }
def delete_campaign(campaign_id, **options)
delete("campaigns/#{campaign_id}", params: options)
end
# Starts a campaign.
#
# @param [String] campaign_id The campaign ID
# @param [DateTime, Time, String, nil] scheduled_for Optional scheduled start time
# @param [DateTime, Time, String, nil] stop_at Optional scheduled stop time
# @return [StreamChat::StreamResponse] API response
sig { params(campaign_id: String, scheduled_for: T.nilable(T.any(DateTime, Time, String)), stop_at: T.nilable(T.any(DateTime, Time, String))).returns(StreamChat::StreamResponse) }
def start_campaign(campaign_id, scheduled_for: nil, stop_at: nil)
payload = {}
payload['scheduled_for'] = StreamChat.normalize_timestamp(scheduled_for) if scheduled_for
payload['stop_at'] = StreamChat.normalize_timestamp(stop_at) if stop_at
post("campaigns/#{campaign_id}/start", data: payload)
end
# Stops a campaign.
#
# @param [String] campaign_id The campaign ID
# @return [StreamChat::StreamResponse] API response
sig { params(campaign_id: String).returns(StreamChat::StreamResponse) }
def stop_campaign(campaign_id)
post("campaigns/#{campaign_id}/stop")
end
# Queries campaigns.
#
# You can query campaigns based on built-in fields as well as any custom field you add to campaigns.
# Multiple filters can be combined using AND, OR logical operators, each filter can use its
# comparison (equality, inequality, greater than, greater or equal, etc.).
# @param [StringKeyHash] filter_conditions Filter conditions for the query
# @param [Hash, nil] sort Optional sort parameters (e.g., { 'created_at' => -1 })
# @param [Hash] options Additional query options (limit, offset, etc.)
# @return [StreamChat::StreamResponse] API response
sig { params(filter_conditions: StringKeyHash, sort: T.nilable(T::Hash[String, Integer]), options: T.untyped).returns(StreamChat::StreamResponse) }
def query_campaigns(filter_conditions, sort: nil, **options)
data = options.merge({
filter: filter_conditions,
sort: StreamChat.get_sort_fields(sort)
})
post('campaigns/query', data: data)
end
# Adds a device to a user.
sig { params(device_id: String, push_provider: String, user_id: String, push_provider_name: T.nilable(String)).returns(StreamChat::StreamResponse) }
def add_device(device_id, push_provider, user_id, push_provider_name = nil)
post('devices', data: {
id: device_id,
push_provider: push_provider,
push_provider_name: push_provider_name,
user_id: user_id
})
end
# Delete a device.
sig { params(device_id: String, user_id: String).returns(StreamChat::StreamResponse) }
def delete_device(device_id, user_id)
delete('devices', params: { id: device_id, user_id: user_id })
end
# Returns a list of devices.
sig { params(user_id: String).returns(StreamChat::StreamResponse) }
def get_devices(user_id)
get('devices', params: { user_id: user_id })
end
# Get rate limit quotas and usage.
# If no params are toggled, all limits for all endpoints are returned.
sig { params(server_side: T::Boolean, android: T::Boolean, ios: T::Boolean, web: T::Boolean, endpoints: T::Array[String]).returns(StreamChat::StreamResponse) }
def get_rate_limits(server_side: false, android: false, ios: false, web: false, endpoints: [])
params = {}
params['server_side'] = server_side if server_side
params['android'] = android if android
params['ios'] = ios if ios
params['web'] = web if web
params['endpoints'] = endpoints.join(',') unless endpoints.empty?
get('rate_limits', params: params)
end
# Verify the signature added to a webhook event.
sig { params(request_body: String, x_signature: String).returns(T::Boolean) }
def verify_webhook(request_body, x_signature)
signature = OpenSSL::HMAC.hexdigest('SHA256', @api_secret, request_body)
signature == x_signature
end
# Allows you to send custom events to a connected user.
sig { params(user_id: String, event: StringKeyHash).returns(StreamChat::StreamResponse) }
def send_user_event(user_id, event)
post("users/#{user_id}/event", data: event)
end
# Translates an existing message to another language. The source language
# is inferred from the user language or detected automatically by analyzing its text.
# If possible it is recommended to store the user language. See the documentation.
sig { params(message_id: String, language: String).returns(StreamChat::StreamResponse) }
def translate_message(message_id, language)
post("messages/#{message_id}/translate", data: { language: language })
end
# Runs a message command action.
sig { params(message_id: String, data: StringKeyHash).returns(StreamChat::StreamResponse) }
def run_message_action(message_id, data)
post("messages/#{message_id}/action", data: data)
end
# Creates a guest user.
#
# Guest sessions can be created client-side and do not require any server-side authentication.
# Support and livestreams are common use cases for guests users because really
# often you want a visitor to be able to use chat on your application without (or before)
# they have a regular user account.
sig { params(user: StringKeyHash).returns(StreamChat::StreamResponse) }
def create_guest(user)
post('guests', data: user)
end
# Returns all blocklists.
#
# A Block List is a list of words that you can use to moderate chat messages. Stream Chat
# comes with a built-in Block List called profanity_en_2020_v1 which contains over a thousand
# of the most common profane words.
# You can manage your own block lists via the Stream dashboard or APIs to a manage
# blocklists and configure your channel types to use them.
sig { returns(StreamChat::StreamResponse) }
def list_blocklists
get('blocklists')
end
# Returns a blocklist.
#
# A Block List is a list of words that you can use to moderate chat messages. Stream Chat
# comes with a built-in Block List called profanity_en_2020_v1 which contains over a thousand
# of the most common profane words.
# You can manage your own block lists via the Stream dashboard or APIs to a manage
# blocklists and configure your channel types to use them.
sig { params(name: String).returns(StreamChat::StreamResponse) }
def get_blocklist(name)
get("blocklists/#{name}")
end
# Creates a blocklist.
#
# A Block List is a list of words that you can use to moderate chat messages. Stream Chat
# comes with a built-in Block List called profanity_en_2020_v1 which contains over a thousand
# of the most common profane words.
# You can manage your own block lists via the Stream dashboard or APIs to a manage
# blocklists and configure your channel types to use them.
sig { params(name: String, words: T::Array[String]).returns(StreamChat::StreamResponse) }
def create_blocklist(name, words)
post('blocklists', data: { name: name, words: words })
end
# Updates a blocklist.
#
# A Block List is a list of words that you can use to moderate chat messages. Stream Chat
# comes with a built-in Block List called profanity_en_2020_v1 which contains over a thousand
# of the most common profane words.
# You can manage your own block lists via the Stream dashboard or APIs to a manage
# blocklists and configure your channel types to use them.
sig { params(name: String, words: T::Array[String]).returns(StreamChat::StreamResponse) }
def update_blocklist(name, words)
put("blocklists/#{name}", data: { words: words })
end
# Deletes a blocklist.
#
# A Block List is a list of words that you can use to moderate chat messages. Stream Chat
# comes with a built-in Block List called profanity_en_2020_v1 which contains over a thousand
# of the most common profane words.
# You can manage your own block lists via the Stream dashboard or APIs to a manage
# blocklists and configure your channel types to use them.
sig { params(name: String).returns(StreamChat::StreamResponse) }
def delete_blocklist(name)
delete("blocklists/#{name}")
end
# Requests a channel export.
#
# Channel exports are created asynchronously, you can use the Task ID returned by
# the APIs to keep track of the status and to download the final result when it is ready.
# Use `get_task` to check the status of the export.
sig { params(channels: StringKeyHash, options: T.untyped).returns(StreamChat::StreamResponse) }
def export_channels(*channels, **options)
post('export_channels', data: { channels: channels, **options })
end
# Returns the status of a channel export. It contains the URL to the JSON file.
sig { params(task_id: String).returns(StreamChat::StreamResponse) }
def get_export_channel_status(task_id)
get("export_channels/#{task_id}")
end
# Requests a users export.
#
# User exports are created asynchronously, you can use the Task ID returned by
# the APIs to keep track of the status and to download the final result when it is ready.
# Use `get_task` to check the status of the export.
sig { params(user_ids: T::Array[String]).returns(StreamChat::StreamResponse) }
def export_users(user_ids)
post('export/users', data: { user_ids: user_ids })
end
# Returns the status of a task.
sig { params(task_id: String).returns(StreamChat::StreamResponse) }
def get_task(task_id)
get("tasks/#{task_id}")
end
# Delete users asynchronously. Use `get_task` to check the status of the task.
sig { params(user_ids: T::Array[String], user: String, messages: T.nilable(String), conversations: T.nilable(String)).returns(StreamChat::StreamResponse) }
def delete_users(user_ids, user: SOFT_DELETE, messages: nil, conversations: nil)
post('users/delete', data: { user_ids: user_ids, user: user, messages: messages, conversations: conversations })
end
# Deletes multiple channels. This is an asynchronous operation and the returned value is a task Id.
# You can use `get_task` method to check the status of the task.
sig { params(cids: T::Array[String], hard_delete: T::Boolean).returns(StreamChat::StreamResponse) }
def delete_channels(cids, hard_delete: false)
post('channels/delete', data: { cids: cids, hard_delete: hard_delete })
end
# Revoke tokens for an application issued since the given date.
sig { params(before: T.any(DateTime, String)).returns(StreamChat::StreamResponse) }
def revoke_tokens(before)
before = StreamChat.normalize_timestamp(before)
update_app_settings({ 'revoke_tokens_issued_before' => before })
end
# Revoke tokens for a user issued since the given date.
sig { params(user_id: String, before: T.any(DateTime, String)).returns(StreamChat::StreamResponse) }
def revoke_user_token(user_id, before)
revoke_users_token([user_id], before)
end
# Revoke tokens for users issued since.
sig { params(user_ids: T::Array[String], before: T.any(DateTime, String)).returns(StreamChat::StreamResponse) }
def revoke_users_token(user_ids, before)
before = StreamChat.normalize_timestamp(before)
updates = []
user_ids.map do |user_id|
{
'id' => user_id,
'set' => {
'revoke_tokens_issued_before' => before
}
}
end
update_users_partial(updates)
end
sig { params(relative_url: String, params: T.nilable(StringKeyHash), data: T.nilable(StringKeyHash)).returns(StreamChat::StreamResponse) }
def put(relative_url, params: nil, data: nil)
make_http_request(:put, relative_url, params: params, data: data)
end
sig { params(relative_url: String, params: T.nilable(StringKeyHash), data: T.nilable(StringKeyHash)).returns(StreamChat::StreamResponse) }
def post(relative_url, params: nil, data: nil)
make_http_request(:post, relative_url, params: params, data: data)
end
sig { params(relative_url: String, params: T.nilable(StringKeyHash)).returns(StreamChat::StreamResponse) }
def get(relative_url, params: nil)
make_http_request(:get, relative_url, params: params)
end
sig { params(relative_url: String, params: T.nilable(StringKeyHash)).returns(StreamChat::StreamResponse) }
def delete(relative_url, params: nil)
make_http_request(:delete, relative_url, params: params)
end
sig { params(relative_url: String, params: T.nilable(StringKeyHash), data: T.nilable(StringKeyHash)).returns(StreamChat::StreamResponse) }
def patch(relative_url, params: nil, data: nil)
make_http_request(:patch, relative_url, params: params, data: data)
end
# Uploads a file.
#
# This functionality defaults to using the Stream CDN. If you would like, you can
# easily change the logic to upload to your own CDN of choice.
sig { params(relative_url: String, file_url: String, user: StringKeyHash, content_type: T.nilable(String)).returns(StreamChat::StreamResponse) }
def send_file(relative_url, file_url, user, content_type = nil)
url = [@base_url, relative_url].join('/')
body = { user: user.to_json }
body[:file] = Faraday::UploadIO.new(file_url, content_type || 'application/octet-stream')
response = @conn.post url do |req|
req.headers['X-Stream-Client'] = get_user_agent
req.headers['Authorization'] = @auth_token
req.headers['stream-auth-type'] = 'jwt'
req.params = get_default_params
req.body = body
end
parse_response(response)
end
# Check push notification settings.
sig { params(push_data: StringKeyHash).returns(StreamChat::StreamResponse) }
def check_push(push_data)
post('check_push', data: push_data)
end
# Check SQS Push settings
#
# When no parameters are given, the current SQS app settings are used.
sig { params(sqs_key: T.nilable(String), sqs_secret: T.nilable(String), sqs_url: T.nilable(String)).returns(StreamChat::StreamResponse) }
def check_sqs(sqs_key = nil, sqs_secret = nil, sqs_url = nil)
post('check_sqs', data: { sqs_key: sqs_key, sqs_secret: sqs_secret, sqs_url: sqs_url })
end
# Check SNS Push settings
#
# When no parameters are given, the current SNS app settings are used.
sig { params(sns_key: T.nilable(String), sns_secret: T.nilable(String), sns_topic_arn: T.nilable(String)).returns(StreamChat::StreamResponse) }
def check_sns(sns_key = nil, sns_secret = nil, sns_topic_arn = nil)
post('check_sns', data: { sns_key: sns_key, sns_secret: sns_secret, sns_topic_arn: sns_topic_arn })
end
# Creates a new command.
sig { params(command: StringKeyHash).returns(StreamChat::StreamResponse) }
def create_command(command)
post('commands', data: command)
end
# Queries draft messages for the current user.
#
# @param [String] user_id The ID of the user to query drafts for
# @param [StringKeyHash] filter Optional filter conditions for the query
# @param [Array] sort Optional sort parameters
# @param [Hash] options Additional query options
# @return [StreamChat::StreamResponse]
sig { params(user_id: String, filter: T.nilable(StringKeyHash), sort: T.nilable(T::Array[StringKeyHash]), options: T.untyped).returns(StreamChat::StreamResponse) }
def query_drafts(user_id, filter: nil, sort: nil, **options)
data = { user_id: user_id }
data['filter'] = filter if filter
data['sort'] = sort if sort
data.merge!(options) if options
post('drafts/query', data: data)
end
# Get active_live_locations for the current user
#
# @return [StreamChat::StreamResponse]
sig { params(user_id: String).returns(StreamChat::StreamResponse) }
def get_active_live_locations(user_id)
get('users/live_locations', params: { user_id: user_id })
end
# Update live location
#
# @param [String] user_id The ID of the user to update the location
# @param [String] created_by_device_id The device ID that created the location
# @param [String] message_id The message ID associated with the location
# @param [Float] latitude Optional latitude coordinate
# @param [Float] longitude Optional longitude coordinate
# @param [String] end_at Optional end time for the location sharing
# @return [StreamChat::StreamResponse]
sig { params(user_id: String, created_by_device_id: String, message_id: String, options: T.untyped).returns(StreamChat::StreamResponse) }
def update_location(user_id, created_by_device_id:, message_id:, **options)
data = {
created_by_device_id: created_by_device_id,
message_id: message_id
}
data.merge!(options) if options
put('users/live_locations', data: data, params: { user_id: user_id })
end
# Gets a comamnd.
sig { params(name: String).returns(StreamChat::StreamResponse) }
def get_command(name)
get("commands/#{name}")
end
# Updates a command.
sig { params(name: String, command: StringKeyHash).returns(StreamChat::StreamResponse) }