summaryrefslogtreecommitdiff
path: root/chromium/third_party/nearby/src/connections/clients/swift/NearbyCoreAdapter/Sources/GNCCoreAdapter.mm
blob: bf39c99645d33894cc9a919f95e735e1243b03ca (plain)
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
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#import "connections/clients/swift/NearbyCoreAdapter/Sources/Public/NearbyCoreAdapter/GNCCoreAdapter.h"

#import <Foundation/Foundation.h>

#include <memory>
#include <string>
#include <utility>
#include <vector>

#include "connections/core.h"

#import "connections/clients/swift/NearbyCoreAdapter/Sources/GNCAdvertisingOptions+CppConversions.h"
#import "connections/clients/swift/NearbyCoreAdapter/Sources/GNCConnectionOptions+CppConversions.h"
#import "connections/clients/swift/NearbyCoreAdapter/Sources/GNCDiscoveryOptions+CppConversions.h"
#import "connections/clients/swift/NearbyCoreAdapter/Sources/GNCError+Internal.h"
#import "connections/clients/swift/NearbyCoreAdapter/Sources/GNCPayload+CppConversions.h"
#import "connections/clients/swift/NearbyCoreAdapter/Sources/Public/NearbyCoreAdapter/GNCAdvertisingOptions.h"
#import "connections/clients/swift/NearbyCoreAdapter/Sources/Public/NearbyCoreAdapter/GNCConnectionDelegate.h"
#import "connections/clients/swift/NearbyCoreAdapter/Sources/Public/NearbyCoreAdapter/GNCConnectionOptions.h"
#import "connections/clients/swift/NearbyCoreAdapter/Sources/Public/NearbyCoreAdapter/GNCDiscoveryDelegate.h"
#import "connections/clients/swift/NearbyCoreAdapter/Sources/Public/NearbyCoreAdapter/GNCDiscoveryOptions.h"
#import "connections/clients/swift/NearbyCoreAdapter/Sources/Public/NearbyCoreAdapter/GNCError.h"
#import "connections/clients/swift/NearbyCoreAdapter/Sources/Public/NearbyCoreAdapter/GNCPayload.h"
#import "connections/clients/swift/NearbyCoreAdapter/Sources/Public/NearbyCoreAdapter/GNCPayloadDelegate.h"

using ::location::nearby::ByteArray;
using ::location::nearby::connections::AdvertisingOptions;
using ::location::nearby::connections::ConnectionListener;
using ::location::nearby::connections::ConnectionOptions;
using ::location::nearby::connections::ConnectionRequestInfo;
using ::location::nearby::connections::ConnectionResponseInfo;
using ::location::nearby::connections::Core;
using ::location::nearby::connections::DiscoveryListener;
using ::location::nearby::connections::DiscoveryOptions;
using ::location::nearby::connections::Payload;
using ::location::nearby::connections::PayloadListener;
using ::location::nearby::connections::PayloadProgressInfo;
using ResultListener = ::location::nearby::connections::ResultCallback;
using ::location::nearby::connections::ServiceControllerRouter;
using ::location::nearby::connections::Status;

GNCStatus GNCStatusFromCppStatus(Status status) {
  switch (status.value) {
    case Status::kSuccess:
      return GNCStatusSuccess;
    case Status::kError:
      return GNCStatusError;
    case Status::kOutOfOrderApiCall:
      return GNCStatusOutOfOrderApiCall;
    case Status::kAlreadyHaveActiveStrategy:
      return GNCStatusAlreadyHaveActiveStrategy;
    case Status::kAlreadyAdvertising:
      return GNCStatusAlreadyAdvertising;
    case Status::kAlreadyDiscovering:
      return GNCStatusAlreadyDiscovering;
    case Status::kEndpointIoError:
      return GNCStatusEndpointIoError;
    case Status::kEndpointUnknown:
      return GNCStatusEndpointUnknown;
    case Status::kConnectionRejected:
      return GNCStatusConnectionRejected;
    case Status::kAlreadyConnectedToEndpoint:
      return GNCStatusAlreadyConnectedToEndpoint;
    case Status::kNotConnectedToEndpoint:
      return GNCStatusNotConnectedToEndpoint;
    case Status::kBluetoothError:
      return GNCStatusBluetoothError;
    case Status::kBleError:
      return GNCStatusBleError;
    case Status::kWifiLanError:
      return GNCStatusWifiLanError;
    case Status::kPayloadUnknown:
      return GNCStatusPayloadUnknown;
  }
}

@interface GNCCoreAdapter () {
  std::unique_ptr<Core> _core;
  std::unique_ptr<ServiceControllerRouter> _serviceControllerRouter;
}

@end

@implementation GNCCoreAdapter

+ (GNCCoreAdapter *)shared {
  static dispatch_once_t onceToken;
  static GNCCoreAdapter *shared = nil;
  dispatch_once(&onceToken, ^{
    shared = [[GNCCoreAdapter alloc] init];
  });
  return shared;
}

- (instancetype)init {
  self = [super init];
  if (self) {
    _serviceControllerRouter = std::make_unique<ServiceControllerRouter>();
    _core = std::make_unique<Core>(_serviceControllerRouter.get());
  }
  return self;
}

- (void)dealloc {
  // Make sure Core is deleted before ServiceControllerRouter.
  _core.reset();
  _serviceControllerRouter.reset();
}

- (void)startAdvertisingAsService:(NSString *)serviceID
                     endpointInfo:(NSData *)endpointInfo
                          options:(GNCAdvertisingOptions *)advertisingOptions
                         delegate:(id<GNCConnectionDelegate>)delegate
            withCompletionHandler:(void (^)(NSError *error))completionHandler {
  std::string service_id = [serviceID cStringUsingEncoding:[NSString defaultCStringEncoding]];

  AdvertisingOptions advertising_options = [advertisingOptions toCpp];

  ConnectionListener listener;
  listener.initiated_cb = ^(const std::string &endpoint_id, const ConnectionResponseInfo &info) {
    NSString *endpointID = @(endpoint_id.c_str());
    NSData *endpointInfo = [NSData dataWithBytes:info.remote_endpoint_info.data()
                                          length:info.remote_endpoint_info.size()];
    NSString *authenticationToken = @(info.authentication_token.c_str());
    [delegate connectedToEndpoint:endpointID
                 withEndpointInfo:endpointInfo
              authenticationToken:authenticationToken];
  };
  listener.accepted_cb = ^(const std::string &endpoint_id) {
    NSString *endpointID = @(endpoint_id.c_str());
    [delegate acceptedConnectionToEndpoint:endpointID];
  };
  listener.rejected_cb = ^(const std::string &endpoint_id, Status status) {
    NSString *endpointID = @(endpoint_id.c_str());
    [delegate rejectedConnectionToEndpoint:endpointID withStatus:GNCStatusFromCppStatus(status)];
  };
  listener.disconnected_cb = ^(const std::string &endpoint_id) {
    NSString *endpointID = @(endpoint_id.c_str());
    [delegate disconnectedFromEndpoint:endpointID];
  };

  ConnectionRequestInfo connection_request_info;
  connection_request_info.endpoint_info =
      ByteArray((const char *)endpointInfo.bytes, endpointInfo.length);
  connection_request_info.listener = std::move(listener);

  ResultListener result;
  result.result_cb = ^(Status status) {
    NSError *err = NSErrorFromCppStatus(status);
    if (completionHandler) {
      completionHandler(err);
    }
  };

  _core->StartAdvertising(service_id, advertising_options, connection_request_info, result);
}

- (void)stopAdvertisingWithCompletionHandler:(void (^)(NSError *error))completionHandler {
  ResultListener result;
  result.result_cb = ^(Status status) {
    NSError *err = NSErrorFromCppStatus(status);
    if (completionHandler) {
      completionHandler(err);
    }
  };

  _core->StopAdvertising(result);
}

- (void)startDiscoveryAsService:(NSString *)serviceID
                        options:(GNCDiscoveryOptions *)discoveryOptions
                       delegate:(id<GNCDiscoveryDelegate>)delegate
          withCompletionHandler:(void (^)(NSError *error))completionHandler {
  std::string service_id = [serviceID cStringUsingEncoding:[NSString defaultCStringEncoding]];

  DiscoveryOptions discovery_options = [discoveryOptions toCpp];

  DiscoveryListener listener;
  listener.endpoint_found_cb = ^(const std::string &endpoint_id, const ByteArray &endpoint_info,
                                 const std::string &service_id) {
    NSString *endpointID = @(endpoint_id.c_str());
    NSData *info = [NSData dataWithBytes:endpoint_info.data() length:endpoint_info.size()];
    [delegate foundEndpoint:endpointID withEndpointInfo:info];
  };
  listener.endpoint_lost_cb = ^(const std::string &endpoint_id) {
    NSString *endpointID = @(endpoint_id.c_str());
    [delegate lostEndpoint:endpointID];
  };

  ResultListener result;
  result.result_cb = ^(Status status) {
    NSError *err = NSErrorFromCppStatus(status);
    if (completionHandler) {
      completionHandler(err);
    }
  };

  _core->StartDiscovery(service_id, discovery_options, std::move(listener), result);
}

- (void)stopDiscoveryWithCompletionHandler:(void (^)(NSError *error))completionHandler {
  ResultListener result;
  result.result_cb = ^(Status status) {
    NSError *err = NSErrorFromCppStatus(status);
    if (completionHandler) {
      completionHandler(err);
    }
  };

  _core->StopDiscovery(result);
}

- (void)requestConnectionToEndpoint:(NSString *)endpointID
                       endpointInfo:(NSData *)endpointInfo
                            options:(GNCConnectionOptions *)connectionOptions
                           delegate:(id<GNCConnectionDelegate>)delegate
              withCompletionHandler:(void (^)(NSError *error))completionHandler {
  std::string endpoint_id = [endpointID cStringUsingEncoding:[NSString defaultCStringEncoding]];

  ConnectionListener listener;
  listener.initiated_cb = ^(const std::string &endpoint_id, const ConnectionResponseInfo &info) {
    NSString *endpointID = @(endpoint_id.c_str());
    NSData *endpointInfo = [NSData dataWithBytes:info.remote_endpoint_info.data()
                                          length:info.remote_endpoint_info.size()];
    NSString *authenticationToken = @(info.authentication_token.c_str());
    [delegate connectedToEndpoint:endpointID
                 withEndpointInfo:endpointInfo
              authenticationToken:authenticationToken];
  };
  listener.accepted_cb = ^(const std::string &endpoint_id) {
    NSString *endpointID = @(endpoint_id.c_str());
    [delegate acceptedConnectionToEndpoint:endpointID];
  };
  listener.rejected_cb = ^(const std::string &endpoint_id, Status status) {
    NSString *endpointID = @(endpoint_id.c_str());
    [delegate rejectedConnectionToEndpoint:endpointID withStatus:GNCStatusFromCppStatus(status)];
  };
  listener.disconnected_cb = ^(const std::string &endpoint_id) {
    NSString *endpointID = @(endpoint_id.c_str());
    [delegate disconnectedFromEndpoint:endpointID];
  };

  ConnectionRequestInfo connection_request_info;
  connection_request_info.endpoint_info =
      ByteArray((const char *)endpointInfo.bytes, endpointInfo.length);
  connection_request_info.listener = std::move(listener);

  ConnectionOptions connection_options = [connectionOptions toCpp];

  ResultListener result;
  result.result_cb = ^(Status status) {
    NSError *err = NSErrorFromCppStatus(status);
    if (completionHandler) {
      completionHandler(err);
    }
  };

  _core->RequestConnection(endpoint_id, connection_request_info, connection_options, result);
}

- (void)acceptConnectionRequestFromEndpoint:(NSString *)endpointID
                                   delegate:(id<GNCPayloadDelegate>)delegate
                      withCompletionHandler:(void (^)(NSError *error))completionHandler {
  std::string endpoint_id = [endpointID cStringUsingEncoding:[NSString defaultCStringEncoding]];

  PayloadListener listener;
  listener.payload_cb = ^(const std::string &endpoint_id, Payload payload) {
    NSString *endpointID = @(endpoint_id.c_str());
    GNCPayload *gncPayload = [GNCPayload fromCpp:std::move(payload)];
    [delegate receivedPayload:gncPayload fromEndpoint:endpointID];
  };
  listener.payload_progress_cb =
      ^(const std::string &endpoint_id, const PayloadProgressInfo &info) {
        NSString *endpointID = @(endpoint_id.c_str());
        GNCPayloadStatus status;
        switch (info.status) {
          case PayloadProgressInfo::Status::kSuccess:
            status = GNCPayloadStatusSuccess;
            break;
          case PayloadProgressInfo::Status::kFailure:
            status = GNCPayloadStatusFailure;
            break;
          case PayloadProgressInfo::Status::kInProgress:
            status = GNCPayloadStatusInProgress;
            break;
          case PayloadProgressInfo::Status::kCanceled:
            status = GNCPayloadStatusCanceled;
            break;
        }
        [delegate receivedProgressUpdateForPayload:info.payload_id
                                        withStatus:status
                                      fromEndpoint:endpointID
                                   bytesTransfered:info.bytes_transferred
                                        totalBytes:info.total_bytes];
      };

  ResultListener result;
  result.result_cb = ^(Status status) {
    NSError *err = NSErrorFromCppStatus(status);
    if (completionHandler) {
      completionHandler(err);
    }
  };

  _core->AcceptConnection(endpoint_id, std::move(listener), result);
}

- (void)rejectConnectionRequestFromEndpoint:(NSString *)endpointID
                      withCompletionHandler:(void (^)(NSError *error))completionHandler {
  std::string endpoint_id = [endpointID cStringUsingEncoding:[NSString defaultCStringEncoding]];

  ResultListener result;
  result.result_cb = ^(Status status) {
    NSError *err = NSErrorFromCppStatus(status);
    if (completionHandler) {
      completionHandler(err);
    }
  };

  _core->RejectConnection(endpoint_id, result);
}

- (void)sendPayload:(GNCPayload *)payload
              toEndpoints:(NSArray<NSString *> *)endpointIDs
    withCompletionHandler:(void (^)(NSError *error))completionHandler {
  std::vector<std::string> endpoint_ids;
  endpoint_ids.reserve([endpointIDs count]);
  for (NSString *endpointID in endpointIDs) {
    std::string endpoint_id = [endpointID cStringUsingEncoding:[NSString defaultCStringEncoding]];
    endpoint_ids.push_back(endpoint_id);
  }

  ResultListener result;
  result.result_cb = ^(Status status) {
    NSError *err = NSErrorFromCppStatus(status);
    if (completionHandler) {
      completionHandler(err);
    }
  };

  _core->SendPayload(endpoint_ids, [payload toCpp], result);
}

- (void)cancelPayload:(int64_t)payloadID
    withCompletionHandler:(void (^)(NSError *error))completionHandler {
  ResultListener result;
  result.result_cb = ^(Status status) {
    NSError *err = NSErrorFromCppStatus(status);
    if (completionHandler) {
      completionHandler(err);
    }
  };

  _core->CancelPayload(payloadID, result);
}

- (void)disconnectFromEndpoint:(NSString *)endpointID
         withCompletionHandler:(void (^)(NSError *error))completionHandler {
  std::string endpoint_id = [endpointID cStringUsingEncoding:[NSString defaultCStringEncoding]];

  ResultListener result;
  result.result_cb = ^(Status status) {
    NSError *err = NSErrorFromCppStatus(status);
    if (completionHandler) {
      completionHandler(err);
    }
  };

  _core->DisconnectFromEndpoint(endpoint_id, result);
}

- (void)stopAllEndpointsWithCompletionHandler:(void (^)(NSError *error))completionHandler {
  ResultListener result;
  result.result_cb = ^(Status status) {
    NSError *err = NSErrorFromCppStatus(status);
    if (completionHandler) {
      completionHandler(err);
    }
  };
  _core->StopAllEndpoints(result);
}

- (void)initiateBandwidthUpgrade:(NSString *)endpointID
           withCompletionHandler:(void (^)(NSError *error))completionHandler {
  std::string endpoint_id = [endpointID cStringUsingEncoding:[NSString defaultCStringEncoding]];

  ResultListener result;
  result.result_cb = ^(Status status) {
    NSError *err = NSErrorFromCppStatus(status);
    if (completionHandler) {
      completionHandler(err);
    }
  };

  _core->InitiateBandwidthUpgrade(endpoint_id, result);
}

- (NSString *)localEndpointID {
  std::string endpoint_id = _core->GetLocalEndpointId();
  return @(endpoint_id.c_str());
}

@end