react-native-mosquito-transport 0.0.14

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.
Files changed (86) hide show
  1. package/CODE_OF_CONDUCT.md +133 -0
  2. package/CONTRIBUTING.md +114 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1 -0
  5. package/android/build.gradle +77 -0
  6. package/android/gradle.properties +5 -0
  7. package/android/src/main/AndroidManifest.xml +4 -0
  8. package/android/src/main/java/com/mosquitodb/MosquitodbModule.java +32 -0
  9. package/android/src/main/java/com/mosquitodb/MosquitodbPackage.java +28 -0
  10. package/example/.bundle/config +2 -0
  11. package/example/.node-version +1 -0
  12. package/example/.watchmanconfig +1 -0
  13. package/example/Gemfile +6 -0
  14. package/example/android/app/build.gradle +170 -0
  15. package/example/android/app/debug.keystore +0 -0
  16. package/example/android/app/proguard-rules.pro +10 -0
  17. package/example/android/app/src/debug/AndroidManifest.xml +13 -0
  18. package/example/android/app/src/debug/java/com/mosquitodbexample/ReactNativeFlipper.java +75 -0
  19. package/example/android/app/src/main/AndroidManifest.xml +25 -0
  20. package/example/android/app/src/main/java/com/mosquitodbexample/MainActivity.java +35 -0
  21. package/example/android/app/src/main/java/com/mosquitodbexample/MainApplication.java +62 -0
  22. package/example/android/app/src/main/res/drawable/rn_edit_text_material.xml +36 -0
  23. package/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png +0 -0
  24. package/example/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png +0 -0
  25. package/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png +0 -0
  26. package/example/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png +0 -0
  27. package/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png +0 -0
  28. package/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png +0 -0
  29. package/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png +0 -0
  30. package/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png +0 -0
  31. package/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png +0 -0
  32. package/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png +0 -0
  33. package/example/android/app/src/main/res/values/strings.xml +3 -0
  34. package/example/android/app/src/main/res/values/styles.xml +9 -0
  35. package/example/android/app/src/release/java/com/mosquitodbexample/ReactNativeFlipper.java +20 -0
  36. package/example/android/build.gradle +21 -0
  37. package/example/android/gradle/wrapper/gradle-wrapper.jar +0 -0
  38. package/example/android/gradle/wrapper/gradle-wrapper.properties +5 -0
  39. package/example/android/gradle.properties +44 -0
  40. package/example/android/gradlew +234 -0
  41. package/example/android/gradlew.bat +89 -0
  42. package/example/android/settings.gradle +4 -0
  43. package/example/app.json +4 -0
  44. package/example/babel.config.js +17 -0
  45. package/example/index.js +5 -0
  46. package/example/ios/.xcode.env +11 -0
  47. package/example/ios/File.swift +6 -0
  48. package/example/ios/MosquitodbExample/AppDelegate.h +6 -0
  49. package/example/ios/MosquitodbExample/AppDelegate.mm +36 -0
  50. package/example/ios/MosquitodbExample/Images.xcassets/AppIcon.appiconset/Contents.json +53 -0
  51. package/example/ios/MosquitodbExample/Images.xcassets/Contents.json +6 -0
  52. package/example/ios/MosquitodbExample/Info.plist +55 -0
  53. package/example/ios/MosquitodbExample/LaunchScreen.storyboard +47 -0
  54. package/example/ios/MosquitodbExample/main.m +10 -0
  55. package/example/ios/MosquitodbExample-Bridging-Header.h +3 -0
  56. package/example/ios/MosquitodbExample.xcodeproj/project.pbxproj +702 -0
  57. package/example/ios/MosquitodbExample.xcodeproj/xcshareddata/xcschemes/MosquitodbExample.xcscheme +88 -0
  58. package/example/ios/MosquitodbExampleTests/Info.plist +24 -0
  59. package/example/ios/MosquitodbExampleTests/MosquitodbExampleTests.m +66 -0
  60. package/example/ios/Podfile +60 -0
  61. package/example/metro.config.js +40 -0
  62. package/example/package.json +22 -0
  63. package/example/react-native.config.js +10 -0
  64. package/example/src/App.tsx +31 -0
  65. package/ios/Mosquitodb-Bridging-Header.h +2 -0
  66. package/ios/Mosquitodb.m +22 -0
  67. package/ios/Mosquitodb.swift +305 -0
  68. package/ios/Mosquitodb.xcodeproj/project.pbxproj +283 -0
  69. package/package.json +45 -0
  70. package/react-native-mosquitodb.podspec +35 -0
  71. package/src/helpers/EngineApi.js +34 -0
  72. package/src/helpers/listeners.js +7 -0
  73. package/src/helpers/peripherals.js +195 -0
  74. package/src/helpers/utils.js +113 -0
  75. package/src/helpers/values.js +72 -0
  76. package/src/helpers/variables.js +34 -0
  77. package/src/index.d.ts +373 -0
  78. package/src/index.js +369 -0
  79. package/src/products/auth/accessor.js +151 -0
  80. package/src/products/auth/index.js +279 -0
  81. package/src/products/database/accessor.js +316 -0
  82. package/src/products/database/index.js +603 -0
  83. package/src/products/database/types.js +22 -0
  84. package/src/products/database/validator.js +282 -0
  85. package/src/products/http_callable/index.js +230 -0
  86. package/src/products/storage/index.js +217 -0
@@ -0,0 +1,88 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <Scheme
3
+ LastUpgradeVersion = "1210"
4
+ version = "1.3">
5
+ <BuildAction
6
+ parallelizeBuildables = "YES"
7
+ buildImplicitDependencies = "YES">
8
+ <BuildActionEntries>
9
+ <BuildActionEntry
10
+ buildForTesting = "YES"
11
+ buildForRunning = "YES"
12
+ buildForProfiling = "YES"
13
+ buildForArchiving = "YES"
14
+ buildForAnalyzing = "YES">
15
+ <BuildableReference
16
+ BuildableIdentifier = "primary"
17
+ BlueprintIdentifier = "13B07F861A680F5B00A75B9A"
18
+ BuildableName = "MosquitodbExample.app"
19
+ BlueprintName = "MosquitodbExample"
20
+ ReferencedContainer = "container:MosquitodbExample.xcodeproj">
21
+ </BuildableReference>
22
+ </BuildActionEntry>
23
+ </BuildActionEntries>
24
+ </BuildAction>
25
+ <TestAction
26
+ buildConfiguration = "Debug"
27
+ selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
28
+ selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
29
+ shouldUseLaunchSchemeArgsEnv = "YES">
30
+ <Testables>
31
+ <TestableReference
32
+ skipped = "NO">
33
+ <BuildableReference
34
+ BuildableIdentifier = "primary"
35
+ BlueprintIdentifier = "00E356ED1AD99517003FC87E"
36
+ BuildableName = "MosquitodbExampleTests.xctest"
37
+ BlueprintName = "MosquitodbExampleTests"
38
+ ReferencedContainer = "container:MosquitodbExample.xcodeproj">
39
+ </BuildableReference>
40
+ </TestableReference>
41
+ </Testables>
42
+ </TestAction>
43
+ <LaunchAction
44
+ buildConfiguration = "Debug"
45
+ selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
46
+ selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
47
+ launchStyle = "0"
48
+ useCustomWorkingDirectory = "NO"
49
+ ignoresPersistentStateOnLaunch = "NO"
50
+ debugDocumentVersioning = "YES"
51
+ debugServiceExtension = "internal"
52
+ allowLocationSimulation = "YES">
53
+ <BuildableProductRunnable
54
+ runnableDebuggingMode = "0">
55
+ <BuildableReference
56
+ BuildableIdentifier = "primary"
57
+ BlueprintIdentifier = "13B07F861A680F5B00A75B9A"
58
+ BuildableName = "MosquitodbExample.app"
59
+ BlueprintName = "MosquitodbExample"
60
+ ReferencedContainer = "container:MosquitodbExample.xcodeproj">
61
+ </BuildableReference>
62
+ </BuildableProductRunnable>
63
+ </LaunchAction>
64
+ <ProfileAction
65
+ buildConfiguration = "Release"
66
+ shouldUseLaunchSchemeArgsEnv = "YES"
67
+ savedToolIdentifier = ""
68
+ useCustomWorkingDirectory = "NO"
69
+ debugDocumentVersioning = "YES">
70
+ <BuildableProductRunnable
71
+ runnableDebuggingMode = "0">
72
+ <BuildableReference
73
+ BuildableIdentifier = "primary"
74
+ BlueprintIdentifier = "13B07F861A680F5B00A75B9A"
75
+ BuildableName = "MosquitodbExample.app"
76
+ BlueprintName = "MosquitodbExample"
77
+ ReferencedContainer = "container:MosquitodbExample.xcodeproj">
78
+ </BuildableReference>
79
+ </BuildableProductRunnable>
80
+ </ProfileAction>
81
+ <AnalyzeAction
82
+ buildConfiguration = "Debug">
83
+ </AnalyzeAction>
84
+ <ArchiveAction
85
+ buildConfiguration = "Release"
86
+ revealArchiveInOrganizer = "YES">
87
+ </ArchiveAction>
88
+ </Scheme>
@@ -0,0 +1,24 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
+ <plist version="1.0">
4
+ <dict>
5
+ <key>CFBundleDevelopmentRegion</key>
6
+ <string>en</string>
7
+ <key>CFBundleExecutable</key>
8
+ <string>$(EXECUTABLE_NAME)</string>
9
+ <key>CFBundleIdentifier</key>
10
+ <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
11
+ <key>CFBundleInfoDictionaryVersion</key>
12
+ <string>6.0</string>
13
+ <key>CFBundleName</key>
14
+ <string>$(PRODUCT_NAME)</string>
15
+ <key>CFBundlePackageType</key>
16
+ <string>BNDL</string>
17
+ <key>CFBundleShortVersionString</key>
18
+ <string>1.0</string>
19
+ <key>CFBundleSignature</key>
20
+ <string>????</string>
21
+ <key>CFBundleVersion</key>
22
+ <string>1</string>
23
+ </dict>
24
+ </plist>
@@ -0,0 +1,66 @@
1
+ #import <UIKit/UIKit.h>
2
+ #import <XCTest/XCTest.h>
3
+
4
+ #import <React/RCTLog.h>
5
+ #import <React/RCTRootView.h>
6
+
7
+ #define TIMEOUT_SECONDS 600
8
+ #define TEXT_TO_LOOK_FOR @"Welcome to React"
9
+
10
+ @interface MosquitodbExampleTests : XCTestCase
11
+
12
+ @end
13
+
14
+ @implementation MosquitodbExampleTests
15
+
16
+ - (BOOL)findSubviewInView:(UIView *)view matching:(BOOL (^)(UIView *view))test
17
+ {
18
+ if (test(view)) {
19
+ return YES;
20
+ }
21
+ for (UIView *subview in [view subviews]) {
22
+ if ([self findSubviewInView:subview matching:test]) {
23
+ return YES;
24
+ }
25
+ }
26
+ return NO;
27
+ }
28
+
29
+ - (void)testRendersWelcomeScreen
30
+ {
31
+ UIViewController *vc = [[[RCTSharedApplication() delegate] window] rootViewController];
32
+ NSDate *date = [NSDate dateWithTimeIntervalSinceNow:TIMEOUT_SECONDS];
33
+ BOOL foundElement = NO;
34
+
35
+ __block NSString *redboxError = nil;
36
+ #ifdef DEBUG
37
+ RCTSetLogFunction(
38
+ ^(RCTLogLevel level, RCTLogSource source, NSString *fileName, NSNumber *lineNumber, NSString *message) {
39
+ if (level >= RCTLogLevelError) {
40
+ redboxError = message;
41
+ }
42
+ });
43
+ #endif
44
+
45
+ while ([date timeIntervalSinceNow] > 0 && !foundElement && !redboxError) {
46
+ [[NSRunLoop mainRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
47
+ [[NSRunLoop mainRunLoop] runMode:NSRunLoopCommonModes beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
48
+
49
+ foundElement = [self findSubviewInView:vc.view
50
+ matching:^BOOL(UIView *view) {
51
+ if ([view.accessibilityLabel isEqualToString:TEXT_TO_LOOK_FOR]) {
52
+ return YES;
53
+ }
54
+ return NO;
55
+ }];
56
+ }
57
+
58
+ #ifdef DEBUG
59
+ RCTSetLogFunction(RCTDefaultLogFunction);
60
+ #endif
61
+
62
+ XCTAssertNil(redboxError, @"RedBox error: %@", redboxError);
63
+ XCTAssertTrue(foundElement, @"Couldn't find element with text '%@' in %d seconds", TEXT_TO_LOOK_FOR, TIMEOUT_SECONDS);
64
+ }
65
+
66
+ @end
@@ -0,0 +1,60 @@
1
+ require_relative '../node_modules/react-native/scripts/react_native_pods'
2
+ require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'
3
+
4
+ platform :ios, min_ios_version_supported
5
+ prepare_react_native_project!
6
+
7
+ # If you are using a `react-native-flipper` your iOS build will fail when `NO_FLIPPER=1` is set.
8
+ # because `react-native-flipper` depends on (FlipperKit,...) that will be excluded
9
+ #
10
+ # To fix this you can also exclude `react-native-flipper` using a `react-native.config.js`
11
+ # ```js
12
+ # module.exports = {
13
+ # dependencies: {
14
+ # ...(process.env.NO_FLIPPER ? { 'react-native-flipper': { platforms: { ios: null } } } : {}),
15
+ # ```
16
+ flipper_config = ENV['NO_FLIPPER'] == "1" ? FlipperConfiguration.disabled : FlipperConfiguration.enabled
17
+
18
+ linkage = ENV['USE_FRAMEWORKS']
19
+ if linkage != nil
20
+ Pod::UI.puts "Configuring Pod with #{linkage}ally linked Frameworks".green
21
+ use_frameworks! :linkage => linkage.to_sym
22
+ end
23
+
24
+ target 'MosquitodbExample' do
25
+ config = use_native_modules!
26
+
27
+ # Flags change depending on the env values.
28
+ flags = get_default_flags()
29
+
30
+ use_react_native!(
31
+ :path => config[:reactNativePath],
32
+ # Hermes is now enabled by default. Disable by setting this flag to false.
33
+ # Upcoming versions of React Native may rely on get_default_flags(), but
34
+ # we make it explicit here to aid in the React Native upgrade process.
35
+ :hermes_enabled => flags[:hermes_enabled],
36
+ :fabric_enabled => flags[:fabric_enabled],
37
+ # Enables Flipper.
38
+ #
39
+ # Note that if you have use_frameworks! enabled, Flipper will not work and
40
+ # you should disable the next line.
41
+ :flipper_configuration => flipper_config,
42
+ # An absolute path to your application root.
43
+ :app_path => "#{Pod::Config.instance.installation_root}/.."
44
+ )
45
+
46
+ target 'MosquitodbExampleTests' do
47
+ inherit! :complete
48
+ # Pods for testing
49
+ end
50
+
51
+ post_install do |installer|
52
+ react_native_post_install(
53
+ installer,
54
+ # Set `mac_catalyst_enabled` to `true` in order to apply patches
55
+ # necessary for Mac Catalyst builds
56
+ :mac_catalyst_enabled => false
57
+ )
58
+ __apply_Xcode_12_5_M1_post_install_workaround(installer)
59
+ end
60
+ end
@@ -0,0 +1,40 @@
1
+ const path = require('path');
2
+ const escape = require('escape-string-regexp');
3
+ const exclusionList = require('metro-config/src/defaults/exclusionList');
4
+ const pak = require('../package.json');
5
+
6
+ const root = path.resolve(__dirname, '..');
7
+
8
+ const modules = Object.keys({
9
+ ...pak.peerDependencies,
10
+ });
11
+
12
+ module.exports = {
13
+ projectRoot: __dirname,
14
+ watchFolders: [root],
15
+
16
+ // We need to make sure that only one version is loaded for peerDependencies
17
+ // So we block them at the root, and alias them to the versions in example's node_modules
18
+ resolver: {
19
+ blacklistRE: exclusionList(
20
+ modules.map(
21
+ (m) =>
22
+ new RegExp(`^${escape(path.join(root, 'node_modules', m))}\\/.*$`)
23
+ )
24
+ ),
25
+
26
+ extraNodeModules: modules.reduce((acc, name) => {
27
+ acc[name] = path.join(__dirname, 'node_modules', name);
28
+ return acc;
29
+ }, {}),
30
+ },
31
+
32
+ transformer: {
33
+ getTransformOptions: async () => ({
34
+ transform: {
35
+ experimentalImportSupport: false,
36
+ inlineRequires: true,
37
+ },
38
+ }),
39
+ },
40
+ };
@@ -0,0 +1,22 @@
1
+ {
2
+ "name": "MosquitodbExample",
3
+ "version": "0.0.1",
4
+ "private": true,
5
+ "scripts": {
6
+ "android": "react-native run-android",
7
+ "ios": "react-native run-ios",
8
+ "start": "react-native start",
9
+ "pods": "pod-install --quiet"
10
+ },
11
+ "dependencies": {
12
+ "react": "18.2.0",
13
+ "react-native": "0.71.8"
14
+ },
15
+ "devDependencies": {
16
+ "@babel/core": "^7.20.0",
17
+ "@babel/preset-env": "^7.20.0",
18
+ "@babel/runtime": "^7.20.0",
19
+ "metro-react-native-babel-preset": "0.73.9",
20
+ "babel-plugin-module-resolver": "^4.1.0"
21
+ }
22
+ }
@@ -0,0 +1,10 @@
1
+ const path = require('path');
2
+ const pak = require('../package.json');
3
+
4
+ module.exports = {
5
+ dependencies: {
6
+ [pak.name]: {
7
+ root: path.join(__dirname, '..'),
8
+ },
9
+ },
10
+ };
@@ -0,0 +1,31 @@
1
+ import * as React from 'react';
2
+
3
+ import { StyleSheet, View, Text } from 'react-native';
4
+ import { multiply } from 'react-native-mosquitodb';
5
+
6
+ export default function App() {
7
+ const [result, setResult] = React.useState<number | undefined>();
8
+
9
+ React.useEffect(() => {
10
+ multiply(3, 7).then(setResult);
11
+ }, []);
12
+
13
+ return (
14
+ <View style={styles.container}>
15
+ <Text>Result: {result}</Text>
16
+ </View>
17
+ );
18
+ }
19
+
20
+ const styles = StyleSheet.create({
21
+ container: {
22
+ flex: 1,
23
+ alignItems: 'center',
24
+ justifyContent: 'center',
25
+ },
26
+ box: {
27
+ width: 60,
28
+ height: 60,
29
+ marginVertical: 20,
30
+ },
31
+ });
@@ -0,0 +1,2 @@
1
+ #import <React/RCTBridgeModule.h>
2
+ #import <React/RCTViewManager.h>
@@ -0,0 +1,22 @@
1
+ #import <React/RCTBridgeModule.h>
2
+
3
+ @interface RCT_EXTERN_MODULE(Mosquitodb, NSObject)
4
+
5
+ RCT_EXTERN_METHOD(uploadFile:(NSDictionary *)options)
6
+
7
+ RCT_EXTERN_METHOD(cancelUpload:(NSString *)processID)
8
+
9
+ RCT_EXTERN_METHOD(downloadFile:(NSDictionary *)options)
10
+
11
+ RCT_EXTERN_METHOD(cancelDownload:(NSString *)processID)
12
+
13
+ RCT_EXTERN_METHOD(pauseDownload:(NSString *)processID)
14
+
15
+ RCT_EXTERN_METHOD(resumeDownload:(NSString *)processID)
16
+
17
+ + (BOOL)requiresMainQueueSetup
18
+ {
19
+ return NO;
20
+ }
21
+ @end
22
+
@@ -0,0 +1,305 @@
1
+ import React
2
+
3
+ @objc(Mosquitodb)
4
+ class Mosquitodb: RCTEventEmitter, URLSessionDataDelegate {
5
+
6
+ public override init() {
7
+ super.init()
8
+ }
9
+
10
+ override public static func requiresMainQueueSetup() -> Bool {
11
+ return true;
12
+ }
13
+
14
+ @objc(supportedEvents)
15
+ override public func supportedEvents() -> [String] {
16
+ return [
17
+ "mt-uploading-progress",
18
+ "mt-uploading-status",
19
+ "mt-download-progress",
20
+ "mt-download-status"
21
+ ]
22
+ }
23
+
24
+ var uploadTask: [String: MosquitodbUploadTask] = [:]
25
+ var downloadTask: [String: MosquitodbDownloadTask] = [:]
26
+
27
+ @objc(downloadFile:)
28
+ func downloadFile(options: [String: Any]) -> Void {
29
+ let processID = options["processID"] as! String
30
+ downloadTask[processID] = MosquitodbDownloadTask()
31
+ downloadTask[processID]?.downloadFile(options: options, completion: { res in
32
+ let status = res![0] as? String
33
+
34
+ self.sendEvent(withName: status, body: res![1])
35
+ if status == "mt-download-status" {
36
+ self.downloadTask.removeValue(forKey: processID)
37
+ }
38
+ })
39
+ }
40
+
41
+ @objc(uploadFile:)
42
+ func uploadFile(options: [String: Any]) -> Void {
43
+ let processID = options["processID"] as! String
44
+
45
+ uploadTask[processID] = MosquitodbUploadTask()
46
+ uploadTask[processID]?.uploadFile(options: options, completion: { res in
47
+ let status = res![0] as? String
48
+
49
+ self.sendEvent(withName: status, body: res![1])
50
+ if status == "mt-uploading-status" {
51
+ self.uploadTask.removeValue(forKey: processID)
52
+ }
53
+ })
54
+ }
55
+
56
+ @objc(cancelUpload:)
57
+ func cancelUpload (processID: String)-> Void {
58
+ uploadTask[processID]?.cancelUpload()
59
+ }
60
+
61
+ @objc(cancelDownload:)
62
+ func cancelDownload (processID: String)-> Void {
63
+ downloadTask[processID]?.cancelDownload()
64
+ }
65
+
66
+ @objc(pauseDownload:)
67
+ func pauseDownload (processID: String)-> Void {
68
+ downloadTask[processID]?.pauseDownload()
69
+ }
70
+
71
+ @objc(resumeDownload:)
72
+ func resumeDownload (processID: String)-> Void {
73
+ downloadTask[processID]?.resumeDownload()
74
+ }
75
+ }
76
+
77
+
78
+ class MosquitodbUploadTask: NSObject, URLSessionDataDelegate {
79
+
80
+ var mainProcessID: String = ""
81
+ var mainTask : URLSessionUploadTask? = nil
82
+ var mainOptions: [String: Any] = [:]
83
+ var trigger: (([Any]?)->())? = nil
84
+
85
+
86
+ func uploadFile(options: [String: Any], completion: @escaping ([Any]?)->()) -> Void {
87
+ let processID = options["processID"] as! String
88
+ let filepath = options["file"] as! String
89
+ let url = options["url"] as! String
90
+ let destination = options["destination"] as! String
91
+ let authorization = options["authorization"] as! String
92
+
93
+ do {
94
+ let rawData = try Data(contentsOf: URL(fileURLWithPath: filepath))
95
+
96
+ var request = URLRequest(url: URL(string: url)!)
97
+ request.httpMethod = "POST"
98
+ request.setValue("application/json", forHTTPHeaderField: "Accept")
99
+ request.setValue(authorization, forHTTPHeaderField: "Authorization")
100
+ if options["authToken"] != nil {
101
+ request.setValue(options["authToken"] as? String, forHTTPHeaderField: "Mosquito-Token")
102
+ }
103
+ request.setValue("buffer/upload", forHTTPHeaderField: "Content-Type")
104
+ request.setValue(destination, forHTTPHeaderField: "Mosquito-Destination")
105
+
106
+ let session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil)
107
+ let task = session.uploadTask(with: request, from: rawData)
108
+
109
+ mainProcessID = processID
110
+ mainTask = task
111
+ mainOptions = options
112
+ trigger = completion
113
+
114
+ task.resume()
115
+ } catch {
116
+ completion([
117
+ "mt-uploading-status", [
118
+ "processID": processID,
119
+ "error": "file_not_found",
120
+ "errorDes": "\(error)"
121
+ ]
122
+ ])
123
+ trigger = nil
124
+ }
125
+ }
126
+
127
+ func cancelUpload(){
128
+ mainTask?.cancel()
129
+ }
130
+
131
+ func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
132
+
133
+ trigger!([
134
+ "mt-uploading-progress", [
135
+ "sentBtyes": Float(totalBytesSent),
136
+ "totalBytes": Float(totalBytesExpectedToSend),
137
+ "processID": mainProcessID
138
+ ]
139
+ ])
140
+ }
141
+
142
+ func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
143
+ if error != nil {
144
+ trigger!([
145
+ "mt-uploading-status", [
146
+ "processID": mainProcessID,
147
+ "error": "failed",
148
+ "errorDes": error?.localizedDescription
149
+ ]
150
+ ])
151
+ trigger = nil
152
+ }
153
+ }
154
+
155
+ func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
156
+
157
+ if let responseText = String(data: data, encoding: .utf8) {
158
+ trigger!([
159
+ "mt-uploading-status", [
160
+ "processID": mainProcessID,
161
+ "result": responseText
162
+ ]])
163
+ }else {
164
+ trigger!([
165
+ "mt-uploading-status", [
166
+ "processID": mainProcessID,
167
+ "error": "invalid_response",
168
+ "errorDes": "the server response was invalid"
169
+ ]])
170
+ }
171
+ trigger = nil
172
+ }
173
+ }
174
+
175
+
176
+ class MosquitodbDownloadTask: NSObject, URLSessionDownloadDelegate {
177
+
178
+ var mainProcessID: String = ""
179
+ var mainTask : URLSessionDownloadTask? = nil
180
+ var mainOptions: [String: Any] = [:]
181
+ var trigger: (([Any]?)->())? = nil
182
+
183
+ func downloadFile(options: [String: Any], completion: @escaping ([Any]?)->()) -> Void {
184
+ let processID = options["processID"] as! String
185
+ let url = options["url"] as! String
186
+ let authorization = options["authorization"] as! String
187
+
188
+ var request = URLRequest(url: URL(string: url)!)
189
+ request.httpMethod = "POST"
190
+ request.setValue(authorization, forHTTPHeaderField: "Authorization")
191
+ if options["authToken"] != nil {
192
+ request.setValue(options["authToken"] as? String, forHTTPHeaderField: "Mosquito-Token")
193
+ }
194
+
195
+ let session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil)
196
+ let task = session.downloadTask(with: request)
197
+
198
+ mainProcessID = processID
199
+ mainTask = task
200
+ mainOptions = options
201
+ trigger = completion
202
+ task.resume()
203
+ print("MosquitodbDownloadTask started:\(mainProcessID)")
204
+ }
205
+
206
+ func cancelDownload ()-> Void {
207
+ mainTask?.cancel()
208
+ }
209
+
210
+ func pauseDownload ()-> Void {
211
+ mainTask?.suspend()
212
+ }
213
+
214
+ func resumeDownload ()-> Void {
215
+ mainTask?.resume()
216
+ }
217
+
218
+ func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?){
219
+ print("mosquito didCompleteWithError process:\(String(describing: error?.localizedDescription))")
220
+
221
+ if error != nil {
222
+ trigger!([
223
+ "mt-download-status", [
224
+ "processID": mainProcessID,
225
+ "error": "failed",
226
+ "errorDes": error?.localizedDescription
227
+ ]
228
+ ])
229
+ trigger = nil
230
+ }
231
+ }
232
+
233
+ func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
234
+ print("mosquito didFinishDownloadingTo process:\(mainProcessID)")
235
+
236
+ do {
237
+ if mainProcessID != "" {
238
+ let data = try Data(contentsOf: location)
239
+
240
+ if mainOptions.keys.contains("destination") {
241
+ let dest = mainOptions["destination"] as! String
242
+ let destDir = mainOptions["destinationDir"] as! String
243
+ try FileManager.default.createDirectory(at: URL(string:destDir)!, withIntermediateDirectories: true, attributes: nil)
244
+ try data.write(to: URL(string: dest)!)
245
+
246
+ trigger!([
247
+ "mt-download-status", [
248
+ "processID": mainProcessID,
249
+ "result": "{\"file\": \"\(dest)\"}"
250
+ ]
251
+ ])
252
+ }else{
253
+ let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
254
+ let urlName = mainOptions["urlName"] as! String
255
+ let destDir = documentsURL.appendingPathComponent("mosquito-transport")
256
+ try FileManager.default.createDirectory(at: destDir, withIntermediateDirectories: true, attributes: nil)
257
+ let destURL = destDir.appendingPathComponent("\(NSDate().timeIntervalSince1970)-\(urlName)")
258
+ try data.write(to: destURL)
259
+
260
+ trigger!([
261
+ "mt-download-status", [
262
+ "processID": mainProcessID,
263
+ "result": "{\"file\": \"\(destURL.absoluteString)\"}"
264
+ ]
265
+ ])
266
+ }
267
+ }
268
+ } catch {
269
+ print("downloadWrite err:", error)
270
+ if mainProcessID != "" {
271
+ trigger!([
272
+ "mt-download-status",[
273
+ "processID": mainProcessID,
274
+ "error": "saving_file_error",
275
+ "errorDes": "\(error)"
276
+ ]
277
+ ])
278
+ }
279
+ }
280
+ trigger = nil
281
+ }
282
+
283
+ func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
284
+ print("mosquito nativeProgress :\(Float(bytesWritten))")
285
+
286
+ trigger!([
287
+ "mt-download-progress", [
288
+ "receivedBtyes": Float(totalBytesWritten),
289
+ "expectedBytes": Float(totalBytesExpectedToWrite),
290
+ "processID": mainProcessID
291
+ ]
292
+ ])
293
+ }
294
+
295
+ // func getSystemFreeSpace(){
296
+ // do{
297
+ // let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
298
+ // let dic = try FileManager.default.attributesOfFileSystem(forPath: path.last!)
299
+ //
300
+ // let freeSpace = dic[FileAttributeKey.systemFreeSize] as! CUnsignedLongLong
301
+ // }catch{
302
+ //
303
+ // }
304
+ // }
305
+ }