node-datachannel 0.5.5 → 0.6.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.
@@ -0,0 +1,651 @@
1
+ #include "web-socket-wrapper.h"
2
+
3
+ #include "plog/Log.h"
4
+
5
+ Napi::FunctionReference WebSocketWrapper::constructor;
6
+ std::unordered_set<WebSocketWrapper *> WebSocketWrapper::instances;
7
+
8
+ void WebSocketWrapper::CloseAll()
9
+ {
10
+ PLOG_DEBUG << "CloseAll() called";
11
+ auto copy(instances);
12
+ for (auto inst : copy)
13
+ inst->doClose();
14
+ }
15
+
16
+ Napi::Object WebSocketWrapper::Init(Napi::Env env, Napi::Object exports)
17
+ {
18
+ Napi::HandleScope scope(env);
19
+
20
+ Napi::Function func = DefineClass(
21
+ env,
22
+ "WebSocket",
23
+ {
24
+ InstanceMethod("open", &WebSocketWrapper::open),
25
+ InstanceMethod("close", &WebSocketWrapper::close),
26
+ InstanceMethod("sendMessage", &WebSocketWrapper::sendMessage),
27
+ InstanceMethod("sendMessageBinary", &WebSocketWrapper::sendMessageBinary),
28
+ InstanceMethod("isOpen", &WebSocketWrapper::isOpen),
29
+ InstanceMethod("bufferedAmount", &WebSocketWrapper::bufferedAmount),
30
+ InstanceMethod("maxMessageSize", &WebSocketWrapper::maxMessageSize),
31
+ InstanceMethod("setBufferedAmountLowThreshold", &WebSocketWrapper::setBufferedAmountLowThreshold),
32
+ InstanceMethod("onOpen", &WebSocketWrapper::onOpen),
33
+ InstanceMethod("onClosed", &WebSocketWrapper::onClosed),
34
+ InstanceMethod("onError", &WebSocketWrapper::onError),
35
+ InstanceMethod("onBufferedAmountLow", &WebSocketWrapper::onBufferedAmountLow),
36
+ InstanceMethod("onMessage", &WebSocketWrapper::onMessage),
37
+ });
38
+
39
+ constructor = Napi::Persistent(func);
40
+ constructor.SuppressDestruct();
41
+
42
+ exports.Set("WebSocket", func);
43
+ return exports;
44
+ }
45
+
46
+ WebSocketWrapper::WebSocketWrapper(const Napi::CallbackInfo &info) : Napi::ObjectWrap<WebSocketWrapper>(info)
47
+ {
48
+ PLOG_DEBUG << "Constructor called";
49
+ Napi::Env env = info.Env();
50
+
51
+ // Create WebSocket using rtc::WebSocket provided by WebSocketServer
52
+ if (info.Length() > 1)
53
+ {
54
+ mWebSocketPtr = *(info[1].As<Napi::External<std::shared_ptr<rtc::WebSocket>>>().Data());
55
+ PLOG_DEBUG << "Using WebSocket got from WebSocketServer";
56
+ instances.insert(this);
57
+ return;
58
+ }
59
+
60
+ // Create WebSocket without config
61
+ if (info.Length() == 0)
62
+ {
63
+ try
64
+ {
65
+ PLOG_DEBUG << "Creating a new WebSocket without config";
66
+ mWebSocketPtr = std::make_unique<rtc::WebSocket>();
67
+ }
68
+ catch (std::exception &ex)
69
+ {
70
+ Napi::Error::New(env, std::string("libdatachannel error while creating WebSocket without config: ") + ex.what()).ThrowAsJavaScriptException();
71
+ return;
72
+ }
73
+ instances.insert(this);
74
+ return;
75
+ }
76
+
77
+ // Create WebSocket with config
78
+ PLOG_DEBUG << "Creating a new WebSocket with config";
79
+
80
+ Napi::Object config = info[0].As<Napi::Object>();
81
+ rtc::WebSocketConfiguration webSocketConfig;
82
+
83
+ if (config.Has("disableTlsVerification"))
84
+ {
85
+ if (!config.Get("disableTlsVerification").IsBoolean())
86
+ {
87
+ Napi::TypeError::New(info.Env(), "disableTlsVerification must be boolean").ThrowAsJavaScriptException();
88
+ return;
89
+ }
90
+ webSocketConfig.disableTlsVerification = config.Get("disableTlsVerification").ToBoolean();
91
+ }
92
+
93
+ // Proxy Server
94
+ if (config.Has("proxyServer") && config.Get("proxyServer").IsObject())
95
+ {
96
+ Napi::Object proxyServer = config.Get("proxyServer").As<Napi::Object>();
97
+
98
+ // IP
99
+ std::string ip = proxyServer.Get("ip").As<Napi::String>();
100
+
101
+ // Port
102
+ uint16_t port = proxyServer.Get("port").As<Napi::Number>().Uint32Value();
103
+
104
+ // Type
105
+ std::string strType = proxyServer.Get("type").As<Napi::String>().ToString();
106
+ rtc::ProxyServer::Type type = rtc::ProxyServer::Type::Http;
107
+
108
+ if (strType == "Socks5")
109
+ type = rtc::ProxyServer::Type::Socks5;
110
+
111
+ // Username & Password
112
+ std::string username = "";
113
+ std::string password = "";
114
+
115
+ if (proxyServer.Get("username").IsString())
116
+ username = proxyServer.Get("username").As<Napi::String>().ToString();
117
+ if (proxyServer.Get("password").IsString())
118
+ password = proxyServer.Get("password").As<Napi::String>().ToString();
119
+
120
+ webSocketConfig.proxyServer = rtc::ProxyServer(type, ip, port, username, password);
121
+ }
122
+
123
+ if (config.Has("protocols"))
124
+ {
125
+ if (!config.Get("protocols").IsArray())
126
+ {
127
+ Napi::TypeError::New(info.Env(), "protocols must be an array").ThrowAsJavaScriptException();
128
+ return;
129
+ }
130
+ Napi::Array protocols = config.Get("protocols").As<Napi::Array>();
131
+ for (uint32_t i = 0; i < protocols.Length(); i++)
132
+ {
133
+ webSocketConfig.protocols.push_back(protocols.Get(i).ToString());
134
+ }
135
+ }
136
+
137
+ if (config.Has("connectionTimeout"))
138
+ {
139
+ if (!config.Get("connectionTimeout").IsNumber())
140
+ {
141
+ Napi::TypeError::New(info.Env(), "connectionTimeout must be a number").ThrowAsJavaScriptException();
142
+ return;
143
+ }
144
+ webSocketConfig.connectionTimeout = std::chrono::milliseconds(config.Get("connectionTimeout").ToNumber().Int64Value());
145
+ }
146
+
147
+ if (config.Has("pingInterval"))
148
+ {
149
+ if (!config.Get("pingInterval").IsNumber())
150
+ {
151
+ Napi::TypeError::New(info.Env(), "pingInterval must be a number").ThrowAsJavaScriptException();
152
+ return;
153
+ }
154
+ webSocketConfig.pingInterval = std::chrono::milliseconds(config.Get("pingInterval").ToNumber().Int64Value());
155
+ }
156
+
157
+ if (config.Has("maxOutstandingPings"))
158
+ {
159
+ if (!config.Get("maxOutstandingPings").IsNumber())
160
+ {
161
+ Napi::TypeError::New(info.Env(), "maxOutstandingPings must be a number").ThrowAsJavaScriptException();
162
+ return;
163
+ }
164
+ webSocketConfig.maxOutstandingPings = config.Get("maxOutstandingPings").ToNumber().Int32Value();
165
+ }
166
+
167
+ if (config.Has("caCertificatePemFile"))
168
+ {
169
+ if (!config.Get("caCertificatePemFile").IsString())
170
+ {
171
+ Napi::TypeError::New(info.Env(), "caCertificatePemFile must be a string").ThrowAsJavaScriptException();
172
+ return;
173
+ }
174
+ webSocketConfig.caCertificatePemFile = config.Get("caCertificatePemFile").ToString();
175
+ }
176
+
177
+ if (config.Has("certificatePemFile"))
178
+ {
179
+ if (!config.Get("certificatePemFile").IsString())
180
+ {
181
+ Napi::TypeError::New(info.Env(), "certificatePemFile must be a string").ThrowAsJavaScriptException();
182
+ return;
183
+ }
184
+ webSocketConfig.certificatePemFile = config.Get("certificatePemFile").ToString();
185
+ }
186
+
187
+ if (config.Has("keyPemFile"))
188
+ {
189
+ if (!config.Get("keyPemFile").IsString())
190
+ {
191
+ Napi::TypeError::New(info.Env(), "keyPemFile must be a string").ThrowAsJavaScriptException();
192
+ return;
193
+ }
194
+ webSocketConfig.keyPemFile = config.Get("keyPemFile").ToString();
195
+ }
196
+
197
+ if (config.Has("keyPemPass"))
198
+ {
199
+ if (!config.Get("keyPemPass").IsString())
200
+ {
201
+ Napi::TypeError::New(info.Env(), "keyPemPass must be a string").ThrowAsJavaScriptException();
202
+ return;
203
+ }
204
+ webSocketConfig.keyPemPass = config.Get("keyPemPass").ToString();
205
+ }
206
+
207
+ if (config.Has("maxMessageSize"))
208
+ {
209
+ if (!config.Get("maxMessageSize").IsNumber())
210
+ {
211
+ Napi::TypeError::New(info.Env(), "maxMessageSize must be a number").ThrowAsJavaScriptException();
212
+ return;
213
+ }
214
+ webSocketConfig.maxMessageSize = config.Get("maxMessageSize").ToNumber().Int32Value();
215
+ }
216
+
217
+ // Create WebSocket
218
+ try
219
+ {
220
+ PLOG_DEBUG << "Creating a new WebSocket";
221
+ mWebSocketPtr = std::make_unique<rtc::WebSocket>(webSocketConfig);
222
+ }
223
+ catch (std::exception &ex)
224
+ {
225
+ Napi::Error::New(env, std::string("libdatachannel error while creating WebSocket: ") + ex.what()).ThrowAsJavaScriptException();
226
+ return;
227
+ }
228
+
229
+ PLOG_DEBUG << "WebSocket created";
230
+ instances.insert(this);
231
+ }
232
+
233
+ WebSocketWrapper::~WebSocketWrapper()
234
+ {
235
+ PLOG_DEBUG << "Destructor called";
236
+ doClose();
237
+ }
238
+
239
+ void WebSocketWrapper::doClose()
240
+ {
241
+ PLOG_DEBUG << "doClose() called";
242
+ if (mWebSocketPtr)
243
+ {
244
+ PLOG_DEBUG << "Closing...";
245
+ try
246
+ {
247
+ mWebSocketPtr->close();
248
+ mWebSocketPtr.reset();
249
+ }
250
+ catch (std::exception &ex)
251
+ {
252
+ std::cerr << std::string("libWebSocket error while closing WebSocket: ") + ex.what() << std::endl;
253
+ return;
254
+ }
255
+ }
256
+
257
+ mOnOpenCallback.reset();
258
+ mOnClosedCallback.reset();
259
+ mOnErrorCallback.reset();
260
+ mOnBufferedAmountLowCallback.reset();
261
+ mOnMessageCallback.reset();
262
+
263
+ instances.erase(this);
264
+ }
265
+
266
+ void WebSocketWrapper::open(const Napi::CallbackInfo &info)
267
+ {
268
+ PLOG_DEBUG << "open() called";
269
+ Napi::Env env = info.Env();
270
+
271
+ if (!mWebSocketPtr)
272
+ {
273
+ Napi::Error::New(env, "open() called on destroyed WebSocket").ThrowAsJavaScriptException();
274
+ return;
275
+ }
276
+ if (info.Length() < 1 || !info[0].IsString())
277
+ {
278
+ Napi::TypeError::New(env, "url must be string").ThrowAsJavaScriptException();
279
+ return;
280
+ }
281
+
282
+ try
283
+ {
284
+ mWebSocketPtr->open(info[0].As<Napi::String>().ToString());
285
+ }
286
+ catch (std::exception &ex)
287
+ {
288
+ Napi::Error::New(env, std::string("libWebSocket error while opening WebSocket: ") + ex.what()).ThrowAsJavaScriptException();
289
+ return;
290
+ }
291
+ }
292
+
293
+ void WebSocketWrapper::close(const Napi::CallbackInfo &info)
294
+ {
295
+ PLOG_DEBUG << "close() called";
296
+ doClose();
297
+ }
298
+
299
+ Napi::Value WebSocketWrapper::sendMessage(const Napi::CallbackInfo &info)
300
+ {
301
+ PLOG_DEBUG << "sendMessage() called";
302
+ if (!mWebSocketPtr)
303
+ {
304
+ Napi::Error::New(info.Env(), "sendMessage() called on destroyed channel").ThrowAsJavaScriptException();
305
+ return info.Env().Null();
306
+ }
307
+
308
+ Napi::Env env = info.Env();
309
+ int length = info.Length();
310
+
311
+ // Allow call with NULL
312
+ if (length < 1 || (!info[0].IsString() && !info[0].IsNull()))
313
+ {
314
+ Napi::TypeError::New(env, "String or Null expected").ThrowAsJavaScriptException();
315
+ return info.Env().Null();
316
+ }
317
+
318
+ try
319
+ {
320
+ return Napi::Boolean::New(info.Env(), mWebSocketPtr->send(info[0].As<Napi::String>().ToString()));
321
+ }
322
+ catch (std::exception &ex)
323
+ {
324
+ Napi::Error::New(env, std::string("libWebSocket error while sending data channel message: ") + ex.what()).ThrowAsJavaScriptException();
325
+ return Napi::Boolean::New(info.Env(), false);
326
+ }
327
+ }
328
+
329
+ Napi::Value WebSocketWrapper::sendMessageBinary(const Napi::CallbackInfo &info)
330
+ {
331
+ PLOG_DEBUG << "sendMessageBinary() called";
332
+ if (!mWebSocketPtr)
333
+ {
334
+ Napi::Error::New(info.Env(), "sendMessagBinary() called on destroyed channel").ThrowAsJavaScriptException();
335
+ return info.Env().Null();
336
+ }
337
+
338
+ Napi::Env env = info.Env();
339
+ int length = info.Length();
340
+
341
+ if (length < 1 || !info[0].IsBuffer())
342
+ {
343
+ Napi::TypeError::New(env, "Buffer expected").ThrowAsJavaScriptException();
344
+ return info.Env().Null();
345
+ }
346
+
347
+ try
348
+ {
349
+ Napi::Uint8Array buffer = info[0].As<Napi::Uint8Array>();
350
+ return Napi::Boolean::New(info.Env(), mWebSocketPtr->send((std::byte *)buffer.Data(), buffer.ByteLength()));
351
+ }
352
+ catch (std::exception &ex)
353
+ {
354
+ Napi::Error::New(env, std::string("libWebSocket error while sending data channel message: ") + ex.what()).ThrowAsJavaScriptException();
355
+ return Napi::Boolean::New(info.Env(), false);
356
+ }
357
+ }
358
+
359
+ Napi::Value WebSocketWrapper::isOpen(const Napi::CallbackInfo &info)
360
+ {
361
+ PLOG_DEBUG << "isOpen() called";
362
+ Napi::Env env = info.Env();
363
+
364
+ if (!mWebSocketPtr)
365
+ {
366
+ return Napi::Boolean::New(info.Env(), false);
367
+ }
368
+
369
+ try
370
+ {
371
+ return Napi::Boolean::New(info.Env(), mWebSocketPtr->isOpen());
372
+ }
373
+ catch (std::exception &ex)
374
+ {
375
+ Napi::Error::New(env, std::string("libWebSocket error: ") + ex.what()).ThrowAsJavaScriptException();
376
+ return Napi::Boolean::New(info.Env(), false);
377
+ }
378
+ }
379
+
380
+ Napi::Value WebSocketWrapper::bufferedAmount(const Napi::CallbackInfo &info)
381
+ {
382
+ PLOG_DEBUG << "bufferedAmount() called";
383
+ Napi::Env env = info.Env();
384
+
385
+ if (!mWebSocketPtr)
386
+ {
387
+ return Napi::Number::New(info.Env(), 0);
388
+ }
389
+
390
+ try
391
+ {
392
+ return Napi::Number::New(info.Env(), mWebSocketPtr->bufferedAmount());
393
+ }
394
+ catch (std::exception &ex)
395
+ {
396
+ Napi::Error::New(env, std::string("libWebSocket error: ") + ex.what()).ThrowAsJavaScriptException();
397
+ return Napi::Number::New(info.Env(), 0);
398
+ }
399
+ }
400
+
401
+ Napi::Value WebSocketWrapper::maxMessageSize(const Napi::CallbackInfo &info)
402
+ {
403
+ PLOG_DEBUG << "maxMessageSize() called";
404
+ Napi::Env env = info.Env();
405
+
406
+ if (!mWebSocketPtr)
407
+ {
408
+ return Napi::Number::New(info.Env(), 0);
409
+ }
410
+
411
+ try
412
+ {
413
+ return Napi::Number::New(info.Env(), mWebSocketPtr->maxMessageSize());
414
+ }
415
+ catch (std::exception &ex)
416
+ {
417
+ Napi::Error::New(env, std::string("libWebSocket error: ") + ex.what()).ThrowAsJavaScriptException();
418
+ return Napi::Number::New(info.Env(), 0);
419
+ }
420
+ }
421
+
422
+ void WebSocketWrapper::setBufferedAmountLowThreshold(const Napi::CallbackInfo &info)
423
+ {
424
+ PLOG_DEBUG << "setBufferedAmountLowThreshold() called";
425
+ if (!mWebSocketPtr)
426
+ {
427
+ Napi::Error::New(info.Env(), "setBufferedAmountLowThreshold() called on destroyed channel").ThrowAsJavaScriptException();
428
+ return;
429
+ }
430
+
431
+ Napi::Env env = info.Env();
432
+ int length = info.Length();
433
+
434
+ if (length < 1 || !info[0].IsNumber())
435
+ {
436
+ Napi::TypeError::New(env, "Number expected").ThrowAsJavaScriptException();
437
+ return;
438
+ }
439
+
440
+ try
441
+ {
442
+ mWebSocketPtr->setBufferedAmountLowThreshold(info[0].ToNumber().Uint32Value());
443
+ }
444
+ catch (std::exception &ex)
445
+ {
446
+ Napi::Error::New(env, std::string("libWebSocket error: ") + ex.what()).ThrowAsJavaScriptException();
447
+ return;
448
+ }
449
+ }
450
+
451
+ void WebSocketWrapper::onOpen(const Napi::CallbackInfo &info)
452
+ {
453
+ PLOG_DEBUG << "new onOpen() called";
454
+ if (!mWebSocketPtr)
455
+ {
456
+ Napi::Error::New(info.Env(), "onOpen() called on destroyed channel").ThrowAsJavaScriptException();
457
+ return;
458
+ }
459
+
460
+ Napi::Env env = info.Env();
461
+ int length = info.Length();
462
+
463
+ if (length < 1 || !info[0].IsFunction())
464
+ {
465
+ Napi::TypeError::New(env, "Function expected").ThrowAsJavaScriptException();
466
+ return;
467
+ }
468
+
469
+ // Callback
470
+ mOnOpenCallback = std::make_unique<ThreadSafeCallback>(info[0].As<Napi::Function>());
471
+
472
+ mWebSocketPtr->onOpen([&]()
473
+ {
474
+ PLOG_DEBUG << "onOpen cb received from rtc";
475
+
476
+ if (mOnOpenCallback)
477
+ mOnOpenCallback->call([this](Napi::Env env, std::vector<napi_value> &args)
478
+ {
479
+ PLOG_DEBUG << "mOnOpenCallback call(1)";
480
+ // Check the WebSocket is not closed
481
+ if(instances.find(this) == instances.end())
482
+ {
483
+ PLOG_DEBUG << "WebSocket not found in instances";
484
+ throw ThreadSafeCallback::CancelException();
485
+ }
486
+
487
+
488
+ // This will run in main thread and needs to construct the
489
+ // arguments for the call
490
+ args = {};
491
+ PLOG_DEBUG << "mOnOpenCallback call(2)"; });
492
+ });
493
+ }
494
+
495
+ void WebSocketWrapper::onClosed(const Napi::CallbackInfo &info)
496
+ {
497
+ PLOG_DEBUG << "onClosed() called";
498
+ if (!mWebSocketPtr)
499
+ {
500
+ Napi::Error::New(info.Env(), "onClosed() called on destroyed WebSocket").ThrowAsJavaScriptException();
501
+ return;
502
+ }
503
+
504
+ Napi::Env env = info.Env();
505
+ int length = info.Length();
506
+
507
+ if (length < 1 || !info[0].IsFunction())
508
+ {
509
+ Napi::TypeError::New(env, "Function expected").ThrowAsJavaScriptException();
510
+ return;
511
+ }
512
+
513
+ // Callback
514
+ mOnClosedCallback = std::make_unique<ThreadSafeCallback>(info[0].As<Napi::Function>());
515
+
516
+ mWebSocketPtr->onClosed([&]()
517
+ {
518
+ PLOG_DEBUG << "onClosed cb received from rtc";
519
+ if (mOnClosedCallback)
520
+ mOnClosedCallback->call([this](Napi::Env env, std::vector<napi_value> &args) {
521
+ PLOG_DEBUG << "mOnClosedCallback call";
522
+ // Do not check if the data channel has been closed here
523
+
524
+ // This will run in main thread and needs to construct the
525
+ // arguments for the call
526
+ args = {};
527
+ }); });
528
+ }
529
+
530
+ void WebSocketWrapper::onError(const Napi::CallbackInfo &info)
531
+ {
532
+ PLOG_DEBUG << "onError() called";
533
+ if (!mWebSocketPtr)
534
+ {
535
+ Napi::Error::New(info.Env(), "onError() called on destroyed channel").ThrowAsJavaScriptException();
536
+ return;
537
+ }
538
+
539
+ Napi::Env env = info.Env();
540
+ int length = info.Length();
541
+
542
+ if (length < 1 || !info[0].IsFunction())
543
+ {
544
+ Napi::TypeError::New(env, "Function expected").ThrowAsJavaScriptException();
545
+ return;
546
+ }
547
+
548
+ // Callback
549
+ mOnErrorCallback = std::make_unique<ThreadSafeCallback>(info[0].As<Napi::Function>());
550
+
551
+ mWebSocketPtr->onError([&](std::string error)
552
+ {
553
+ PLOG_DEBUG << "onError cb received from rtc";
554
+ if (mOnErrorCallback)
555
+ mOnErrorCallback->call([this, error = std::move(error)](Napi::Env env, std::vector<napi_value> &args) {
556
+ PLOG_DEBUG << "mOnErrorCallback call(1)";
557
+ // Check the data channel is not closed
558
+ if(instances.find(this) == instances.end())
559
+ throw ThreadSafeCallback::CancelException();
560
+
561
+ // This will run in main thread and needs to construct the
562
+ // arguments for the call
563
+ args = {Napi::String::New(env, error)};
564
+ PLOG_DEBUG << "mOnErrorCallback call(2)";
565
+ }); });
566
+ }
567
+
568
+ void WebSocketWrapper::onBufferedAmountLow(const Napi::CallbackInfo &info)
569
+ {
570
+ PLOG_DEBUG << "onBufferedAmountLow() called";
571
+ if (!mWebSocketPtr)
572
+ {
573
+ Napi::Error::New(info.Env(), "onBufferedAmountLow() called on destroyed channel").ThrowAsJavaScriptException();
574
+ return;
575
+ }
576
+
577
+ Napi::Env env = info.Env();
578
+ int length = info.Length();
579
+
580
+ if (length < 1 || !info[0].IsFunction())
581
+ {
582
+ Napi::TypeError::New(env, "Function expected").ThrowAsJavaScriptException();
583
+ return;
584
+ }
585
+
586
+ // Callback
587
+ mOnBufferedAmountLowCallback = std::make_unique<ThreadSafeCallback>(info[0].As<Napi::Function>());
588
+
589
+ mWebSocketPtr->onBufferedAmountLow([&]()
590
+ {
591
+ PLOG_DEBUG << "onBufferedAmountLow cb received from rtc";
592
+ if (mOnBufferedAmountLowCallback)
593
+ mOnBufferedAmountLowCallback->call([this](Napi::Env env, std::vector<napi_value> &args) {
594
+ PLOG_DEBUG << "mOnBufferedAmountLowCallback call(1)";
595
+ // Check the data channel is not closed
596
+ if(instances.find(this) == instances.end())
597
+ throw ThreadSafeCallback::CancelException();
598
+
599
+ // This will run in main thread and needs to construct the
600
+ // arguments for the call
601
+ args = {};
602
+ PLOG_DEBUG << "mOnBufferedAmountLowCallback call(2)";
603
+ }); });
604
+ }
605
+
606
+ void WebSocketWrapper::onMessage(const Napi::CallbackInfo &info)
607
+ {
608
+ PLOG_DEBUG << "onMessage() called";
609
+ if (!mWebSocketPtr)
610
+ {
611
+ Napi::Error::New(info.Env(), "onMessage() called on destroyed channel").ThrowAsJavaScriptException();
612
+ return;
613
+ }
614
+
615
+ Napi::Env env = info.Env();
616
+ int length = info.Length();
617
+
618
+ if (length < 1 || !info[0].IsFunction())
619
+ {
620
+ Napi::TypeError::New(env, "Function expected").ThrowAsJavaScriptException();
621
+ return;
622
+ }
623
+
624
+ // Callback
625
+ mOnMessageCallback = std::make_unique<ThreadSafeCallback>(info[0].As<Napi::Function>());
626
+
627
+ PLOG_DEBUG << "setting onMessage cb on mWebSocketPtr";
628
+ mWebSocketPtr->onMessage([&](std::variant<rtc::binary, std::string> message)
629
+ {
630
+ PLOG_DEBUG << "onMessage cb received from rtc";
631
+ if (mOnMessageCallback)
632
+ mOnMessageCallback->call([this, message = std::move(message)](Napi::Env env, std::vector<napi_value> &args) {
633
+ PLOG_DEBUG << "mOnMessageCallback call(1)";
634
+ // Check the data channel is not closed
635
+ if(instances.find(this) == instances.end())
636
+ throw ThreadSafeCallback::CancelException();
637
+
638
+ // This will run in main thread and needs to construct the
639
+ // arguments for the call
640
+ if (std::holds_alternative<std::string>(message))
641
+ {
642
+ args = {Napi::String::New(env, std::get<std::string>(message))};
643
+ }
644
+ else
645
+ {
646
+ auto bin = std::get<rtc::binary>(std::move(message));
647
+ args = {Napi::Buffer<std::byte>::Copy(env, bin.data(), bin.size())};
648
+ }
649
+ PLOG_DEBUG << "mOnMessageCallback call(2)";
650
+ }); });
651
+ }
@@ -0,0 +1,58 @@
1
+ #ifndef WEB_SOCKET_WRAPPER_H
2
+ #define WEB_SOCKET_WRAPPER_H
3
+
4
+ #include <iostream>
5
+ #include <string>
6
+ #include <variant>
7
+ #include <memory>
8
+ #include <unordered_set>
9
+
10
+ #include <napi.h>
11
+ #include <rtc/rtc.hpp>
12
+
13
+ #include "thread-safe-callback.h"
14
+
15
+ class WebSocketWrapper : public Napi::ObjectWrap<WebSocketWrapper>
16
+ {
17
+ public:
18
+ static Napi::FunctionReference constructor;
19
+ static Napi::Object Init(Napi::Env env, Napi::Object exports);
20
+ WebSocketWrapper(const Napi::CallbackInfo &info);
21
+ ~WebSocketWrapper();
22
+
23
+ // Functions
24
+ void open(const Napi::CallbackInfo &info);
25
+ void close(const Napi::CallbackInfo &info);
26
+ Napi::Value sendMessage(const Napi::CallbackInfo &info);
27
+ Napi::Value sendMessageBinary(const Napi::CallbackInfo &info);
28
+ Napi::Value isOpen(const Napi::CallbackInfo &info);
29
+ Napi::Value bufferedAmount(const Napi::CallbackInfo &info);
30
+ Napi::Value maxMessageSize(const Napi::CallbackInfo &info);
31
+ void setBufferedAmountLowThreshold(const Napi::CallbackInfo &info);
32
+
33
+ // Callbacks
34
+ void onOpen(const Napi::CallbackInfo &info);
35
+ void onClosed(const Napi::CallbackInfo &info);
36
+ void onError(const Napi::CallbackInfo &info);
37
+ void onBufferedAmountLow(const Napi::CallbackInfo &info);
38
+ void onMessage(const Napi::CallbackInfo &info);
39
+
40
+ // Close all existing WebSockets
41
+ static void CloseAll();
42
+
43
+ private:
44
+ static std::unordered_set<WebSocketWrapper*> instances;
45
+
46
+ void doClose();
47
+
48
+ std::shared_ptr<rtc::WebSocket> mWebSocketPtr = nullptr;
49
+
50
+ // Callback Ptrs
51
+ std::unique_ptr<ThreadSafeCallback> mOnOpenCallback = nullptr;
52
+ std::unique_ptr<ThreadSafeCallback> mOnClosedCallback = nullptr;
53
+ std::unique_ptr<ThreadSafeCallback> mOnErrorCallback = nullptr;
54
+ std::unique_ptr<ThreadSafeCallback> mOnBufferedAmountLowCallback = nullptr;
55
+ std::unique_ptr<ThreadSafeCallback> mOnMessageCallback = nullptr;
56
+ };
57
+
58
+ #endif // WEB_SOCKET_WRAPPER_H