-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsync.rb
More file actions
356 lines (324 loc) · 11.1 KB
/
Copy pathsync.rb
File metadata and controls
356 lines (324 loc) · 11.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
require 'net/http'
require 'json'
require 'securerandom'
require 'faye/websocket'
require 'eventmachine'
require 'uri'
STREAM_BASE_URL = 'chat.stream-io-api.com'
STREAM_HTTP_URL = "https://#{STREAM_BASE_URL}"
STREAM_WSS_URL = "wss://#{STREAM_BASE_URL}/connect"
STREAM_DEMO_API_KEY = '8br4watad788'
STREAM_DEMO_TOKEN = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoibHVrZV9za3l3YWxrZXIifQ.kFSLHRB5X62t0Zlc7nwczWUfsQMwfkpylC6jCUZ6Mc0'
STREAM_USER_ID = 'luke_skywalker'
STREAM_HEADERS = {
'Authorization' => STREAM_DEMO_TOKEN,
'Stream-Auth-Type' => 'jwt',
'Content-Type' => 'application/json'
}
MOCK_SERVER_FIXTURES_PATH = 'src/jsons'
def connect_endpoint
payload = {
user_id: STREAM_USER_ID,
user_details: {
id: STREAM_USER_ID,
name: 'Luke Skywalker',
image: 'https://vignette.wikia.nocookie.net/starwars/images/2/20/LukeTLJ.jpg',
birthland: 'Tatooine'
},
server_determines_connection_id: true
}.to_json
query_params = ["api_key=#{STREAM_DEMO_API_KEY}", "json=#{URI.encode_www_form_component(payload)}"]
"#{STREAM_WSS_URL}?#{query_params.join('&')}"
end
def establish_websocket_connection(event_data)
health_check = JSON.parse(event_data)
health_check['me']['channel_mutes'] = []
health_check['me']['mutes'] = []
health_check['me']['devices'] = []
save_json(health_check, 'ws_health_check.json')
health_check['connection_id']
end
def request_channels(connection_id)
payload = {
filter_conditions: {
members: { '$in': [STREAM_USER_ID] }
},
limit: 20,
member_limit: 30,
message_limit: 25,
watch: true
}.to_json
query_params = [
"api_key=#{STREAM_DEMO_API_KEY}",
"connection_id=#{connection_id}",
"payload=#{URI.encode_www_form_component(payload)}"
]
endpoint = "#{STREAM_HTTP_URL}/channels?#{query_params.join('&')}"
response = http_get(endpoint)
response['channels'] = [response['channels'][0]]
response['channels'][0]['members'].each_with_index do |member, i|
response['channels'][0]['read'][i] = {}
response['channels'][0]['read'][i]['user'] = member['user']
response['channels'][0]['read'][i]['unread_messages'] = 0
response['channels'][0]['read'][i]['last_read'] = Time.now.utc.strftime('%Y-%m-%dT%H:%M:%SZ')
end
save_json(response, 'http_channels.json')
end
def send_typing_event(channel_id)
payload = { event: { type: 'typing.start' } }.to_json
endpoint = "#{STREAM_HTTP_URL}/channels/messaging/#{channel_id}/event?api_key=#{STREAM_DEMO_API_KEY}"
response = http_post(endpoint, payload)
save_json(response, 'http_events.json')
end
def send_message(channel_id, text, filename, fill_attachment: false)
message_id = SecureRandom.uuid
payload = {
message: {
id: message_id,
show_in_channel: false,
pinned: false,
silent: false,
text: text
}
}.to_json
endpoint = "#{STREAM_HTTP_URL}/channels/messaging/#{channel_id}/message?api_key=#{STREAM_DEMO_API_KEY}"
response = http_post(endpoint, payload)
fill_attachment_defaults(response) if fill_attachment
save_json(response, filename)
message_id
end
# Image link previews (e.g. Unsplash) come back without `title`/`text`, so the
# preview card has no copy. Fill them with defaults when the scrape left them blank.
def fill_attachment_defaults(response)
attachment = response.dig('message', 'attachments', 0)
return unless attachment
attachment['title'] = 'Title' if attachment['title'].to_s.empty?
attachment['text'] = 'Description' if attachment['text'].to_s.empty?
end
def send_youtube_link(channel_id)
send_message(
channel_id,
'https://www.youtube.com/watch?v=xOX7MsrbaPY',
'http_youtube_link.json',
fill_attachment: true
)
end
def send_ephemeral_message(channel_id)
send_message(channel_id, '/giphy Test', 'http_message_ephemeral.json')
end
def send_unsplash_link(channel_id)
send_message(
channel_id,
'https://images.unsplash.com/photo-1568574728383-06fca083883d',
'http_unsplash_link.json',
fill_attachment: true
)
end
def send_giphy_link(channel_id)
send_message(channel_id, 'https://giphy.com/gifs/test-gw3IWyGkC0rsazTi', 'http_giphy_link.json')
end
def create_draft_message(channel_id, text, filename)
message_id = SecureRandom.uuid
payload = {
message: {
id: message_id,
show_in_channel: false,
silent: false,
text: text
}
}.to_json
endpoint = "#{STREAM_HTTP_URL}/channels/messaging/#{channel_id}/draft?api_key=#{STREAM_DEMO_API_KEY}"
response = http_post(endpoint, payload)
save_json(response, filename)
message_id
end
def delete_draft_message(channel_id)
endpoint = "#{STREAM_HTTP_URL}/channels/messaging/#{channel_id}/draft?api_key=#{STREAM_DEMO_API_KEY}"
http_delete(endpoint)
end
def create_channel(connection_id)
payload = {
data: {
members: [STREAM_USER_ID, 'lando_calrissian', 'count_dooku'],
name: 'Sync Mock Server'
},
presence: true,
state: true,
watch: true,
messages: { limit: 25 }
}.to_json
channel_id = SecureRandom.uuid
query_params = ["api_key=#{STREAM_DEMO_API_KEY}", "connection_id=#{connection_id}"]
endpoint = "#{STREAM_HTTP_URL}/channels/messaging/#{channel_id}/query?#{query_params.join('&')}"
response = http_post(endpoint, payload)
save_json(response, 'http_channel_creation.json')
channel_id
end
def add_reaction(message_id)
payload = {
enforce_unique: false,
reaction: {
type: 'like',
score: 1
}
}.to_json
endpoint = "#{STREAM_HTTP_URL}/messages/#{message_id}/reaction?api_key=#{STREAM_DEMO_API_KEY}"
response = http_post(endpoint, payload)
save_json(response, 'http_reaction.json')
end
def truncate_channel_with_message(channel_id)
payload = {
hard_delete: true,
skip_push: false,
message: {
id: SecureRandom.uuid,
show_in_channel: false,
pinned: false,
silent: false,
text: 'Channel truncated'
}
}.to_json
endpoint = "#{STREAM_HTTP_URL}/channels/messaging/#{channel_id}/truncate?api_key=#{STREAM_DEMO_API_KEY}"
response = http_post(endpoint, payload)
save_json(response, 'http_truncate.json')
end
def add_member_to_channel(channel_id)
payload = {
add_members: ['leia_organa'],
hide_history: false
}.to_json
endpoint = "#{STREAM_HTTP_URL}/channels/messaging/#{channel_id}?api_key=#{STREAM_DEMO_API_KEY}"
response = http_post(endpoint, payload)
save_json(response, 'http_add_member.json')
end
def remove_channel(channel_id)
endpoint = "#{STREAM_HTTP_URL}/channels/messaging/#{channel_id}?api_key=#{STREAM_DEMO_API_KEY}"
response = http_delete(endpoint)
save_json(response, 'http_channel_removal.json')
end
def send_attachment(channel_id)
boundary = "----RubyMultipartPostBoundary"
image_path = File.expand_path('src/assets/file.png')
image_basename = File.basename(image_path)
image = File.open(image_path, 'rb')
payload = []
payload << "--#{boundary}\r\n"
payload << "Content-Disposition: form-data; name=\"file\"; filename=\"#{image_basename}\"\r\n"
payload << "Content-Type: image/jpeg\r\n\r\n"
payload << image
payload << "\r\n--#{boundary}--\r\n"
headers = STREAM_HEADERS.dup
headers['Content-Type'] = "multipart/form-data; boundary=#{boundary}"
endpoint = "#{STREAM_HTTP_URL}/channels/messaging/#{channel_id}/image?api_key=#{STREAM_DEMO_API_KEY}"
response = http_post(endpoint, payload.join, headers)
save_json(response, 'http_attachment.json')
end
def save_json(data, filename)
File.write("#{MOCK_SERVER_FIXTURES_PATH}/#{filename}", JSON.pretty_generate(data))
puts("✅ #{filename}")
end
# Strip the `i18n` object out of every `message` in all generated fixtures.
# The translation metadata is noise for the mock server, so remove it as a
# final pass once all JSONs have been written.
def remove_message_i18n(node)
case node
when Hash
node.each do |key, value|
value.delete('i18n') if key == 'message' && value.kind_of?(Hash)
if key == 'messages' && value.kind_of?(Array)
value.each { |message| message.delete('i18n') if message.kind_of?(Hash) }
end
remove_message_i18n(value)
end
when Array
node.each { |item| remove_message_i18n(item) }
end
end
def cleanup_message_i18n
Dir.glob("#{MOCK_SERVER_FIXTURES_PATH}/*.json").sort.each do |path|
data = JSON.parse(File.read(path))
remove_message_i18n(data)
File.write(path, JSON.pretty_generate(data))
end
puts('🧹 Removed i18n from message objects')
end
def http_get(url, headers = STREAM_HEADERS)
uri = URI(url)
request = Net::HTTP::Get.new(uri, headers)
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
http.request(request)
end
JSON.parse(response.body)
end
def http_post(url, payload, headers = STREAM_HEADERS)
uri = URI(url)
request = Net::HTTP::Post.new(uri, headers)
request.body = payload
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
http.request(request)
end
JSON.parse(response.body)
end
def http_delete(url, headers = STREAM_HEADERS)
uri = URI(url)
request = Net::HTTP::Delete.new(uri, headers)
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
http.request(request)
end
JSON.parse(response.body)
end
EM.run do
ws = Faye::WebSocket::Client.new(connect_endpoint, nil, headers: STREAM_HEADERS)
ws.on(:message) do |event|
case JSON.parse(event.data)['type']
when 'health.check'
next if @connection_id
@connection_id = establish_websocket_connection(event.data)
channel_id = create_channel(@connection_id)
request_channels(@connection_id)
send_typing_event(channel_id)
message_id = send_message(channel_id, 'Test', 'http_message.json')
add_reaction(message_id)
add_member_to_channel(channel_id)
send_attachment(channel_id)
send_ephemeral_message(channel_id)
send_youtube_link(channel_id)
send_unsplash_link(channel_id)
send_giphy_link(channel_id)
create_draft_message(channel_id, 'Test', 'http_draft.json')
delete_draft_message(channel_id)
truncate_channel_with_message(channel_id)
remove_channel(channel_id)
when 'typing.start'
save_json(JSON.parse(event.data), 'ws_events.json')
when 'message.new'
next if @new_message
@new_message = 1
save_json(JSON.parse(event.data), 'ws_message.json')
when 'reaction.new'
save_json(JSON.parse(event.data), 'ws_reaction.json')
when 'member.added'
save_json(JSON.parse(event.data), 'ws_events_member.json')
when 'draft.updated'
save_json(JSON.parse(event.data), 'ws_draft_updated.json')
when 'draft.deleted'
save_json(JSON.parse(event.data), 'ws_draft_deleted.json')
when 'channel.updated'
json = JSON.parse(event.data)
json['user']['privacy_settings']['typing_indicators']['enabled'] = true
json['user']['privacy_settings']['read_receipts']['enabled'] = true
json['channel']['members'].each do |member|
member['user']['privacy_settings']['typing_indicators']['enabled'] = true
member['user']['privacy_settings']['read_receipts']['enabled'] = true
end
save_json(json, 'ws_events_channel.json')
when 'channel.deleted'
ws.close
end
end
ws.on(:close) do |event|
ws = nil
cleanup_message_i18n
exit 0
end
end