@fountispanel/connect-react-native 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/CHANGELOG.md +9 -1
  2. package/README.md +7 -6
  3. package/android/build.gradle +35 -16
  4. package/android/src/main/AndroidManifest.xml +5 -16
  5. package/build/index.js +1 -126
  6. package/build/index.web.js +1 -57
  7. package/ios/FountisConnect.xcframework/Info.plist +44 -0
  8. package/{android/connect-sdk/main/assets/fountis-connect → ios/FountisConnect.xcframework/ios-arm64/FountisConnect.framework/Engine}/engine.html +5 -5
  9. package/ios/FountisConnect.xcframework/ios-arm64/FountisConnect.framework/FountisConnect +0 -0
  10. package/ios/FountisConnect.xcframework/ios-arm64/FountisConnect.framework/Info.plist +53 -0
  11. package/ios/FountisConnect.xcframework/ios-arm64/FountisConnect.framework/Modules/FountisConnect.swiftmodule/arm64-apple-ios.swiftdoc +0 -0
  12. package/ios/FountisConnect.xcframework/ios-arm64/FountisConnect.framework/Modules/FountisConnect.swiftmodule/arm64-apple-ios.swiftinterface +48 -0
  13. package/ios/{FountisConnectSDK → FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework}/Engine/engine.html +5 -5
  14. package/ios/FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework/FountisConnect +0 -0
  15. package/ios/FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework/Info.plist +49 -0
  16. package/ios/FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework/Modules/FountisConnect.swiftmodule/arm64-apple-ios-simulator.swiftdoc +0 -0
  17. package/ios/FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework/Modules/FountisConnect.swiftmodule/arm64-apple-ios-simulator.swiftinterface +48 -0
  18. package/ios/FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework/Modules/FountisConnect.swiftmodule/x86_64-apple-ios-simulator.swiftdoc +0 -0
  19. package/ios/FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework/Modules/FountisConnect.swiftmodule/x86_64-apple-ios-simulator.swiftinterface +48 -0
  20. package/ios/FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework/PrivacyInfo.xcprivacy +23 -0
  21. package/ios/FountisConnectAppDelegateSubscriber.swift +3 -0
  22. package/ios/FountisConnectModule.swift +3 -0
  23. package/ios/FountisConnectReactNative.podspec +27 -6
  24. package/package.json +14 -12
  25. package/android/connect-sdk/main/kotlin/org/fountis/connect/ApiClient.kt +0 -161
  26. package/android/connect-sdk/main/kotlin/org/fountis/connect/FountisConnect.kt +0 -616
  27. package/android/connect-sdk/main/kotlin/org/fountis/connect/FountisSurveyActivity.kt +0 -321
  28. package/android/connect-sdk/main/kotlin/org/fountis/connect/LocalState.kt +0 -143
  29. package/android/connect-sdk/main/kotlin/org/fountis/connect/Matcher.kt +0 -167
  30. package/android/connect-sdk/main/kotlin/org/fountis/connect/Models.kt +0 -128
  31. package/android/connect-sdk/main/kotlin/org/fountis/connect/Notifier.kt +0 -109
  32. package/android/connect-sdk/main/kotlin/org/fountis/connect/RequestDeadline.kt +0 -74
  33. package/android/connect-sdk/main/kotlin/org/fountis/connect/Strings.kt +0 -45
  34. package/android/connect-sdk/main/kotlin/org/fountis/connect/TokenProviderCall.kt +0 -72
  35. package/android/connect-sdk/main/res/drawable/fountis_ic_notification.xml +0 -12
  36. package/android/connect-sdk/main/res/values/fountis_styles.xml +0 -13
  37. package/android/connect-sdk/main/res/values-v27/fountis_styles.xml +0 -12
  38. package/build/types.js +0 -1
  39. package/ios/FountisConnectBundle.swift +0 -15
  40. package/ios/FountisConnectSDK/ApiClient.swift +0 -113
  41. package/ios/FountisConnectSDK/FountisConnect.swift +0 -436
  42. package/ios/FountisConnectSDK/LocalState.swift +0 -81
  43. package/ios/FountisConnectSDK/Matcher.swift +0 -102
  44. package/ios/FountisConnectSDK/Models.swift +0 -116
  45. package/ios/FountisConnectSDK/Notifier.swift +0 -63
  46. package/ios/FountisConnectSDK/RequestDeadline.swift +0 -93
  47. package/ios/FountisConnectSDK/SheetController.swift +0 -259
  48. package/ios/FountisConnectSDK/Strings.swift +0 -34
  49. package/ios/FountisConnectSDK/TokenProviderCall.swift +0 -91
  50. package/scripts/vendor-native.sh +0 -16
  51. package/src/index.ts +0 -142
  52. package/src/index.web.ts +0 -64
  53. package/src/types.ts +0 -26
  54. /package/{android/connect-sdk/main/assets/fountis-connect → ios/FountisConnect.xcframework/ios-arm64/FountisConnect.framework/Engine}/i18n/ar.json +0 -0
  55. /package/{android/connect-sdk/main/assets/fountis-connect → ios/FountisConnect.xcframework/ios-arm64/FountisConnect.framework/Engine}/i18n/en.json +0 -0
  56. /package/{android/connect-sdk/main/assets/fountis-connect → ios/FountisConnect.xcframework/ios-arm64/FountisConnect.framework/Engine}/i18n/kmr.json +0 -0
  57. /package/{android/connect-sdk/main/assets/fountis-connect → ios/FountisConnect.xcframework/ios-arm64/FountisConnect.framework/Engine}/i18n/ku.json +0 -0
  58. /package/ios/{FountisConnectSDK → FountisConnect.xcframework/ios-arm64/FountisConnect.framework}/PrivacyInfo.xcprivacy +0 -0
  59. /package/ios/{FountisConnectSDK → FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework}/Engine/i18n/ar.json +0 -0
  60. /package/ios/{FountisConnectSDK → FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework}/Engine/i18n/en.json +0 -0
  61. /package/ios/{FountisConnectSDK → FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework}/Engine/i18n/kmr.json +0 -0
  62. /package/ios/{FountisConnectSDK → FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework}/Engine/i18n/ku.json +0 -0
@@ -0,0 +1,49 @@
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>FountisConnect</string>
9
+ <key>CFBundleIdentifier</key>
10
+ <string>org.fountis.connect.FountisConnect</string>
11
+ <key>CFBundleInfoDictionaryVersion</key>
12
+ <string>6.0</string>
13
+ <key>CFBundleName</key>
14
+ <string>FountisConnect</string>
15
+ <key>CFBundlePackageType</key>
16
+ <string>FMWK</string>
17
+ <key>CFBundleShortVersionString</key>
18
+ <string>1.2.0</string>
19
+ <key>CFBundleSupportedPlatforms</key>
20
+ <array>
21
+ <string>iPhoneSimulator</string>
22
+ </array>
23
+ <key>CFBundleVersion</key>
24
+ <string>1.2.0</string>
25
+ <key>DTCompiler</key>
26
+ <string>com.apple.compilers.llvm.clang.1_0</string>
27
+ <key>DTPlatformBuild</key>
28
+ <string>22F76</string>
29
+ <key>DTPlatformName</key>
30
+ <string>iphonesimulator</string>
31
+ <key>DTPlatformVersion</key>
32
+ <string>18.5</string>
33
+ <key>DTSDKBuild</key>
34
+ <string>22F76</string>
35
+ <key>DTSDKName</key>
36
+ <string>iphonesimulator18.5</string>
37
+ <key>DTXcode</key>
38
+ <string>1640</string>
39
+ <key>DTXcodeBuild</key>
40
+ <string>16F6</string>
41
+ <key>MinimumOSVersion</key>
42
+ <string>15.0</string>
43
+ <key>UIDeviceFamily</key>
44
+ <array>
45
+ <integer>1</integer>
46
+ <integer>2</integer>
47
+ </array>
48
+ </dict>
49
+ </plist>
@@ -0,0 +1,48 @@
1
+ // swift-interface-format-version: 1.0
2
+ // swift-compiler-version: Apple Swift version 6.1.2 effective-5.10 (swiftlang-6.1.2.1.2 clang-1700.0.13.5)
3
+ // swift-module-flags: -target arm64-apple-ios15.0-simulator -enable-objc-interop -enable-library-evolution -swift-version 5 -enforce-exclusivity=checked -O -enable-experimental-feature DebugDescriptionMacro -module-name FountisConnect -package-name fountisconnect -module-alias Module___FountisConnect=FountisConnect -module-alias Module____StringProcessing=_StringProcessing -module-alias Module____SwiftConcurrencyShims=_SwiftConcurrencyShims -module-alias Module____Concurrency=_Concurrency -module-alias Module___CryptoKit=CryptoKit -module-alias Module___DeviceCheck=DeviceCheck -module-alias Module___UIKit=UIKit -module-alias Module___UserNotifications=UserNotifications -module-alias Module___os=os -module-alias Module___BackgroundTasks=BackgroundTasks -module-alias Module___WebKit=WebKit
4
+ // swift-module-flags-ignorable: -interface-compiler-version 6.1.2
5
+ import Module___BackgroundTasks
6
+ import Module___CryptoKit
7
+ import Module___DeviceCheck
8
+ import Foundation
9
+ import Swift
10
+ import Module___UIKit
11
+ import Module___UserNotifications
12
+ import Module___WebKit
13
+ import Module____Concurrency
14
+ import Module____StringProcessing
15
+ import Module____SwiftConcurrencyShims
16
+ import Module___os
17
+ @Module____Concurrency.MainActor public enum FountisConnect {
18
+ @Module____Concurrency.MainActor public static let defaultAPIBase: Foundation.URL
19
+ @Module____Concurrency.MainActor public static func start(key: Swift.String, apiBase: Foundation.URL? = nil)
20
+ @Module____Concurrency.MainActor public static func setUserToken(_ provider: @escaping () async throws -> Swift.String?)
21
+ @Module____Concurrency.MainActor public static func enableNotifications()
22
+ @discardableResult
23
+ @Module____Concurrency.MainActor public static func show() async -> Module___FountisConnect.FountisResult
24
+ @discardableResult
25
+ @Module____Concurrency.MainActor public static func handlePush(_ userInfo: [Swift.AnyHashable : Any]) -> Swift.Bool
26
+ @discardableResult
27
+ @Module____Concurrency.MainActor public static func handleNotificationResponse(_ response: Module___UserNotifications.UNNotificationResponse) -> Swift.Bool
28
+ @Module____Concurrency.MainActor public static func setUserConsent(_ granted: Swift.Bool)
29
+ @Module____Concurrency.MainActor public static func signOut()
30
+ @Module____Concurrency.MainActor public static func onEvent(_ listener: @escaping (Module___FountisConnect.FountisEvent) -> Swift.Void)
31
+ }
32
+ @frozen public enum FountisResult : Swift.Equatable, Swift.Sendable {
33
+ case noFill
34
+ case dismissed
35
+ case completed
36
+ public static func == (a: Module___FountisConnect.FountisResult, b: Module___FountisConnect.FountisResult) -> Swift.Bool
37
+ public func hash(into hasher: inout Swift.Hasher)
38
+ public var hashValue: Swift.Int {
39
+ get
40
+ }
41
+ }
42
+ public struct FountisEvent : Swift.Sendable {
43
+ public let type: Swift.String
44
+ public let offerId: Swift.String?
45
+ }
46
+ extension Module___FountisConnect.FountisConnect : Swift.Sendable {}
47
+ extension Module___FountisConnect.FountisResult : Swift.Hashable {}
48
+ extension Module___FountisConnect.FountisResult : Swift.BitwiseCopyable {}
@@ -0,0 +1,48 @@
1
+ // swift-interface-format-version: 1.0
2
+ // swift-compiler-version: Apple Swift version 6.1.2 effective-5.10 (swiftlang-6.1.2.1.2 clang-1700.0.13.5)
3
+ // swift-module-flags: -target x86_64-apple-ios15.0-simulator -enable-objc-interop -enable-library-evolution -swift-version 5 -enforce-exclusivity=checked -O -enable-experimental-feature DebugDescriptionMacro -module-name FountisConnect -package-name fountisconnect -module-alias Module___FountisConnect=FountisConnect -module-alias Module____StringProcessing=_StringProcessing -module-alias Module____SwiftConcurrencyShims=_SwiftConcurrencyShims -module-alias Module____Concurrency=_Concurrency -module-alias Module___CryptoKit=CryptoKit -module-alias Module___DeviceCheck=DeviceCheck -module-alias Module___UIKit=UIKit -module-alias Module___UserNotifications=UserNotifications -module-alias Module___os=os -module-alias Module___BackgroundTasks=BackgroundTasks -module-alias Module___WebKit=WebKit
4
+ // swift-module-flags-ignorable: -interface-compiler-version 6.1.2
5
+ import Module___BackgroundTasks
6
+ import Module___CryptoKit
7
+ import Module___DeviceCheck
8
+ import Foundation
9
+ import Swift
10
+ import Module___UIKit
11
+ import Module___UserNotifications
12
+ import Module___WebKit
13
+ import Module____Concurrency
14
+ import Module____StringProcessing
15
+ import Module____SwiftConcurrencyShims
16
+ import Module___os
17
+ @Module____Concurrency.MainActor public enum FountisConnect {
18
+ @Module____Concurrency.MainActor public static let defaultAPIBase: Foundation.URL
19
+ @Module____Concurrency.MainActor public static func start(key: Swift.String, apiBase: Foundation.URL? = nil)
20
+ @Module____Concurrency.MainActor public static func setUserToken(_ provider: @escaping () async throws -> Swift.String?)
21
+ @Module____Concurrency.MainActor public static func enableNotifications()
22
+ @discardableResult
23
+ @Module____Concurrency.MainActor public static func show() async -> Module___FountisConnect.FountisResult
24
+ @discardableResult
25
+ @Module____Concurrency.MainActor public static func handlePush(_ userInfo: [Swift.AnyHashable : Any]) -> Swift.Bool
26
+ @discardableResult
27
+ @Module____Concurrency.MainActor public static func handleNotificationResponse(_ response: Module___UserNotifications.UNNotificationResponse) -> Swift.Bool
28
+ @Module____Concurrency.MainActor public static func setUserConsent(_ granted: Swift.Bool)
29
+ @Module____Concurrency.MainActor public static func signOut()
30
+ @Module____Concurrency.MainActor public static func onEvent(_ listener: @escaping (Module___FountisConnect.FountisEvent) -> Swift.Void)
31
+ }
32
+ @frozen public enum FountisResult : Swift.Equatable, Swift.Sendable {
33
+ case noFill
34
+ case dismissed
35
+ case completed
36
+ public static func == (a: Module___FountisConnect.FountisResult, b: Module___FountisConnect.FountisResult) -> Swift.Bool
37
+ public func hash(into hasher: inout Swift.Hasher)
38
+ public var hashValue: Swift.Int {
39
+ get
40
+ }
41
+ }
42
+ public struct FountisEvent : Swift.Sendable {
43
+ public let type: Swift.String
44
+ public let offerId: Swift.String?
45
+ }
46
+ extension Module___FountisConnect.FountisConnect : Swift.Sendable {}
47
+ extension Module___FountisConnect.FountisResult : Swift.Hashable {}
48
+ extension Module___FountisConnect.FountisResult : Swift.BitwiseCopyable {}
@@ -0,0 +1,23 @@
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>NSPrivacyTracking</key>
6
+ <false/>
7
+ <key>NSPrivacyTrackingDomains</key>
8
+ <array/>
9
+ <key>NSPrivacyCollectedDataTypes</key>
10
+ <array/>
11
+ <key>NSPrivacyAccessedAPITypes</key>
12
+ <array>
13
+ <dict>
14
+ <key>NSPrivacyAccessedAPIType</key>
15
+ <string>NSPrivacyAccessedAPICategoryUserDefaults</string>
16
+ <key>NSPrivacyAccessedAPITypeReasons</key>
17
+ <array>
18
+ <string>CA92.1</string>
19
+ </array>
20
+ </dict>
21
+ </array>
22
+ </dict>
23
+ </plist>
@@ -1,5 +1,8 @@
1
1
  import ExpoModulesCore
2
2
  import UIKit
3
+ #if canImport(FountisConnect)
4
+ import FountisConnect
5
+ #endif
3
6
 
4
7
  /// Starts the SDK while the app is still launching when the config plugin was given a key
5
8
  /// (`FountisConnectKey` in Info.plist). iOS only accepts the background refresh registration at that moment.
@@ -1,5 +1,8 @@
1
1
  import ExpoModulesCore
2
2
  import UIKit
3
+ #if canImport(FountisConnect)
4
+ import FountisConnect
5
+ #endif
3
6
 
4
7
  /// JS bridge for the FOUNTIS Connect iOS SDK. All SDK calls run on the main thread, in the order JS made them.
5
8
  public final class FountisConnectModule: Module {
@@ -3,15 +3,31 @@ require 'fileutils'
3
3
 
4
4
  package = JSON.parse(File.read(File.join(__dir__, '..', 'package.json')))
5
5
 
6
- # CocoaPods cannot read files outside the pod folder, so the Swift SDK is copied into ios/FountisConnectSDK
7
- # when `pod install` reads this file inside the repository (re-run `pod install` after changing the SDK).
8
- # The npm package already carries that copy (scripts/vendor-native.sh runs on `npm pack`).
6
+ # Two ways to get the FOUNTIS iOS SDK into the app:
7
+ #
8
+ # 1. Binary (the only mode of a published package): ios/FountisConnect.xcframework is in this folder. It is copied
9
+ # there when the package is packed (scripts/vendor-native.sh) and holds the public API plus the survey engine and
10
+ # privacy manifest. The pod links it and compiles only the two Swift files of this folder.
11
+ # 2. Source (development and CI inside this repository only): the Swift sources are in ../../ios/Sources/FountisConnect.
12
+ # CocoaPods cannot read files outside the pod folder, so they are copied into ios/FountisConnectSDK when
13
+ # `pod install` reads this file (re-run it after changing the SDK) and compiled into this pod. If you packed the
14
+ # package here, delete ios/FountisConnect.xcframework to get back to this mode.
15
+ xcframework = File.join(__dir__, 'FountisConnect.xcframework')
9
16
  repo_sdk = File.join(__dir__, '..', '..', 'ios', 'Sources', 'FountisConnect')
10
17
  sdk = 'FountisConnectSDK'
11
- if File.directory?(repo_sdk)
18
+
19
+ if File.directory?(xcframework)
20
+ mode = :binary
21
+ elsif File.directory?(repo_sdk)
22
+ mode = :source
12
23
  FileUtils.rm_rf(File.join(__dir__, sdk))
13
24
  FileUtils.mkdir_p(File.join(__dir__, sdk))
14
25
  FileUtils.cp_r(Dir.glob(File.join(repo_sdk, '*')), File.join(__dir__, sdk))
26
+ else
27
+ raise "FountisConnectReactNative: ios/FountisConnect.xcframework is missing from the package " \
28
+ "(and the SDK sources are not next to it). Reinstall @fountispanel/connect-react-native; " \
29
+ "if this is the FOUNTIS repository, build the XCFramework with ios/scripts/build-xcframework.sh " \
30
+ "and pack the package again."
15
31
  end
16
32
 
17
33
  Pod::Spec.new do |s|
@@ -29,7 +45,12 @@ Pod::Spec.new do |s|
29
45
 
30
46
  s.dependency 'ExpoModulesCore'
31
47
 
32
- s.source_files = ['*.swift', "#{sdk}/*.swift"]
33
- s.resource_bundles = { 'FountisConnect' => ["#{sdk}/Engine", "#{sdk}/PrivacyInfo.xcprivacy"] }
48
+ if mode == :binary
49
+ s.source_files = '*.swift'
50
+ s.vendored_frameworks = 'FountisConnect.xcframework'
51
+ else
52
+ s.source_files = ['*.swift', "#{sdk}/*.swift"]
53
+ s.resource_bundles = { 'FountisConnect' => ["#{sdk}/Engine", "#{sdk}/PrivacyInfo.xcprivacy"] }
54
+ end
34
55
  s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' }
35
56
  end
package/package.json CHANGED
@@ -1,27 +1,29 @@
1
1
  {
2
2
  "name": "@fountispanel/connect-react-native",
3
- "version": "1.0.0",
3
+ "version": "1.2.0",
4
4
  "description": "FOUNTIS Connect for React Native and Expo (development builds): native iOS and Android SDKs, Web SDK on React Native Web.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "main": "build/index.js",
7
7
  "types": "build/index.d.ts",
8
8
  "files": [
9
- "build",
10
- "src",
11
- "ios",
12
- "android",
9
+ "build/",
10
+ "ios/*.swift",
11
+ "ios/*.podspec",
12
+ "ios/FountisConnect.xcframework/",
13
+ "android/build.gradle",
14
+ "android/src/",
13
15
  "app.plugin.js",
14
16
  "expo-module.config.json",
15
- "scripts",
16
17
  "README.md",
17
18
  "CHANGELOG.md",
18
19
  "LICENSE"
19
20
  ],
20
21
  "scripts": {
21
- "build": "tsc -p tsconfig.json",
22
+ "build": "node build.mjs",
22
23
  "typecheck": "tsc --noEmit",
23
24
  "prepack": "npm run build && sh scripts/vendor-native.sh",
24
- "prepublishOnly": "npm run typecheck && npm run build && sh scripts/vendor-native.sh"
25
+ "postpack": "rm -rf ios/FountisConnect.xcframework",
26
+ "prepublishOnly": "npm run typecheck && npm run build && sh scripts/vendor-native.sh --require"
25
27
  },
26
28
  "keywords": [
27
29
  "fountis",
@@ -35,7 +37,7 @@
35
37
  "expo-modules-core": "*",
36
38
  "react": "*",
37
39
  "react-native": "*",
38
- "@fountispanel/connect": "^1.0.0"
40
+ "@fountispanel/connect": "^1.2.0"
39
41
  },
40
42
  "peerDependenciesMeta": {
41
43
  "@fountispanel/connect": {
@@ -50,14 +52,14 @@
50
52
  "react": "19.1.0",
51
53
  "react-native": "0.81.5",
52
54
  "typescript": "^5",
53
- "@fountispanel/connect": "file:../web"
55
+ "@fountispanel/connect": "file:../web",
56
+ "esbuild": "0.25.12"
54
57
  },
55
58
  "author": "FOUNTIS",
56
59
  "homepage": "https://github.com/darbaz/fountis-connect#readme",
57
60
  "repository": {
58
61
  "type": "git",
59
- "url": "git+https://github.com/darbaz/fountis-connect.git",
60
- "directory": "react-native"
62
+ "url": "git+https://github.com/darbaz/fountis-connect.git"
61
63
  },
62
64
  "bugs": {
63
65
  "url": "https://github.com/darbaz/fountis-connect/issues",
@@ -1,161 +0,0 @@
1
- package org.fountis.connect
2
-
3
- import java.io.ByteArrayOutputStream
4
- import java.io.IOException
5
- import java.io.InputStream
6
- import java.net.HttpURLConnection
7
- import java.net.URL
8
- import java.net.URLEncoder
9
- import kotlinx.coroutines.CoroutineScope
10
- import kotlinx.coroutines.Dispatchers
11
- import kotlinx.coroutines.SupervisorJob
12
- import org.json.JSONObject
13
-
14
- internal class ApiError(val status: Int, val code: String, override val message: String) : Exception(message) {
15
- /** Errors that end the attempt for good (the engine shows the matching screen). */
16
- val isFatal: Boolean get() = code in FATAL
17
-
18
- companion object {
19
- val FATAL = setOf("invalid_token", "not_eligible", "already_taken", "closed", "quota_full")
20
- }
21
- }
22
-
23
- /**
24
- * One request in flight, reachable from the thread that gave up waiting for it: [abandon] closes its connection so the
25
- * thread blocked on the socket is freed, and the read loop checks it so a body that is still trickling in stops too.
26
- */
27
- internal class Exchange {
28
- @Volatile private var conn: HttpURLConnection? = null
29
- @Volatile private var abandoned = false
30
-
31
- /** Remembers the connection. Throws if the caller has already given up, so the request never starts. */
32
- fun attach(c: HttpURLConnection) {
33
- conn = c
34
- checkNotAbandoned()
35
- }
36
-
37
- fun checkNotAbandoned() {
38
- if (abandoned) throw IOException("the request was abandoned")
39
- }
40
-
41
- /** Called on another thread once the caller stopped waiting. Best effort: the caller is already released. */
42
- fun abandon() {
43
- abandoned = true
44
- conn?.disconnect()
45
- }
46
- }
47
-
48
- /**
49
- * Thin client for the connect-api (HttpURLConnection, no cookies, no cache). Tokens are only ever sent in headers or bodies.
50
- *
51
- * Every request has an overall deadline ([deadlineMs], 15 s): connection, request and the whole response body. The
52
- * per-step limits on the connection alone cannot give that, because a server that sends a byte now and then keeps
53
- * every single read within its limit. When the deadline passes the call fails with a [RequestTimeoutException], an
54
- * [IOException] like the read timeout it replaces, so it ends as noFill the same way.
55
- */
56
- internal class ApiClient(base: String, val key: String, private val deadlineMs: Long = REQUEST_DEADLINE_MS) {
57
- private val base = base.trimEnd('/')
58
-
59
- /** Where the blocking requests run. A SupervisorJob keeps a failed request in its Deferred. It owns no thread of its own. */
60
- private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
61
-
62
- private fun Exchange.request(method: String, path: String, query: Map<String, String> = emptyMap(), body: JSONObject? = null, attemptToken: String? = null): String {
63
- var url = "$base/$path"
64
- if (query.isNotEmpty()) url += "?" + query.entries.joinToString("&") { URLEncoder.encode(it.key, "UTF-8") + "=" + URLEncoder.encode(it.value, "UTF-8") }
65
- val conn = URL(url).openConnection() as HttpURLConnection
66
- try {
67
- attach(conn)
68
- conn.requestMethod = method
69
- // Second line of defence only: the deadline ends a request first (these are per step, the deadline is the whole).
70
- conn.connectTimeout = 15_000
71
- conn.readTimeout = 20_000
72
- conn.useCaches = false
73
- conn.instanceFollowRedirects = false
74
- conn.setRequestProperty("X-Fountis-Key", key)
75
- conn.setRequestProperty("Accept", "application/json")
76
- if (attemptToken != null) conn.setRequestProperty("Authorization", "Attempt $attemptToken")
77
- if (body != null) {
78
- conn.doOutput = true
79
- conn.setRequestProperty("Content-Type", "application/json")
80
- conn.outputStream.use { it.write(body.toString().toByteArray(Charsets.UTF_8)) }
81
- }
82
- val status = conn.responseCode
83
- val stream = if (status in 200..299) conn.inputStream else conn.errorStream
84
- val text = readBody(stream)
85
- if (status in 200..299) return text
86
- var code = "http_$status"
87
- var message = ""
88
- try {
89
- val o = JSONObject(text)
90
- code = o.optString("error", code)
91
- message = o.optString("message", "")
92
- } catch (_: Exception) {
93
- }
94
- throw ApiError(status, code, message)
95
- } finally {
96
- conn.disconnect()
97
- }
98
- }
99
-
100
- /** Reads the body in pieces, so an abandoned request stops at the next piece instead of waiting for the whole body. */
101
- private fun Exchange.readBody(stream: InputStream?): String {
102
- if (stream == null) return ""
103
- return stream.use { s ->
104
- val out = ByteArrayOutputStream()
105
- val buf = ByteArray(8192)
106
- var n = s.read(buf)
107
- while (n >= 0) {
108
- checkNotAbandoned()
109
- out.write(buf, 0, n)
110
- n = s.read(buf)
111
- }
112
- out.toString("UTF-8")
113
- }
114
- }
115
-
116
- private suspend fun io(work: Exchange.() -> String): String {
117
- val exchange = Exchange()
118
- return callWithinDeadline(scope, deadlineMs, abandon = exchange::abandon) { exchange.work() }
119
- }
120
-
121
- private fun obj(text: String): JSONObject =
122
- try {
123
- JSONObject(text)
124
- } catch (e: Exception) {
125
- throw ApiError(0, "bad_response", "unexpected response")
126
- }
127
-
128
- suspend fun surveys(lang: String): SurveysResponse =
129
- parseSurveys(io { request("GET", "surveys", query = mapOf("lang" to lang)) })
130
-
131
- suspend fun createAttempt(offerId: String, token: String, lang: String): JSONObject =
132
- obj(io { request("POST", "attempts", body = JSONObject().put("offer_id", offerId).put("token", token).put("lang", lang)) })
133
-
134
- /** Guests: the install id in, a short-lived guest session token out. 403 `guests_not_allowed` when the app has guests off. */
135
- suspend fun guestSession(installId: String): String {
136
- val o = obj(io { request("POST", "guest/session", body = JSONObject().put("install_id", installId)) })
137
- return o.optString("guest_session", "").ifEmpty { throw ApiError(0, "bad_response", "no session") }
138
- }
139
-
140
- suspend fun createGuestAttempt(offerId: String, guestSession: String, lang: String): JSONObject =
141
- obj(io { request("POST", "attempts", body = JSONObject().put("offer_id", offerId).put("guest_session", guestSession).put("lang", lang)) })
142
-
143
- suspend fun putAnswer(code: String, value: Any?, attemptToken: String): JSONObject =
144
- obj(io { request("PUT", "attempt/answers", body = JSONObject().put("code", code).put("value", value ?: JSONObject.NULL), attemptToken = attemptToken) })
145
-
146
- suspend fun consent(attemptToken: String) {
147
- io { request("POST", "attempt/consent", body = JSONObject(), attemptToken = attemptToken) }
148
- }
149
-
150
- suspend fun complete(attemptToken: String): JSONObject =
151
- obj(io { request("POST", "attempt/complete", body = JSONObject(), attemptToken = attemptToken) })
152
-
153
- suspend fun event(offerId: String, type: String) {
154
- try {
155
- io { request("POST", "events", body = JSONObject().put("offer_id", offerId).put("type", type)) }
156
- } catch (_: IOException) {
157
- } catch (_: ApiError) {
158
- } catch (_: RuntimeException) {
159
- }
160
- }
161
- }