-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathbridge.android.ts
More file actions
189 lines (175 loc) · 6.36 KB
/
bridge.android.ts
File metadata and controls
189 lines (175 loc) · 6.36 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
import { HeaderType } from './common';
import { NativeBridgeDefinition } from './websocket.definition';
interface ExtendedArrayBuffer extends ArrayBuffer {
from?(nativeBuffer: java.nio.ByteBuffer): ArrayBuffer;
}
const fastConversionAvailable = !!(ArrayBuffer as unknown as ExtendedArrayBuffer).from;
@NativeClass()
class WebSocketListenerImpl extends okhttp3.WebSocketListener {
private owner: WeakRef<NativeBridge>;
constructor(owner: NativeBridge) {
super();
this.owner = new WeakRef(owner);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return (global as any).__native(this);
}
public onClosed(param0: okhttp3.WebSocket, param1: number, param2: string): void {
this.owner.get()?.onClosed(param0, param1, param2);
}
public onMessage(param0: okhttp3.WebSocket, param1: string | okio.ByteString): void {
this.owner.get()?.onMessage(param0, param1);
}
public onFailure(param0: okhttp3.WebSocket, param1: java.lang.Throwable, param2: okhttp3.Response): void {
this.owner.get()?.onFailure(param0, param1, param2);
}
public onOpen(param0: okhttp3.WebSocket, param1: okhttp3.Response): void {
this.owner.get()?.onOpen(param0, param1);
}
public onClosing(param0: okhttp3.WebSocket, param1: number, param2: string): void {
this.owner.get()?.onClosing(param0, param1, param2);
}
}
function getDefaultOrigin(uri: string) {
try {
let defaultOrigin;
let scheme = '';
const requestURI = new java.net.URI(uri);
switch (requestURI.getScheme()) {
case 'wss':
scheme += 'https';
break;
case 'ws':
scheme += 'http';
break;
case 'http':
case 'https':
scheme += requestURI.getScheme();
break;
default:
break;
}
if (requestURI.getPort() != -1) {
defaultOrigin = `${scheme}://${requestURI.getHost()}:${requestURI.getPort()}`;
} else {
defaultOrigin = `${scheme}://${requestURI.getHost()}`;
}
return defaultOrigin;
} catch (e) {
throw new java.lang.IllegalArgumentException('Unable to set ' + uri + ' as default origin header');
}
}
export class NativeBridge extends NativeBridgeDefinition {
client!: okhttp3.OkHttpClient;
listener!: WebSocketListenerImpl;
nativeWs!: okhttp3.WebSocket;
startLooper?: android.os.Looper;
handler?: android.os.Handler;
connect(url: string, protocols: string[], headers: HeaderType): void {
this.startLooper = android.os.Looper.myLooper();
this.handler = new android.os.Handler(this.startLooper);
protocols = protocols || [];
this.client = new okhttp3.OkHttpClient.Builder()
.connectTimeout(10, java.util.concurrent.TimeUnit.SECONDS)
.writeTimeout(10, java.util.concurrent.TimeUnit.SECONDS)
.readTimeout(0, java.util.concurrent.TimeUnit.MINUTES) // Disable timeouts for read
.build();
const requestBuilder = new okhttp3.Request.Builder();
requestBuilder.url(url);
for (const header of Object.keys(headers.headers)) {
requestBuilder.addHeader(header, `${headers.headers[header]}`);
}
if (protocols.length > 0) {
requestBuilder.addHeader('Sec-WebSocket-Protocol', protocols.join(','));
}
if (!headers.headers['origin']) {
requestBuilder.addHeader('origin', getDefaultOrigin(url));
}
// TODO: cookies? There isn't a default cookie jar in android/nativescript
this.listener = new WebSocketListenerImpl(this);
this.nativeWs = this.client.newWebSocket(requestBuilder.build(), this.listener);
}
send(data: string | ArrayBuffer | ArrayBufferView | Blob): void {
if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {
const byteBuffer = Array.create('byte', data.byteLength);
const view = new Uint8Array(data instanceof ArrayBuffer ? data : data.buffer);
for (let i = 0; i < view.length; i++) {
byteBuffer[i] = view[i];
}
this.nativeWs.send(okio.ByteString.of(byteBuffer));
return;
}
if (typeof data === 'string') {
this.nativeWs.send(data);
return;
}
throw new Error('Unsupported data type');
}
closeWithCodeReason(statusCode: number, closeReason: string) {
this.nativeWs.close(statusCode, closeReason);
}
sendPing() {
this.nativeWs.send(okio.ByteString.EMPTY);
}
public onClosed(ws: okhttp3.WebSocket, code: number, reason: string): void {
this.ws._websocketClosed(code, reason, true);
}
public onMessage(ws: okhttp3.WebSocket, data: okio.ByteString | string): void {
if (!this.isCorrectThread()) {
this.scheduleToThread(() => this.onMessage(ws, data));
return;
}
if (data instanceof okio.ByteString) {
let arrayBuffer: ArrayBuffer;
if (fastConversionAvailable) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
arrayBuffer = (ArrayBuffer as unknown as ExtendedArrayBuffer).from!(data.asByteBuffer());
} else {
const bufferView = new Uint8Array(data.size());
for (let i = 0; i < data.size(); i++) {
bufferView[i] = data.getByte(i);
}
arrayBuffer = bufferView.buffer;
}
this.ws._websocketMessage(arrayBuffer);
return;
}
this.ws._websocketMessage(data);
}
public onFailure(param0: okhttp3.WebSocket, param1: java.lang.Throwable, param2: okhttp3.Response): void {
if (!this.isCorrectThread()) {
this.scheduleToThread(() => this.onFailure(param0, param1, param2));
return;
}
let message = param1.getLocalizedMessage();
if (!message) {
if (param1 instanceof java.io.EOFException) {
message = 'The remote server closed the connection.';
}
}
this.ws._websocketFailed(message);
}
public onOpen(param0: okhttp3.WebSocket, param1: okhttp3.Response): void {
if (!this.isCorrectThread()) {
this.scheduleToThread(() => this.onOpen(param0, param1));
return;
}
this.ws._websocketOpen(param1.protocol().toString());
}
public onClosing(websocket: okhttp3.WebSocket, code: number, reason: string): void {
websocket.close(code, reason);
}
private isCorrectThread() {
return !this.handleThreading || !this.startLooper || android.os.Looper.myLooper() === this.startLooper;
}
private scheduleToThread(action: () => void) {
if (this.handleThreading && this.handler) {
this.handler.post(
new java.lang.Runnable({
run: action,
})
);
} else {
action();
}
}
}