@functionland/react-native-fula 1.54.8 → 1.54.10

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.
package/ios/Fula.swift CHANGED
@@ -135,7 +135,31 @@ class FulaModule: NSObject {
135
135
  return convertIntToByte(keyInt)
136
136
  }
137
137
 
138
- @objc func registerLifecycleListener() {
138
+ @objc func applicationWillResignActive() {
139
+ // Log that the app will resign active
140
+ os_log("Application will resign active", log: OSLog.viewCycle, type: .info)
141
+ }
142
+
143
+ @objc func applicationDidEnterBackground() {
144
+ // Log that the app has entered the background
145
+ os_log("Application did enter background", log: OSLog.viewCycle, type: .info)
146
+ }
147
+
148
+ @objc func applicationWillTerminate() {
149
+ // Attempt to shut down Fula cleanly (similar to onHostDestroy)
150
+ os_log("Application will terminate - shutting down Fula", log: OSLog.viewCycle, type: .info)
151
+ do {
152
+ if let fulaClient = self.fula {
153
+ try fulaClient.shutdown()
154
+ os_log("Fula shutdown successfully.", log: OSLog.viewCycle, type: .info)
155
+ }
156
+ } catch {
157
+ os_log("Error shutting down Fula: %{public}@", log: OSLog.viewCycle, type: .error, String(describing: error))
158
+ }
159
+ }
160
+
161
+ @objc(registerLifecycleListener:withRejecter:)
162
+ func registerLifecycleListener(resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
139
163
  NotificationCenter.default.addObserver(
140
164
  self,
141
165
  selector: #selector(applicationWillResignActive),
@@ -153,49 +177,34 @@ class FulaModule: NSObject {
153
177
  selector: #selector(applicationWillTerminate),
154
178
  name: UIApplication.willTerminateNotification,
155
179
  object: nil)
180
+
181
+ // Assuming the operation is always successful
182
+ resolve(true)
156
183
  }
157
184
 
158
185
  deinit {
159
186
  NotificationCenter.default.removeObserver(self)
160
187
  }
161
188
 
162
- @objc func applicationWillResignActive() {
163
- // Handle app will resign active (similar to onHostPause)
164
- }
165
-
166
- @objc func applicationDidEnterBackground() {
167
- // Handle app entered background
168
- }
169
-
170
- @objc func applicationWillTerminate() {
171
- // Attempt to shut down Fula cleanly (similar to onHostDestroy)
172
- do {
173
- try shutdownInternal()
174
- } catch {
175
- print("Error shutting down Fula: \(error)")
176
- }
177
- }
178
-
179
-
180
189
  @objc(checkConnection:withResolver:withRejecter:)
181
190
  func checkConnection(timeout: NSNumber, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
182
- OSLog.viewCycle.info("ReactNative checkConnection started with timeout=\(timeout)")
191
+ NSLog("ReactNative checkConnection started with timeout=\(timeout)")
183
192
 
184
193
  if let timeoutInt = timeout as? Int {
185
- if fula != nil {
194
+ if self.fula != nil {
186
195
  DispatchQueue.global(qos: .default).async {
187
196
  do {
188
197
  let connectionStatus = try self.checkConnectionInternal(timeout: timeoutInt)
189
- OSLog.viewCycle.info("ReactNative checkConnection ended \(connectionStatus)")
198
+ NSLog("ReactNative checkConnection ended \(connectionStatus)")
190
199
  resolve(connectionStatus)
191
200
  }
192
201
  catch let error {
193
- OSLog.viewCycle.info("ReactNative checkConnection failed with Error: \(error.localizedDescription)")
202
+ NSLog("ReactNative checkConnection failed with Error: \(error.localizedDescription)")
194
203
  resolve(false)
195
204
  }
196
205
  }
197
206
  } else {
198
- OSLog.viewCycle.info("ReactNative checkConnection fula is null")
207
+ NSLog("ReactNative checkConnection fula is null")
199
208
  resolve(false)
200
209
  }
201
210
  } else {
@@ -207,13 +216,13 @@ class FulaModule: NSObject {
207
216
 
208
217
  @objc(newClient:withStorePath:withBloxAddr:withExchange:withAutoFlush:withUseRelay:withRefresh:withResolver:withRejecter:)
209
218
  func newClient(identityString: String, storePath: String, bloxAddr: String, exchange: String, autoFlush: Bool, useRelay: Bool, refresh: Bool, resolve:RCTPromiseResolveBlock,reject:RCTPromiseRejectBlock) -> Void {
210
- print("ReactNative", "newClient storePath= " , storePath , " bloxAddr= " , bloxAddr , " exchange= " , exchange , " autoFlush= " , autoFlush , " useRelay= " , useRelay , " refresh= " , refresh);
219
+ print("ReactNative", "newClient storePath= " , storePath , " bloxAddr= " , bloxAddr , " exchange= " , exchange , " autoFlush= " , autoFlush , " useRelay= " , useRelay , " refresh= " , refresh)
211
220
  do {
212
221
  print("ReactNative", "newClient storePath= ", storePath)
213
222
  let identity = toByte(identityString)
214
223
  print("ReactNative", "newClient identity= ", identityString)
215
224
  try newClientInternal(identity: identity, storePath: storePath, bloxAddr: bloxAddr, exchange: exchange, autoFlush: autoFlush, useRelay: useRelay, refresh: refresh)
216
- let peerId = fula?.id_()
225
+ let peerId = self.fula?.id_()
217
226
  resolve(peerId)
218
227
  } catch let error {
219
228
  print("ReactNative", "newClient failed with Error: ", error.localizedDescription)
@@ -227,9 +236,9 @@ class FulaModule: NSObject {
227
236
  print("ReactNative", "isReady started")
228
237
  var initialized = false
229
238
  do {
230
- if (fula != nil && !fula!.id_().isEmpty) {
239
+ if (self.fula != nil && !self.fula!.id_().isEmpty) {
231
240
  if (filesystemCheck) {
232
- if (client != nil && rootCid != nil && !rootCid!.isEmpty) {
241
+ if (self.client != nil && rootCid != nil && !rootCid!.isEmpty) {
233
242
  initialized = true
234
243
  }
235
244
  } else {
@@ -248,23 +257,23 @@ class FulaModule: NSObject {
248
257
  @objc(initFula:withStorePath:withBloxAddr:withExchange:withAutoFlush:withRootConfig:withUseRelay:withRefresh:withResolver:withRejecter:)
249
258
  func initFula(identityString: String, storePath: String, bloxAddr: String, exchange: String, autoFlush: Bool, rootConfig: String, useRelay: Bool, refresh: Bool, resolve:RCTPromiseResolveBlock,reject:RCTPromiseRejectBlock) -> Void {
250
259
 
251
- OSLog.viewCycle.info("ReactNative - init started")
260
+ NSLog("ReactNative - init started")
252
261
 
253
262
  do {
254
263
 
255
264
  var resultData = Dictionary<String, String>()
256
- OSLog.viewCycle.info("ReactNative init storePath= \(storePath)")
265
+ NSLog("ReactNative init storePath= \(storePath)")
257
266
  let identity = self.toByte(identityString)
258
- OSLog.viewCycle.info("ReactNative init identity= \(identityString)")
267
+ NSLog("ReactNative init identity= \(identityString)")
259
268
  let obj = try initInternal(identity: identity, storePath: storePath, bloxAddr: bloxAddr, exchange: exchange, autoFlush: autoFlush, _rootCid: rootConfig, useRelay: useRelay, refresh: refresh)
260
- OSLog.viewCycle.info("ReactNative init object created: [ \(obj[0]), \(obj[1]), \(obj[2]) ]")
269
+ NSLog("ReactNative init object created: [ \(obj[0]), \(obj[1]), \(obj[2]) ]")
261
270
  resultData["peerId"] = obj[0]
262
271
  resultData["rootCid"] = obj[1]
263
272
  resultData["wnfs_key"] = obj[2]
264
273
  resolve(resultData as NSDictionary)
265
274
 
266
275
  } catch let error {
267
- OSLog.viewCycle.info("ReactNative init failed with Error: \(error.localizedDescription)")
276
+ NSLog("ReactNative init failed with Error: \(error.localizedDescription)")
268
277
  reject("ERR_FULA", "init failed", error)
269
278
  }
270
279
 
@@ -288,7 +297,7 @@ class FulaModule: NSObject {
288
297
  }
289
298
 
290
299
  func checkConnectionInternal(timeout: Int) throws -> Bool {
291
- OSLog.viewCycle.info("ReactNative checkConnectionInternal started with timeout: \(timeout)")
300
+ NSLog("ReactNative checkConnectionInternal started with timeout: \(timeout)")
292
301
  var connectionStatus = false
293
302
 
294
303
  if let fula = self.fula {
@@ -297,13 +306,13 @@ class FulaModule: NSObject {
297
306
 
298
307
  queue.async {
299
308
  do {
300
- OSLog.viewCycle.info("ReactNative connectToBlox started")
309
+ NSLog("ReactNative connectToBlox started")
301
310
  try fula.connectToBlox()
302
311
  connectionStatus = true
303
- OSLog.viewCycle.info("ReactNative checkConnectionInternal succeeded")
312
+ NSLog("ReactNative checkConnectionInternal succeeded")
304
313
  semaphore.signal()
305
314
  } catch let error {
306
- OSLog.viewCycle.info("ReactNative checkConnectionInternal failed with Error: \(error.localizedDescription)")
315
+ NSLog("ReactNative checkConnectionInternal failed with Error: \(error.localizedDescription)")
307
316
  semaphore.signal()
308
317
  }
309
318
  }
@@ -311,13 +320,13 @@ class FulaModule: NSObject {
311
320
  let timeoutResult = semaphore.wait(timeout: .now() + .seconds(timeout))
312
321
  switch timeoutResult {
313
322
  case .timedOut:
314
- OSLog.viewCycle.info("ReactNative checkConnectionInternal timed out")
323
+ NSLog("ReactNative checkConnectionInternal timed out")
315
324
  return false
316
325
  case .success:
317
326
  return connectionStatus
318
327
  }
319
328
  } else {
320
- OSLog.viewCycle.info("ReactNative checkConnectionInternal failed because fula is not initialized")
329
+ NSLog("ReactNative checkConnectionInternal failed because fula is not initialized")
321
330
  return false
322
331
  }
323
332
  }
@@ -325,29 +334,29 @@ class FulaModule: NSObject {
325
334
  @objc(checkFailedActions:withTimeout:withResolver:withRejecter:)
326
335
  func checkFailedActions(retry: Bool, timeout: Int, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) -> Void {
327
336
  do {
328
- guard let fula = fula else {
337
+ guard let fula = self.fula else {
329
338
  throw NSError(domain: "ERR_FULA", code: 1001, userInfo: [NSLocalizedDescriptionKey: "Fula is not initialized"])
330
339
  }
331
340
 
332
341
  if !retry {
333
- OSLog.viewCycle.info("ReactNative checkFailedActions without retry")
342
+ NSLog("ReactNative checkFailedActions without retry")
334
343
  let failedLinks = try fula.listFailedPushes()
335
344
 
336
345
  let nextFailedLink = try failedLinks.next()
337
346
  if nextFailedLink != nil {
338
347
  // Assuming nextFailedLink is of type Data; replace `toHex()` with an appropriate method to convert Data to a hex string
339
- OSLog.viewCycle.info("ReactNative checkFailedActions found")
348
+ NSLog("ReactNative checkFailedActions found")
340
349
  resolve(true)
341
350
  } else {
342
351
  resolve(false)
343
352
  }
344
353
  } else {
345
- OSLog.viewCycle.info("ReactNative checkFailedActions with retry")
354
+ NSLog("ReactNative checkFailedActions with retry")
346
355
  let retryResults = try retryFailedActionsInternal(timeout: timeout) // Ensure retryFailedActionsInternal accepts a timeout parameter
347
356
  resolve(!retryResults)
348
357
  }
349
358
  } catch let error {
350
- OSLog.viewCycle.info("ReactNative checkFailedActions failed with Error: \(error.localizedDescription)")
359
+ NSLog("ReactNative checkFailedActions failed with Error: \(error.localizedDescription)")
351
360
  reject("ERR_FULA", "CheckFailedActions failed", error)
352
361
  }
353
362
  }
@@ -355,10 +364,10 @@ class FulaModule: NSObject {
355
364
 
356
365
 
357
366
  func retryFailedActionsInternal(timeout: Int) throws -> Bool {
358
- OSLog.viewCycle.info("ReactNative retryFailedActionsInternal started")
367
+ NSLog("ReactNative retryFailedActionsInternal started")
359
368
 
360
- guard let fula = fula else {
361
- OSLog.viewCycle.info("ReactNative retryFailedActionsInternal failed because fula is not initialized")
369
+ guard let fula = self.fula else {
370
+ NSLog("ReactNative retryFailedActionsInternal failed because fula is not initialized")
362
371
  return false
363
372
  }
364
373
 
@@ -367,79 +376,107 @@ class FulaModule: NSObject {
367
376
 
368
377
  if connectionCheck {
369
378
  do {
370
- OSLog.viewCycle.info("ReactNative retryFailedPushes started")
379
+ NSLog("ReactNative retryFailedPushes started")
371
380
  try fula.retryFailedPushes()
372
- OSLog.viewCycle.info("ReactNative flush started")
381
+ NSLog("ReactNative flush started")
373
382
  try fula.flush()
374
383
  return true
375
384
  } catch let error {
376
385
  try fula.flush()
377
- OSLog.viewCycle.info("ReactNative retryFailedActionsInternal failed with Error: \(error.localizedDescription)")
386
+ NSLog("ReactNative retryFailedActionsInternal failed with Error: \(error.localizedDescription)")
378
387
  return false
379
388
  }
380
389
  } else {
381
- OSLog.viewCycle.info("ReactNative retryFailedActionsInternal failed because blox is offline")
390
+ NSLog("ReactNative retryFailedActionsInternal failed because blox is offline")
382
391
  return false
383
392
  }
384
393
  } catch let error {
385
- OSLog.viewCycle.info("ReactNative retryFailedActionsInternal failed with Error: \(error.localizedDescription)")
394
+ NSLog("ReactNative retryFailedActionsInternal failed with Error: \(error.localizedDescription)")
386
395
  return false
387
396
  }
388
397
  }
389
398
 
390
-
391
-
392
399
  func createPeerIdentity(privateKey: Data) throws -> Data {
393
- do {
394
- // 1: First: create public key from provided private key
395
- // 2: Should read the local keychain store (if it is key-value, key is public key above,
396
- // 3: if found, decrypt using the private key
397
- // 4: If not found or decryption not successful, generate an identity
398
- // 5: then encrypt and store in keychain
399
- // TODO: recheck error handling
400
- var encryptedKey = userDataHelper.getValue(FulaModule.PRIVATE_KEY_STORE_ID)
401
- let secretKey = try Cryptography.generateKey(privateKey)
402
- if (encryptedKey == nil) {
403
- var error: NSError?
404
- let autoGeneratedIdentity = FulamobileGenerateEd25519Key(&error)
405
- if error != nil {
406
- throw error!
407
- }
408
- encryptedKey = try Cryptography.encryptMsg(autoGeneratedIdentity!.toUint8Array(), secretKey)
409
- userDataHelper.add(FulaModule.PRIVATE_KEY_STORE_ID, encryptedKey!)
400
+ let secretKey = try Cryptography.generateKey(privateKey)
401
+
402
+ var encryptedKey: String? = userDataHelper.getValue(FulaModule.PRIVATE_KEY_STORE_ID)
403
+ NSLog("ReactNative createPeerIdentity encryptedKey=\(encryptedKey ?? "nil")")
404
+ if encryptedKey == nil {
405
+ let privateKeyString = String(data: privateKey, encoding: .utf8) ?? ""
406
+
407
+ guard !privateKeyString.isEmpty else {
408
+ throw NSError(domain: "KeyGenerationError", code: -1, userInfo: [NSLocalizedDescriptionKey: "Private key string conversion failed"])
410
409
  }
411
- return try Cryptography.decryptMsg(encryptedKey!, secretKey).toData()
410
+ var error: NSError?
411
+ guard let autoGeneratedIdentity = FulamobileGenerateEd25519KeyFromString(privateKeyString, &error)?.toUint8Array() else {
412
+ throw error ?? NSError(domain: "KeyGenerationError", code: -1, userInfo: nil)
413
+ }
414
+ encryptedKey = try Cryptography.encryptMsg([UInt8](autoGeneratedIdentity), [UInt8](secretKey))
415
+ NSLog("ReactNative createPeerIdentity encryptedKey2=\(encryptedKey)")
416
+ userDataHelper.add(FulaModule.PRIVATE_KEY_STORE_ID, encryptedKey ?? "")
417
+ }
418
+
419
+ // Assuming decryptMsg returns Data or throws an error if decryption fails
420
+ guard let encryptedKeyData = encryptedKey, !encryptedKeyData.isEmpty else {
421
+ throw NSError(domain: "DecryptionError", code: -1, userInfo: [NSLocalizedDescriptionKey: "Encrypted key is empty"])
422
+ }
423
+ let decryptedData = try Cryptography.decryptMsg(encryptedKeyData, Array(secretKey))
424
+ let hexString = decryptedData.map { String(format: "%02hhx", $0) }.joined()
425
+ NSLog("ReactNative createPeerIdentity decryptedData=\(hexString)")
426
+ return Data(decryptedData)
427
+ }
428
+
429
+ func decryptLibp2pIdentity(_ encryptedLibp2pId: String, with encryptionSecretKey: Data) throws -> String {
430
+ // Convert Data to [UInt8]
431
+ let secretKeyBytes = [UInt8](encryptionSecretKey)
432
+
433
+ // Attempt decryption
434
+ guard let decryptedBytes = try? Cryptography.decryptMsg(encryptedLibp2pId, secretKeyBytes) else {
435
+ throw NSError(domain: "DecryptionError", code: 1, userInfo: [NSLocalizedDescriptionKey: "Failed to decrypt Libp2p ID"])
436
+ }
437
+
438
+ // Assuming decryptedBytes is an array of UInt8
439
+ return String(decoding: decryptedBytes, as: UTF8.self)
440
+ }
412
441
 
413
- } catch let error {
414
- print("ReactNative", "createPeerIdentity failed with Error: ", error.localizedDescription)
415
- throw error
442
+ func createEncryptedLibp2pId(from identity: Data, with encryptionSecretKey: Data) throws -> String {
443
+ var error: NSError?
444
+ guard let autoGeneratedIdentity = FulamobileGenerateEd25519Key(&error) else {
445
+ throw error ?? NSError(domain: "KeyGenerationError", code: -1, userInfo: nil)
416
446
  }
447
+ let encryptedLibp2pId = try Cryptography.encryptMsg(Array(autoGeneratedIdentity), Array(encryptionSecretKey))
448
+ userDataHelper.add(FulaModule.PRIVATE_KEY_STORE_ID, encryptedLibp2pId)
449
+ return encryptedLibp2pId
417
450
  }
418
451
 
419
452
  func createNewrootCid(identity: Data) throws -> Void {
420
453
  let hash32 = identity.sha256()
421
- print("ReactNative", "wnfsKey=" , identity.toHex() , "; hash32 = " , hash32.toHex());
422
- if (fula != nil) {
423
- try fula?.flush()
454
+ NSLog("ReactNative createNewrootCid wnfsKey= \(identity.toHex()) , hash32 = \(hash32.toHex())")
455
+ if (self.fula != nil) {
456
+ NSLog("ReactNative createNewrootCid self.fula not null")
457
+ try self.fula?.flush()
424
458
  }
425
- rootCid = try wnfs?.Init(wnfsKey: hash32)
426
- print("ReactNative", "privateForest is created: ", rootCid!)
459
+ NSLog("ReactNative fula flushed")
460
+ rootCid = try self.wnfs?.Init(wnfsKey: hash32)
461
+ NSLog("ReactNative privateForest is created: \(rootCid!)")
427
462
  wnfsKey = identity
428
- print("ReactNative", "rootCid is created: cid=", rootCid!, " ; wnfs_key=", wnfsKey!.toHex(), "; hash32=", hash32)
463
+ NSLog("ReactNative rootCid is created: cid= \(rootCid!) wnfs_key= \(wnfsKey!.toHex()), hash32=\(hash32)")
429
464
  try encryptAndStoreConfig()
430
465
  }
431
466
 
432
467
  func loadWnfs(_ _wnfsKey: Data , _ _rootCid: String) throws {
433
- OSLog.viewCycle.info("ReactNative loadWnfs called: rootCid=\(_rootCid)")
468
+ NSLog("ReactNative loadWnfs called: _rootCid=\(_rootCid)")
434
469
  let hash32 = _wnfsKey.sha256()
435
- OSLog.viewCycle.info("ReactNative wnfsKey= \(_wnfsKey.toHex()) ; hash32 = \(hash32.toHex())");
436
- try wnfs?.LoadWithWNFSKey(wnfsKey: hash32, cid: _rootCid)
470
+ NSLog("ReactNative wnfsKey= \(_wnfsKey.toHex()) ; hash32 = \(hash32.toHex())")
471
+ try self.wnfs?.LoadWithWNFSKey(wnfsKey: hash32, cid: _rootCid)
472
+ NSLog("ReactNative loadWnfs LoadWithWNFSKey")
437
473
  rootCid = _rootCid
438
474
  wnfsKey = _wnfsKey
439
- if (fula != nil) {
440
- try fula?.flush()
475
+ NSLog("ReactNative loadWnfs called: rootCid=\(rootCid)")
476
+ if (self.fula != nil) {
477
+ try self.fula?.flush()
441
478
  }
442
- OSLog.viewCycle.info("ReactNative loadWnfs completed")
479
+ NSLog("ReactNative loadWnfs completed")
443
480
  try encryptAndStoreConfig()
444
481
  }
445
482
 
@@ -447,37 +484,38 @@ class FulaModule: NSObject {
447
484
  func encryptAndStoreConfig() throws {
448
485
  do {
449
486
  if let identityEncryptedGlobalUnwrapped = identityEncryptedGlobal {
450
- OSLog.viewCycle.info("ReactNative encryptAndStoreConfig started")
487
+ NSLog("ReactNative encryptAndStoreConfig started")
451
488
 
452
489
  if let rootCidUnwrapped = rootCid, let wnfsKeyUnwrapped = wnfsKey, let secretKeyGlobalUnwrapped = secretKeyGlobal {
453
- OSLog.viewCycle.info("ReactNative encryptAndStoreConfig started with rootCid: \(rootCidUnwrapped.toUint8Array()) and wnfsKey:\(wnfsKeyUnwrapped)")
490
+ NSLog("ReactNative encryptAndStoreConfig started with rootCid: \(rootCidUnwrapped.toUint8Array()) and wnfsKey:\(wnfsKeyUnwrapped)")
454
491
 
455
492
  let cid_encrypted = try Cryptography.encryptMsg(rootCidUnwrapped.toUint8Array(), secretKeyGlobalUnwrapped)
456
- OSLog.viewCycle.info("ReactNative encryptAndStoreConfig cid_encrypted: \(cid_encrypted)")
493
+ NSLog("ReactNative encryptAndStoreConfig cid_encrypted: \(cid_encrypted)")
457
494
 
458
495
  let wnfs_key_encrypted = try Cryptography.encryptMsg(wnfsKeyUnwrapped.toUint8Array(), secretKeyGlobalUnwrapped)
459
- OSLog.viewCycle.info("ReactNative encryptAndStoreConfig wnfs_key_encrypted: \(wnfs_key_encrypted)")
496
+ NSLog("ReactNative encryptAndStoreConfig wnfs_key_encrypted: \(wnfs_key_encrypted)")
460
497
 
461
498
  userDataHelper.add("cid_encrypted_" + identityEncryptedGlobalUnwrapped, cid_encrypted)
462
499
  userDataHelper.add("wnfs_key_encrypted_" + identityEncryptedGlobalUnwrapped, wnfs_key_encrypted)
463
500
  } else {
464
501
  // Handle the case where rootCid, wnfsKey, or secretKeyGlobal is nil
465
- OSLog.viewCycle.info("ReactNative encryptAndStoreConfig failed because one of the values is nil")
502
+ NSLog("ReactNative encryptAndStoreConfig failed because one of the values is nil")
466
503
  }
467
504
  }
468
505
  } catch let error {
469
- OSLog.viewCycle.info("ReactNative encryptAndStoreConfig failed with Error: \(error.localizedDescription)")
506
+ NSLog("ReactNative encryptAndStoreConfig failed with Error: \(error.localizedDescription)")
470
507
  throw error
471
508
  }
472
509
  }
473
510
 
474
511
  func logoutInternal(identity: Data, _storePath: String?) throws {
475
512
  do {
476
- if (fula != nil) {
477
- try fula?.flush()
513
+ if (self.fula != nil) {
514
+ try self.fula?.flush()
478
515
  }
479
516
  let secretKey = try Cryptography.generateKey(identity)
480
- let identity_encrypted: String = try Cryptography.encryptMsg(identity.toUint8Array(), secretKey)
517
+ let identity_encrypted: String = try Cryptography.encryptMsg(identity.toUint8Array(), [UInt8](secretKey))
518
+
481
519
  userDataHelper.remove("cid_encrypted_"+identity_encrypted)
482
520
 
483
521
  //TODO: Should also remove peerid @Mahdi
@@ -505,46 +543,59 @@ class FulaModule: NSObject {
505
543
  }
506
544
 
507
545
  func getFulaClient() -> FulamobileClient? {
508
- return fula
546
+ return self.fula
509
547
  }
510
548
 
511
- func newClientInternal(identity: Data, storePath: String?, bloxAddr: String, exchange: String, autoFlush: Bool, useRelay: Bool, refresh: Bool) throws -> Data {
549
+ func newClientInternal(identity: Data, storePath: String?, bloxAddr: String, exchange: String, autoFlush: Bool, useRelay: Bool, refresh: Bool) throws -> Void {
512
550
  do {
551
+ NSLog("ReactNative fula newClientInternal refresh=\(refresh)")
513
552
  fulaConfig = FulamobileConfig()
553
+ NSLog("ReactNative: cofig is set")
514
554
  if (storePath == nil || storePath!.isEmpty) {
515
555
  fulaConfig!.storePath = fulaStorePath
516
556
  } else {
517
557
  fulaConfig!.storePath = storePath!
518
558
  }
519
- print("ReactNative", "storePath is set: " + fulaConfig!.storePath)
559
+ NSLog("ReactNative storePath is set: \(fulaConfig!.storePath)")
520
560
 
521
561
  let peerIdentity = try createPeerIdentity(privateKey: identity)
522
562
  fulaConfig!.identity = peerIdentity
523
- print("ReactNative", "peerIdentity is set: " + fulaConfig!.identity!.toHex())
563
+ NSLog("ReactNative peerIdentity is set: \(fulaConfig!.identity!.toHex())")
524
564
  fulaConfig!.bloxAddr = bloxAddr
525
- print("ReactNative", "bloxAddr is set: " + fulaConfig!.bloxAddr)
565
+ NSLog("ReactNative bloxAddr is set: \(fulaConfig!.bloxAddr)")
526
566
  fulaConfig!.exchange = exchange
527
567
  fulaConfig!.syncWrites = autoFlush
528
568
  if (useRelay) {
529
569
  fulaConfig!.allowTransientConnection = true
530
570
  fulaConfig!.forceReachabilityPrivate = true
531
571
  }
532
- if (fula == nil || refresh) {
533
- print("ReactNative", "Creating a new Fula instance");
572
+ if (self.fula == nil || refresh) {
573
+ NSLog("ReactNative Creating a new Fula instance")
534
574
  do {
535
- try shutdownInternal();
536
- fula = FulamobileClient(fulaConfig)
537
- if (fula != nil) {
538
- try fula?.flush();
539
- }
575
+ try shutdownInternal()
576
+ NSLog("ReactNative Creating a new Fula instance shutdown done")
577
+ var error: NSError?
578
+ let client = FulamobileNewClient(fulaConfig, &error)
579
+ if let error = error {
580
+ throw error
581
+ }
582
+
583
+ self.fula = client
584
+ NSLog("ReactNative FulamobileClient created")
585
+ if (self.fula != nil) {
586
+ NSLog("ReactNative Creating a new Fula instance fula is not null, flushing")
587
+ try self.fula?.flush()
588
+ } else {
589
+ NSLog("** ReactNative Creating a new Fula instance fula failed **")
590
+ }
540
591
  } catch let error {
541
- print("ReactNative", "Failed to create new Fula instance: " , error.localizedDescription);
542
- throw MyError.runtimeError("Failed to create new Fula instance")
592
+ NSLog("ReactNative Failed to create new Fula instance: \(error.localizedDescription)")
593
+ throw MyError.runtimeError("ReactNative Failed to create new Fula instance")
543
594
  }
544
595
  }
545
- return peerIdentity
596
+ NSLog("ReactNative peerIdentity returned: \(peerIdentity)")
546
597
  } catch let error {
547
- print("ReactNative", "newclientInternal failed with Error: ", error.localizedDescription)
598
+ NSLog("ReactNative newclientInternal failed with Error: \(error.localizedDescription)")
548
599
  throw error
549
600
  }
550
601
  }
@@ -552,61 +603,79 @@ class FulaModule: NSObject {
552
603
  func initInternal(identity: Data, storePath: String, bloxAddr: String, exchange: String, autoFlush: Bool, _rootCid: String, useRelay: Bool, refresh: Bool) throws -> [String] {
553
604
 
554
605
  do {
555
- if (fula == nil || refresh) {
606
+ os_log("ReactNative: This is an info message.", log: OSLog.viewCycle, type: .info)
607
+ NSLog("ReactNative: This is a simple log message.")
608
+
609
+ NSLog("ReactNative fula initInternal=\(refresh)")
610
+ if (self.fula == nil || refresh) {
611
+ NSLog("ReactNative fula self.fula is null or refresh is set")
556
612
  try newClientInternal(identity: identity, storePath: storePath, bloxAddr: bloxAddr, exchange: exchange, autoFlush: autoFlush, useRelay: useRelay, refresh: refresh)
557
- OSLog.viewCycle.info("ReactNative fula initialized: \(self.fula!.id_())")
613
+ NSLog("ReactNative fula initialized")
614
+ if (self.fula == nil) {
615
+ NSLog("ReactNative: fula is not initialized")
616
+ }
617
+ guard let fulaId = self.fula?.id_() else {
618
+ NSLog("ReactNative error: fula is not initialized")
619
+ throw MyError.runtimeError("ReactNative: fula client not ready")
620
+ }
621
+ NSLog("ReactNative fula initialized: \(fulaId)")
558
622
  }
559
- if(client == nil || refresh) {
560
- client = Client(clientInput: fula!)
561
- wnfs = Wnfs(putFn: { cid, data in
623
+ if(self.client == nil || self.wnfs == nil || refresh) {
624
+ NSLog("ReactNative fula self.client is null or refresh is set")
625
+ self.client = Client(clientInput: self.fula!)
626
+ self.wnfs = Wnfs(putFn: { cid, data in
562
627
  guard let c = self.client else {
563
- throw MyError.runtimeError("wnfs: fula client not ready")
628
+ NSLog("ReactNative wnfs put: fula client not ready")
629
+ throw MyError.runtimeError("ReactNative wnfs: fula client not ready")
564
630
  }
565
631
  try c.put(cid, data)
566
632
  }, getFn: { cid in
567
633
  guard let c = self.client else {
568
- throw MyError.runtimeError("wnfs: fula client not ready")
634
+ NSLog("ReactNative wnfs get: fula client not ready")
635
+ throw MyError.runtimeError("ReactNative wnfs: fula client not ready")
569
636
  }
570
637
  return try c.get(cid)
571
638
  })
572
- OSLog.viewCycle.info("ReactNative wnfs initialized")
639
+ NSLog("ReactNative wnfs initialized")
573
640
  }
574
641
 
575
642
  let secretKey = try Cryptography.generateKey(identity)
576
- let identity_encrypted = try Cryptography.encryptMsg(identity.toUint8Array(), secretKey)
643
+ let identity_encrypted = try Cryptography.encryptMsg(identity.toUint8Array(), [UInt8](secretKey))
644
+
577
645
  identityEncryptedGlobal = identity_encrypted
578
- secretKeyGlobal = secretKey
646
+ secretKeyGlobal = [UInt8](secretKey)
579
647
 
580
648
  if (rootCid == nil || rootCid!.isEmpty) {
581
- OSLog.viewCycle.info("ReactNative rootCid is empty.")
649
+ NSLog("ReactNative rootCid is empty.")
582
650
  //Load from keystore
583
651
 
584
652
  let cid_encrypted_fetched = userDataHelper.getValue("cid_encrypted_"+identity_encrypted)
585
- OSLog.viewCycle.info("ReactNative Here1")
653
+ NSLog("ReactNative Here1")
586
654
  var cid: Array<UInt8>? = nil
587
655
  if(cid_encrypted_fetched != nil && !cid_encrypted_fetched!.isEmpty) {
588
- OSLog.viewCycle.info("ReactNative decrypting cid= \(cid_encrypted_fetched!) with secret \(secretKey.toHex())")
589
- cid = try Cryptography.decryptMsg(cid_encrypted_fetched!, secretKey)
656
+ NSLog("ReactNative decrypting cid= \(cid_encrypted_fetched!) with secret \(secretKey.toHex())")
657
+ cid = try Cryptography.decryptMsg(cid_encrypted_fetched!, [UInt8](secretKey))
658
+
590
659
  }
591
- print("ReactNative", "Here2")
660
+ NSLog("ReactNative Here2")
592
661
  //print("ReactNative", "Attempted to fetch cid from keystore cid="+cid+" & wnfs_key="+wnfs_key)
593
662
  if(cid == nil || cid!.isEmpty){
594
- OSLog.viewCycle.info("ReactNative cid or wnfs key was not found")
663
+ NSLog("ReactNative cid or wnfs key was not found")
595
664
  if(!_rootCid.isEmpty){
596
- OSLog.viewCycle.info("ReactNative Re-setting cid from input: \(_rootCid)")
665
+ NSLog("ReactNative Re-setting cid from input: \(_rootCid)")
597
666
  cid = _rootCid.toUint8Array()
598
667
  }
599
668
 
600
669
  }
601
670
  if(cid == nil || cid!.isEmpty){
602
- OSLog.viewCycle.info("ReactNative Tried to recover cid but was not successful. Creating ones")
671
+ NSLog("ReactNative Tried to recover cid but was not successful. Creating ones")
603
672
  try createNewrootCid(identity: identity)
604
673
  } else {
605
- OSLog.viewCycle.info("ReactNative Found cid and wnfs key in keychain store")
606
- OSLog.viewCycle.info("ReactNative Recovered cid and private ref from keychain store. cid=\(cid!) & wnfs_key=\(identity)")
674
+ NSLog("ReactNative Found cid and wnfs key in keychain store")
675
+ NSLog("ReactNative Recovered cid and private ref from keychain store. cid=\(cid!) & wnfs_key=\(identity)")
607
676
  try loadWnfs(identity, cid!.toData().toUTF8String()!)
608
677
  }
609
- OSLog.viewCycle.info("ReactNative creating/reloading rootCid completed")
678
+ NSLog("ReactNative creating/reloading rootCid completed")
610
679
 
611
680
  /*
612
681
  byte[] testbyte = convertStringToByte("-104,40,24,-93,24,100,24,114,24,111,24,111,24,116,24,-126,24,-126,0,0,24,-128,24,103,24,118,24,101,24,114,24,115,24,105,24,111,24,110,24,101,24,48,24,46,24,49,24,46,24,48,24,105,24,115,24,116,24,114,24,117,24,99,24,116,24,117,24,114,24,101,24,100,24,104,24,97,24,109,24,116")
@@ -619,22 +688,26 @@ class FulaModule: NSObject {
619
688
  */
620
689
 
621
690
 
622
- OSLog.viewCycle.info("ReactNative rootCid is created: cid=\(self.rootCid!) & wnfs_key=\(self.wnfsKey!.toHex())")
691
+ NSLog("ReactNative rootCid is created: cid=\(self.rootCid!) & wnfs_key=\(self.wnfsKey!.toHex())")
623
692
  } else {
624
- OSLog.viewCycle.info("ReactNative rootCid existed: cid=\(self.rootCid!) & wnfs_key=\(self.wnfsKey!.toHex())")
693
+ NSLog("ReactNative rootCid existed: cid=\(self.rootCid!) & wnfs_key=\(self.wnfsKey!.toHex())")
625
694
  }
626
- let peerId = fula!.id_()
695
+ guard let peerId = self.fula?.id_() else {
696
+ NSLog("ReactNative error: fula is not initialized")
697
+ throw MyError.runtimeError("ReactNative: fula client not ready")
698
+ }
699
+ NSLog("ReactNative fula peerId initialized: \(peerId)")
627
700
  var obj = [String]()
628
701
  obj.append(peerId)
629
702
  obj.append(rootCid!)
630
703
  obj.append(wnfsKey!.toHex())
631
- OSLog.viewCycle.info("ReactNative initInternal is completed successfully")
632
- if (fula != nil) {
633
- try fula?.flush()
704
+ NSLog("ReactNative initInternal is completed successfully")
705
+ if (self.fula != nil) {
706
+ try self.fula?.flush()
634
707
  }
635
708
  return obj
636
709
  } catch let error {
637
- OSLog.viewCycle.info("ReactNative init internal failed with Error: \(error.localizedDescription)")
710
+ NSLog("ReactNative init internal failed with Error: \(error.localizedDescription)")
638
711
  throw error
639
712
  }
640
713
  }
@@ -642,18 +715,18 @@ class FulaModule: NSObject {
642
715
 
643
716
  @objc(mkdir:withResolver:withRejecter:)
644
717
  func mkdir(path: String, resolve:RCTPromiseResolveBlock,reject:RCTPromiseRejectBlock) -> Void {
645
- print("ReactNative", "mkdir: path = " + path)
718
+ NSLog("ReactNative mkdir: path = \(path)")
646
719
  do {
647
- let cid = try wnfs?.MkDir(cid: rootCid!, remotePath: path)
720
+ let cid = try self.wnfs?.MkDir(cid: rootCid!, remotePath: path)
648
721
  if(cid != nil) {
649
722
  rootCid = cid
650
723
  try encryptAndStoreConfig()
651
- if (fula != nil) {
652
- try fula?.flush()
724
+ if (self.fula != nil) {
725
+ try self.fula?.flush()
653
726
  }
654
727
  resolve(rootCid)
655
728
  } else {
656
- print("ReactNative", "mkdir Error: config is nil")
729
+ NSLog("ReactNative mkdir Error: config is nil")
657
730
  reject("ERR_WNFS", "Can't make dir", nil)
658
731
  }
659
732
 
@@ -672,18 +745,18 @@ class FulaModule: NSObject {
672
745
  // localFilename: a string containing full path and filename of local file on hte device (e.g /usr/bin/cat.jpg)
673
746
  // Returns: new cid of the root after this file is placed in the tree
674
747
  */
675
- print("ReactNative", "writeFile to : path = " + fulaTargetFilename + ", from: " + localFilename)
748
+ NSLog("ReactNative writeFile to : path = \(fulaTargetFilename) + from: \(localFilename)")
676
749
  do {
677
- let cid = try wnfs?.WriteFileFromPath(cid: rootCid!, remotePath: fulaTargetFilename, fileUrl: URL.init(string: localFilename)!)
750
+ let cid = try self.wnfs?.WriteFileFromPath(cid: rootCid!, remotePath: fulaTargetFilename, fileUrl: URL.init(string: localFilename)!)
678
751
  if(cid != nil) {
679
752
  rootCid = cid
680
753
  try encryptAndStoreConfig()
681
- if (fula != nil) {
682
- try fula?.flush()
754
+ if (self.fula != nil) {
755
+ try self.fula?.flush()
683
756
  }
684
757
  resolve(rootCid)
685
758
  } else {
686
- print("ReactNative", "writeFile Error: config is nil")
759
+ NSLog("ReactNative writeFile Error: config is nil")
687
760
  reject("ERR_WNFS", "writeFile Error: config is nil", nil)
688
761
  }
689
762
  } catch let error {
@@ -695,15 +768,15 @@ class FulaModule: NSObject {
695
768
  @objc(writeFileContent:withContentString:withResolver:withRejecter:)
696
769
  func writeFileContent(path: String, contentString: String, resolve:RCTPromiseResolveBlock,reject:RCTPromiseRejectBlock) -> Void {
697
770
 
698
- print("ReactNative", "writeFile: contentString = " + contentString)
699
- print("ReactNative", "writeFile: path = " + path)
771
+ NSLog("ReactNative writeFile: contentString = \(contentString)")
772
+ NSLog("ReactNative writeFile: path = \(path)")
700
773
  do {
701
774
  let content = convertStringToByte(contentString)
702
- let cid = try wnfs?.WriteFile(cid: rootCid!, remotePath: path, data: content.toData())
775
+ let cid = try self.wnfs?.WriteFile(cid: rootCid!, remotePath: path, data: content.toData())
703
776
  rootCid = cid
704
777
  try encryptAndStoreConfig()
705
- if (fula != nil) {
706
- try fula?.flush()
778
+ if (self.fula != nil) {
779
+ try self.fula?.flush()
707
780
  }
708
781
  resolve(rootCid)
709
782
  } catch let error {
@@ -715,15 +788,15 @@ class FulaModule: NSObject {
715
788
 
716
789
  @objc(ls:withResolver:withRejecter:)
717
790
  func ls(path: String, resolve:RCTPromiseResolveBlock,reject:RCTPromiseRejectBlock) -> Void {
718
- print("ReactNative", "ls: path = " + path)
791
+ NSLog("ReactNative ls: path = \(path)")
719
792
  do {
720
- let res = try wnfs?.Ls(cid: rootCid!, remotePath: path)
793
+ let res = try self.wnfs?.Ls(cid: rootCid!, remotePath: path)
721
794
 
722
795
  //JSONArray jsonArray = new JSONArray(res)
723
796
  guard let s = res?.toUTF8String() else {
724
- throw MyError.runtimeError("converting bytes to utf8 string")
797
+ throw MyError.runtimeError("ReactNative converting bytes to utf8 string")
725
798
  }
726
- print("ReactNative", "ls: res = " + s)
799
+ NSLog("ReactNative ls: res = \(s)")
727
800
  resolve(s)
728
801
  } catch let error {
729
802
  print("ls", error.localizedDescription)
@@ -737,12 +810,12 @@ class FulaModule: NSObject {
737
810
 
738
811
  print("ReactNative", "rm: path = " + path)
739
812
  do {
740
- let cid = try wnfs?.Rm(cid: rootCid!, remotePath: path)
813
+ let cid = try self.wnfs?.Rm(cid: rootCid!, remotePath: path)
741
814
  if(cid != nil) {
742
815
  rootCid = cid
743
816
  try encryptAndStoreConfig()
744
- if (fula != nil) {
745
- try fula?.flush()
817
+ if (self.fula != nil) {
818
+ try self.fula?.flush()
746
819
  }
747
820
  resolve(rootCid)
748
821
  } else {
@@ -761,12 +834,12 @@ class FulaModule: NSObject {
761
834
 
762
835
  print("ReactNative", "rm: sourcePath = " + sourcePath)
763
836
  do {
764
- let cid = try wnfs?.Cp(cid: rootCid!, remotePathFrom: sourcePath, remotePathTo: targetPath)
837
+ let cid = try self.wnfs?.Cp(cid: rootCid!, remotePathFrom: sourcePath, remotePathTo: targetPath)
765
838
  if(cid != nil) {
766
839
  rootCid = cid
767
840
  try encryptAndStoreConfig()
768
- if (fula != nil) {
769
- try fula?.flush()
841
+ if (self.fula != nil) {
842
+ try self.fula?.flush()
770
843
  }
771
844
  resolve(rootCid)
772
845
  } else {
@@ -784,12 +857,12 @@ class FulaModule: NSObject {
784
857
  func mv(sourcePath: String, targetPath: String, resolve:RCTPromiseResolveBlock,reject:RCTPromiseRejectBlock) -> Void {
785
858
  print("ReactNative", "rm: sourcePath = " + sourcePath)
786
859
  do {
787
- let cid = try wnfs?.Mv(cid: rootCid!, remotePathFrom: sourcePath, remotePathTo: targetPath)
860
+ let cid = try self.wnfs?.Mv(cid: rootCid!, remotePathFrom: sourcePath, remotePathTo: targetPath)
788
861
  if(cid != nil) {
789
862
  rootCid = cid
790
863
  try encryptAndStoreConfig()
791
- if (fula != nil) {
792
- try fula?.flush()
864
+ if (self.fula != nil) {
865
+ try self.fula?.flush()
793
866
  }
794
867
  resolve(rootCid)
795
868
  } else {
@@ -814,7 +887,7 @@ class FulaModule: NSObject {
814
887
  */
815
888
  print("ReactNative", "readFile: fulaTargetFilename = " + fulaTargetFilename)
816
889
  do {
817
- let path = try wnfs?.ReadFileToPath(cid: rootCid!, remotePath: fulaTargetFilename, fileUrl: URL.init(string: localFilename)!)
890
+ let path = try self.wnfs?.ReadFileToPath(cid: rootCid!, remotePath: fulaTargetFilename, fileUrl: URL.init(string: localFilename)!)
818
891
  resolve(path)
819
892
  } catch let error {
820
893
  print("readFile", error.localizedDescription)
@@ -829,9 +902,9 @@ class FulaModule: NSObject {
829
902
  print("ReactNative", "readFileContent: path = " + path)
830
903
  do {
831
904
  // FIXME: dhouldn't we output an NSData object instead?
832
- let res = try wnfs?.ReadFile(cid: rootCid!, remotePath: path)
905
+ let res = try self.wnfs?.ReadFile(cid: rootCid!, remotePath: path)
833
906
  guard let resString = res?.toUTF8String() else{
834
- throw MyError.runtimeError("converting bytes to utf8 string")
907
+ throw MyError.runtimeError(" ReactNative converting bytes to utf8 string")
835
908
  }
836
909
  resolve(resString)
837
910
  } catch let error {
@@ -861,7 +934,7 @@ class FulaModule: NSObject {
861
934
  do {
862
935
  print("ReactNative", "getInternal: key.toUTF8String() = " , key.toUTF8String()!)
863
936
  print("ReactNative", "getInternal: key.toHex().bytes = " , key.toHex())
864
- let value = try fula!.get(key)
937
+ let value = try self.fula!.get(key)
865
938
  print("ReactNative", "getInternal: value.toHex() = " , value.toHex())
866
939
  return value
867
940
  } catch let error {
@@ -889,7 +962,7 @@ class FulaModule: NSObject {
889
962
  func hasInternal(_ key: Data) throws -> Bool {
890
963
  do {
891
964
  let ret = UnsafeMutablePointer<ObjCBool>.allocate(capacity: 1)
892
- try fula?.has(key, ret0_: ret)
965
+ try self.fula?.has(key, ret0_: ret)
893
966
  let res = ret.pointee.boolValue
894
967
  ret.deallocate()
895
968
  return res
@@ -901,7 +974,7 @@ class FulaModule: NSObject {
901
974
 
902
975
  func pullInternal(key: Data) throws -> Void {
903
976
  do {
904
- try fula!.pull(key)
977
+ try self.fula!.pull(key)
905
978
  } catch let error {
906
979
  print("pullInternal", error.localizedDescription)
907
980
  throw error
@@ -923,12 +996,12 @@ class FulaModule: NSObject {
923
996
  func pushInternal(key: Data) throws -> Void {
924
997
  do {
925
998
  let hasIt = try hasInternal(key)
926
- if (fula != nil && hasIt) {
927
- try fula?.push(key)
928
- try fula?.flush()
999
+ if (self.fula != nil && hasIt) {
1000
+ try self.fula?.push(key)
1001
+ try self.fula?.flush()
929
1002
  } else {
930
1003
  print("ReactNative", "pushInternal error: key wasn't found or fula is not initialized")
931
- throw MyError.runtimeError("pushInternal error: key wasn't found or fula is not initialized")
1004
+ throw MyError.runtimeError("ReactNative pushInternal error: key wasn't found or fula is not initialized")
932
1005
  }
933
1006
  } catch let error {
934
1007
  print("ReactNative", "pushInternal", error.localizedDescription)
@@ -964,13 +1037,13 @@ class FulaModule: NSObject {
964
1037
  // FIXME: unused codec arg
965
1038
  func putInternal(value: Data, codec: Int) throws -> Data {
966
1039
  do {
967
- if(fula != nil) {
968
- let key: Data = try fula!.put(value, codec: Int64(FulaModule.CODEC_DAG_CBOR))
969
- try fula?.flush()
1040
+ if(self.fula != nil) {
1041
+ let key: Data = try self.fula!.put(value, codec: Int64(FulaModule.CODEC_DAG_CBOR))
1042
+ try self.fula?.flush()
970
1043
  return key
971
1044
  } else {
972
1045
  print("ReactNative", "putInternal Error: fula is not initialized")
973
- throw MyError.runtimeError("putInternal Error: fula is not initialized")
1046
+ throw MyError.runtimeError("ReactNative putInternal Error: fula is not initialized")
974
1047
  }
975
1048
  } catch let error {
976
1049
  print("ReactNative", "putInternal", error.localizedDescription)
@@ -983,15 +1056,15 @@ class FulaModule: NSObject {
983
1056
 
984
1057
  print("ReactNative", "setAuth: peerIdString = " + peerIdString)
985
1058
  do {
986
- if (fula != nil && !(fula?.id_().isEmpty)! && fulaConfig != nil && !fulaConfig!.bloxAddr.isEmpty) {
1059
+ if (self.fula != nil && !(self.fula?.id_().isEmpty)! && fulaConfig != nil && !fulaConfig!.bloxAddr.isEmpty) {
987
1060
  let bloxAddr = fulaConfig!.bloxAddr
988
1061
  print("ReactNative", "setAuth: bloxAddr = '",bloxAddr,"'"," peerIdString = '",peerIdString,"'")
989
1062
  let parts = bloxAddr.split(separator: "/").map(String.init)
990
- try fula?.setAuth(parts.last, subject: peerIdString, allow: allow)
1063
+ try self.fula?.setAuth(parts.last, subject: peerIdString, allow: allow)
991
1064
  resolve(true)
992
1065
  } else {
993
1066
  print("ReactNative", "setAuth error: fula is not initialized")
994
- throw MyError.runtimeError("fula is not initialized")
1067
+ throw MyError.runtimeError("ReactNative fula is not initialized")
995
1068
  }
996
1069
  resolve(false)
997
1070
  } catch let error {
@@ -1006,14 +1079,14 @@ class FulaModule: NSObject {
1006
1079
  DispatchQueue.global(qos: .default).async {
1007
1080
  do {
1008
1081
  guard let fulaClient = self.fula else {
1009
- throw MyError.runtimeError("Fula client is not initialized")
1082
+ throw MyError.runtimeError("ReactNative Fula client is not initialized")
1010
1083
  }
1011
1084
 
1012
1085
  // Concatenate all CID strings into a single string separated by "|"
1013
1086
  let concatenatedCids = (cidArray as? [String])?.joined(separator: "|")
1014
1087
 
1015
1088
  guard let cidsData = concatenatedCids?.data(using: .utf8) else {
1016
- throw MyError.runtimeError("Unable to encode CIDs as data")
1089
+ throw MyError.runtimeError("ReactNative Unable to encode CIDs as data")
1017
1090
  }
1018
1091
 
1019
1092
  try fulaClient.clearCids(fromRecent: cidsData)
@@ -1031,7 +1104,7 @@ class FulaModule: NSObject {
1031
1104
  DispatchQueue.global(qos: .default).async {
1032
1105
  do {
1033
1106
  guard let fulaClient = self.fula else {
1034
- throw MyError.runtimeError("Fula client is not initialized")
1107
+ throw MyError.runtimeError("ReactNative Fula client is not initialized")
1035
1108
  }
1036
1109
 
1037
1110
  let recentLinksIterator = try fulaClient.listRecentCidsAsString()
@@ -1066,7 +1139,7 @@ class FulaModule: NSObject {
1066
1139
  DispatchQueue.global(qos: .default).async {
1067
1140
  do {
1068
1141
  guard let fulaClient = self.fula else {
1069
- throw MyError.runtimeError("Fula client is not initialized")
1142
+ throw MyError.runtimeError("ReactNative Fula client is not initialized")
1070
1143
  }
1071
1144
 
1072
1145
  let recentLinksIterator = try fulaClient.listRecentCidsAsStringWithChildren()
@@ -1101,14 +1174,18 @@ class FulaModule: NSObject {
1101
1174
  DispatchQueue.global(qos: .default).async {
1102
1175
  do {
1103
1176
  guard let fulaClient = self.fula else {
1104
- throw MyError.runtimeError("Fula client is not initialized")
1177
+ throw MyError.runtimeError("ReactNative Fula client is not initialized")
1105
1178
  }
1106
1179
  guard let poolID = Int64(poolIDStr) else {
1107
- reject("ERR_FULA", "Invalid poolID - not a valid number: \(poolIDStr)")
1180
+ let error = NSError(domain: "FULAErrorDomain", code: 1001, userInfo: [NSLocalizedDescriptionKey: "Invalid poolID - not a valid number: \(poolIDStr)"])
1181
+ reject("ERR_FULA", "Invalid poolID - not a valid number: \(poolIDStr)", error)
1108
1182
  return
1109
1183
  }
1110
1184
  guard let replicationFactor = Int64(replicationFactorStr) else {
1111
- reject("ERR_FULA", "Invalid replicationFactorStr - not a valid number: \(replicationFactorStr)")
1185
+ let error = NSError(domain: "FULAErrorDomain",
1186
+ code: 1002,
1187
+ userInfo: [NSLocalizedDescriptionKey: "Invalid replicationFactor - not a valid number: \(replicationFactorStr)"])
1188
+ reject("ERR_FULA", "Invalid replicationFactorStr - not a valid number: \(replicationFactorStr)", error)
1112
1189
  return
1113
1190
  }
1114
1191
 
@@ -1116,10 +1193,11 @@ class FulaModule: NSObject {
1116
1193
  let concatenatedCids = (cidArray as? [String])?.joined(separator: "|")
1117
1194
 
1118
1195
  guard let cidsData = concatenatedCids?.data(using: .utf8) else {
1119
- throw MyError.runtimeError("Unable to encode CIDs as data")
1196
+ throw MyError.runtimeError("ReactNative Unable to encode CIDs as data")
1120
1197
  }
1121
1198
 
1122
- try fulaClient.batchUploadManifest(cidsData, poolID, replicationFactor)
1199
+ // Adjusted call to match the expected method signature and argument types
1200
+ try fulaClient.batchUploadManifest(cidsData, poolID: Int(poolID), replicationFactor: Int(replicationFactor))
1123
1201
  resolve(true)
1124
1202
  } catch let error {
1125
1203
  print("ReactNative", "batchUploadManifest failed with Error: \(error.localizedDescription)")
@@ -1136,18 +1214,21 @@ class FulaModule: NSObject {
1136
1214
  try shutdownInternal()
1137
1215
  resolve(true)
1138
1216
  } catch let error {
1139
- print("ReactNative", "shutdown", error.localizedDescription)
1217
+ NSLog("ReactNative shutdown \(error.localizedDescription)")
1140
1218
  reject("ERR_FULA", "shutdown", error)
1141
1219
  }
1142
1220
 
1143
1221
  }
1144
1222
 
1145
1223
  func shutdownInternal() throws {
1146
- if(fula != nil) {
1147
- try fula?.shutdown()
1148
- fula = nil
1149
- client = nil
1150
- wnfs = nil
1224
+ NSLog("ReactNative shutdownInternal")
1225
+ if(self.fula != nil) {
1226
+ NSLog("ReactNative shutdownInternal fula is not null")
1227
+ try self.fula?.shutdown()
1228
+ NSLog("ReactNative shutdownInternal fula.shutdown called")
1229
+ self.fula = nil
1230
+ self.client = nil
1231
+ self.wnfs = nil
1151
1232
  }
1152
1233
  }
1153
1234
 
@@ -1162,7 +1243,7 @@ class FulaModule: NSObject {
1162
1243
  func checkAccountExists(accountString: String, resolve:RCTPromiseResolveBlock,reject:RCTPromiseRejectBlock) -> Void {
1163
1244
  print("ReactNative", "checkAccountExists: accountString = ", accountString)
1164
1245
  do {
1165
- let result = try fula!.accountExists(accountString)
1246
+ let result = try self.fula!.accountExists(accountString)
1166
1247
  let resultString = result.toUTF8String()!
1167
1248
  resolve(resultString)
1168
1249
  } catch let error {
@@ -1176,7 +1257,7 @@ class FulaModule: NSObject {
1176
1257
  func accountFund(accountString: String, resolve:RCTPromiseResolveBlock,reject:RCTPromiseRejectBlock) -> Void {
1177
1258
  print("ReactNative", "accountFund: accountString = ", accountString)
1178
1259
  do {
1179
- let result = try fula!.accountFund(accountString)
1260
+ let result = try self.fula!.accountFund(accountString)
1180
1261
  let resultString = result.toUTF8String()!
1181
1262
  resolve(resultString)
1182
1263
  } catch let error {
@@ -1190,7 +1271,7 @@ class FulaModule: NSObject {
1190
1271
  func listPools( resolve:RCTPromiseResolveBlock,reject:RCTPromiseRejectBlock) -> Void {
1191
1272
  print("ReactNative", "listPools")
1192
1273
  do {
1193
- let result = try fula!.poolList()
1274
+ let result = try self.fula!.poolList()
1194
1275
  let resultString = result.toUTF8String()!
1195
1276
  resolve(resultString)
1196
1277
  } catch let error {
@@ -1201,49 +1282,60 @@ class FulaModule: NSObject {
1201
1282
  }
1202
1283
 
1203
1284
  @objc(listPoolJoinRequests:withResolver:withRejecter:)
1204
- func listPoolJoinRequests(poolIDStr: String, resolve:RCTPromiseResolveBlock,reject:RCTPromiseRejectBlock) -> Void {
1285
+ func listPoolJoinRequests(poolIDStr: String, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
1205
1286
  print("ReactNative", "listPoolJoinRequests: poolIDStr = ", poolIDStr)
1206
1287
  do {
1207
- if let poolID = Int64(poolIDStr) {
1208
- // Conversion successful - use longPoolID
1209
-
1210
- let result = try fula!.poolRequests(poolID)
1211
- let resultString = result.toUTF8String()!
1212
- resolve(resultString)
1288
+ if let poolID = Int64(poolIDStr), let intPoolID = Int(exactly: poolID) {
1289
+ // Conversion to Int successful - use intPoolID
1290
+ let result = try self.fula!.poolRequests(intPoolID)
1291
+ let resultString = result.toUTF8String()!
1292
+ resolve(resultString)
1213
1293
  } else {
1214
- // Handle invalid input (e.g., "abc", "123.45")
1215
- reject("ERR_FULA", "Invalid poolIDStr - not a valid number: \(poolIDStr)")
1294
+ // Handle invalid input or Int64 not convertible to Int
1295
+ let error = NSError(domain: "FULAErrorDomain",
1296
+ code: 1003,
1297
+ userInfo: [NSLocalizedDescriptionKey: "Invalid poolIDStr - not a valid number or too large: \(poolIDStr)"])
1298
+ reject("ERR_FULA", "Invalid poolIDStr - not a valid number or too large: \(poolIDStr)", error)
1216
1299
  }
1217
1300
  } catch let error {
1218
1301
  print("listPoolJoinRequests", error.localizedDescription)
1219
- reject("ERR_FULA", "listPoolJoinRequests", error)
1302
+ let nsError = error as NSError
1303
+ reject("ERR_FULA", "Failed listPoolJoinRequests due to error", nsError)
1220
1304
  }
1221
-
1222
1305
  }
1223
1306
 
1224
1307
  @objc(listAvailableReplicationRequests:withResolver:withRejecter:)
1225
- func listAvailableReplicationRequests(poolIDStr: String, resolve:RCTPromiseResolveBlock,reject:RCTPromiseRejectBlock) -> Void {
1308
+ func listAvailableReplicationRequests(poolIDStr: String, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
1226
1309
  print("ReactNative", "listAvailableReplicationRequests: poolIDStr = ", poolIDStr)
1227
1310
  do {
1228
- guard let poolID = Int64(poolIDStr) else {
1229
- reject("ERR_FULA", "Invalid poolID - not a valid number: \(poolIDStr)")
1311
+ guard let poolID = Int64(poolIDStr), let intPoolID = Int(exactly: poolID) else {
1312
+ let error = NSError(domain: "FULAErrorDomain",
1313
+ code: 1004, // Use appropriate error code
1314
+ userInfo: [NSLocalizedDescriptionKey: "Invalid poolID - not a valid number: \(poolIDStr)"])
1315
+ reject("ERR_FULA", "Invalid poolID - not a valid number: \(poolIDStr)", error)
1316
+ return
1317
+ }
1318
+ let result = try self.fula!.manifestAvailable(intPoolID)
1319
+ guard let resultString = result.toUTF8String() else {
1320
+ let error = NSError(domain: "FULAErrorDomain",
1321
+ code: 1005, // Use appropriate error code
1322
+ userInfo: [NSLocalizedDescriptionKey: "Failed to convert result to UTF8 String"])
1323
+ reject("ERR_FULA", "Conversion Error", error)
1230
1324
  return
1231
1325
  }
1232
- let result = try fula!.manifestAvailable(poolID)
1233
- let resultString = result.toUTF8String()!
1234
1326
  resolve(resultString)
1235
- } catch let error {
1327
+ } catch let error as NSError {
1236
1328
  print("listAvailableReplicationRequests", error.localizedDescription)
1237
- reject("ERR_FULA", "listAvailableReplicationRequests", error)
1329
+ reject("ERR_FULA", "listAvailableReplicationRequests failed with error: \(error.localizedDescription)", error)
1238
1330
  }
1239
-
1240
1331
  }
1241
1332
 
1333
+
1242
1334
  @objc(bloxFreeSpace:withRejecter:)
1243
1335
  func bloxFreeSpace( resolve:RCTPromiseResolveBlock,reject:RCTPromiseRejectBlock) -> Void {
1244
1336
  print("ReactNative", "bloxFreeSpace")
1245
1337
  do {
1246
- let result = try fula!.bloxFreeSpace()
1338
+ let result = try self.fula!.bloxFreeSpace()
1247
1339
  let resultString = result.toUTF8String()!
1248
1340
  resolve(resultString)
1249
1341
  } catch let error {
@@ -1272,7 +1364,7 @@ class FulaModule: NSObject {
1272
1364
  @objc(getAccount:withRejecter:)
1273
1365
  func getAccount(resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
1274
1366
  do {
1275
- let account = try fula!.getAccount()
1367
+ let account = try self.fula!.getAccount()
1276
1368
  let accountString = String(data: account, encoding: .utf8)
1277
1369
  resolve(accountString)
1278
1370
  } catch let error {
@@ -1288,7 +1380,7 @@ class FulaModule: NSObject {
1288
1380
  }
1289
1381
 
1290
1382
  do {
1291
- let balance = try fula!.assetsBalance(account, assetId: assetIdInt, classId: classIdInt)
1383
+ let balance = try self.fula!.assetsBalance(account, assetId: assetIdInt, classId: classIdInt)
1292
1384
  let balanceString = String(data: balance, encoding: .utf8)
1293
1385
  resolve(balanceString)
1294
1386
  } catch let error {
@@ -1303,7 +1395,7 @@ class FulaModule: NSObject {
1303
1395
  guard let poolIdInt = Int(poolID) else {
1304
1396
  throw NSError(domain: "Invalid poolID", code: 0, userInfo: nil)
1305
1397
  }
1306
- let result = try fula!.poolJoin(poolIdInt)
1398
+ let result = try self.fula!.poolJoin(poolIdInt)
1307
1399
  let resultString = String(data: result, encoding: .utf8)
1308
1400
  resolve(resultString)
1309
1401
  } catch let error {
@@ -1317,7 +1409,7 @@ class FulaModule: NSObject {
1317
1409
  guard let poolIdInt = Int(poolID) else {
1318
1410
  throw NSError(domain: "Invalid poolID", code: 0, userInfo: nil)
1319
1411
  }
1320
- let result = try fula!.poolCancelJoin(poolIdInt)
1412
+ let result = try self.fula!.poolCancelJoin(poolIdInt)
1321
1413
  let resultString = String(data: result, encoding: .utf8)
1322
1414
  resolve(resultString)
1323
1415
  } catch let error {
@@ -1332,7 +1424,7 @@ class FulaModule: NSObject {
1332
1424
  guard let poolIdInt = Int(poolID) else {
1333
1425
  throw NSError(domain: "Invalid poolID", code: 0, userInfo: nil)
1334
1426
  }
1335
- let result = try fula!.poolLeave(poolIdInt)
1427
+ let result = try self.fula!.poolLeave(poolIdInt)
1336
1428
  let resultString = String(data: result, encoding: .utf8)
1337
1429
  resolve(resultString)
1338
1430
  } catch let error {
@@ -1344,7 +1436,7 @@ class FulaModule: NSObject {
1344
1436
  @objc(eraseBlData:withRejecter:)
1345
1437
  func eraseBlData(resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
1346
1438
  do {
1347
- let result = try fula!.eraseBlData()
1439
+ let result = try self.fula!.eraseBlData()
1348
1440
  let resultString = String(data: result, encoding: .utf8)
1349
1441
  resolve(resultString)
1350
1442
  } catch let error {
@@ -1355,7 +1447,7 @@ class FulaModule: NSObject {
1355
1447
  @objc(reboot:withRejecter:)
1356
1448
  func reboot(resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) -> Void {
1357
1449
  do {
1358
- let result = try fula!.reboot()
1450
+ let result = try self.fula!.reboot()
1359
1451
  let resultString = result.toUTF8String()!
1360
1452
  resolve(resultString)
1361
1453
  } catch let error {
@@ -1367,7 +1459,7 @@ class FulaModule: NSObject {
1367
1459
  @objc(partition:withRejecter:)
1368
1460
  func partition(resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) -> Void {
1369
1461
  do {
1370
- let result = try fula!.partition()
1462
+ let result = try self.fula!.partition()
1371
1463
  let resultString = result.toUTF8String()!
1372
1464
  resolve(resultString)
1373
1465
  } catch let error {
@@ -1379,7 +1471,7 @@ class FulaModule: NSObject {
1379
1471
  @objc(wifiRemoveall:withRejecter:)
1380
1472
  func wifiRemoveall(resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) -> Void {
1381
1473
  do {
1382
- let result = try fula!.wifiRemoveall()
1474
+ let result = try self.fula!.wifiRemoveall()
1383
1475
  let resultString = result.toUTF8String()!
1384
1476
  resolve(resultString)
1385
1477
  } catch let error {
@@ -1388,22 +1480,32 @@ class FulaModule: NSObject {
1388
1480
  }
1389
1481
  }
1390
1482
 
1391
- @objc(fetchContainerLogs:tailCount:withResolver:withRejecter:)
1392
- func fetchContainerLogs(containerName: String, tailCount: String, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) -> Void {
1393
- do {
1394
- let result = try fula!.fetchContainerLogs(containerName, tailCount)
1395
- let resultString = result.toUTF8String()!
1396
- resolve(resultString)
1397
- } catch let error {
1398
- print("fetchContainerLogs", error.localizedDescription)
1399
- reject("ERR_FULA", "fetchContainerLogs", error)
1400
- }
1401
- }
1483
+ @objc(fetchContainerLogs:tailCount:withResolver:withRejecter:)
1484
+ func fetchContainerLogs(containerName: String, tailCount: String, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) -> Void {
1485
+ do {
1486
+ // Since fetchContainerLogs expects a String for tailCount, pass it directly
1487
+ let result = try self.fula!.fetchContainerLogs(containerName, tailCount: tailCount)
1488
+ guard let resultString = result.toUTF8String() else {
1489
+ // Handle the case where result.toUTF8String() returns nil
1490
+ let error = NSError(domain: "FULAErrorDomain",
1491
+ code: 1007, // Choose a suitable error code
1492
+ userInfo: [NSLocalizedDescriptionKey: "Failed to convert log data to string."])
1493
+ reject("ERR_FULA", "Log Conversion Error", error)
1494
+ return
1495
+ }
1496
+ resolve(resultString)
1497
+ } catch let error as NSError {
1498
+ print("fetchContainerLogs", error.localizedDescription)
1499
+ reject("ERR_FULA", "fetchContainerLogs failed", error)
1500
+ }
1501
+ }
1502
+
1503
+
1402
1504
 
1403
1505
  @objc(getFolderSize:withResolver:withRejecter:)
1404
1506
  func getFolderSize(folderPath: String, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) -> Void {
1405
1507
  do {
1406
- let result = try fula!.getFolderSize(folderPath)
1508
+ let result = try self.fula!.getFolderSize(folderPath)
1407
1509
  let resultString = result.toUTF8String()!
1408
1510
  resolve(resultString)
1409
1511
  } catch let error {
@@ -1412,17 +1514,32 @@ class FulaModule: NSObject {
1412
1514
  }
1413
1515
  }
1414
1516
 
1415
- @objc(getDatastoreSize:withResolver:withRejecter:)
1416
- func getDatastoreSize(resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) -> Void {
1417
- do {
1418
- let result = try fula!.getDatastoreSize()
1419
- let resultString = result.toUTF8String()!
1420
- resolve(resultString)
1421
- } catch let error {
1422
- print("getDatastoreSize", error.localizedDescription)
1423
- reject("ERR_FULA", "getDatastoreSize", error)
1424
- }
1425
- }
1517
+ @objc
1518
+ func getDatastoreSize(_ resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) {
1519
+ DispatchQueue.global(qos: .background).async {
1520
+ // Safely unwrap `self.fula` using `guard let`
1521
+ guard let fulaClient = self.fula else {
1522
+ let error = NSError(domain: "FulaModuleError", code: 0, userInfo: [NSLocalizedDescriptionKey: "Fula client is not initialized"])
1523
+ DispatchQueue.main.async {
1524
+ reject("ERR_FULA_NOT_INITIALIZED", "Fula client is not initialized", error)
1525
+ }
1526
+ return
1527
+ }
1528
+
1529
+ do {
1530
+ let result = try fulaClient.getDatastoreSize()
1531
+ let resultString = String(decoding: result, as: UTF8.self)
1532
+ DispatchQueue.main.async {
1533
+ resolve(resultString)
1534
+ }
1535
+ } catch let error {
1536
+ DispatchQueue.main.async {
1537
+ reject("ERR_FULA", "Failed to get datastore size: \(error.localizedDescription)", error)
1538
+ }
1539
+ }
1540
+ }
1541
+ }
1542
+
1426
1543
 
1427
1544
  //Add Replicate In Pool (replicateInPool)
1428
1545