diff --git a/.swift-format b/.swift-format new file mode 100644 index 0000000..55aaa54 --- /dev/null +++ b/.swift-format @@ -0,0 +1,79 @@ +{ + "version": 1, + "indentation": { + "spaces": 4 + }, + "tabWidth": 4, + "lineLength": 200, + "maximumBlankLines": 1, + "respectsExistingLineBreaks": true, + "lineBreakBeforeEachArgument": false, + "lineBreakBeforeControlFlowKeywords": false, + "lineBreakAroundMultilineExpressionChainComponents": false, + "lineBreakBeforeEachGenericRequirement": false, + "lineBreakBetweenDeclarationAttributes": false, + "indentBlankLines": false, + "indentConditionalCompilationBlocks": true, + "indentSwitchCaseLabels": false, + "multiElementCollectionTrailingCommas": true, + "spacesAroundRangeFormationOperators": false, + "spacesBeforeEndOfLineComments": 2, + "prioritizeKeepingFunctionOutputTogether": false, + "reflowMultilineStringLiterals": "never", + "fileScopedDeclarationPrivacy": { + "accessLevel": "private" + }, + "orderedImports": { + "includeConditionalImports": false + }, + "noAssignmentInExpressions": { + "allowedFunctions": [ + "XCTAssertNoThrow" + ] + }, + "rules": { + "AllPublicDeclarationsHaveDocumentation": false, + "AlwaysUseLiteralForEmptyCollectionInit": false, + "AlwaysUseLowerCamelCase": false, + "AmbiguousTrailingClosureOverload": false, + "AvoidRetroactiveConformances": false, + "BeginDocumentationCommentWithOneLineSummary": false, + "DoNotUseSemicolons": true, + "DontRepeatTypeInStaticProperties": false, + "FileScopedDeclarationPrivacy": false, + "FullyIndirectEnum": false, + "GroupNumericLiterals": false, + "IdentifiersMustBeASCII": false, + "NeverForceUnwrap": false, + "NeverUseForceTry": false, + "NeverUseImplicitlyUnwrappedOptionals": false, + "NoAccessLevelOnExtensionDeclaration": false, + "NoAssignmentInExpressions": false, + "NoBlockComments": false, + "NoCasesWithOnlyFallthrough": false, + "NoEmptyLinesOpeningClosingBraces": false, + "NoEmptyTrailingClosureParentheses": true, + "NoLabelsInCasePatterns": false, + "NoLeadingUnderscores": false, + "NoParensAroundConditions": true, + "NoPlaygroundLiterals": false, + "NoVoidReturnOnFunctionSignature": true, + "OmitExplicitReturns": false, + "OneCasePerLine": true, + "OneVariableDeclarationPerLine": true, + "OnlyOneTrailingClosureArgument": false, + "OrderedImports": true, + "ReplaceForEachWithForLoop": false, + "ReturnVoidInsteadOfEmptyTuple": true, + "TypeNamesShouldBeCapitalized": false, + "UseEarlyExits": false, + "UseExplicitNilCheckInConditions": false, + "UseLetInEveryBoundCaseVariable": false, + "UseShorthandTypeNames": true, + "UseSingleLinePropertyGetter": true, + "UseSynthesizedInitializer": false, + "UseTripleSlashForDocumentationComments": true, + "UseWhereClausesInForLoops": false, + "ValidateDocumentationComments": false + } +} diff --git a/CHANGELOG.md b/CHANGELOG.md index 6977cbd..d818f3c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,25 @@ # Change Log +## 19.0.0 + +* Breaking: `Execution.functionId` replaced by `resourceId` and `resourceType` (`ExecutionResourceType`) +* Breaking: `createOperations` `operations` parameter now typed `[AnyCodable]` instead of `[Any]` +* Breaking: SDK now targets Appwrite 2.0 (`x-appwrite-response-format: 2.0.0`) +* Added: `DocumentsDB` and `VectorsDB` services for document and vector database access +* Added: `Organization` service with `listInstallations`, `createInstallation`, `getInstallation`, `updateInstallation`, `deleteInstallation` +* Added: `Teams` installation methods `listInstallations`, `createInstallation`, `getInstallation`, `updateInstallation`, `deleteInstallation` +* Added: `Account` consent methods `listConsents`, `getConsent`, `deleteConsent`, `listConsentTokens`, `getConsentToken`, `deleteConsentToken` +* Added: `Avatars.getPhoto` returning the best available user profile photo +* Added: `folder` parameter to `Storage.createFile` and `folder`, `key` fields on `File` +* Added: `AppInstallation`, `Oauth2Consent`, `Oauth2ConsentToken` models and list variants +* Added: `ExecutionResourceType` enum, `AuthenticationFactor.custom` and `MfaFactors.custom` +* Added: `cloudflare`, `huggingface`, `resend` cases to `OAuthProvider` +* Added: `auto` case to `ImageGravity` enum +* Updated: binary endpoints send `X-Appwrite-Project` header instead of `project` query parameter +* Updated: `async-http-client` to 1.36.1 and `swift-nio` to 2.102.0 +* Fixed: README install snippet now uses product name `Appwrite` +* Fixed: object array parameters such as `createOperations` are sent as JSON arrays, not strings + ## 18.3.0 * Added: `Client.setBearer` method for OAuth bearer token authentication diff --git a/Package.swift b/Package.swift index e16cf18..89c6b32 100644 --- a/Package.swift +++ b/Package.swift @@ -17,13 +17,13 @@ let package = Package( "Appwrite", "AppwriteEnums", "AppwriteModels", - "JSONCodable" + "JSONCodable", ] - ), + ) ], dependencies: [ - .package(url: "https://github.com/swift-server/async-http-client.git", from: "1.35.0"), - .package(url: "https://github.com/apple/swift-nio.git", from: "2.101.2"), + .package(url: "https://github.com/swift-server/async-http-client.git", from: "1.36.1"), + .package(url: "https://github.com/apple/swift-nio.git", from: "2.102.0"), ], targets: [ .target( @@ -33,14 +33,14 @@ let package = Package( .product(name: "NIOWebSocket", package: "swift-nio"), "AppwriteModels", "AppwriteEnums", - "JSONCodable" + "JSONCodable", ] ), .target( name: "AppwriteModels", dependencies: [ "AppwriteEnums", - "JSONCodable" + "JSONCodable", ] ), .target( @@ -54,7 +54,7 @@ let package = Package( dependencies: [ "Appwrite" ] - ) + ), ], swiftLanguageVersions: [.v5] ) diff --git a/README.md b/README.md index 3cf6930..6f0c37a 100644 --- a/README.md +++ b/README.md @@ -2,12 +2,12 @@ ![Swift Package Manager](https://img.shields.io/github/v/release/appwrite/sdk-for-apple.svg?color=green&style=flat-square) ![License](https://img.shields.io/github/license/appwrite/sdk-for-apple.svg?style=flat-square) -![Version](https://img.shields.io/badge/api%20version-1.9.5-blue.svg?style=flat-square) +![Version](https://img.shields.io/badge/api%20version-2.0.0-blue.svg?style=flat-square) [![Build Status](https://img.shields.io/travis/com/appwrite/sdk-generator?style=flat-square)](https://travis-ci.com/appwrite/sdk-generator) [![Twitter Account](https://img.shields.io/twitter/follow/appwrite?color=00acee&label=twitter&style=flat-square)](https://twitter.com/appwrite) [![Discord](https://img.shields.io/discord/564160730845151244?label=discord&style=flat-square)](https://appwrite.io/discord) -**This SDK is compatible with Appwrite server version 1.9.x. For older versions, please check [previous releases](https://github.com/appwrite/sdk-for-apple/releases).** +**This SDK targets Appwrite server version 2.0.x as shipped on Appwrite Cloud.** Self-hosted releases can lag behind Cloud — if you run an older self-hosted build, use a matching older SDK from [previous releases](https://github.com/appwrite/sdk-for-apple/releases) when APIs differ. Appwrite is an open-source backend as a service server that abstracts and simplifies complex and repetitive development tasks behind a very simple to use REST API. Appwrite aims to help you develop your apps faster and in a more secure way. Use the Apple SDK to integrate your app with the Appwrite server to easily start interacting with all of Appwrite backend APIs and tools. For full API documentation and tutorials go to [https://appwrite.io/docs](https://appwrite.io/docs) @@ -31,7 +31,7 @@ Add the package to your `Package.swift` dependencies: ```swift dependencies: [ - .package(url: "git@github.com:appwrite/sdk-for-apple.git", from: "18.3.0"), + .package(url: "git@github.com:appwrite/sdk-for-apple.git", from: "19.0.0"), ], ``` @@ -42,7 +42,7 @@ Then add it to your target: .target( name: "YourAppTarget", dependencies: [ - .product(name: "", package: "sdk-for-apple") + .product(name: "Appwrite", package: "sdk-for-apple") ] ), ``` diff --git a/Sources/Appwrite/Channel.swift b/Sources/Appwrite/Channel.swift index 1672409..475317b 100644 --- a/Sources/Appwrite/Channel.swift +++ b/Sources/Appwrite/Channel.swift @@ -33,11 +33,11 @@ private func normalize(_ id: String) throws -> String { /// Channel class with generic type parameter for type-safe method chaining public class RealtimeChannel { private let segments: [String] - + internal init(_ segments: [String]) { self.segments = segments } - + /// Internal helper to transition to next state with segment and optional ID internal func next(_ segment: String, _ id: String? = nil) throws -> RealtimeChannel { if let id = id { @@ -46,12 +46,12 @@ public class RealtimeChannel { return RealtimeChannel(segments + [segment]) } - + /// Internal helper for terminal actions (no ID segment) internal func resolve(_ action: String) -> RealtimeChannel<_Resolved> { return RealtimeChannel<_Resolved>(segments + [action]) } - + /// Convert channel to string representation public func toString() -> String { return segments.joined(separator: ".") @@ -60,33 +60,33 @@ public class RealtimeChannel { /// Non-generic Channel enum for static factory methods public enum Channel { - + // MARK: - Root Factories - + public static func database(_ id: String) throws -> RealtimeChannel<_Database> { return RealtimeChannel<_Database>(["databases", try normalize(id)]) } - + public static func tablesdb(_ id: String) throws -> RealtimeChannel<_TablesDB> { return RealtimeChannel<_TablesDB>(["tablesdb", try normalize(id)]) } - + public static func bucket(_ id: String) throws -> RealtimeChannel<_Bucket> { return RealtimeChannel<_Bucket>(["buckets", try normalize(id)]) } - + public static func function(_ id: String) throws -> RealtimeChannel<_Func> { return RealtimeChannel<_Func>(["functions", try normalize(id)]) } - + public static func execution(_ id: String) throws -> RealtimeChannel<_Execution> { return RealtimeChannel<_Execution>(["executions", try normalize(id)]) } - + public static func team(_ id: String) throws -> RealtimeChannel<_Team> { return RealtimeChannel<_Team>(["teams", try normalize(id)]) } - + public static func membership(_ id: String) throws -> RealtimeChannel<_Membership> { return RealtimeChannel<_Membership>(["memberships", try normalize(id)]) } @@ -159,15 +159,15 @@ extension RealtimeChannel where T == _Document { public func create() -> RealtimeChannel<_Resolved> { return self.resolve("create") } - + public func upsert() -> RealtimeChannel<_Resolved> { return self.resolve("upsert") } - + public func update() -> RealtimeChannel<_Resolved> { return self.resolve("update") } - + public func delete() -> RealtimeChannel<_Resolved> { return self.resolve("delete") } @@ -178,15 +178,15 @@ extension RealtimeChannel where T == _Row { public func create() -> RealtimeChannel<_Resolved> { return self.resolve("create") } - + public func upsert() -> RealtimeChannel<_Resolved> { return self.resolve("upsert") } - + public func update() -> RealtimeChannel<_Resolved> { return self.resolve("update") } - + public func delete() -> RealtimeChannel<_Resolved> { return self.resolve("delete") } @@ -197,11 +197,11 @@ extension RealtimeChannel where T == _File { public func create() -> RealtimeChannel<_Resolved> { return self.resolve("create") } - + public func update() -> RealtimeChannel<_Resolved> { return self.resolve("update") } - + public func delete() -> RealtimeChannel<_Resolved> { return self.resolve("delete") } @@ -212,11 +212,11 @@ extension RealtimeChannel where T == _Team { public func create() -> RealtimeChannel<_Resolved> { return self.resolve("create") } - + public func update() -> RealtimeChannel<_Resolved> { return self.resolve("update") } - + public func delete() -> RealtimeChannel<_Resolved> { return self.resolve("delete") } diff --git a/Sources/Appwrite/Client.swift b/Sources/Appwrite/Client.swift index bec8dbd..a335c35 100644 --- a/Sources/Appwrite/Client.swift +++ b/Sources/Appwrite/Client.swift @@ -1,13 +1,14 @@ +@_exported import AppwriteModels +import AsyncHTTPClient +import Foundation +@_exported import JSONCodable import NIO import NIOCore -#if canImport(NIOFoundationCompat) -import NIOFoundationCompat -#endif import NIOSSL -import Foundation -import AsyncHTTPClient -@_exported import AppwriteModels -@_exported import JSONCodable + +#if canImport(NIOFoundationCompat) + import NIOFoundationCompat +#endif let DASHDASH = "--" let CRLF = "\r\n" @@ -15,7 +16,7 @@ let CRLF = "\r\n" open class Client { // MARK: Properties - public static var chunkSize = 5 * 1024 * 1024 // 5MB + public static var chunkSize = 5 * 1024 * 1024 // 5MB public static var maxConcurrentUploads = 8 open var endPoint = "https://cloud.appwrite.io/v1" @@ -27,8 +28,8 @@ open class Client { "x-sdk-name": "Apple", "x-sdk-platform": "client", "x-sdk-language": "apple", - "x-sdk-version": "18.3.0", - "x-appwrite-response-format": "1.9.5" + "x-sdk-version": "19.0.0", + "x-appwrite-response-format": "2.0.0", ] internal var config: [String: String] = [:] @@ -71,7 +72,8 @@ open class Client { max: 5, allowCycles: false ) - var tls = TLSConfiguration + var tls = + TLSConfiguration .makeClientConfiguration() if selfSigned { @@ -244,7 +246,6 @@ open class Client { return self } - /// /// Set self signed /// @@ -302,7 +303,8 @@ open class Client { } self.endPoint = endPoint - self.endPointRealtime = endPoint + self.endPointRealtime = + endPoint .replacingOccurrences(of: "http://", with: "ws://") .replacingOccurrences(of: "https://", with: "wss://") @@ -346,47 +348,53 @@ open class Client { return self.headers } - /// - /// Builds a query string from parameters - /// - /// @param Dictionary params - /// @param String prefix - /// - /// @return String - /// - open func parametersToQueryString(params: [String: Any?]) -> String { - var output: String = "" + /// + /// Builds a query string from parameters + /// + /// @param Dictionary params + /// @param String prefix + /// + /// @return String + /// + open func parametersToQueryString(params: [String: Any?]) -> String { + var output: String = "" - func appendWhenNotLast(_ index: Int, ofTotal count: Int, outerIndex: Int? = nil, outerCount: Int? = nil) { - if (index != count - 1 || (outerIndex != nil - && outerCount != nil - && index == count - 1 - && outerIndex! != outerCount! - 1)) { - output += "&" - } - } + func appendWhenNotLast( + _ index: Int, ofTotal count: Int, outerIndex: Int? = nil, outerCount: Int? = nil + ) { + if index != count - 1 + || (outerIndex != nil + && outerCount != nil + && index == count - 1 + && outerIndex! != outerCount! - 1) + { + output += "&" + } + } - for (parameterIndex, element) in params.enumerated() { - switch element.value { - case nil: - break - case is Array: - let list = element.value as! Array - for (nestedIndex, item) in list.enumerated() { - output += "\(element.key)[]=\(item!)" - appendWhenNotLast(nestedIndex, ofTotal: list.count, outerIndex: parameterIndex, outerCount: params.count) - } - appendWhenNotLast(parameterIndex, ofTotal: params.count) - default: - output += "\(element.key)=\(element.value!)" - appendWhenNotLast(parameterIndex, ofTotal: params.count) - } - } + for (parameterIndex, element) in params.enumerated() { + switch element.value { + case nil: + break + case is [Any?]: + let list = element.value as! [Any?] + for (nestedIndex, item) in list.enumerated() { + output += "\(element.key)[]=\(item!)" + appendWhenNotLast( + nestedIndex, ofTotal: list.count, outerIndex: parameterIndex, + outerCount: params.count) + } + appendWhenNotLast(parameterIndex, ofTotal: params.count) + default: + output += "\(element.key)=\(element.value!)" + appendWhenNotLast(parameterIndex, ofTotal: params.count) + } + } - return output.addingPercentEncoding( - withAllowedCharacters: .urlHostAllowed - )?.replacingOccurrences(of: "+", with: "%2B") ?? "" // since urlHostAllowed doesn't include + - } + return output.addingPercentEncoding( + withAllowedCharacters: .urlHostAllowed + )?.replacingOccurrences(of: "+", with: "%2B") ?? "" // since urlHostAllowed doesn't include + + } /// /// Send a ping to project as part of onboarding. @@ -394,19 +402,19 @@ open class Client { /// @return String /// @throws Exception /// - open func ping() async throws -> String { - let apiPath: String = "/ping" + open func ping() async throws -> String { + let apiPath: String = "/ping" - let apiHeaders: [String: String] = [ - "X-Appwrite-Project": config["project"] ?? "", - "accept": "application/json", - ] + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": config["project"] ?? "", + "accept": "application/json", + ] - return try await call( - method: "GET", - path: apiPath, - headers: apiHeaders - ) + return try await call( + method: "GET", + path: apiPath, + headers: apiHeaders + ) } /// @@ -429,7 +437,8 @@ open class Client { ) async throws -> T { let validParams = params.filter { $0.value != nil } - let queryParameters = method == "GET" && !validParams.isEmpty + let queryParameters = + method == "GET" && !validParams.isEmpty ? (path.contains("?") ? "&" : "?") + parametersToQueryString(params: validParams) : "" @@ -519,7 +528,7 @@ open class Client { type = dict?["type"] as? String ?? "" responseString = String(decoding: data.readableBytesView, as: UTF8.self) } catch { - message = data.readString(length: data.readableBytes)! + message = data.readString(length: data.readableBytes)! responseString = message } @@ -543,7 +552,7 @@ open class Client { ) async throws -> T { let input = params[paramName] as! InputFile - switch(input.sourceType) { + switch input.sourceType { case "path": input.data = ByteBuffer(bytes: try! Data(contentsOf: URL(fileURLWithPath: input.path))) case "data": @@ -566,15 +575,15 @@ open class Client { } var offset = 0 - var result = [String:Any]() + var result = [String: Any]() var uploadId = idParamName != nil ? params[idParamName!] as? String : nil - if idParamName != nil { + if let uploadId { // Make a request to check if a file already exists do { let map = try await call( method: "GET", - path: path + "/" + (params[idParamName!] as! String), + path: path + "/" + uploadId, headers: headers, params: [:], converter: { return $0 as! [String: Any] } @@ -637,13 +646,14 @@ open class Client { nextChunk = 1 completedChunks = 1 uploadedBytes = first.1 - onProgress?(UploadProgress( - id: uploadId ?? "", - progress: Double(uploadedBytes)/Double(size) * 100.0, - sizeUploaded: uploadedBytes, - chunksTotal: result["chunksTotal"] as? Int ?? totalChunks, - chunksUploaded: result["chunksUploaded"] as? Int ?? completedChunks - )) + onProgress?( + UploadProgress( + id: uploadId ?? "", + progress: Double(uploadedBytes) / Double(size) * 100.0, + sizeUploaded: uploadedBytes, + chunksTotal: result["chunksTotal"] as? Int ?? totalChunks, + chunksUploaded: result["chunksUploaded"] as? Int ?? completedChunks + )) } let maxConcurrency = Client.maxConcurrentUploads @@ -668,13 +678,14 @@ open class Client { completedResponse = chunk.2 } - onProgress?(UploadProgress( - id: uploadId ?? "", - progress: Double(min(uploadedBytes, size))/Double(size) * 100.0, - sizeUploaded: min(uploadedBytes, size), - chunksTotal: chunk.2["chunksTotal"] as? Int ?? totalChunks, - chunksUploaded: chunk.2["chunksUploaded"] as? Int ?? completedChunks - )) + onProgress?( + UploadProgress( + id: uploadId ?? "", + progress: Double(min(uploadedBytes, size)) / Double(size) * 100.0, + sizeUploaded: min(uploadedBytes, size), + chunksTotal: chunk.2["chunksTotal"] as? Int ?? totalChunks, + chunksUploaded: chunk.2["chunksUploaded"] as? Int ?? completedChunks + )) while inFlight < maxConcurrency && nextChunk < totalChunks { let index = nextChunk @@ -703,7 +714,7 @@ open class Client { _ request: inout HTTPClientRequest, with params: [String: Any?] = [:] ) throws { - var encodedParams = [String:Any]() + var encodedParams = [String: Any]() for (key, param) in params { if param is String @@ -720,10 +731,11 @@ open class Client { || param is [Int: Any] || param is [Float: Any] || param is [Double: Any] - || param is [Bool: Any] { + || param is [Bool: Any] + { encodedParams[key] = param } else if let encodable = param as? Encodable { - encodedParams[key] = try encodable.toJson() + encodedParams[key] = try encodable.toJsonObject() } else if let param = param { encodedParams[key] = String(describing: param) } @@ -749,7 +761,7 @@ open class Client { bodyBuffer.writeString("; filename=\"\(file.filename)\"") bodyBuffer.writeString(CRLF) bodyBuffer.writeString("Content-Length: \(bodyBuffer.readableBytes)") - bodyBuffer.writeString(CRLF+CRLF) + bodyBuffer.writeString(CRLF + CRLF) var buffer = file.data! as! ByteBuffer @@ -761,7 +773,7 @@ open class Client { let string = String(describing: value) bodyBuffer.writeString(CRLF) bodyBuffer.writeString("Content-Length: \(string.count)") - bodyBuffer.writeString(CRLF+CRLF) + bodyBuffer.writeString(CRLF + CRLF) bodyBuffer.writeString(string) bodyBuffer.writeString(CRLF) } @@ -801,10 +813,10 @@ open class Client { let device = Client.getDevice() #if !os(Linux) && !os(Windows) - _ = addHeader( - key: "user-agent", - value: "\(packageInfo.packageName)/\(packageInfo.version) \(device)" - ) + _ = addHeader( + key: "user-agent", + value: "\(packageInfo.packageName)/\(packageInfo.version) \(device)" + ) #endif } @@ -821,19 +833,19 @@ open class Client { extension Client { private static func getOperatingSystem() -> String { #if os(iOS) - return "ios" + return "ios" #elseif os(watchOS) - return "watchos" + return "watchos" #elseif os(tvOS) - return "tvos" + return "tvos" #elseif os(macOS) - return "macos" + return "macos" #elseif os(visionOS) - return "visionos" + return "visionos" #elseif os(Linux) - return "linux" + return "linux" #elseif os(Windows) - return "windows" + return "windows" #endif } @@ -842,23 +854,23 @@ extension Client { var device = "" #if os(iOS) - let info = deviceInfo.iOSInfo - device = "\(info!.modelIdentifier) iOS/\(info!.systemVersion)" + let info = deviceInfo.iOSInfo + device = "\(info!.modelIdentifier) iOS/\(info!.systemVersion)" #elseif os(watchOS) - let info = deviceInfo.watchOSInfo - device = "\(info!.modelIdentifier) watchOS/\(info!.systemVersion)" + let info = deviceInfo.watchOSInfo + device = "\(info!.modelIdentifier) watchOS/\(info!.systemVersion)" #elseif os(tvOS) - let info = deviceInfo.iOSInfo - device = "\(info!.modelIdentifier) tvOS/\(info!.systemVersion)" + let info = deviceInfo.iOSInfo + device = "\(info!.modelIdentifier) tvOS/\(info!.systemVersion)" #elseif os(macOS) - let info = deviceInfo.macOSInfo - device = "(Macintosh; \(info!.model))" + let info = deviceInfo.macOSInfo + device = "(Macintosh; \(info!.model))" #elseif os(Linux) - let info = deviceInfo.linuxInfo - device = "(Linux; U; \(info!.id) \(info!.version))" + let info = deviceInfo.linuxInfo + device = "(Linux; U; \(info!.id) \(info!.version))" #elseif os(Windows) - let info = deviceInfo.windowsInfo - device = "(Windows NT; \(info!.computerName))" + let info = deviceInfo.windowsInfo + device = "(Windows NT; \(info!.computerName))" #endif return device diff --git a/Sources/Appwrite/DeviceInfo/Linux/LinuxDeviceInfo.swift b/Sources/Appwrite/DeviceInfo/Linux/LinuxDeviceInfo.swift index bc03292..5990520 100644 --- a/Sources/Appwrite/DeviceInfo/Linux/LinuxDeviceInfo.swift +++ b/Sources/Appwrite/DeviceInfo/Linux/LinuxDeviceInfo.swift @@ -1,71 +1,71 @@ #if os(Linux) -import Foundation + import Foundation -class LinuxDeviceInfo { + class LinuxDeviceInfo { - let name: String - let version: String - let id: String - let idLike: [String] - let versionCodename: String - let versionId: String - let prettyName: String - let buildId: String - let variant: String - let variantId: String - let machineId: String + let name: String + let version: String + let id: String + let idLike: [String] + let versionCodename: String + let versionId: String + let prettyName: String + let buildId: String + let variant: String + let variantId: String + let machineId: String - public init() { - let os = LinuxDeviceInfo.getOsRelease() - let lsb = LinuxDeviceInfo.getLsbRelease() + public init() { + let os = LinuxDeviceInfo.getOsRelease() + let lsb = LinuxDeviceInfo.getLsbRelease() - name = os["NAME"] ?? "Linux" - version = os["VERSION"] ?? lsb["LSB_VERSION"] ?? "" - id = os["ID"] ?? lsb["DISTRIB_ID"] ?? "linux" - idLike = os["ID_LIKE"]?.split(separator: " ").map { String($0) } ?? [] - versionCodename = os["VERSION_CODENAME"] ?? lsb["DISTRIB_CODENAME"] ?? "" - versionId = os["VERSION_ID"] ?? lsb["DISTRIB_RELEASE"] ?? "" - prettyName = os["PRETTY_NAME"] ?? lsb["DISTRIB_DESCRIPTION"] ?? "Linux" - buildId = os["BUILD_ID"] ?? "" - variant = os["VARIANT"] ?? "" - variantId = os["VARIANT_ID"] ?? "" - machineId = LinuxDeviceInfo.getMachineId() - } - - private static func getOsRelease() -> [String: String] { - return tryReadKeyValues(path: "/etc/os-release") - } - - private static func getLsbRelease() -> [String: String] { - return tryReadKeyValues(path: "/etc/lsb-release") - } - - private static func getMachineId() -> String { - return tryReadValue(path: "/etc/machine-id")! - } - - private static func tryReadValue(path: String) -> String? { - let url = URL(fileURLWithPath: path) - return try! String(contentsOf: url, encoding: .utf8) - } - - private static func tryReadKeyValues(path: String) -> [String: String] { - let url = URL(fileURLWithPath: path) - let string = try! String(contentsOf: url, encoding: .utf8) - let lines = string.components(separatedBy: .newlines) - - var dict = [String: String]() - for line in lines { - let splits = line.split(separator: "=") - if splits.count > 1 { - let key = String(splits[0]) - let value = String(splits[1]) - - dict[key] = value - } + name = os["NAME"] ?? "Linux" + version = os["VERSION"] ?? lsb["LSB_VERSION"] ?? "" + id = os["ID"] ?? lsb["DISTRIB_ID"] ?? "linux" + idLike = os["ID_LIKE"]?.split(separator: " ").map { String($0) } ?? [] + versionCodename = os["VERSION_CODENAME"] ?? lsb["DISTRIB_CODENAME"] ?? "" + versionId = os["VERSION_ID"] ?? lsb["DISTRIB_RELEASE"] ?? "" + prettyName = os["PRETTY_NAME"] ?? lsb["DISTRIB_DESCRIPTION"] ?? "Linux" + buildId = os["BUILD_ID"] ?? "" + variant = os["VARIANT"] ?? "" + variantId = os["VARIANT_ID"] ?? "" + machineId = LinuxDeviceInfo.getMachineId() } - return dict + private static func getOsRelease() -> [String: String] { + return tryReadKeyValues(path: "/etc/os-release") + } + + private static func getLsbRelease() -> [String: String] { + return tryReadKeyValues(path: "/etc/lsb-release") + } + + private static func getMachineId() -> String { + return tryReadValue(path: "/etc/machine-id")! + } + + private static func tryReadValue(path: String) -> String? { + let url = URL(fileURLWithPath: path) + return try! String(contentsOf: url, encoding: .utf8) + } + + private static func tryReadKeyValues(path: String) -> [String: String] { + let url = URL(fileURLWithPath: path) + let string = try! String(contentsOf: url, encoding: .utf8) + let lines = string.components(separatedBy: .newlines) + + var dict = [String: String]() + for line in lines { + let splits = line.split(separator: "=") + if splits.count > 1 { + let key = String(splits[0]) + let value = String(splits[1]) + + dict[key] = value + } + } + + return dict + } } -} #endif diff --git a/Sources/Appwrite/DeviceInfo/OSDeviceInfo.swift b/Sources/Appwrite/DeviceInfo/OSDeviceInfo.swift index 58c0660..6d7ba72 100644 --- a/Sources/Appwrite/DeviceInfo/OSDeviceInfo.swift +++ b/Sources/Appwrite/DeviceInfo/OSDeviceInfo.swift @@ -3,29 +3,28 @@ import Foundation class OSDeviceInfo { #if os(iOS) || os(tvOS) || os(visionOS) - var iOSInfo: IOSDeviceInfo? + var iOSInfo: IOSDeviceInfo? #elseif os(watchOS) - var watchOSInfo: WatchOSDeviceInfo? + var watchOSInfo: WatchOSDeviceInfo? #elseif os(macOS) - var macOSInfo: MacOSDeviceInfo? + var macOSInfo: MacOSDeviceInfo? #elseif os(Linux) - var linuxInfo: LinuxDeviceInfo? + var linuxInfo: LinuxDeviceInfo? #elseif os(Windows) - var windowsInfo: WindowsDeviceInfo? + var windowsInfo: WindowsDeviceInfo? #endif init() { #if os(iOS) || os(tvOS) || os(visionOS) - self.iOSInfo = IOSDeviceInfo() + self.iOSInfo = IOSDeviceInfo() #elseif os(watchOS) - self.watchOSInfo = WatchOSDeviceInfo() + self.watchOSInfo = WatchOSDeviceInfo() #elseif os(macOS) - self.macOSInfo = MacOSDeviceInfo() + self.macOSInfo = MacOSDeviceInfo() #elseif os(Linux) - self.linuxInfo = LinuxDeviceInfo() + self.linuxInfo = LinuxDeviceInfo() #elseif os(Windows) - self.windowsInfo = LinuxDeviceInfo() + self.windowsInfo = LinuxDeviceInfo() #endif } } - diff --git a/Sources/Appwrite/DeviceInfo/Windows/WindowsDeviceInfo.swift b/Sources/Appwrite/DeviceInfo/Windows/WindowsDeviceInfo.swift index 435def8..75b807e 100644 --- a/Sources/Appwrite/DeviceInfo/Windows/WindowsDeviceInfo.swift +++ b/Sources/Appwrite/DeviceInfo/Windows/WindowsDeviceInfo.swift @@ -1,16 +1,16 @@ #if os(Windows) -import Foundation + import Foundation -class WindowsDeviceInfo { + class WindowsDeviceInfo { - let numberOfCores: String - let computerName: String - let systemMemoryInMegabytes: UInt64 + let numberOfCores: String + let computerName: String + let systemMemoryInMegabytes: UInt64 - public init() { - numberOfCores = ProcessInfo.processInfo.processorCount.description - computerName = Host.current().localizedName ?? "" - systemMemoryInMegabytes = ProcessInfo.processInfo.physicalMemory / 1000 / 1000 // Bytes to MB + public init() { + numberOfCores = ProcessInfo.processInfo.processorCount.description + computerName = Host.current().localizedName ?? "" + systemMemoryInMegabytes = ProcessInfo.processInfo.physicalMemory / 1000 / 1000 // Bytes to MB + } } -} -#endif \ No newline at end of file +#endif diff --git a/Sources/Appwrite/DeviceInfo/iOS/IOSDeviceInfo.swift b/Sources/Appwrite/DeviceInfo/iOS/IOSDeviceInfo.swift index 219b958..1c7f6dd 100644 --- a/Sources/Appwrite/DeviceInfo/iOS/IOSDeviceInfo.swift +++ b/Sources/Appwrite/DeviceInfo/iOS/IOSDeviceInfo.swift @@ -1,27 +1,27 @@ #if os(iOS) || os(tvOS) || os(visionOS) -import Foundation -import UIKit + import Foundation + import UIKit -class IOSDeviceInfo { + class IOSDeviceInfo { - let name: String - let systemName: String - let systemVersion: String - let model: String - let localizedModel: String - let identifierForVendor: String - let modelIdentifier: String + let name: String + let systemName: String + let systemVersion: String + let model: String + let localizedModel: String + let identifierForVendor: String + let modelIdentifier: String - public init() { - let device = UIDevice.current + public init() { + let device = UIDevice.current - name = device.name - systemName = device.systemName - systemVersion = device.systemVersion - model = device.model - localizedModel = device.localizedModel - identifierForVendor = device.identifierForVendor?.uuidString ?? "" - modelIdentifier = UIDevice.modelName + name = device.name + systemName = device.systemName + systemVersion = device.systemVersion + model = device.model + localizedModel = device.localizedModel + identifierForVendor = device.identifierForVendor?.uuidString ?? "" + modelIdentifier = UIDevice.modelName + } } -} #endif diff --git a/Sources/Appwrite/DeviceInfo/iOS/UIDevice+ModelName.swift b/Sources/Appwrite/DeviceInfo/iOS/UIDevice+ModelName.swift index ee66cb7..6c50c2a 100644 --- a/Sources/Appwrite/DeviceInfo/iOS/UIDevice+ModelName.swift +++ b/Sources/Appwrite/DeviceInfo/iOS/UIDevice+ModelName.swift @@ -1,108 +1,118 @@ #if os(iOS) || os(tvOS) || os(visionOS) -import Foundation -import UIKit + import Foundation + import UIKit -public extension UIDevice { + public extension UIDevice { - static let modelName: String = { - var systemInfo = utsname() - uname(&systemInfo) - let machineMirror = Mirror(reflecting: systemInfo.machine) - let identifier = machineMirror.children.reduce("") { identifier, element in - guard let value = element.value as? Int8, value != 0 else { return identifier } - return identifier + String(UnicodeScalar(UInt8(value))) - } - - func mapToDevice(identifier: String) -> String { // swiftlint:disable:this cyclomatic_complexity - switch identifier { - #if os(iOS) - case "iPod5,1": return "iPod touch (5th generation)" - case "iPod7,1": return "iPod touch (6th generation)" - case "iPod9,1": return "iPod touch (7th generation)" - case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4" - case "iPhone4,1": return "iPhone 4s" - case "iPhone5,1", "iPhone5,2": return "iPhone 5" - case "iPhone5,3", "iPhone5,4": return "iPhone 5c" - case "iPhone6,1", "iPhone6,2": return "iPhone 5s" - case "iPhone7,2": return "iPhone 6" - case "iPhone7,1": return "iPhone 6 Plus" - case "iPhone8,1": return "iPhone 6s" - case "iPhone8,2": return "iPhone 6s Plus" - case "iPhone8,4": return "iPhone SE" - case "iPhone9,1", "iPhone9,3": return "iPhone 7" - case "iPhone9,2", "iPhone9,4": return "iPhone 7 Plus" - case "iPhone10,1", "iPhone10,4": return "iPhone 8" - case "iPhone10,2", "iPhone10,5": return "iPhone 8 Plus" - case "iPhone10,3", "iPhone10,6": return "iPhone X" - case "iPhone11,2": return "iPhone XS" - case "iPhone11,4", "iPhone11,6": return "iPhone XS Max" - case "iPhone11,8": return "iPhone XR" - case "iPhone12,1": return "iPhone 11" - case "iPhone12,3": return "iPhone 11 Pro" - case "iPhone12,5": return "iPhone 11 Pro Max" - case "iPhone12,8": return "iPhone SE (2nd generation)" - case "iPhone13,1": return "iPhone 12 mini" - case "iPhone13,2": return "iPhone 12" - case "iPhone13,3": return "iPhone 12 Pro" - case "iPhone13,4": return "iPhone 12 Pro Max" - case "iPhone14,4": return "iPhone 13 mini" - case "iPhone14,5": return "iPhone 13" - case "iPhone14,2": return "iPhone 13 Pro" - case "iPhone14,3": return "iPhone 13 Pro Max" - case "iPhone14,6": return "iPhone SE (3rd generation)" - case "iPhone14,7": return "iPhone 14" - case "iPhone14,8": return "iPhone 14 Plus" - case "iPhone15,2": return "iPhone 14 Pro" - case "iPhone15,3": return "iPhone 14 Pro Max" - case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4": return "iPad 2" - case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad (3rd generation)" - case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad (4th generation)" - case "iPad6,11", "iPad6,12": return "iPad (5th generation)" - case "iPad7,5", "iPad7,6": return "iPad (6th generation)" - case "iPad7,11", "iPad7,12": return "iPad (7th generation)" - case "iPad11,6", "iPad11,7": return "iPad (8th generation)" - case "iPad12,1", "iPad12,2": return "iPad (9th generation)" - case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air" - case "iPad5,3", "iPad5,4": return "iPad Air 2" - case "iPad11,3", "iPad11,4": return "iPad Air (3rd generation)" - case "iPad13,1", "iPad13,2": return "iPad Air (4th generation)" - case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad mini" - case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad mini 2" - case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad mini 3" - case "iPad5,1", "iPad5,2": return "iPad mini 4" - case "iPad11,1", "iPad11,2": return "iPad mini (5th generation)" - case "iPad14,1", "iPad14,2": return "iPad mini (6th generation)" - case "iPad6,3", "iPad6,4": return "iPad Pro (9.7-inch)" - case "iPad7,3", "iPad7,4": return "iPad Pro (10.5-inch)" - case "iPad8,1", "iPad8,2", "iPad8,3", "iPad8,4": return "iPad Pro (11-inch) (1st generation)" - case "iPad8,9", "iPad8,10": return "iPad Pro (11-inch) (2nd generation)" - case "iPad13,4", "iPad13,5", "iPad13,6", "iPad13,7": return "iPad Pro (11-inch) (3rd generation)" - case "iPad6,7", "iPad6,8": return "iPad Pro (12.9-inch) (1st generation)" - case "iPad7,1", "iPad7,2": return "iPad Pro (12.9-inch) (2nd generation)" - case "iPad8,5", "iPad8,6", "iPad8,7", "iPad8,8": return "iPad Pro (12.9-inch) (3rd generation)" - case "iPad8,11", "iPad8,12": return "iPad Pro (12.9-inch) (4th generation)" - case "iPad13,8", "iPad13,9", "iPad13,10", "iPad13,11":return "iPad Pro (12.9-inch) (5th generation)" - case "i386", "x86_64", "arm64": return "Simulator \(mapToDevice(identifier: ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] ?? "iOS"))" - default: return identifier - #elseif os(tvOS) - case "AppleTV1,1": return "Apple TV (1st generation)" - case "AppleTV2,1": return "Apple TV (2nd generation)" - case "AppleTV3,1", "AppleTV3,2": return "Apple TV (3rd generation)" - case "AppleTV5,3": return "Apple TV (4th generation)" - case "AppleTV6,2": return "Apple TV 4K (1st generation)" - case "AppleTV11,1": return "Apple TV 4K (2nd generation)" - case "i386", "x86_64", "arm64": return "Simulator \(mapToDevice(identifier: ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] ?? "tvOS"))" - default: return identifier - #elseif os(visionOS) - case "RealityDevice14,1": return "Apple Vision Pro" - case "i386", "x86_64", "arm64": return "Simulator \(mapToDevice(identifier: ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] ?? "visionOS"))" - default: return identifier - #endif + static let modelName: String = { + var systemInfo = utsname() + uname(&systemInfo) + let machineMirror = Mirror(reflecting: systemInfo.machine) + let identifier = machineMirror.children.reduce("") { identifier, element in + guard let value = element.value as? Int8, value != 0 else { return identifier } + return identifier + String(UnicodeScalar(UInt8(value))) } - } - return mapToDevice(identifier: identifier) - }() + func mapToDevice(identifier: String) -> String { // swiftlint:disable:this cyclomatic_complexity + switch identifier { + #if os(iOS) + case "iPod5,1": return "iPod touch (5th generation)" + case "iPod7,1": return "iPod touch (6th generation)" + case "iPod9,1": return "iPod touch (7th generation)" + case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4" + case "iPhone4,1": return "iPhone 4s" + case "iPhone5,1", "iPhone5,2": return "iPhone 5" + case "iPhone5,3", "iPhone5,4": return "iPhone 5c" + case "iPhone6,1", "iPhone6,2": return "iPhone 5s" + case "iPhone7,2": return "iPhone 6" + case "iPhone7,1": return "iPhone 6 Plus" + case "iPhone8,1": return "iPhone 6s" + case "iPhone8,2": return "iPhone 6s Plus" + case "iPhone8,4": return "iPhone SE" + case "iPhone9,1", "iPhone9,3": return "iPhone 7" + case "iPhone9,2", "iPhone9,4": return "iPhone 7 Plus" + case "iPhone10,1", "iPhone10,4": return "iPhone 8" + case "iPhone10,2", "iPhone10,5": return "iPhone 8 Plus" + case "iPhone10,3", "iPhone10,6": return "iPhone X" + case "iPhone11,2": return "iPhone XS" + case "iPhone11,4", "iPhone11,6": return "iPhone XS Max" + case "iPhone11,8": return "iPhone XR" + case "iPhone12,1": return "iPhone 11" + case "iPhone12,3": return "iPhone 11 Pro" + case "iPhone12,5": return "iPhone 11 Pro Max" + case "iPhone12,8": return "iPhone SE (2nd generation)" + case "iPhone13,1": return "iPhone 12 mini" + case "iPhone13,2": return "iPhone 12" + case "iPhone13,3": return "iPhone 12 Pro" + case "iPhone13,4": return "iPhone 12 Pro Max" + case "iPhone14,4": return "iPhone 13 mini" + case "iPhone14,5": return "iPhone 13" + case "iPhone14,2": return "iPhone 13 Pro" + case "iPhone14,3": return "iPhone 13 Pro Max" + case "iPhone14,6": return "iPhone SE (3rd generation)" + case "iPhone14,7": return "iPhone 14" + case "iPhone14,8": return "iPhone 14 Plus" + case "iPhone15,2": return "iPhone 14 Pro" + case "iPhone15,3": return "iPhone 14 Pro Max" + case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4": return "iPad 2" + case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad (3rd generation)" + case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad (4th generation)" + case "iPad6,11", "iPad6,12": return "iPad (5th generation)" + case "iPad7,5", "iPad7,6": return "iPad (6th generation)" + case "iPad7,11", "iPad7,12": return "iPad (7th generation)" + case "iPad11,6", "iPad11,7": return "iPad (8th generation)" + case "iPad12,1", "iPad12,2": return "iPad (9th generation)" + case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air" + case "iPad5,3", "iPad5,4": return "iPad Air 2" + case "iPad11,3", "iPad11,4": return "iPad Air (3rd generation)" + case "iPad13,1", "iPad13,2": return "iPad Air (4th generation)" + case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad mini" + case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad mini 2" + case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad mini 3" + case "iPad5,1", "iPad5,2": return "iPad mini 4" + case "iPad11,1", "iPad11,2": return "iPad mini (5th generation)" + case "iPad14,1", "iPad14,2": return "iPad mini (6th generation)" + case "iPad6,3", "iPad6,4": return "iPad Pro (9.7-inch)" + case "iPad7,3", "iPad7,4": return "iPad Pro (10.5-inch)" + case "iPad8,1", "iPad8,2", "iPad8,3", "iPad8,4": + return "iPad Pro (11-inch) (1st generation)" + case "iPad8,9", "iPad8,10": return "iPad Pro (11-inch) (2nd generation)" + case "iPad13,4", "iPad13,5", "iPad13,6", "iPad13,7": + return "iPad Pro (11-inch) (3rd generation)" + case "iPad6,7", "iPad6,8": return "iPad Pro (12.9-inch) (1st generation)" + case "iPad7,1", "iPad7,2": return "iPad Pro (12.9-inch) (2nd generation)" + case "iPad8,5", "iPad8,6", "iPad8,7", "iPad8,8": + return "iPad Pro (12.9-inch) (3rd generation)" + case "iPad8,11", "iPad8,12": return "iPad Pro (12.9-inch) (4th generation)" + case "iPad13,8", "iPad13,9", "iPad13,10", "iPad13,11": + return "iPad Pro (12.9-inch) (5th generation)" + case "i386", "x86_64", "arm64": + return + "Simulator \(mapToDevice(identifier: ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] ?? "iOS"))" + default: return identifier + #elseif os(tvOS) + case "AppleTV1,1": return "Apple TV (1st generation)" + case "AppleTV2,1": return "Apple TV (2nd generation)" + case "AppleTV3,1", "AppleTV3,2": return "Apple TV (3rd generation)" + case "AppleTV5,3": return "Apple TV (4th generation)" + case "AppleTV6,2": return "Apple TV 4K (1st generation)" + case "AppleTV11,1": return "Apple TV 4K (2nd generation)" + case "i386", "x86_64", "arm64": + return + "Simulator \(mapToDevice(identifier: ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] ?? "tvOS"))" + default: return identifier + #elseif os(visionOS) + case "RealityDevice14,1": return "Apple Vision Pro" + case "i386", "x86_64", "arm64": + return + "Simulator \(mapToDevice(identifier: ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] ?? "visionOS"))" + default: return identifier + #endif + } + } -} + return mapToDevice(identifier: identifier) + }() + + } #endif diff --git a/Sources/Appwrite/DeviceInfo/macOS/CwlSysCtl.swift b/Sources/Appwrite/DeviceInfo/macOS/CwlSysCtl.swift index 55d1134..23c8d54 100644 --- a/Sources/Appwrite/DeviceInfo/macOS/CwlSysCtl.swift +++ b/Sources/Appwrite/DeviceInfo/macOS/CwlSysCtl.swift @@ -19,153 +19,181 @@ // #if os(macOS) -import Foundation + import Foundation -/// A "static"-only namespace around a series of functions that operate on buffers returned from the `Darwin.sysctl` function -public struct Sysctl { - /// Possible errors. - public enum Error: Swift.Error { - case unknown - case malformedUTF8 - case invalidSize - case posixError(POSIXErrorCode) - } - - /// Access the raw data for an array of sysctl identifiers. - public static func data(for keys: [Int32]) throws -> [Int8] { - return try keys.withUnsafeBufferPointer() { keysPointer throws -> [Int8] in - // Preflight the request to get the required data size - var requiredSize = 0 - let preFlightResult = Darwin.sysctl(UnsafeMutablePointer(mutating: keysPointer.baseAddress), UInt32(keys.count), nil, &requiredSize, nil, 0) - if preFlightResult != 0 { - throw POSIXErrorCode(rawValue: errno).map { - print($0.rawValue) - return Error.posixError($0) - } ?? Error.unknown - } - - // Run the actual request with an appropriately sized array buffer - let data = Array(repeating: 0, count: requiredSize) - let result = data.withUnsafeBufferPointer() { dataBuffer -> Int32 in - return Darwin.sysctl(UnsafeMutablePointer(mutating: keysPointer.baseAddress), UInt32(keys.count), UnsafeMutableRawPointer(mutating: dataBuffer.baseAddress), &requiredSize, nil, 0) - } - if result != 0 { - throw POSIXErrorCode(rawValue: errno).map { Error.posixError($0) } ?? Error.unknown - } - - return data + /// A "static"-only namespace around a series of functions that operate on buffers returned from the `Darwin.sysctl` function + public struct Sysctl { + /// Possible errors. + public enum Error: Swift.Error { + case unknown + case malformedUTF8 + case invalidSize + case posixError(POSIXErrorCode) } - } - /// Convert a sysctl name string like "hw.memsize" to the array of `sysctl` identifiers (e.g. [CTL_HW, HW_MEMSIZE]) - public static func keys(for name: String) throws -> [Int32] { - var keysBufferSize = Int(CTL_MAXNAME) - var keysBuffer = Array(repeating: 0, count: keysBufferSize) - try keysBuffer.withUnsafeMutableBufferPointer { (lbp: inout UnsafeMutableBufferPointer) throws in - try name.withCString { (nbp: UnsafePointer) throws in - guard sysctlnametomib(nbp, lbp.baseAddress, &keysBufferSize) == 0 else { - throw POSIXErrorCode(rawValue: errno).map { Error.posixError($0) } ?? Error.unknown + /// Access the raw data for an array of sysctl identifiers. + public static func data(for keys: [Int32]) throws -> [Int8] { + return try keys.withUnsafeBufferPointer { keysPointer throws -> [Int8] in + // Preflight the request to get the required data size + var requiredSize = 0 + let preFlightResult = Darwin.sysctl( + UnsafeMutablePointer(mutating: keysPointer.baseAddress), + UInt32(keys.count), nil, &requiredSize, nil, 0) + if preFlightResult != 0 { + throw POSIXErrorCode(rawValue: errno).map { + print($0.rawValue) + return Error.posixError($0) + } ?? Error.unknown + } + + // Run the actual request with an appropriately sized array buffer + let data = [Int8](repeating: 0, count: requiredSize) + let result = data.withUnsafeBufferPointer { dataBuffer -> Int32 in + return Darwin.sysctl( + UnsafeMutablePointer(mutating: keysPointer.baseAddress), + UInt32(keys.count), + UnsafeMutableRawPointer(mutating: dataBuffer.baseAddress), &requiredSize, + nil, 0) + } + if result != 0 { + throw POSIXErrorCode(rawValue: errno).map { Error.posixError($0) } + ?? Error.unknown + } + + return data + } + } + + /// Convert a sysctl name string like "hw.memsize" to the array of `sysctl` identifiers (e.g. [CTL_HW, HW_MEMSIZE]) + public static func keys(for name: String) throws -> [Int32] { + var keysBufferSize = Int(CTL_MAXNAME) + var keysBuffer = [Int32](repeating: 0, count: keysBufferSize) + try keysBuffer.withUnsafeMutableBufferPointer { + (lbp: inout UnsafeMutableBufferPointer) throws in + try name.withCString { (nbp: UnsafePointer) throws in + guard sysctlnametomib(nbp, lbp.baseAddress, &keysBufferSize) == 0 else { + throw POSIXErrorCode(rawValue: errno).map { Error.posixError($0) } + ?? Error.unknown + } } } + if keysBuffer.count > keysBufferSize { + keysBuffer.removeSubrange(keysBufferSize.. keysBufferSize { - keysBuffer.removeSubrange(keysBufferSize..(ofType: T.Type, forKeys keys: [Int32]) throws -> T { + let buffer = try data(for: keys) + if buffer.count != MemoryLayout.size { + throw Error.invalidSize + } + return try buffer.withUnsafeBufferPointer { bufferPtr throws -> T in + guard let baseAddress = bufferPtr.baseAddress else { throw Error.unknown } + return baseAddress.withMemoryRebound(to: T.self, capacity: 1) { $0.pointee } + } } - return keysBuffer - } - /// Invoke `sysctl` with an array of identifers, interpreting the returned buffer as the specified type. This function will throw `Error.invalidSize` if the size of buffer returned from `sysctl` fails to match the size of `T`. - public static func value(ofType: T.Type, forKeys keys: [Int32]) throws -> T { - let buffer = try data(for: keys) - if buffer.count != MemoryLayout.size { - throw Error.invalidSize + /// Invoke `sysctl` with an array of identifers, interpreting the returned buffer as the specified type. This function will throw `Error.invalidSize` if the size of buffer returned from `sysctl` fails to match the size of `T`. + public static func value(ofType type: T.Type, forKeys keys: Int32...) throws -> T { + return try value(ofType: type, forKeys: keys) } - return try buffer.withUnsafeBufferPointer() { bufferPtr throws -> T in - guard let baseAddress = bufferPtr.baseAddress else { throw Error.unknown } - return baseAddress.withMemoryRebound(to: T.self, capacity: 1) { $0.pointee } + + /// Invoke `sysctl` with the specified name, interpreting the returned buffer as the specified type. This function will throw `Error.invalidSize` if the size of buffer returned from `sysctl` fails to match the size of `T`. + public static func value(ofType type: T.Type, forName name: String) throws -> T { + return try value(ofType: type, forKeys: keys(for: name)) } - } - /// Invoke `sysctl` with an array of identifers, interpreting the returned buffer as the specified type. This function will throw `Error.invalidSize` if the size of buffer returned from `sysctl` fails to match the size of `T`. - public static func value(ofType type: T.Type, forKeys keys: Int32...) throws -> T { - return try value(ofType: type, forKeys: keys) - } - - /// Invoke `sysctl` with the specified name, interpreting the returned buffer as the specified type. This function will throw `Error.invalidSize` if the size of buffer returned from `sysctl` fails to match the size of `T`. - public static func value(ofType type: T.Type, forName name: String) throws -> T { - return try value(ofType: type, forKeys: keys(for: name)) - } - - /// Invoke `sysctl` with an array of identifers, interpreting the returned buffer as a `String`. This function will throw `Error.malformedUTF8` if the buffer returned from `sysctl` cannot be interpreted as a UTF8 buffer. - public static func string(for keys: [Int32]) throws -> String { - let optionalString = try data(for: keys).withUnsafeBufferPointer() { dataPointer -> String? in - dataPointer.baseAddress.flatMap { String(validatingUTF8: $0) } + /// Invoke `sysctl` with an array of identifers, interpreting the returned buffer as a `String`. This function will throw `Error.malformedUTF8` if the buffer returned from `sysctl` cannot be interpreted as a UTF8 buffer. + public static func string(for keys: [Int32]) throws -> String { + let optionalString = try data(for: keys).withUnsafeBufferPointer { + dataPointer -> String? in + dataPointer.baseAddress.flatMap { String(validatingUTF8: $0) } + } + guard let s = optionalString else { + throw Error.malformedUTF8 + } + return s } - guard let s = optionalString else { - throw Error.malformedUTF8 + + /// Invoke `sysctl` with an array of identifers, interpreting the returned buffer as a `String`. This function will throw `Error.malformedUTF8` if the buffer returned from `sysctl` cannot be interpreted as a UTF8 buffer. + public static func string(for keys: Int32...) throws -> String { + return try string(for: keys) } - return s - } - /// Invoke `sysctl` with an array of identifers, interpreting the returned buffer as a `String`. This function will throw `Error.malformedUTF8` if the buffer returned from `sysctl` cannot be interpreted as a UTF8 buffer. - public static func string(for keys: Int32...) throws -> String { - return try string(for: keys) - } + /// Invoke `sysctl` with the specified name, interpreting the returned buffer as a `String`. This function will throw `Error.malformedUTF8` if the buffer returned from `sysctl` cannot be interpreted as a UTF8 buffer. + public static func string(for name: String) throws -> String { + return try string(for: keys(for: name)) + } - /// Invoke `sysctl` with the specified name, interpreting the returned buffer as a `String`. This function will throw `Error.malformedUTF8` if the buffer returned from `sysctl` cannot be interpreted as a UTF8 buffer. - public static func string(for name: String) throws -> String { - return try string(for: keys(for: name)) - } + /// e.g. "MyComputer.local" (from System Preferences -> Sharing -> Computer Name) or + /// "My-Name-iPhone" (from Settings -> General -> About -> Name) + public static var hostName: String { + return try! Sysctl.string(for: [CTL_KERN, KERN_HOSTNAME]) + } - /// e.g. "MyComputer.local" (from System Preferences -> Sharing -> Computer Name) or - /// "My-Name-iPhone" (from Settings -> General -> About -> Name) - public static var hostName: String { return try! Sysctl.string(for: [CTL_KERN, KERN_HOSTNAME]) } + /// e.g. "x86_64" or "N71mAP" + /// NOTE: this is *corrected* on iOS devices to fetch hw.model + public static var machine: String { + #if os(iOS) && !arch(x86_64) && !arch(i386) + return try! Sysctl.string(for: [CTL_HW, HW_MODEL]) + #else + return try! Sysctl.string(for: [CTL_HW, HW_MACHINE]) + #endif + } - /// e.g. "x86_64" or "N71mAP" - /// NOTE: this is *corrected* on iOS devices to fetch hw.model - public static var machine: String { - #if os(iOS) && !arch(x86_64) && !arch(i386) - return try! Sysctl.string(for: [CTL_HW, HW_MODEL]) - #else - return try! Sysctl.string(for: [CTL_HW, HW_MACHINE]) + /// e.g. "MacPro4,1" or "iPhone8,1" + /// NOTE: this is *corrected* on iOS devices to fetch hw.machine + public static var model: String { + #if os(iOS) && !arch(x86_64) && !arch(i386) + return try! Sysctl.string(for: [CTL_HW, HW_MACHINE]) + #else + return try! Sysctl.string(for: [CTL_HW, HW_MODEL]) + #endif + } + + /// e.g. "8" or "2" + public static var activeCPUs: Int32 { + return try! Sysctl.value(ofType: Int32.self, forKeys: [CTL_HW, HW_AVAILCPU]) + } + + /// e.g. "15.3.0" or "15.0.0" + public static var osRelease: String { + return try! Sysctl.string(for: [CTL_KERN, KERN_OSRELEASE]) + } + + /// e.g. "Darwin" or "Darwin" + public static var osType: String { + return try! Sysctl.string(for: [CTL_KERN, KERN_OSTYPE]) + } + + /// e.g. "15D21" or "13D20" + public static var osVersion: String { + return try! Sysctl.string(for: [CTL_KERN, KERN_OSVERSION]) + } + + /// e.g. "Darwin Kernel Version 15.3.0: Thu Dec 10 18:40:58 PST 2015; root:xnu-3248.30.4~1/RELEASE_X86_64" or + /// "Darwin Kernel Version 15.0.0: Wed Dec 9 22:19:38 PST 2015; root:xnu-3248.31.3~2/RELEASE_ARM64_S8000" + public static var version: String { + return try! Sysctl.string(for: [CTL_KERN, KERN_VERSION]) + } + + #if os(macOS) + /// e.g. 199506 (not available on iOS) + public static var osRev: Int32 { + return try! Sysctl.value(ofType: Int32.self, forKeys: [CTL_KERN, KERN_OSREV]) + } + + /// e.g. 2659000000 (not available on iOS) + public static var cpuFreq: Int64 { + return try! Sysctl.value(ofType: Int64.self, forName: "hw.cpufrequency") + } + + /// e.g. 25769803776 (not available on iOS) + public static var memSize: UInt64 { + return try! Sysctl.value(ofType: UInt64.self, forKeys: [CTL_HW, HW_MEMSIZE]) + } #endif } - - /// e.g. "MacPro4,1" or "iPhone8,1" - /// NOTE: this is *corrected* on iOS devices to fetch hw.machine - public static var model: String { - #if os(iOS) && !arch(x86_64) && !arch(i386) - return try! Sysctl.string(for: [CTL_HW, HW_MACHINE]) - #else - return try! Sysctl.string(for: [CTL_HW, HW_MODEL]) - #endif - } - - /// e.g. "8" or "2" - public static var activeCPUs: Int32 { return try! Sysctl.value(ofType: Int32.self, forKeys: [CTL_HW, HW_AVAILCPU]) } - - /// e.g. "15.3.0" or "15.0.0" - public static var osRelease: String { return try! Sysctl.string(for: [CTL_KERN, KERN_OSRELEASE]) } - - /// e.g. "Darwin" or "Darwin" - public static var osType: String { return try! Sysctl.string(for: [CTL_KERN, KERN_OSTYPE]) } - - /// e.g. "15D21" or "13D20" - public static var osVersion: String { return try! Sysctl.string(for: [CTL_KERN, KERN_OSVERSION]) } - - /// e.g. "Darwin Kernel Version 15.3.0: Thu Dec 10 18:40:58 PST 2015; root:xnu-3248.30.4~1/RELEASE_X86_64" or - /// "Darwin Kernel Version 15.0.0: Wed Dec 9 22:19:38 PST 2015; root:xnu-3248.31.3~2/RELEASE_ARM64_S8000" - public static var version: String { return try! Sysctl.string(for: [CTL_KERN, KERN_VERSION]) } - - #if os(macOS) - /// e.g. 199506 (not available on iOS) - public static var osRev: Int32 { return try! Sysctl.value(ofType: Int32.self, forKeys: [CTL_KERN, KERN_OSREV]) } - - /// e.g. 2659000000 (not available on iOS) - public static var cpuFreq: Int64 { return try! Sysctl.value(ofType: Int64.self, forName: "hw.cpufrequency") } - - /// e.g. 25769803776 (not available on iOS) - public static var memSize: UInt64 { return try! Sysctl.value(ofType: UInt64.self, forKeys: [CTL_HW, HW_MEMSIZE]) } - #endif -} #endif diff --git a/Sources/Appwrite/DeviceInfo/macOS/MacOSDeviceInfo.swift b/Sources/Appwrite/DeviceInfo/macOS/MacOSDeviceInfo.swift index 3f42abd..b3da7c9 100644 --- a/Sources/Appwrite/DeviceInfo/macOS/MacOSDeviceInfo.swift +++ b/Sources/Appwrite/DeviceInfo/macOS/MacOSDeviceInfo.swift @@ -1,23 +1,23 @@ #if os(macOS) -import Foundation + import Foundation -class MacOSDeviceInfo { - let computerName: String - let hostName: String - let arch: String - let model: String - let kernelVersion: String - let osRelease: String - let activeCPUs: Int + class MacOSDeviceInfo { + let computerName: String + let hostName: String + let arch: String + let model: String + let kernelVersion: String + let osRelease: String + let activeCPUs: Int - public init() { - computerName = Sysctl.hostName - hostName = Sysctl.osType - arch = Sysctl.machine - model = Sysctl.model - kernelVersion = Sysctl.version - osRelease = Sysctl.osRelease - activeCPUs = Int(Sysctl.activeCPUs) + public init() { + computerName = Sysctl.hostName + hostName = Sysctl.osType + arch = Sysctl.machine + model = Sysctl.model + kernelVersion = Sysctl.version + osRelease = Sysctl.osRelease + activeCPUs = Int(Sysctl.activeCPUs) + } } -} #endif diff --git a/Sources/Appwrite/DeviceInfo/watchOS/WKInterfaceDevice+ModelName.swift b/Sources/Appwrite/DeviceInfo/watchOS/WKInterfaceDevice+ModelName.swift index bf047bd..38a33b5 100644 --- a/Sources/Appwrite/DeviceInfo/watchOS/WKInterfaceDevice+ModelName.swift +++ b/Sources/Appwrite/DeviceInfo/watchOS/WKInterfaceDevice+ModelName.swift @@ -1,65 +1,65 @@ #if os(watchOS) -import Foundation -import WatchKit + import Foundation + import WatchKit -public extension WKInterfaceDevice { + public extension WKInterfaceDevice { - static let modelName: String = { - var systemInfo = utsname() - uname(&systemInfo) - let machineMirror = Mirror(reflecting: systemInfo.machine) - let identifier = machineMirror.children.reduce("") { identifier, element in - guard let value = element.value as? Int8, value != 0 else { return identifier } - return identifier + String(UnicodeScalar(UInt8(value))) - } - - func mapToDevice(identifier: String) -> String { - switch identifier { - case "Watch1,1": return "Apple Watch Series 0 38mm" - case "Watch1,2": return"Apple Watch Series 0 42mm" - case "Watch2,3": return "Apple Watch Series 2 38mm" - case "Watch2,4": return "Apple Watch Series 2 42mmm" - case "Watch2,6": return "Apple Watch Series 1 38mm" - case "Watch2,7": return "Apple Watch Series 1 42mm" - case "Watch3,1": return "Apple Watch Series 3 38mm Cellular" - case "Watch3,2": return "Apple Watch Series 3 42mm Cellular" - case "Watch3,3": return "Apple Watch Series 3 38mm" - case "Watch3,4": return "Apple Watch Series 3 42mm" - case "Watch4,1": return "Apple Watch Series 4 40mm" - case "Watch4,2": return "Apple Watch Series 4 44mm" - case "Watch4,3": return "Apple Watch Series 4 40mm Cellular" - case "Watch4,4": return "Apple Watch Series 4 44mm Cellular" - case "Watch5,1": return "Apple Watch Series 5 40mm" - case "Watch5,2": return "Apple Watch Series 5 44mm" - case "Watch5,3": return "Apple Watch Series 5 40mm Cellular" - case "Watch5,4": return "Apple Watch Series 5 44mm Cellular" - case "Watch5,9": return "Apple Watch SE 40mm" - case "Watch5,10": return "Apple Watch SE 44mm" - case "Watch5,11": return "Apple Watch SE 40mm Cellular" - case "Watch5,12": return "Apple Watch SE 44mm Cellular" - case "Watch6,1": return "Apple Watch Series 6 40mm" - case "Watch6,2": return "Apple Watch Series 6 44mm" - case "Watch6.3": return "Apple Watch Series 6 40mm Cellular" - case "Watch6,4": return "Apple Watch Series 6 44mm Cellular" - case "Watch6,6": return "Apple Watch Series 7 41mm" - case "Watch6,7": return "Apple Watch Series 7 45mm" - case "Watch6,8": return "Apple Watch Series 7 41mm Cellular" - case "Watch6,9": return "Apple Watch Series 7 45mm Cellular" - case "Watch6,10": return "Apple Watch SE (2nd generation) 41mm" - case "Watch6,11": return "Apple Watch SE (2nd generation) 45mm" - case "Watch6,12": return "Apple Watch SE (2nd generation) 41mm Cellular" - case "Watch6,13": return "Apple Watch SE (2nd generation) 45mm Cellular" - case "Watch6,14": return "Apple Watch Series 8 41mm" - case "Watch6,15": return "Apple Watch Series 8 45mm" - case "Watch6,16": return "Apple Watch Series 8 41mm Cellular" - case "Watch6,17": return "Apple Watch Series 8 45mm Cellular" - case "Watch6,18": return "Apple Watch Ultra" - default: return "unknown" + static let modelName: String = { + var systemInfo = utsname() + uname(&systemInfo) + let machineMirror = Mirror(reflecting: systemInfo.machine) + let identifier = machineMirror.children.reduce("") { identifier, element in + guard let value = element.value as? Int8, value != 0 else { return identifier } + return identifier + String(UnicodeScalar(UInt8(value))) } - } - return mapToDevice(identifier: identifier) - }() + func mapToDevice(identifier: String) -> String { + switch identifier { + case "Watch1,1": return "Apple Watch Series 0 38mm" + case "Watch1,2": return "Apple Watch Series 0 42mm" + case "Watch2,3": return "Apple Watch Series 2 38mm" + case "Watch2,4": return "Apple Watch Series 2 42mmm" + case "Watch2,6": return "Apple Watch Series 1 38mm" + case "Watch2,7": return "Apple Watch Series 1 42mm" + case "Watch3,1": return "Apple Watch Series 3 38mm Cellular" + case "Watch3,2": return "Apple Watch Series 3 42mm Cellular" + case "Watch3,3": return "Apple Watch Series 3 38mm" + case "Watch3,4": return "Apple Watch Series 3 42mm" + case "Watch4,1": return "Apple Watch Series 4 40mm" + case "Watch4,2": return "Apple Watch Series 4 44mm" + case "Watch4,3": return "Apple Watch Series 4 40mm Cellular" + case "Watch4,4": return "Apple Watch Series 4 44mm Cellular" + case "Watch5,1": return "Apple Watch Series 5 40mm" + case "Watch5,2": return "Apple Watch Series 5 44mm" + case "Watch5,3": return "Apple Watch Series 5 40mm Cellular" + case "Watch5,4": return "Apple Watch Series 5 44mm Cellular" + case "Watch5,9": return "Apple Watch SE 40mm" + case "Watch5,10": return "Apple Watch SE 44mm" + case "Watch5,11": return "Apple Watch SE 40mm Cellular" + case "Watch5,12": return "Apple Watch SE 44mm Cellular" + case "Watch6,1": return "Apple Watch Series 6 40mm" + case "Watch6,2": return "Apple Watch Series 6 44mm" + case "Watch6.3": return "Apple Watch Series 6 40mm Cellular" + case "Watch6,4": return "Apple Watch Series 6 44mm Cellular" + case "Watch6,6": return "Apple Watch Series 7 41mm" + case "Watch6,7": return "Apple Watch Series 7 45mm" + case "Watch6,8": return "Apple Watch Series 7 41mm Cellular" + case "Watch6,9": return "Apple Watch Series 7 45mm Cellular" + case "Watch6,10": return "Apple Watch SE (2nd generation) 41mm" + case "Watch6,11": return "Apple Watch SE (2nd generation) 45mm" + case "Watch6,12": return "Apple Watch SE (2nd generation) 41mm Cellular" + case "Watch6,13": return "Apple Watch SE (2nd generation) 45mm Cellular" + case "Watch6,14": return "Apple Watch Series 8 41mm" + case "Watch6,15": return "Apple Watch Series 8 45mm" + case "Watch6,16": return "Apple Watch Series 8 41mm Cellular" + case "Watch6,17": return "Apple Watch Series 8 45mm Cellular" + case "Watch6,18": return "Apple Watch Ultra" + default: return "unknown" + } + } -} + return mapToDevice(identifier: identifier) + }() + + } #endif diff --git a/Sources/Appwrite/DeviceInfo/watchOS/WatchOSDeviceInfo.swift b/Sources/Appwrite/DeviceInfo/watchOS/WatchOSDeviceInfo.swift index 0e88af9..a1408a3 100644 --- a/Sources/Appwrite/DeviceInfo/watchOS/WatchOSDeviceInfo.swift +++ b/Sources/Appwrite/DeviceInfo/watchOS/WatchOSDeviceInfo.swift @@ -1,27 +1,27 @@ #if os(watchOS) -import Foundation -import WatchKit + import Foundation + import WatchKit -class WatchOSDeviceInfo { + class WatchOSDeviceInfo { - let name: String - let systemName: String - let systemVersion: String - let model: String - let localizedModel: String - let identifierForVendor: String - let modelIdentifier: String + let name: String + let systemName: String + let systemVersion: String + let model: String + let localizedModel: String + let identifierForVendor: String + let modelIdentifier: String - public init() { - let device = WKInterfaceDevice.current() + public init() { + let device = WKInterfaceDevice.current() - name = device.name - systemName = device.systemName - systemVersion = device.systemVersion - model = device.model - localizedModel = device.localizedModel - identifierForVendor = device.identifierForVendor?.uuidString ?? "" - modelIdentifier = WKInterfaceDevice.modelName + name = device.name + systemName = device.systemName + systemVersion = device.systemVersion + model = device.model + localizedModel = device.localizedModel + identifierForVendor = device.identifierForVendor?.uuidString ?? "" + modelIdentifier = WKInterfaceDevice.modelName + } } -} #endif diff --git a/Sources/Appwrite/Extensions/Cookie+Codable.swift b/Sources/Appwrite/Extensions/Cookie+Codable.swift index 8f0d329..b9a151a 100644 --- a/Sources/Appwrite/Extensions/Cookie+Codable.swift +++ b/Sources/Appwrite/Extensions/Cookie+Codable.swift @@ -1,7 +1,7 @@ -import Foundation import AsyncHTTPClient +import Foundation -extension HTTPClient.Cookie : Codable { +extension HTTPClient.Cookie: Codable { enum CodingKeys: String, CodingKey { case name diff --git a/Sources/Appwrite/Extensions/HTTPClientRequest+Cookies.swift b/Sources/Appwrite/Extensions/HTTPClientRequest+Cookies.swift index db5c682..7ca5586 100644 --- a/Sources/Appwrite/Extensions/HTTPClientRequest+Cookies.swift +++ b/Sources/Appwrite/Extensions/HTTPClientRequest+Cookies.swift @@ -24,4 +24,4 @@ extension HTTPHeaders { add(name: "Cookie", value: cookie) } } -} \ No newline at end of file +} diff --git a/Sources/Appwrite/Extensions/String+MimeTypes.swift b/Sources/Appwrite/Extensions/String+MimeTypes.swift index 4cd2811..627f110 100644 --- a/Sources/Appwrite/Extensions/String+MimeTypes.swift +++ b/Sources/Appwrite/Extensions/String+MimeTypes.swift @@ -106,7 +106,7 @@ fileprivate let mimeTypes = [ "asx": "video/x-ms-asf", "asf": "video/x-ms-asf", "wmv": "video/x-ms-wmv", - "avi": "video/x-msvideo" + "avi": "video/x-msvideo", ] fileprivate func mimeFromExt(ext: String?) -> String { @@ -127,4 +127,4 @@ extension String { public func mimeType() -> String { return (self as NSString).mimeType() } -} \ No newline at end of file +} diff --git a/Sources/Appwrite/Models/AppwriteError.swift b/Sources/Appwrite/Models/AppwriteError.swift index 4c79512..8400537 100644 --- a/Sources/Appwrite/Models/AppwriteError.swift +++ b/Sources/Appwrite/Models/AppwriteError.swift @@ -1,6 +1,6 @@ import Foundation -open class AppwriteError : Swift.Error, Decodable { +open class AppwriteError: Swift.Error, Decodable { public let message: String public let code: Int? @@ -17,16 +17,12 @@ open class AppwriteError : Swift.Error, Decodable { extension AppwriteError: CustomStringConvertible { public var description: String { - get { - return self.message - } + return self.message } } extension AppwriteError: LocalizedError { public var errorDescription: String? { - get { - return self.message - } + return self.message } } diff --git a/Sources/Appwrite/Models/InputFile.swift b/Sources/Appwrite/Models/InputFile.swift index cb9a491..ceabf02 100644 --- a/Sources/Appwrite/Models/InputFile.swift +++ b/Sources/Appwrite/Models/InputFile.swift @@ -30,7 +30,9 @@ open class InputFile { return instance } - public static func fromBuffer(_ buffer: ByteBuffer, filename: String, mimeType: String) -> InputFile { + public static func fromBuffer(_ buffer: ByteBuffer, filename: String, mimeType: String) + -> InputFile + { let instance = InputFile() instance.filename = filename instance.mimeType = mimeType diff --git a/Sources/Appwrite/Models/UploadProgress.swift b/Sources/Appwrite/Models/UploadProgress.swift index a9a8545..8f00ffd 100644 --- a/Sources/Appwrite/Models/UploadProgress.swift +++ b/Sources/Appwrite/Models/UploadProgress.swift @@ -5,11 +5,13 @@ public class UploadProgress { public let chunksTotal: Int public let chunksUploaded: Int - public init(id: String, progress: Double, sizeUploaded: Int, chunksTotal: Int, chunksUploaded: Int) { + public init( + id: String, progress: Double, sizeUploaded: Int, chunksTotal: Int, chunksUploaded: Int + ) { self.id = id self.progress = progress self.sizeUploaded = sizeUploaded self.chunksTotal = chunksTotal self.chunksUploaded = chunksUploaded } -} \ No newline at end of file +} diff --git a/Sources/Appwrite/OAuth/View+OAuth.swift b/Sources/Appwrite/OAuth/View+OAuth.swift index f58ae57..ce78cf9 100644 --- a/Sources/Appwrite/OAuth/View+OAuth.swift +++ b/Sources/Appwrite/OAuth/View+OAuth.swift @@ -1,41 +1,41 @@ #if os(macOS) -typealias OSApplication = NSApplication -typealias OSViewController = NSViewController -let notificationType = NSApplication.willBecomeActiveNotification + typealias OSApplication = NSApplication + typealias OSViewController = NSViewController + let notificationType = NSApplication.willBecomeActiveNotification #elseif os(iOS) || os(tvOS) || os(visionOS) -typealias OSApplication = UIApplication -typealias OSViewController = UIViewController -let notificationType = UIApplication.willEnterForegroundNotification + typealias OSApplication = UIApplication + typealias OSViewController = UIViewController + let notificationType = UIApplication.willEnterForegroundNotification #elseif os(watchOS) -typealias OSApplication = WKApplication -typealias OSViewController = WKInterfaceController -let notificationType = WKApplication.willEnterForegroundNotification + typealias OSApplication = WKApplication + typealias OSViewController = WKInterfaceController + let notificationType = WKApplication.willEnterForegroundNotification #endif #if canImport(SwiftUI) -import SwiftUI -@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, visionOS 1.0, *) -extension View { - public func registerOAuthHandler() -> some View { - onOpenURL { url in - WebAuthComponent.handleIncomingCookie(from: url) - }.onReceive(NotificationCenter.default.publisher(for: notificationType)) { _ in - WebAuthComponent.onCallback() + import SwiftUI + @available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, visionOS 1.0, *) + extension View { + public func registerOAuthHandler() -> some View { + onOpenURL { url in + WebAuthComponent.handleIncomingCookie(from: url) + }.onReceive(NotificationCenter.default.publisher(for: notificationType)) { _ in + WebAuthComponent.onCallback() + } } } -} #endif #if canImport(OSViewController) -@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, visionOS 1.0, *) -extension OSViewController { - public func registerOAuthHandler() { - #if os(macOS) - typealias OSHostingController = NSHostingController - #elseif os(iOS) || os(tvOS) || os(watchOS) || os(visionOS) - typealias OSHostingController = UIHostingController - #endif - self.addChild(OSHostingController(rootView: EmptyView().registerOAuthHandler())) + @available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, visionOS 1.0, *) + extension OSViewController { + public func registerOAuthHandler() { + #if os(macOS) + typealias OSHostingController = NSHostingController + #elseif os(iOS) || os(tvOS) || os(watchOS) || os(visionOS) + typealias OSHostingController = UIHostingController + #endif + self.addChild(OSHostingController(rootView: EmptyView().registerOAuthHandler())) + } } -} #endif diff --git a/Sources/Appwrite/OAuth/WebAuthComponent.swift b/Sources/Appwrite/OAuth/WebAuthComponent.swift index fad0734..69acacc 100644 --- a/Sources/Appwrite/OAuth/WebAuthComponent.swift +++ b/Sources/Appwrite/OAuth/WebAuthComponent.swift @@ -3,7 +3,7 @@ import Foundation import NIO #if canImport(AuthenticationServices) -import AuthenticationServices + import AuthenticationServices #endif /// @@ -15,7 +15,7 @@ public class WebAuthComponent { private static var callbacks = [String: (Result) -> Void]() #if canImport(AuthenticationServices) - private static var currentAuthSession: ASWebAuthenticationSession? + private static var currentAuthSession: ASWebAuthenticationSession? #endif /// @@ -40,7 +40,7 @@ public class WebAuthComponent { callbacks[callbackScheme] = onComplete #if canImport(AuthenticationServices) - currentAuthSession = ASWebAuthenticationSession( + currentAuthSession = ASWebAuthenticationSession( url: url, callbackURLScheme: callbackScheme ) { callbackURL, error in @@ -53,14 +53,14 @@ public class WebAuthComponent { } } - if let session = currentAuthSession { - /// Indicates that the session should be a private session. - session.prefersEphemeralWebBrowserSession = true - session.presentationContextProvider = PresentationContextProvider.shared - session.start() - } else { - print("Failed to create ASWebAuthenticationSession") - } + if let session = currentAuthSession { + /// Indicates that the session should be a private session. + session.prefersEphemeralWebBrowserSession = true + session.presentationContextProvider = PresentationContextProvider.shared + session.start() + } else { + print("Failed to create ASWebAuthenticationSession") + } #endif } @@ -73,20 +73,23 @@ public class WebAuthComponent { public static func handleIncomingCookie(from url: URL) { guard let components = URLComponents(string: url.absoluteString), - let queryItems = components.queryItems else { + let queryItems = components.queryItems + else { return } - - let cookieParts = [String: String](uniqueKeysWithValues: queryItems.compactMap { item in - item.value.map { (item.name, $0) } - }) + + let cookieParts = [String: String]( + uniqueKeysWithValues: queryItems.compactMap { item in + item.value.map { (item.name, $0) } + }) guard var domain = cookieParts["domain"], - let key = cookieParts["key"], - let secret = cookieParts["secret"] else { + let key = cookieParts["key"], + let secret = cookieParts["secret"] + else { return } - + domain.remove(at: domain.startIndex) let path: String? = cookieParts["path"] @@ -150,22 +153,22 @@ public class WebAuthComponent { } #if canImport(AuthenticationServices) - currentAuthSession = nil + currentAuthSession = nil #endif } } #if canImport(AuthenticationServices) -/// Presentation context for the ASWebAuthenticationSession. -class PresentationContextProvider: NSObject, ASWebAuthenticationPresentationContextProviding { - static let shared = PresentationContextProvider() + /// Presentation context for the ASWebAuthenticationSession. + class PresentationContextProvider: NSObject, ASWebAuthenticationPresentationContextProviding { + static let shared = PresentationContextProvider() - func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor { - if let mainWindow = OSApplication.shared.windows.first(where: { $0.isKeyWindow }) { - return mainWindow + func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor { + if let mainWindow = OSApplication.shared.windows.first(where: { $0.isKeyWindow }) { + return mainWindow + } + + return ASPresentationAnchor() } - - return ASPresentationAnchor() } -} -#endif \ No newline at end of file +#endif diff --git a/Sources/Appwrite/Operator.swift b/Sources/Appwrite/Operator.swift index 6af290f..3e4d08f 100644 --- a/Sources/Appwrite/Operator.swift +++ b/Sources/Appwrite/Operator.swift @@ -62,7 +62,7 @@ enum OperatorValue: Codable { } } -public struct Operator : Codable, CustomStringConvertible { +public struct Operator: Codable, CustomStringConvertible { var method: String var values: [OperatorValue]? @@ -150,7 +150,7 @@ public struct Operator : Codable, CustomStringConvertible { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(method, forKey: .method) - if (values != nil) { + if values != nil { try container.encode(values, forKey: .values) } } diff --git a/Sources/Appwrite/PackageInfo/Apple/PackageInfo+Apple.swift b/Sources/Appwrite/PackageInfo/Apple/PackageInfo+Apple.swift index 2138da4..d54d420 100644 --- a/Sources/Appwrite/PackageInfo/Apple/PackageInfo+Apple.swift +++ b/Sources/Appwrite/PackageInfo/Apple/PackageInfo+Apple.swift @@ -1,18 +1,20 @@ import Foundation extension PackageInfo { - + public static func getApplePackage() -> PackageInfo { let bundle = Bundle.main - - let appName = bundle.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String + + let appName = + bundle.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String ?? bundle.object(forInfoDictionaryKey: "CFBundleName") as? String ?? "" - + let packageName = bundle.bundleIdentifier ?? "" - let version = bundle.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "" + let version = + bundle.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "" let build = bundle.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "" - + return PackageInfo( appName: appName, version: version, diff --git a/Sources/Appwrite/PackageInfo/OSPackageInfo.swift b/Sources/Appwrite/PackageInfo/OSPackageInfo.swift index f49b956..02e232c 100644 --- a/Sources/Appwrite/PackageInfo/OSPackageInfo.swift +++ b/Sources/Appwrite/PackageInfo/OSPackageInfo.swift @@ -4,11 +4,11 @@ class OSPackageInfo { public static func get() -> PackageInfo { #if os(iOS) || os(watchOS) || os(tvOS) || os(macOS) || os(visionOS) - return PackageInfo.getApplePackage() + return PackageInfo.getApplePackage() #elseif os(Linux) - return PackageInfo.getLinuxPackage() + return PackageInfo.getLinuxPackage() #elseif os(Windows) - return PackageInfo.getWindowsPackage() + return PackageInfo.getWindowsPackage() #endif } } diff --git a/Sources/Appwrite/PackageInfo/PackageInfo.swift b/Sources/Appwrite/PackageInfo/PackageInfo.swift index 47e8d5a..89b0607 100644 --- a/Sources/Appwrite/PackageInfo/PackageInfo.swift +++ b/Sources/Appwrite/PackageInfo/PackageInfo.swift @@ -1,13 +1,13 @@ import Foundation class PackageInfo { - + let appName: String let version: String let buildNumber: String let packageName: String let buildSignature: String? - + internal init( appName: String, version: String, diff --git a/Sources/Appwrite/PackageInfo/Windows/PackageInfo+Windows.swift b/Sources/Appwrite/PackageInfo/Windows/PackageInfo+Windows.swift index e2966a4..3b58257 100644 --- a/Sources/Appwrite/PackageInfo/Windows/PackageInfo+Windows.swift +++ b/Sources/Appwrite/PackageInfo/Windows/PackageInfo+Windows.swift @@ -1,7 +1,7 @@ import Foundation extension PackageInfo { - + public static func getWindowsPackage() -> PackageInfo { let version = getVersionJson() return PackageInfo( diff --git a/Sources/Appwrite/Permission.swift b/Sources/Appwrite/Permission.swift index 4e053db..6bf17eb 100644 --- a/Sources/Appwrite/Permission.swift +++ b/Sources/Appwrite/Permission.swift @@ -18,4 +18,4 @@ public class Permission { public static func delete(_ role: String) -> String { return "delete(\"\(role)\")" } -} \ No newline at end of file +} diff --git a/Sources/Appwrite/Query.swift b/Sources/Appwrite/Query.swift index 2745460..8aa122a 100644 --- a/Sources/Appwrite/Query.swift +++ b/Sources/Appwrite/Query.swift @@ -6,7 +6,7 @@ enum QueryValue: Codable { case double(Double) case bool(Bool) case query(Query) - case array([QueryValue]) // for nested arrays + case array([QueryValue]) // for nested arrays init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() @@ -50,7 +50,7 @@ enum QueryValue: Codable { } } -public struct Query : Codable, CustomStringConvertible { +public struct Query: Codable, CustomStringConvertible { var method: String var attribute: String? var values: [QueryValue]? @@ -132,11 +132,11 @@ public struct Query : Codable, CustomStringConvertible { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(method, forKey: .method) - if (self.attribute != nil) { + if self.attribute != nil { try container.encode(attribute, forKey: .attribute) } - if (values != nil) { + if values != nil { try container.encode(values, forKey: .values) } } @@ -516,7 +516,9 @@ public struct Query : Codable, CustomStringConvertible { ).description } - public static func distanceEqual(_ attribute: String, values: [Any], distance: Double, meters: Bool = true) -> String { + public static func distanceEqual( + _ attribute: String, values: [Any], distance: Double, meters: Bool = true + ) -> String { return Query( method: "distanceEqual", attribute: attribute, @@ -524,7 +526,9 @@ public struct Query : Codable, CustomStringConvertible { ).description } - public static func distanceNotEqual(_ attribute: String, values: [Any], distance: Double, meters: Bool = true) -> String { + public static func distanceNotEqual( + _ attribute: String, values: [Any], distance: Double, meters: Bool = true + ) -> String { return Query( method: "distanceNotEqual", attribute: attribute, @@ -532,7 +536,9 @@ public struct Query : Codable, CustomStringConvertible { ).description } - public static func distanceGreaterThan(_ attribute: String, values: [Any], distance: Double, meters: Bool = true) -> String { + public static func distanceGreaterThan( + _ attribute: String, values: [Any], distance: Double, meters: Bool = true + ) -> String { return Query( method: "distanceGreaterThan", attribute: attribute, @@ -540,7 +546,9 @@ public struct Query : Codable, CustomStringConvertible { ).description } - public static func distanceLessThan(_ attribute: String, values: [Any], distance: Double, meters: Bool = true) -> String { + public static func distanceLessThan( + _ attribute: String, values: [Any], distance: Double, meters: Bool = true + ) -> String { return Query( method: "distanceLessThan", attribute: attribute, diff --git a/Sources/Appwrite/Role.swift b/Sources/Appwrite/Role.swift index 1e8e755..9f449b7 100644 --- a/Sources/Appwrite/Role.swift +++ b/Sources/Appwrite/Role.swift @@ -2,14 +2,14 @@ public class Role { /// Grants access to anyone. - /// + /// /// This includes authenticated and unauthenticated users. public static func any() -> String { return "any" } /// Grants access to a specific user by user ID. - /// + /// /// You can optionally pass verified or unverified for /// `status` to target specific types of users. /// @@ -17,28 +17,28 @@ public class Role { /// @param String status /// @return String public static func user(_ id: String, _ status: String = "") -> String { - if(status.isEmpty) { + if status.isEmpty { return "user:\(id)" } return "user:\(id)/\(status)" } /// Grants access to any authenticated or anonymous user. - /// + /// /// You can optionally pass verified or unverified for /// `status` to target specific types of users. /// /// @param String status /// @return String public static func users(_ status: String = "") -> String { - if(status.isEmpty) { + if status.isEmpty { return "users" } return "users/\(status)" } /// Grants access to any guest user without a session. - /// + /// /// Authenticated users don't have access to this role. /// /// @return String @@ -47,7 +47,7 @@ public class Role { } /// Grants access to a team by team ID. - /// + /// /// You can optionally pass a role for `role` to target /// team members with the specified role. /// @@ -55,14 +55,14 @@ public class Role { /// @param String role /// @return String public static func team(_ id: String, _ role: String = "") -> String { - if(role.isEmpty) { + if role.isEmpty { return "team:\(id)" } return "team:\(id)/\(role)" } /// Grants access to a specific member of a team. - /// + /// /// When the member is removed from the team, they will /// no longer have access. /// @@ -79,4 +79,4 @@ public class Role { public static func label(_ name: String) -> String { return "label:\(name)" } -} \ No newline at end of file +} diff --git a/Sources/Appwrite/Services/Account.swift b/Sources/Appwrite/Services/Account.swift index a8f386b..0a272d4 100644 --- a/Sources/Appwrite/Services/Account.swift +++ b/Sources/Appwrite/Services/Account.swift @@ -1,9 +1,9 @@ -import AsyncHTTPClient -import Foundation -import NIO -import JSONCodable import AppwriteEnums import AppwriteModels +import AsyncHTTPClient +import Foundation +import JSONCodable +import NIO /// The Account service allows you to authenticate and manage a user account. open class Account: Service { @@ -23,7 +23,7 @@ open class Account: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.User = { response in @@ -45,13 +45,11 @@ open class Account: Service { /// - Throws: Exception if the request fails /// - Returns: AppwriteModels.User /// - open func get( - ) async throws -> AppwriteModels.User<[String: AnyCodable]> { + open func get() async throws -> AppwriteModels.User<[String: AnyCodable]> { return try await get( nestedType: [String: AnyCodable].self ) } - /// /// Use this endpoint to allow a new user to register a new account in your /// project. After the user registration completes successfully, you can use @@ -82,13 +80,13 @@ open class Account: Service { "userId": userId, "email": email, "password": password, - "name": name + "name": name, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.User = { response in @@ -135,7 +133,222 @@ open class Account: Service { nestedType: [String: AnyCodable].self ) } + /// + /// Get a list of the OAuth2 consents the current user has given to third-party + /// apps. + /// + /// - Parameters: + /// - queries: [String] (optional) + /// - total: Bool (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.Oauth2ConsentList + /// + open func listConsents( + queries: [String]? = nil, + total: Bool? = nil + ) async throws -> AppwriteModels.Oauth2ConsentList { + let apiPath: String = "/account/consents" + let apiParams: [String: Any?] = [ + "queries": queries, + "total": total, + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "accept": "application/json", + ] + + let converter: (Any) throws -> AppwriteModels.Oauth2ConsentList = { response in + return AppwriteModels.Oauth2ConsentList.from(map: response as! [String: Any]) + } + + return try await client.call( + method: "GET", + path: apiPath, + headers: apiHeaders, + params: apiParams, + converter: converter + ) + } + /// + /// Get an OAuth2 consent the current user has given to a third-party app by + /// its unique ID. + /// + /// - Parameters: + /// - consentId: String + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.Oauth2Consent + /// + open func getConsent( + consentId: String + ) async throws -> AppwriteModels.Oauth2Consent { + let apiPath: String = "/account/consents/{consentId}" + .replacingOccurrences(of: "{consentId}", with: consentId) + + let apiParams: [String: Any] = [:] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "accept": "application/json", + ] + + let converter: (Any) throws -> AppwriteModels.Oauth2Consent = { response in + return AppwriteModels.Oauth2Consent.from(map: response as! [String: Any]) + } + + return try await client.call( + method: "GET", + path: apiPath, + headers: apiHeaders, + params: apiParams, + converter: converter + ) + } + /// + /// Delete an OAuth2 consent by its unique ID. All token families issued under + /// the consent are revoked, and the app must ask for consent again to regain + /// access. + /// + /// - Parameters: + /// - consentId: String + /// - Throws: Exception if the request fails + /// - Returns: Any + /// + open func deleteConsent( + consentId: String + ) async throws -> Any { + let apiPath: String = "/account/consents/{consentId}" + .replacingOccurrences(of: "{consentId}", with: consentId) + + let apiParams: [String: Any] = [:] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "content-type": "application/json", + "accept": "application/json", + ] + + return try await client.call( + method: "DELETE", + path: apiPath, + headers: apiHeaders, + params: apiParams + ) + } + /// + /// Get a list of the token families issued under an OAuth2 consent. Each entry + /// represents one authorized device or session; the token secrets themselves + /// are never returned. + /// + /// - Parameters: + /// - consentId: String + /// - queries: [String] (optional) + /// - total: Bool (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.Oauth2ConsentTokenList + /// + open func listConsentTokens( + consentId: String, + queries: [String]? = nil, + total: Bool? = nil + ) async throws -> AppwriteModels.Oauth2ConsentTokenList { + let apiPath: String = "/account/consents/{consentId}/tokens" + .replacingOccurrences(of: "{consentId}", with: consentId) + + let apiParams: [String: Any?] = [ + "queries": queries, + "total": total, + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "accept": "application/json", + ] + + let converter: (Any) throws -> AppwriteModels.Oauth2ConsentTokenList = { response in + return AppwriteModels.Oauth2ConsentTokenList.from(map: response as! [String: Any]) + } + + return try await client.call( + method: "GET", + path: apiPath, + headers: apiHeaders, + params: apiParams, + converter: converter + ) + } + /// + /// Get a token family issued under an OAuth2 consent by its unique ID. The + /// token secrets themselves are never returned. + /// + /// - Parameters: + /// - consentId: String + /// - tokenId: String + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.Oauth2ConsentToken + /// + open func getConsentToken( + consentId: String, + tokenId: String + ) async throws -> AppwriteModels.Oauth2ConsentToken { + let apiPath: String = "/account/consents/{consentId}/tokens/{tokenId}" + .replacingOccurrences(of: "{consentId}", with: consentId) + .replacingOccurrences(of: "{tokenId}", with: tokenId) + + let apiParams: [String: Any] = [:] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "accept": "application/json", + ] + + let converter: (Any) throws -> AppwriteModels.Oauth2ConsentToken = { response in + return AppwriteModels.Oauth2ConsentToken.from(map: response as! [String: Any]) + } + + return try await client.call( + method: "GET", + path: apiPath, + headers: apiHeaders, + params: apiParams, + converter: converter + ) + } + /// + /// Delete a token family issued under an OAuth2 consent by its unique ID. The + /// access and refresh tokens of the family stop working immediately; other + /// token families and the consent itself are unaffected. + /// + /// - Parameters: + /// - consentId: String + /// - tokenId: String + /// - Throws: Exception if the request fails + /// - Returns: Any + /// + open func deleteConsentToken( + consentId: String, + tokenId: String + ) async throws -> Any { + let apiPath: String = "/account/consents/{consentId}/tokens/{tokenId}" + .replacingOccurrences(of: "{consentId}", with: consentId) + .replacingOccurrences(of: "{tokenId}", with: tokenId) + + let apiParams: [String: Any] = [:] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "content-type": "application/json", + "accept": "application/json", + ] + + return try await client.call( + method: "DELETE", + path: apiPath, + headers: apiHeaders, + params: apiParams + ) + } /// /// Update currently logged in user account email address. After changing user /// address, the user confirmation status will get reset. A new confirmation @@ -144,7 +357,6 @@ open class Account: Service { /// user password is required to complete this request. /// This endpoint can also be used to convert an anonymous account to a normal /// one, by passing an email address and a new password. - /// /// /// - Parameters: /// - email: String @@ -161,13 +373,13 @@ open class Account: Service { let apiParams: [String: Any?] = [ "email": email, - "password": password + "password": password, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.User = { response in @@ -191,7 +403,6 @@ open class Account: Service { /// user password is required to complete this request. /// This endpoint can also be used to convert an anonymous account to a normal /// one, by passing an email address and a new password. - /// /// /// - Parameters: /// - email: String @@ -209,7 +420,6 @@ open class Account: Service { nestedType: [String: AnyCodable].self ) } - /// /// Get the list of identities for the currently logged in user. /// @@ -227,12 +437,12 @@ open class Account: Service { let apiParams: [String: Any?] = [ "queries": queries, - "total": total + "total": total, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.IdentityList = { response in @@ -247,7 +457,6 @@ open class Account: Service { converter: converter ) } - /// /// Delete an identity by its unique ID. /// @@ -266,16 +475,16 @@ open class Account: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "content-type": "application/json" + "content-type": "application/json", ] return try await client.call( method: "DELETE", path: apiPath, headers: apiHeaders, - params: apiParams ) + params: apiParams + ) } - /// /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT /// to authenticate on behalf of the current user when working with the @@ -300,7 +509,7 @@ open class Account: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Jwt = { response in @@ -315,7 +524,6 @@ open class Account: Service { converter: converter ) } - /// /// Get the list of latest security activity logs for the currently logged in /// user. Each log returns user IP address, location and date and time of log. @@ -334,12 +542,12 @@ open class Account: Service { let apiParams: [String: Any?] = [ "queries": queries, - "total": total + "total": total, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.LogList = { response in @@ -354,7 +562,6 @@ open class Account: Service { converter: converter ) } - /// /// Enable or disable MFA on an account. /// @@ -376,7 +583,7 @@ open class Account: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.User = { response in @@ -408,7 +615,6 @@ open class Account: Service { nestedType: [String: AnyCodable].self ) } - /// /// Add an authenticator app to be used as an MFA factor. Verify the /// authenticator using the [verify @@ -432,7 +638,7 @@ open class Account: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.MfaType = { response in @@ -447,7 +653,6 @@ open class Account: Service { converter: converter ) } - /// /// Add an authenticator app to be used as an MFA factor. Verify the /// authenticator using the [verify @@ -470,7 +675,7 @@ open class Account: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.MfaType = { response in @@ -485,7 +690,6 @@ open class Account: Service { converter: converter ) } - /// /// Verify an authenticator app after adding it using the [add /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) @@ -513,7 +717,7 @@ open class Account: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.User = { response in @@ -551,7 +755,6 @@ open class Account: Service { nestedType: [String: AnyCodable].self ) } - /// /// Verify an authenticator app after adding it using the [add /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) @@ -578,7 +781,7 @@ open class Account: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.User = { response in @@ -615,7 +818,6 @@ open class Account: Service { nestedType: [String: AnyCodable].self ) } - /// /// Delete an authenticator for a user by ID. /// @@ -635,16 +837,16 @@ open class Account: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "content-type": "application/json" + "content-type": "application/json", ] return try await client.call( method: "DELETE", path: apiPath, headers: apiHeaders, - params: apiParams ) + params: apiParams + ) } - /// /// Delete an authenticator for a user by ID. /// @@ -663,16 +865,16 @@ open class Account: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "content-type": "application/json" + "content-type": "application/json", ] return try await client.call( method: "DELETE", path: apiPath, headers: apiHeaders, - params: apiParams ) + params: apiParams + ) } - /// /// Begin the process of MFA verification after sign-in. Finish the flow with /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) @@ -696,7 +898,7 @@ open class Account: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.MfaChallenge = { response in @@ -711,7 +913,6 @@ open class Account: Service { converter: converter ) } - /// /// Begin the process of MFA verification after sign-in. Finish the flow with /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) @@ -734,7 +935,7 @@ open class Account: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.MfaChallenge = { response in @@ -749,7 +950,6 @@ open class Account: Service { converter: converter ) } - /// /// Complete the MFA challenge by providing the one-time password. Finish the /// process of MFA verification by providing the one-time password. To begin @@ -772,13 +972,13 @@ open class Account: Service { let apiParams: [String: Any?] = [ "challengeId": challengeId, - "otp": otp + "otp": otp, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Session = { response in @@ -793,7 +993,6 @@ open class Account: Service { converter: converter ) } - /// /// Complete the MFA challenge by providing the one-time password. Finish the /// process of MFA verification by providing the one-time password. To begin @@ -815,13 +1014,13 @@ open class Account: Service { let apiParams: [String: Any?] = [ "challengeId": challengeId, - "otp": otp + "otp": otp, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Session = { response in @@ -836,7 +1035,6 @@ open class Account: Service { converter: converter ) } - /// /// List the factors available on the account to be used as a MFA challange. /// @@ -844,15 +1042,14 @@ open class Account: Service { /// - Returns: AppwriteModels.MfaFactors /// @available(*, deprecated, message: "This API has been deprecated since 1.8.0. Please use `Account.listMFAFactors` instead.") - open func listMfaFactors( - ) async throws -> AppwriteModels.MfaFactors { + open func listMfaFactors() async throws -> AppwriteModels.MfaFactors { let apiPath: String = "/account/mfa/factors" let apiParams: [String: Any] = [:] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.MfaFactors = { response in @@ -867,22 +1064,20 @@ open class Account: Service { converter: converter ) } - /// /// List the factors available on the account to be used as a MFA challange. /// /// - Throws: Exception if the request fails /// - Returns: AppwriteModels.MfaFactors /// - open func listMFAFactors( - ) async throws -> AppwriteModels.MfaFactors { + open func listMFAFactors() async throws -> AppwriteModels.MfaFactors { let apiPath: String = "/account/mfa/factors" let apiParams: [String: Any] = [:] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.MfaFactors = { response in @@ -897,7 +1092,6 @@ open class Account: Service { converter: converter ) } - /// /// Get recovery codes that can be used as backup for MFA flow. Before getting /// codes, they must be generated using @@ -908,15 +1102,14 @@ open class Account: Service { /// - Returns: AppwriteModels.MfaRecoveryCodes /// @available(*, deprecated, message: "This API has been deprecated since 1.8.0. Please use `Account.getMFARecoveryCodes` instead.") - open func getMfaRecoveryCodes( - ) async throws -> AppwriteModels.MfaRecoveryCodes { + open func getMfaRecoveryCodes() async throws -> AppwriteModels.MfaRecoveryCodes { let apiPath: String = "/account/mfa/recovery-codes" let apiParams: [String: Any] = [:] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.MfaRecoveryCodes = { response in @@ -931,7 +1124,6 @@ open class Account: Service { converter: converter ) } - /// /// Get recovery codes that can be used as backup for MFA flow. Before getting /// codes, they must be generated using @@ -941,15 +1133,14 @@ open class Account: Service { /// - Throws: Exception if the request fails /// - Returns: AppwriteModels.MfaRecoveryCodes /// - open func getMFARecoveryCodes( - ) async throws -> AppwriteModels.MfaRecoveryCodes { + open func getMFARecoveryCodes() async throws -> AppwriteModels.MfaRecoveryCodes { let apiPath: String = "/account/mfa/recovery-codes" let apiParams: [String: Any] = [:] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.MfaRecoveryCodes = { response in @@ -964,7 +1155,6 @@ open class Account: Service { converter: converter ) } - /// /// Generate recovery codes as backup for MFA flow. It's recommended to /// generate and show then immediately after user successfully adds their @@ -976,8 +1166,7 @@ open class Account: Service { /// - Returns: AppwriteModels.MfaRecoveryCodes /// @available(*, deprecated, message: "This API has been deprecated since 1.8.0. Please use `Account.createMFARecoveryCodes` instead.") - open func createMfaRecoveryCodes( - ) async throws -> AppwriteModels.MfaRecoveryCodes { + open func createMfaRecoveryCodes() async throws -> AppwriteModels.MfaRecoveryCodes { let apiPath: String = "/account/mfa/recovery-codes" let apiParams: [String: Any] = [:] @@ -985,7 +1174,7 @@ open class Account: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.MfaRecoveryCodes = { response in @@ -1000,7 +1189,6 @@ open class Account: Service { converter: converter ) } - /// /// Generate recovery codes as backup for MFA flow. It's recommended to /// generate and show then immediately after user successfully adds their @@ -1011,8 +1199,7 @@ open class Account: Service { /// - Throws: Exception if the request fails /// - Returns: AppwriteModels.MfaRecoveryCodes /// - open func createMFARecoveryCodes( - ) async throws -> AppwriteModels.MfaRecoveryCodes { + open func createMFARecoveryCodes() async throws -> AppwriteModels.MfaRecoveryCodes { let apiPath: String = "/account/mfa/recovery-codes" let apiParams: [String: Any] = [:] @@ -1020,7 +1207,7 @@ open class Account: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.MfaRecoveryCodes = { response in @@ -1035,7 +1222,6 @@ open class Account: Service { converter: converter ) } - /// /// Regenerate recovery codes that can be used as backup for MFA flow. Before /// regenerating codes, they must be first generated using @@ -1046,8 +1232,7 @@ open class Account: Service { /// - Returns: AppwriteModels.MfaRecoveryCodes /// @available(*, deprecated, message: "This API has been deprecated since 1.8.0. Please use `Account.updateMFARecoveryCodes` instead.") - open func updateMfaRecoveryCodes( - ) async throws -> AppwriteModels.MfaRecoveryCodes { + open func updateMfaRecoveryCodes() async throws -> AppwriteModels.MfaRecoveryCodes { let apiPath: String = "/account/mfa/recovery-codes" let apiParams: [String: Any] = [:] @@ -1055,7 +1240,7 @@ open class Account: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.MfaRecoveryCodes = { response in @@ -1070,7 +1255,6 @@ open class Account: Service { converter: converter ) } - /// /// Regenerate recovery codes that can be used as backup for MFA flow. Before /// regenerating codes, they must be first generated using @@ -1080,8 +1264,7 @@ open class Account: Service { /// - Throws: Exception if the request fails /// - Returns: AppwriteModels.MfaRecoveryCodes /// - open func updateMFARecoveryCodes( - ) async throws -> AppwriteModels.MfaRecoveryCodes { + open func updateMFARecoveryCodes() async throws -> AppwriteModels.MfaRecoveryCodes { let apiPath: String = "/account/mfa/recovery-codes" let apiParams: [String: Any] = [:] @@ -1089,7 +1272,7 @@ open class Account: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.MfaRecoveryCodes = { response in @@ -1104,7 +1287,6 @@ open class Account: Service { converter: converter ) } - /// /// Update currently logged in user account name. /// @@ -1126,7 +1308,7 @@ open class Account: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.User = { response in @@ -1158,7 +1340,6 @@ open class Account: Service { nestedType: [String: AnyCodable].self ) } - /// /// Update currently logged in user password. For validation, user is required /// to pass in the new password, and the old password. For users created with @@ -1179,13 +1360,13 @@ open class Account: Service { let apiParams: [String: Any?] = [ "password": password, - "oldPassword": oldPassword + "oldPassword": oldPassword, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.User = { response in @@ -1222,7 +1403,6 @@ open class Account: Service { nestedType: [String: AnyCodable].self ) } - /// /// Update the currently logged in user's phone number. After updating the /// phone number, the phone verification status will be reset. A confirmation @@ -1245,13 +1425,13 @@ open class Account: Service { let apiParams: [String: Any?] = [ "phone": phone, - "password": password + "password": password, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.User = { response in @@ -1290,7 +1470,6 @@ open class Account: Service { nestedType: [String: AnyCodable].self ) } - /// /// Get the preferences as a key-value object for the currently logged in user. /// @@ -1306,7 +1485,7 @@ open class Account: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Preferences = { response in @@ -1328,13 +1507,11 @@ open class Account: Service { /// - Throws: Exception if the request fails /// - Returns: AppwriteModels.Preferences /// - open func getPrefs( - ) async throws -> AppwriteModels.Preferences<[String: AnyCodable]> { + open func getPrefs() async throws -> AppwriteModels.Preferences<[String: AnyCodable]> { return try await getPrefs( nestedType: [String: AnyCodable].self ) } - /// /// Update currently logged in user account preferences. The object you pass is /// stored as is, and replaces any previous value. The maximum allowed prefs @@ -1358,7 +1535,7 @@ open class Account: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.User = { response in @@ -1392,7 +1569,6 @@ open class Account: Service { nestedType: [String: AnyCodable].self ) } - /// /// Sends the user an email with a temporary secret key for password reset. /// When the user clicks the confirmation link he is redirected back to your @@ -1417,13 +1593,13 @@ open class Account: Service { let apiParams: [String: Any?] = [ "email": email, - "url": url + "url": url, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Token = { response in @@ -1438,14 +1614,13 @@ open class Account: Service { converter: converter ) } - /// /// Use this endpoint to complete the user account password reset. Both the /// **userId** and **secret** arguments will be passed as query parameters to /// the redirect URL you have provided when sending your request to the [POST /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) /// endpoint. - /// + /// /// Please note that in order to avoid a [Redirect /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) /// the only valid redirect URLs are the ones from domains you have set when @@ -1468,13 +1643,13 @@ open class Account: Service { let apiParams: [String: Any?] = [ "userId": userId, "secret": secret, - "password": password + "password": password, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Token = { response in @@ -1489,7 +1664,6 @@ open class Account: Service { converter: converter ) } - /// /// Get the list of active sessions across different devices for the currently /// logged in user. @@ -1497,15 +1671,14 @@ open class Account: Service { /// - Throws: Exception if the request fails /// - Returns: AppwriteModels.SessionList /// - open func listSessions( - ) async throws -> AppwriteModels.SessionList { + open func listSessions() async throws -> AppwriteModels.SessionList { let apiPath: String = "/account/sessions" let apiParams: [String: Any] = [:] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.SessionList = { response in @@ -1520,7 +1693,6 @@ open class Account: Service { converter: converter ) } - /// /// Delete all sessions from the user account and remove any sessions cookies /// from the end client. @@ -1528,24 +1700,23 @@ open class Account: Service { /// - Throws: Exception if the request fails /// - Returns: Any /// - open func deleteSessions( - ) async throws -> Any { + open func deleteSessions() async throws -> Any { let apiPath: String = "/account/sessions" let apiParams: [String: Any] = [:] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "content-type": "application/json" + "content-type": "application/json", ] return try await client.call( method: "DELETE", path: apiPath, headers: apiHeaders, - params: apiParams ) + params: apiParams + ) } - /// /// Use this endpoint to allow a new user to register an anonymous account in /// your project. This route will also create a new session for the user. To @@ -1558,8 +1729,7 @@ open class Account: Service { /// - Throws: Exception if the request fails /// - Returns: AppwriteModels.Session /// - open func createAnonymousSession( - ) async throws -> AppwriteModels.Session { + open func createAnonymousSession() async throws -> AppwriteModels.Session { let apiPath: String = "/account/sessions/anonymous" let apiParams: [String: Any] = [:] @@ -1567,7 +1737,7 @@ open class Account: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Session = { response in @@ -1582,11 +1752,10 @@ open class Account: Service { converter: converter ) } - /// /// Allow the user to login into their account by providing a valid email and /// password combination. This route will create a new session for the user. - /// + /// /// A user is limited to 10 active sessions at a time by default. [Learn more /// about session /// limits](https://appwrite.io/docs/authentication-security#limits). @@ -1605,13 +1774,13 @@ open class Account: Service { let apiParams: [String: Any?] = [ "email": email, - "password": password + "password": password, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Session = { response in @@ -1626,7 +1795,6 @@ open class Account: Service { converter: converter ) } - /// /// Use this endpoint to create a session from token. Provide the **userId** /// and **secret** parameters from the successful response of authentication @@ -1647,13 +1815,13 @@ open class Account: Service { let apiParams: [String: Any?] = [ "userId": userId, - "secret": secret + "secret": secret, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Session = { response in @@ -1668,24 +1836,22 @@ open class Account: Service { converter: converter ) } - /// /// Allow the user to login to their account using the OAuth2 provider of their /// choice. Each OAuth2 provider should be enabled from the Appwrite console /// first. Use the success and failure arguments to provide a redirect URL's /// back to your app when login is completed. - /// + /// /// If there is already an active session, the new session will be attached to /// the logged-in account. If there are no active sessions, the server will /// attempt to look for a user with the same email address as the email /// received from the OAuth2 provider and attach the new session to the /// existing user. If no matching user is found - the server will create a new /// user. - /// + /// /// A user is limited to 10 active sessions at a time by default. [Learn more /// about session /// limits](https://appwrite.io/docs/authentication-security#limits). - /// /// /// - Parameters: /// - provider: AppwriteEnums.OAuthProvider @@ -1709,7 +1875,12 @@ open class Account: Service { "success": success, "failure": failure, "scopes": scopes, - "project": client.config["project"] + "project": client.config["project"], + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "accept": "text/html", ] let query = "?\(client.parametersToQueryString(params: apiParams))" @@ -1728,7 +1899,6 @@ open class Account: Service { return true } - /// /// Use this endpoint to create a session from token. Provide the **userId** /// and **secret** parameters from the successful response of authentication @@ -1749,13 +1919,13 @@ open class Account: Service { let apiParams: [String: Any?] = [ "userId": userId, - "secret": secret + "secret": secret, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Session = { response in @@ -1770,7 +1940,6 @@ open class Account: Service { converter: converter ) } - /// /// Use this endpoint to create a session from token. Provide the **userId** /// and **secret** parameters from the successful response of authentication @@ -1790,13 +1959,13 @@ open class Account: Service { let apiParams: [String: Any?] = [ "userId": userId, - "secret": secret + "secret": secret, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Session = { response in @@ -1811,7 +1980,6 @@ open class Account: Service { converter: converter ) } - /// /// Use this endpoint to get a logged in user's session using a Session ID. /// Inputting 'current' will return the current session being used. @@ -1831,7 +1999,7 @@ open class Account: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Session = { response in @@ -1846,7 +2014,6 @@ open class Account: Service { converter: converter ) } - /// /// Use this endpoint to extend a session's length. Extending a session is /// useful when session expiry is short. If the session was created using an @@ -1868,7 +2035,7 @@ open class Account: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Session = { response in @@ -1883,7 +2050,6 @@ open class Account: Service { converter: converter ) } - /// /// Logout the user. Use 'current' as the session ID to logout on this device, /// use a session ID to logout on another device. If you're looking to logout @@ -1906,16 +2072,16 @@ open class Account: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "content-type": "application/json" + "content-type": "application/json", ] return try await client.call( method: "DELETE", path: apiPath, headers: apiHeaders, - params: apiParams ) + params: apiParams + ) } - /// /// Block the currently logged in user account. Behind the scene, the user /// record is not deleted but permanently blocked from any access. To @@ -1934,7 +2100,7 @@ open class Account: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.User = { response in @@ -1958,13 +2124,11 @@ open class Account: Service { /// - Throws: Exception if the request fails /// - Returns: AppwriteModels.User /// - open func updateStatus( - ) async throws -> AppwriteModels.User<[String: AnyCodable]> { + open func updateStatus() async throws -> AppwriteModels.User<[String: AnyCodable]> { return try await updateStatus( nestedType: [String: AnyCodable].self ) } - /// /// Use this endpoint to register a device for push notifications. Provide a /// target ID (custom or generated using ID.unique()), a device identifier @@ -1989,13 +2153,13 @@ open class Account: Service { let apiParams: [String: Any?] = [ "targetId": targetId, "identifier": identifier, - "providerId": providerId + "providerId": providerId, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Target = { response in @@ -2010,7 +2174,6 @@ open class Account: Service { converter: converter ) } - /// /// Update the currently logged in user's push notification target. You can /// modify the target's identifier (device token) and provider ID (token, @@ -2038,7 +2201,7 @@ open class Account: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Target = { response in @@ -2053,7 +2216,6 @@ open class Account: Service { converter: converter ) } - /// /// Delete a push notification target for the currently logged in user. After /// deletion, the device will no longer receive push notifications. The target @@ -2074,16 +2236,16 @@ open class Account: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "content-type": "application/json" + "content-type": "application/json", ] return try await client.call( method: "DELETE", path: apiPath, headers: apiHeaders, - params: apiParams ) + params: apiParams + ) } - /// /// Sends the user an email with a secret key for creating a session. If the /// email address has never been used, a **new account is created** using the @@ -2094,11 +2256,10 @@ open class Account: Service { /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) /// endpoint to complete the login process. The secret sent to the user's email /// is valid for 15 minutes. - /// + /// /// A user is limited to 10 active sessions at a time by default. [Learn more /// about session /// limits](https://appwrite.io/docs/authentication-security#limits). - /// /// /// - Parameters: /// - userId: String @@ -2117,13 +2278,13 @@ open class Account: Service { let apiParams: [String: Any?] = [ "userId": userId, "email": email, - "phrase": phrase + "phrase": phrase, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Token = { response in @@ -2138,7 +2299,6 @@ open class Account: Service { converter: converter ) } - /// /// Sends the user an email with a secret key for creating a session. If the /// provided user ID has not been registered, a new user will be created. When @@ -2149,11 +2309,10 @@ open class Account: Service { /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) /// endpoint to complete the login process. The link sent to the user's email /// address is valid for 1 hour. - /// + /// /// A user is limited to 10 active sessions at a time by default. [Learn more /// about session /// limits](https://appwrite.io/docs/authentication-security#limits). - /// /// /// - Parameters: /// - userId: String @@ -2175,13 +2334,13 @@ open class Account: Service { "userId": userId, "email": email, "url": url, - "phrase": phrase + "phrase": phrase, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Token = { response in @@ -2196,19 +2355,18 @@ open class Account: Service { converter: converter ) } - /// /// Allow the user to login to their account using the OAuth2 provider of their /// choice. Each OAuth2 provider should be enabled from the Appwrite console /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// + /// back to your app when login is completed. + /// /// If authentication succeeds, `userId` and `secret` of a token will be /// appended to the success URL as query parameters. These can be used to /// create a new session using the [Create /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) /// endpoint. - /// + /// /// A user is limited to 10 active sessions at a time by default. [Learn more /// about session /// limits](https://appwrite.io/docs/authentication-security#limits). @@ -2235,7 +2393,12 @@ open class Account: Service { "success": success, "failure": failure, "scopes": scopes, - "project": client.config["project"] + "project": client.config["project"], + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "accept": "text/html", ] let query = "?\(client.parametersToQueryString(params: apiParams))" @@ -2254,7 +2417,6 @@ open class Account: Service { return true } - /// /// Sends the user an SMS with a secret key for creating a session. If the /// provided user ID has not be registered, a new user will be created. Use the @@ -2262,7 +2424,7 @@ open class Account: Service { /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) /// endpoint to complete the login process. The secret sent to the user's phone /// is valid for 15 minutes. - /// + /// /// A user is limited to 10 active sessions at a time by default. [Learn more /// about session /// limits](https://appwrite.io/docs/authentication-security#limits). @@ -2281,13 +2443,13 @@ open class Account: Service { let apiParams: [String: Any?] = [ "userId": userId, - "phone": phone + "phone": phone, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Token = { response in @@ -2302,7 +2464,6 @@ open class Account: Service { converter: converter ) } - /// /// Use this endpoint to send a verification message to your user email address /// to confirm they are the valid owners of that address. Both the **userId** @@ -2313,12 +2474,11 @@ open class Account: Service { /// parameters. Learn more about how to [complete the verification /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). /// The verification link sent to the user's email address is valid for 7 days. - /// + /// /// Please note that in order to avoid a [Redirect /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), /// the only valid redirect URLs are the ones from domains you have set when /// adding your platforms in the console interface. - /// /// /// - Parameters: /// - url: String @@ -2337,7 +2497,7 @@ open class Account: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Token = { response in @@ -2352,7 +2512,6 @@ open class Account: Service { converter: converter ) } - /// /// Use this endpoint to send a verification message to your user email address /// to confirm they are the valid owners of that address. Both the **userId** @@ -2363,12 +2522,11 @@ open class Account: Service { /// parameters. Learn more about how to [complete the verification /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). /// The verification link sent to the user's email address is valid for 7 days. - /// + /// /// Please note that in order to avoid a [Redirect /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), /// the only valid redirect URLs are the ones from domains you have set when /// adding your platforms in the console interface. - /// /// /// - Parameters: /// - url: String @@ -2388,7 +2546,7 @@ open class Account: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Token = { response in @@ -2403,7 +2561,6 @@ open class Account: Service { converter: converter ) } - /// /// Use this endpoint to complete the user email verification process. Use both /// the **userId** and **secret** parameters that were attached to your app URL @@ -2424,13 +2581,13 @@ open class Account: Service { let apiParams: [String: Any?] = [ "userId": userId, - "secret": secret + "secret": secret, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Token = { response in @@ -2445,7 +2602,6 @@ open class Account: Service { converter: converter ) } - /// /// Use this endpoint to complete the user email verification process. Use both /// the **userId** and **secret** parameters that were attached to your app URL @@ -2467,13 +2623,13 @@ open class Account: Service { let apiParams: [String: Any?] = [ "userId": userId, - "secret": secret + "secret": secret, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Token = { response in @@ -2488,7 +2644,6 @@ open class Account: Service { converter: converter ) } - /// /// Use this endpoint to send a verification SMS to the currently logged in /// user. This endpoint is meant for use after updating a user's phone number @@ -2502,8 +2657,7 @@ open class Account: Service { /// - Throws: Exception if the request fails /// - Returns: AppwriteModels.Token /// - open func createPhoneVerification( - ) async throws -> AppwriteModels.Token { + open func createPhoneVerification() async throws -> AppwriteModels.Token { let apiPath: String = "/account/verifications/phone" let apiParams: [String: Any] = [:] @@ -2511,7 +2665,7 @@ open class Account: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Token = { response in @@ -2526,7 +2680,6 @@ open class Account: Service { converter: converter ) } - /// /// Use this endpoint to complete the user phone verification process. Use the /// **userId** and **secret** that were sent to your user's phone number to @@ -2547,13 +2700,13 @@ open class Account: Service { let apiParams: [String: Any?] = [ "userId": userId, - "secret": secret + "secret": secret, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Token = { response in @@ -2568,6 +2721,4 @@ open class Account: Service { converter: converter ) } - - } diff --git a/Sources/Appwrite/Services/Avatars.swift b/Sources/Appwrite/Services/Avatars.swift index 94bfcca..da535c3 100644 --- a/Sources/Appwrite/Services/Avatars.swift +++ b/Sources/Appwrite/Services/Avatars.swift @@ -1,9 +1,9 @@ -import AsyncHTTPClient -import Foundation -import NIO -import JSONCodable import AppwriteEnums import AppwriteModels +import AsyncHTTPClient +import Foundation +import JSONCodable +import NIO /// The Avatars service aims to help you complete everyday tasks related to your app image, icons, and avatars. open class Avatars: Service { @@ -14,7 +14,7 @@ open class Avatars: Service { /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) /// endpoint. Use width, height and quality arguments to change the output /// settings. - /// + /// /// When one dimension is specified and the other is 0, the image is scaled /// with preserved aspect ratio. If both dimensions are 0, the API provides an /// image at source quality. If dimensions are not specified, the default size @@ -41,27 +41,29 @@ open class Avatars: Service { "width": width, "height": height, "quality": quality, - "project": client.config["project"], - "impersonateuserid": client.config["impersonateuserid"] + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "accept": "image/png", ] return try await client.call( method: "GET", path: apiPath, + headers: apiHeaders, params: apiParams ) } - /// /// The credit card endpoint will return you the icon of the credit card /// provider you need. Use width, height and quality arguments to change the /// output settings. - /// + /// /// When one dimension is specified and the other is 0, the image is scaled /// with preserved aspect ratio. If both dimensions are 0, the API provides an /// image at source quality. If dimensions are not specified, the default size /// of image returned is 100x100px. - /// /// /// - Parameters: /// - code: AppwriteEnums.CreditCard @@ -84,21 +86,24 @@ open class Avatars: Service { "width": width, "height": height, "quality": quality, - "project": client.config["project"], - "impersonateuserid": client.config["impersonateuserid"] + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "accept": "image/png", ] return try await client.call( method: "GET", path: apiPath, + headers: apiHeaders, params: apiParams ) } - /// /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote /// website URL. - /// + /// /// This endpoint does not follow HTTP redirects. /// /// - Parameters: @@ -112,29 +117,31 @@ open class Avatars: Service { let apiPath: String = "/avatars/favicon" let apiParams: [String: Any?] = [ - "url": url, - "project": client.config["project"], - "impersonateuserid": client.config["impersonateuserid"] + "url": url + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "accept": "image/*", ] return try await client.call( method: "GET", path: apiPath, + headers: apiHeaders, params: apiParams ) } - /// /// You can use this endpoint to show different country flags icons to your /// users. The code argument receives the 2 letter country code. Use width, /// height and quality arguments to change the output settings. Country codes /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. - /// + /// /// When one dimension is specified and the other is 0, the image is scaled /// with preserved aspect ratio. If both dimensions are 0, the API provides an /// image at source quality. If dimensions are not specified, the default size /// of image returned is 100x100px. - /// /// /// - Parameters: /// - code: AppwriteEnums.Flag @@ -157,28 +164,31 @@ open class Avatars: Service { "width": width, "height": height, "quality": quality, - "project": client.config["project"], - "impersonateuserid": client.config["impersonateuserid"] + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "accept": "image/png", ] return try await client.call( method: "GET", path: apiPath, + headers: apiHeaders, params: apiParams ) } - /// /// Use this endpoint to fetch a remote image URL and crop it to any image size /// you want. This endpoint is very useful if you need to crop and display /// remote images in your app or in case you want to make sure a 3rd party /// image is properly served using a TLS protocol. - /// + /// /// When one dimension is specified and the other is 0, the image is scaled /// with preserved aspect ratio. If both dimensions are 0, the API provides an /// image at source quality. If dimensions are not specified, the default size /// of image returned is 400x400px. - /// + /// /// This endpoint does not follow HTTP redirects. /// /// - Parameters: @@ -199,34 +209,36 @@ open class Avatars: Service { "url": url, "width": width, "height": height, - "project": client.config["project"], - "impersonateuserid": client.config["impersonateuserid"] + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "accept": "image/*", ] return try await client.call( method: "GET", path: apiPath, + headers: apiHeaders, params: apiParams ) } - /// /// Use this endpoint to show your user initials avatar icon on your website or /// app. By default, this route will try to print your logged-in user name or /// email initials. You can also overwrite the user name if you pass the 'name' /// parameter. If no name is given and no user is logged, an empty avatar will /// be returned. - /// + /// /// You can use the color and background params to change the avatar colors. By /// default, a random theme will be selected. The random theme will persist for /// the user's initials when reloading the same theme will always return for /// the same initials. - /// + /// /// When one dimension is specified and the other is 0, the image is scaled /// with preserved aspect ratio. If both dimensions are 0, the API provides an /// image at source quality. If dimensions are not specified, the default size /// of image returned is 100x100px. - /// /// /// - Parameters: /// - name: String (optional) @@ -249,21 +261,87 @@ open class Avatars: Service { "width": width, "height": height, "background": background, - "project": client.config["project"], - "impersonateuserid": client.config["impersonateuserid"] + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "accept": "image/png", ] return try await client.call( method: "GET", path: apiPath, + headers: apiHeaders, params: apiParams ) } + /// + /// Returns the best available profile photo for a user. The endpoint tries + /// each source in priority order and returns the first successful result: + /// OAuth2 identity photo, Gravatar, Libravatar, Appwrite Initials, built-in + /// static fallback. + /// + /// Passing `userId` — `current()` for the authenticated user — resolves + /// the photo from everything known about that user: identity photos, email, + /// and name. An explicit `emailHash` or `name` then overrides just that value, + /// and the user's remaining sources stay in the chain. Without `userId`, + /// passing `emailHash` and/or `name` resolves the avatar from those values + /// alone: the hash is looked up on Gravatar and Libravatar, the name is + /// rendered as initials, and the session user stays out of the chain so their + /// own photo never shadows the avatar being asked for. When nothing is passed, + /// the photo resolves for the currently authenticated user. Emails are only + /// ever accepted pre-hashed, so no address ends up in a URL. + /// + /// - Parameters: + /// - width: Int (optional) + /// - height: Int (optional) + /// - quality: Int (optional) + /// - output: String (optional) + /// - rating: String (optional) + /// - userId: String (optional) + /// - emailHash: String (optional) + /// - name: String (optional) + /// - Throws: Exception if the request fails + /// - Returns: ByteBuffer + /// + open func getPhoto( + width: Int? = nil, + height: Int? = nil, + quality: Int? = nil, + output: String? = nil, + rating: String? = nil, + userId: String? = nil, + emailHash: String? = nil, + name: String? = nil + ) async throws -> ByteBuffer { + let apiPath: String = "/avatars/photo" + let apiParams: [String: Any?] = [ + "width": width, + "height": height, + "quality": quality, + "output": output, + "rating": rating, + "userId": userId, + "emailHash": emailHash, + "name": name, + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "accept": "image/*", + ] + + return try await client.call( + method: "GET", + path: apiPath, + headers: apiHeaders, + params: apiParams + ) + } /// /// Converts a given plain text to a QR code image. You can use the query /// parameters to change the size and style of the resulting image. - /// /// /// - Parameters: /// - text: String @@ -286,25 +364,28 @@ open class Avatars: Service { "size": size, "margin": margin, "download": download, - "project": client.config["project"], - "impersonateuserid": client.config["impersonateuserid"] + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "accept": "image/png", ] return try await client.call( method: "GET", path: apiPath, + headers: apiHeaders, params: apiParams ) } - /// /// Use this endpoint to capture a screenshot of any website URL. This endpoint /// uses a headless browser to render the webpage and capture it as an image. - /// + /// /// You can configure the browser viewport size, theme, user agent, /// geolocation, permissions, and more. Capture either just the viewport or the /// full page scroll. - /// + /// /// When width and height are specified, the image is resized accordingly. If /// both dimensions are 0, the API provides an image at original size. If /// dimensions are not specified, the default viewport size is 1280x720px. @@ -378,16 +459,18 @@ open class Avatars: Service { "height": height, "quality": quality, "output": output?.rawValue, - "project": client.config["project"], - "impersonateuserid": client.config["impersonateuserid"] + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "accept": "image/png", ] return try await client.call( method: "GET", path: apiPath, + headers: apiHeaders, params: apiParams ) } - - } diff --git a/Sources/Appwrite/Services/Databases.swift b/Sources/Appwrite/Services/Databases.swift index 84f013c..aa8aa87 100644 --- a/Sources/Appwrite/Services/Databases.swift +++ b/Sources/Appwrite/Services/Databases.swift @@ -1,9 +1,9 @@ -import AsyncHTTPClient -import Foundation -import NIO -import JSONCodable import AppwriteEnums import AppwriteModels +import AsyncHTTPClient +import Foundation +import JSONCodable +import NIO /// The Databases service allows you to create structured collections of documents, query and filter lists of documents open class Databases: Service { @@ -28,7 +28,7 @@ open class Databases: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.TransactionList = { response in @@ -43,7 +43,6 @@ open class Databases: Service { converter: converter ) } - /// /// Create a new transaction. /// @@ -65,7 +64,7 @@ open class Databases: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Transaction = { response in @@ -80,7 +79,6 @@ open class Databases: Service { converter: converter ) } - /// /// Get a transaction by its unique ID. /// @@ -100,7 +98,7 @@ open class Databases: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Transaction = { response in @@ -115,7 +113,6 @@ open class Databases: Service { converter: converter ) } - /// /// Update a transaction, to either commit or roll back its operations. /// @@ -137,13 +134,13 @@ open class Databases: Service { let apiParams: [String: Any?] = [ "commit": commit, - "rollback": rollback + "rollback": rollback, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Transaction = { response in @@ -158,7 +155,6 @@ open class Databases: Service { converter: converter ) } - /// /// Delete a transaction by its unique ID. /// @@ -178,29 +174,29 @@ open class Databases: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "content-type": "application/json" + "content-type": "application/json", ] return try await client.call( method: "DELETE", path: apiPath, headers: apiHeaders, - params: apiParams ) + params: apiParams + ) } - /// /// Create multiple operations in a single transaction. /// /// - Parameters: /// - transactionId: String - /// - operations: [Any] (optional) + /// - operations: [AnyCodable] (optional) /// - Throws: Exception if the request fails /// - Returns: AppwriteModels.Transaction /// @available(*, deprecated, message: "This API has been deprecated since 1.8.0. Please use `TablesDB.createOperations` instead.") open func createOperations( transactionId: String, - operations: [Any]? = nil + operations: [AnyCodable]? = nil ) async throws -> AppwriteModels.Transaction { let apiPath: String = "/databases/transactions/{transactionId}/operations" .replacingOccurrences(of: "{transactionId}", with: transactionId) @@ -212,7 +208,7 @@ open class Databases: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Transaction = { response in @@ -227,7 +223,6 @@ open class Databases: Service { converter: converter ) } - /// /// Get a list of all the user's documents in a given collection. You can use /// the query params to filter your results. @@ -260,12 +255,12 @@ open class Databases: Service { "queries": queries, "transactionId": transactionId, "total": total, - "ttl": ttl + "ttl": ttl, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.DocumentList = { response in @@ -314,7 +309,6 @@ open class Databases: Service { nestedType: [String: AnyCodable].self ) } - /// /// Create a new Document. Before using this route, you should create a new /// collection resource using either a [server @@ -349,13 +343,13 @@ open class Databases: Service { "documentId": documentId, "data": data, "permissions": permissions, - "transactionId": transactionId + "transactionId": transactionId, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Document = { response in @@ -406,7 +400,6 @@ open class Databases: Service { nestedType: [String: AnyCodable].self ) } - /// /// Get a document by its unique ID. This endpoint response returns a JSON /// object with the document data. @@ -436,12 +429,12 @@ open class Databases: Service { let apiParams: [String: Any?] = [ "queries": queries, - "transactionId": transactionId + "transactionId": transactionId, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Document = { response in @@ -487,7 +480,6 @@ open class Databases: Service { nestedType: [String: AnyCodable].self ) } - /// /// Create or update a Document. Before using this route, you should create a /// new collection resource using either a [server @@ -522,13 +514,13 @@ open class Databases: Service { let apiParams: [String: Any?] = [ "data": data, "permissions": permissions, - "transactionId": transactionId + "transactionId": transactionId, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Document = { response in @@ -579,7 +571,6 @@ open class Databases: Service { nestedType: [String: AnyCodable].self ) } - /// /// Update a document by its unique ID. Using the patch method you can pass /// only specific fields that will get updated. @@ -612,13 +603,13 @@ open class Databases: Service { let apiParams: [String: Any?] = [ "data": data, "permissions": permissions, - "transactionId": transactionId + "transactionId": transactionId, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Document = { response in @@ -667,7 +658,6 @@ open class Databases: Service { nestedType: [String: AnyCodable].self ) } - /// /// Delete a document by its unique ID. /// @@ -697,16 +687,16 @@ open class Databases: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "content-type": "application/json" + "content-type": "application/json", ] return try await client.call( method: "DELETE", path: apiPath, headers: apiHeaders, - params: apiParams ) + params: apiParams + ) } - /// /// Decrement a specific attribute of a document by a given value. /// @@ -741,13 +731,13 @@ open class Databases: Service { let apiParams: [String: Any?] = [ "value": value, "min": min, - "transactionId": transactionId + "transactionId": transactionId, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Document = { response in @@ -798,7 +788,6 @@ open class Databases: Service { nestedType: [String: AnyCodable].self ) } - /// /// Increment a specific attribute of a document by a given value. /// @@ -833,13 +822,13 @@ open class Databases: Service { let apiParams: [String: Any?] = [ "value": value, "max": max, - "transactionId": transactionId + "transactionId": transactionId, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Document = { response in @@ -890,6 +879,4 @@ open class Databases: Service { nestedType: [String: AnyCodable].self ) } - - } diff --git a/Sources/Appwrite/Services/DocumentsDB.swift b/Sources/Appwrite/Services/DocumentsDB.swift new file mode 100644 index 0000000..2abc87a --- /dev/null +++ b/Sources/Appwrite/Services/DocumentsDB.swift @@ -0,0 +1,938 @@ +import AppwriteEnums +import AppwriteModels +import AsyncHTTPClient +import Foundation +import JSONCodable +import NIO + +/// +open class DocumentsDB: Service { + + /// + /// List transactions across all databases. + /// + /// - Parameters: + /// - queries: [String] (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.TransactionList + /// + open func listTransactions( + queries: [String]? = nil + ) async throws -> AppwriteModels.TransactionList { + let apiPath: String = "/documentsdb/transactions" + + let apiParams: [String: Any?] = [ + "queries": queries + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "accept": "application/json", + ] + + let converter: (Any) throws -> AppwriteModels.TransactionList = { response in + return AppwriteModels.TransactionList.from(map: response as! [String: Any]) + } + + return try await client.call( + method: "GET", + path: apiPath, + headers: apiHeaders, + params: apiParams, + converter: converter + ) + } + /// + /// Create a new transaction. + /// + /// - Parameters: + /// - ttl: Int (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.Transaction + /// + open func createTransaction( + ttl: Int? = nil + ) async throws -> AppwriteModels.Transaction { + let apiPath: String = "/documentsdb/transactions" + + let apiParams: [String: Any?] = [ + "ttl": ttl + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "content-type": "application/json", + "accept": "application/json", + ] + + let converter: (Any) throws -> AppwriteModels.Transaction = { response in + return AppwriteModels.Transaction.from(map: response as! [String: Any]) + } + + return try await client.call( + method: "POST", + path: apiPath, + headers: apiHeaders, + params: apiParams, + converter: converter + ) + } + /// + /// Get a transaction by its unique ID. + /// + /// - Parameters: + /// - transactionId: String + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.Transaction + /// + open func getTransaction( + transactionId: String + ) async throws -> AppwriteModels.Transaction { + let apiPath: String = "/documentsdb/transactions/{transactionId}" + .replacingOccurrences(of: "{transactionId}", with: transactionId) + + let apiParams: [String: Any] = [:] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "accept": "application/json", + ] + + let converter: (Any) throws -> AppwriteModels.Transaction = { response in + return AppwriteModels.Transaction.from(map: response as! [String: Any]) + } + + return try await client.call( + method: "GET", + path: apiPath, + headers: apiHeaders, + params: apiParams, + converter: converter + ) + } + /// + /// Update a transaction, to either commit or roll back its operations. + /// + /// - Parameters: + /// - transactionId: String + /// - commit: Bool (optional) + /// - rollback: Bool (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.Transaction + /// + open func updateTransaction( + transactionId: String, + commit: Bool? = nil, + rollback: Bool? = nil + ) async throws -> AppwriteModels.Transaction { + let apiPath: String = "/documentsdb/transactions/{transactionId}" + .replacingOccurrences(of: "{transactionId}", with: transactionId) + + let apiParams: [String: Any?] = [ + "commit": commit, + "rollback": rollback, + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "content-type": "application/json", + "accept": "application/json", + ] + + let converter: (Any) throws -> AppwriteModels.Transaction = { response in + return AppwriteModels.Transaction.from(map: response as! [String: Any]) + } + + return try await client.call( + method: "PATCH", + path: apiPath, + headers: apiHeaders, + params: apiParams, + converter: converter + ) + } + /// + /// Delete a transaction by its unique ID. + /// + /// - Parameters: + /// - transactionId: String + /// - Throws: Exception if the request fails + /// - Returns: Any + /// + open func deleteTransaction( + transactionId: String + ) async throws -> Any { + let apiPath: String = "/documentsdb/transactions/{transactionId}" + .replacingOccurrences(of: "{transactionId}", with: transactionId) + + let apiParams: [String: Any] = [:] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "content-type": "application/json", + ] + + return try await client.call( + method: "DELETE", + path: apiPath, + headers: apiHeaders, + params: apiParams + ) + } + /// + /// Create multiple operations in a single transaction. + /// + /// - Parameters: + /// - transactionId: String + /// - operations: [AnyCodable] (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.Transaction + /// + open func createOperations( + transactionId: String, + operations: [AnyCodable]? = nil + ) async throws -> AppwriteModels.Transaction { + let apiPath: String = "/documentsdb/transactions/{transactionId}/operations" + .replacingOccurrences(of: "{transactionId}", with: transactionId) + + let apiParams: [String: Any?] = [ + "operations": operations + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "content-type": "application/json", + "accept": "application/json", + ] + + let converter: (Any) throws -> AppwriteModels.Transaction = { response in + return AppwriteModels.Transaction.from(map: response as! [String: Any]) + } + + return try await client.call( + method: "POST", + path: apiPath, + headers: apiHeaders, + params: apiParams, + converter: converter + ) + } + /// + /// Get a list of all the user's documents in a given collection. You can use + /// the query params to filter your results. + /// + /// - Parameters: + /// - databaseId: String + /// - collectionId: String + /// - queries: [String] (optional) + /// - transactionId: String (optional) + /// - total: Bool (optional) + /// - ttl: Int (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.DocumentList + /// + open func listDocuments( + databaseId: String, + collectionId: String, + queries: [String]? = nil, + transactionId: String? = nil, + total: Bool? = nil, + ttl: Int? = nil, + nestedType: T.Type + ) async throws -> AppwriteModels.DocumentList { + let apiPath: String = "/documentsdb/{databaseId}/collections/{collectionId}/documents" + .replacingOccurrences(of: "{databaseId}", with: databaseId) + .replacingOccurrences(of: "{collectionId}", with: collectionId) + + let apiParams: [String: Any?] = [ + "queries": queries, + "transactionId": transactionId, + "total": total, + "ttl": ttl, + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "accept": "application/json", + ] + + let converter: (Any) throws -> AppwriteModels.DocumentList = { response in + return AppwriteModels.DocumentList.from(map: response as! [String: Any]) + } + + return try await client.call( + method: "GET", + path: apiPath, + headers: apiHeaders, + params: apiParams, + converter: converter + ) + } + + /// + /// Get a list of all the user's documents in a given collection. You can use + /// the query params to filter your results. + /// + /// - Parameters: + /// - databaseId: String + /// - collectionId: String + /// - queries: [String] (optional) + /// - transactionId: String (optional) + /// - total: Bool (optional) + /// - ttl: Int (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.DocumentList + /// + open func listDocuments( + databaseId: String, + collectionId: String, + queries: [String]? = nil, + transactionId: String? = nil, + total: Bool? = nil, + ttl: Int? = nil + ) async throws -> AppwriteModels.DocumentList<[String: AnyCodable]> { + return try await listDocuments( + databaseId: databaseId, + collectionId: collectionId, + queries: queries, + transactionId: transactionId, + total: total, + ttl: ttl, + nestedType: [String: AnyCodable].self + ) + } + /// + /// Create a new Document. Before using this route, you should create a new + /// collection resource using either a [server + /// integration](https://appwrite.io/docs/server/databases#documentsDBCreateCollection) + /// API or directly from your database console. + /// + /// - Parameters: + /// - databaseId: String + /// - collectionId: String + /// - documentId: String + /// - data: Any + /// - permissions: [String] (optional) + /// - transactionId: String (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.Document + /// + open func createDocument( + databaseId: String, + collectionId: String, + documentId: String, + data: Any, + permissions: [String]? = nil, + transactionId: String? = nil, + nestedType: T.Type + ) async throws -> AppwriteModels.Document { + let apiPath: String = "/documentsdb/{databaseId}/collections/{collectionId}/documents" + .replacingOccurrences(of: "{databaseId}", with: databaseId) + .replacingOccurrences(of: "{collectionId}", with: collectionId) + + let apiParams: [String: Any?] = [ + "documentId": documentId, + "data": data, + "permissions": permissions, + "transactionId": transactionId, + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "content-type": "application/json", + "accept": "application/json", + ] + + let converter: (Any) throws -> AppwriteModels.Document = { response in + return AppwriteModels.Document.from(map: response as! [String: Any]) + } + + return try await client.call( + method: "POST", + path: apiPath, + headers: apiHeaders, + params: apiParams, + converter: converter + ) + } + + /// + /// Create a new Document. Before using this route, you should create a new + /// collection resource using either a [server + /// integration](https://appwrite.io/docs/server/databases#documentsDBCreateCollection) + /// API or directly from your database console. + /// + /// - Parameters: + /// - databaseId: String + /// - collectionId: String + /// - documentId: String + /// - data: Any + /// - permissions: [String] (optional) + /// - transactionId: String (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.Document + /// + open func createDocument( + databaseId: String, + collectionId: String, + documentId: String, + data: Any, + permissions: [String]? = nil, + transactionId: String? = nil + ) async throws -> AppwriteModels.Document<[String: AnyCodable]> { + return try await createDocument( + databaseId: databaseId, + collectionId: collectionId, + documentId: documentId, + data: data, + permissions: permissions, + transactionId: transactionId, + nestedType: [String: AnyCodable].self + ) + } + /// + /// Create new Documents. Before using this route, you should create a new + /// collection resource using either a [server + /// integration](https://appwrite.io/docs/server/databases#documentsDBCreateCollection) + /// API or directly from your database console. + /// + /// - Parameters: + /// - databaseId: String + /// - collectionId: String + /// - documents: [AnyCodable] + /// - transactionId: String (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.DocumentList + /// + open func createDocuments( + databaseId: String, + collectionId: String, + documents: [AnyCodable], + transactionId: String? = nil, + nestedType: T.Type + ) async throws -> AppwriteModels.DocumentList { + let apiPath: String = "/documentsdb/{databaseId}/collections/{collectionId}/documents" + .replacingOccurrences(of: "{databaseId}", with: databaseId) + .replacingOccurrences(of: "{collectionId}", with: collectionId) + + let apiParams: [String: Any?] = [ + "documents": documents, + "transactionId": transactionId, + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "content-type": "application/json", + "accept": "application/json", + ] + + let converter: (Any) throws -> AppwriteModels.DocumentList = { response in + return AppwriteModels.DocumentList.from(map: response as! [String: Any]) + } + + return try await client.call( + method: "POST", + path: apiPath, + headers: apiHeaders, + params: apiParams, + converter: converter + ) + } + + /// + /// Create new Documents. Before using this route, you should create a new + /// collection resource using either a [server + /// integration](https://appwrite.io/docs/server/databases#documentsDBCreateCollection) + /// API or directly from your database console. + /// + /// - Parameters: + /// - databaseId: String + /// - collectionId: String + /// - documents: [AnyCodable] + /// - transactionId: String (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.DocumentList + /// + open func createDocuments( + databaseId: String, + collectionId: String, + documents: [AnyCodable], + transactionId: String? = nil + ) async throws -> AppwriteModels.DocumentList<[String: AnyCodable]> { + return try await createDocuments( + databaseId: databaseId, + collectionId: collectionId, + documents: documents, + transactionId: transactionId, + nestedType: [String: AnyCodable].self + ) + } + /// + /// Get a document by its unique ID. This endpoint response returns a JSON + /// object with the document data. + /// + /// - Parameters: + /// - databaseId: String + /// - collectionId: String + /// - documentId: String + /// - queries: [String] (optional) + /// - transactionId: String (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.Document + /// + open func getDocument( + databaseId: String, + collectionId: String, + documentId: String, + queries: [String]? = nil, + transactionId: String? = nil, + nestedType: T.Type + ) async throws -> AppwriteModels.Document { + let apiPath: String = "/documentsdb/{databaseId}/collections/{collectionId}/documents/{documentId}" + .replacingOccurrences(of: "{databaseId}", with: databaseId) + .replacingOccurrences(of: "{collectionId}", with: collectionId) + .replacingOccurrences(of: "{documentId}", with: documentId) + + let apiParams: [String: Any?] = [ + "queries": queries, + "transactionId": transactionId, + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "accept": "application/json", + ] + + let converter: (Any) throws -> AppwriteModels.Document = { response in + return AppwriteModels.Document.from(map: response as! [String: Any]) + } + + return try await client.call( + method: "GET", + path: apiPath, + headers: apiHeaders, + params: apiParams, + converter: converter + ) + } + + /// + /// Get a document by its unique ID. This endpoint response returns a JSON + /// object with the document data. + /// + /// - Parameters: + /// - databaseId: String + /// - collectionId: String + /// - documentId: String + /// - queries: [String] (optional) + /// - transactionId: String (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.Document + /// + open func getDocument( + databaseId: String, + collectionId: String, + documentId: String, + queries: [String]? = nil, + transactionId: String? = nil + ) async throws -> AppwriteModels.Document<[String: AnyCodable]> { + return try await getDocument( + databaseId: databaseId, + collectionId: collectionId, + documentId: documentId, + queries: queries, + transactionId: transactionId, + nestedType: [String: AnyCodable].self + ) + } + /// + /// Create or update a Document. Before using this route, you should create a + /// new collection resource using either a [server + /// integration](https://appwrite.io/docs/server/databases#documentsDBCreateCollection) + /// API or directly from your database console. + /// + /// - Parameters: + /// - databaseId: String + /// - collectionId: String + /// - documentId: String + /// - data: Any (optional) + /// - permissions: [String] (optional) + /// - transactionId: String (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.Document + /// + open func upsertDocument( + databaseId: String, + collectionId: String, + documentId: String, + data: Any? = nil, + permissions: [String]? = nil, + transactionId: String? = nil, + nestedType: T.Type + ) async throws -> AppwriteModels.Document { + let apiPath: String = "/documentsdb/{databaseId}/collections/{collectionId}/documents/{documentId}" + .replacingOccurrences(of: "{databaseId}", with: databaseId) + .replacingOccurrences(of: "{collectionId}", with: collectionId) + .replacingOccurrences(of: "{documentId}", with: documentId) + + let apiParams: [String: Any?] = [ + "data": data, + "permissions": permissions, + "transactionId": transactionId, + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "content-type": "application/json", + "accept": "application/json", + ] + + let converter: (Any) throws -> AppwriteModels.Document = { response in + return AppwriteModels.Document.from(map: response as! [String: Any]) + } + + return try await client.call( + method: "PUT", + path: apiPath, + headers: apiHeaders, + params: apiParams, + converter: converter + ) + } + + /// + /// Create or update a Document. Before using this route, you should create a + /// new collection resource using either a [server + /// integration](https://appwrite.io/docs/server/databases#documentsDBCreateCollection) + /// API or directly from your database console. + /// + /// - Parameters: + /// - databaseId: String + /// - collectionId: String + /// - documentId: String + /// - data: Any (optional) + /// - permissions: [String] (optional) + /// - transactionId: String (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.Document + /// + open func upsertDocument( + databaseId: String, + collectionId: String, + documentId: String, + data: Any? = nil, + permissions: [String]? = nil, + transactionId: String? = nil + ) async throws -> AppwriteModels.Document<[String: AnyCodable]> { + return try await upsertDocument( + databaseId: databaseId, + collectionId: collectionId, + documentId: documentId, + data: data, + permissions: permissions, + transactionId: transactionId, + nestedType: [String: AnyCodable].self + ) + } + /// + /// Update a document by its unique ID. Using the patch method you can pass + /// only specific fields that will get updated. + /// + /// - Parameters: + /// - databaseId: String + /// - collectionId: String + /// - documentId: String + /// - data: Any (optional) + /// - permissions: [String] (optional) + /// - transactionId: String (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.Document + /// + open func updateDocument( + databaseId: String, + collectionId: String, + documentId: String, + data: Any? = nil, + permissions: [String]? = nil, + transactionId: String? = nil, + nestedType: T.Type + ) async throws -> AppwriteModels.Document { + let apiPath: String = "/documentsdb/{databaseId}/collections/{collectionId}/documents/{documentId}" + .replacingOccurrences(of: "{databaseId}", with: databaseId) + .replacingOccurrences(of: "{collectionId}", with: collectionId) + .replacingOccurrences(of: "{documentId}", with: documentId) + + let apiParams: [String: Any?] = [ + "data": data, + "permissions": permissions, + "transactionId": transactionId, + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "content-type": "application/json", + "accept": "application/json", + ] + + let converter: (Any) throws -> AppwriteModels.Document = { response in + return AppwriteModels.Document.from(map: response as! [String: Any]) + } + + return try await client.call( + method: "PATCH", + path: apiPath, + headers: apiHeaders, + params: apiParams, + converter: converter + ) + } + + /// + /// Update a document by its unique ID. Using the patch method you can pass + /// only specific fields that will get updated. + /// + /// - Parameters: + /// - databaseId: String + /// - collectionId: String + /// - documentId: String + /// - data: Any (optional) + /// - permissions: [String] (optional) + /// - transactionId: String (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.Document + /// + open func updateDocument( + databaseId: String, + collectionId: String, + documentId: String, + data: Any? = nil, + permissions: [String]? = nil, + transactionId: String? = nil + ) async throws -> AppwriteModels.Document<[String: AnyCodable]> { + return try await updateDocument( + databaseId: databaseId, + collectionId: collectionId, + documentId: documentId, + data: data, + permissions: permissions, + transactionId: transactionId, + nestedType: [String: AnyCodable].self + ) + } + /// + /// Delete a document by its unique ID. + /// + /// - Parameters: + /// - databaseId: String + /// - collectionId: String + /// - documentId: String + /// - transactionId: String (optional) + /// - Throws: Exception if the request fails + /// - Returns: Any + /// + open func deleteDocument( + databaseId: String, + collectionId: String, + documentId: String, + transactionId: String? = nil + ) async throws -> Any { + let apiPath: String = "/documentsdb/{databaseId}/collections/{collectionId}/documents/{documentId}" + .replacingOccurrences(of: "{databaseId}", with: databaseId) + .replacingOccurrences(of: "{collectionId}", with: collectionId) + .replacingOccurrences(of: "{documentId}", with: documentId) + + let apiParams: [String: Any?] = [ + "transactionId": transactionId + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "content-type": "application/json", + ] + + return try await client.call( + method: "DELETE", + path: apiPath, + headers: apiHeaders, + params: apiParams + ) + } + /// + /// Decrement a specific column of a row by a given value. + /// + /// - Parameters: + /// - databaseId: String + /// - collectionId: String + /// - documentId: String + /// - attribute: String + /// - value: Double (optional) + /// - min: Double (optional) + /// - transactionId: String (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.Document + /// + open func decrementDocumentAttribute( + databaseId: String, + collectionId: String, + documentId: String, + attribute: String, + value: Double? = nil, + min: Double? = nil, + transactionId: String? = nil, + nestedType: T.Type + ) async throws -> AppwriteModels.Document { + let apiPath: String = "/documentsdb/{databaseId}/collections/{collectionId}/documents/{documentId}/{attribute}/decrement" + .replacingOccurrences(of: "{databaseId}", with: databaseId) + .replacingOccurrences(of: "{collectionId}", with: collectionId) + .replacingOccurrences(of: "{documentId}", with: documentId) + .replacingOccurrences(of: "{attribute}", with: attribute) + + let apiParams: [String: Any?] = [ + "value": value, + "min": min, + "transactionId": transactionId, + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "content-type": "application/json", + "accept": "application/json", + ] + + let converter: (Any) throws -> AppwriteModels.Document = { response in + return AppwriteModels.Document.from(map: response as! [String: Any]) + } + + return try await client.call( + method: "PATCH", + path: apiPath, + headers: apiHeaders, + params: apiParams, + converter: converter + ) + } + + /// + /// Decrement a specific column of a row by a given value. + /// + /// - Parameters: + /// - databaseId: String + /// - collectionId: String + /// - documentId: String + /// - attribute: String + /// - value: Double (optional) + /// - min: Double (optional) + /// - transactionId: String (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.Document + /// + open func decrementDocumentAttribute( + databaseId: String, + collectionId: String, + documentId: String, + attribute: String, + value: Double? = nil, + min: Double? = nil, + transactionId: String? = nil + ) async throws -> AppwriteModels.Document<[String: AnyCodable]> { + return try await decrementDocumentAttribute( + databaseId: databaseId, + collectionId: collectionId, + documentId: documentId, + attribute: attribute, + value: value, + min: min, + transactionId: transactionId, + nestedType: [String: AnyCodable].self + ) + } + /// + /// Increment a specific column of a row by a given value. + /// + /// - Parameters: + /// - databaseId: String + /// - collectionId: String + /// - documentId: String + /// - attribute: String + /// - value: Double (optional) + /// - max: Double (optional) + /// - transactionId: String (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.Document + /// + open func incrementDocumentAttribute( + databaseId: String, + collectionId: String, + documentId: String, + attribute: String, + value: Double? = nil, + max: Double? = nil, + transactionId: String? = nil, + nestedType: T.Type + ) async throws -> AppwriteModels.Document { + let apiPath: String = "/documentsdb/{databaseId}/collections/{collectionId}/documents/{documentId}/{attribute}/increment" + .replacingOccurrences(of: "{databaseId}", with: databaseId) + .replacingOccurrences(of: "{collectionId}", with: collectionId) + .replacingOccurrences(of: "{documentId}", with: documentId) + .replacingOccurrences(of: "{attribute}", with: attribute) + + let apiParams: [String: Any?] = [ + "value": value, + "max": max, + "transactionId": transactionId, + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "content-type": "application/json", + "accept": "application/json", + ] + + let converter: (Any) throws -> AppwriteModels.Document = { response in + return AppwriteModels.Document.from(map: response as! [String: Any]) + } + + return try await client.call( + method: "PATCH", + path: apiPath, + headers: apiHeaders, + params: apiParams, + converter: converter + ) + } + + /// + /// Increment a specific column of a row by a given value. + /// + /// - Parameters: + /// - databaseId: String + /// - collectionId: String + /// - documentId: String + /// - attribute: String + /// - value: Double (optional) + /// - max: Double (optional) + /// - transactionId: String (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.Document + /// + open func incrementDocumentAttribute( + databaseId: String, + collectionId: String, + documentId: String, + attribute: String, + value: Double? = nil, + max: Double? = nil, + transactionId: String? = nil + ) async throws -> AppwriteModels.Document<[String: AnyCodable]> { + return try await incrementDocumentAttribute( + databaseId: databaseId, + collectionId: collectionId, + documentId: documentId, + attribute: attribute, + value: value, + max: max, + transactionId: transactionId, + nestedType: [String: AnyCodable].self + ) + } +} diff --git a/Sources/Appwrite/Services/Functions.swift b/Sources/Appwrite/Services/Functions.swift index b7f0ecf..d5e90b0 100644 --- a/Sources/Appwrite/Services/Functions.swift +++ b/Sources/Appwrite/Services/Functions.swift @@ -1,9 +1,9 @@ -import AsyncHTTPClient -import Foundation -import NIO -import JSONCodable import AppwriteEnums import AppwriteModels +import AsyncHTTPClient +import Foundation +import JSONCodable +import NIO /// The Functions Service allows you view, create and manage your Cloud Functions. open class Functions: Service { @@ -29,12 +29,12 @@ open class Functions: Service { let apiParams: [String: Any?] = [ "queries": queries, - "total": total + "total": total, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.ExecutionList = { response in @@ -49,7 +49,6 @@ open class Functions: Service { converter: converter ) } - /// /// Trigger a function execution. The returned object will return you the /// current execution status. You can ping the `Get Execution` endpoint to get @@ -85,13 +84,13 @@ open class Functions: Service { "path": path, "method": method?.rawValue, "headers": headers, - "scheduledAt": scheduledAt + "scheduledAt": scheduledAt, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Execution = { response in @@ -106,7 +105,6 @@ open class Functions: Service { converter: converter ) } - /// /// Get a function execution log by its unique ID. /// @@ -128,7 +126,7 @@ open class Functions: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Execution = { response in @@ -143,6 +141,4 @@ open class Functions: Service { converter: converter ) } - - } diff --git a/Sources/Appwrite/Services/Graphql.swift b/Sources/Appwrite/Services/Graphql.swift index 34b49f8..a3fae25 100644 --- a/Sources/Appwrite/Services/Graphql.swift +++ b/Sources/Appwrite/Services/Graphql.swift @@ -1,9 +1,9 @@ -import AsyncHTTPClient -import Foundation -import NIO -import JSONCodable import AppwriteEnums import AppwriteModels +import AsyncHTTPClient +import Foundation +import JSONCodable +import NIO /// The GraphQL API allows you to query and mutate your Appwrite server using GraphQL. open class Graphql: Service { @@ -29,7 +29,7 @@ open class Graphql: Service { "X-Appwrite-Project": client.config["project"] ?? "", "x-sdk-graphql": "true", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> Any = { response in @@ -44,7 +44,6 @@ open class Graphql: Service { converter: converter ) } - /// /// Execute a GraphQL mutation. /// @@ -66,7 +65,7 @@ open class Graphql: Service { "X-Appwrite-Project": client.config["project"] ?? "", "x-sdk-graphql": "true", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> Any = { response in @@ -81,6 +80,4 @@ open class Graphql: Service { converter: converter ) } - - } diff --git a/Sources/Appwrite/Services/Locale.swift b/Sources/Appwrite/Services/Locale.swift index 86cc129..82d9a65 100644 --- a/Sources/Appwrite/Services/Locale.swift +++ b/Sources/Appwrite/Services/Locale.swift @@ -1,9 +1,9 @@ -import AsyncHTTPClient -import Foundation -import NIO -import JSONCodable import AppwriteEnums import AppwriteModels +import AsyncHTTPClient +import Foundation +import JSONCodable +import NIO /// The Locale service allows you to customize your app based on your users' location. open class Locale: Service { @@ -13,21 +13,20 @@ open class Locale: Service { /// country code, country name, continent name, continent code, ip address and /// suggested currency. You can use the locale header to get the data in a /// supported language. - /// + /// /// ([IP Geolocation by DB-IP](https://db-ip.com)) /// /// - Throws: Exception if the request fails /// - Returns: AppwriteModels.Locale /// - open func get( - ) async throws -> AppwriteModels.Locale { + open func get() async throws -> AppwriteModels.Locale { let apiPath: String = "/locale" let apiParams: [String: Any] = [:] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Locale = { response in @@ -42,7 +41,6 @@ open class Locale: Service { converter: converter ) } - /// /// List of all locale codes in [ISO /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). @@ -50,15 +48,14 @@ open class Locale: Service { /// - Throws: Exception if the request fails /// - Returns: AppwriteModels.LocaleCodeList /// - open func listCodes( - ) async throws -> AppwriteModels.LocaleCodeList { + open func listCodes() async throws -> AppwriteModels.LocaleCodeList { let apiPath: String = "/locale/codes" let apiParams: [String: Any] = [:] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.LocaleCodeList = { response in @@ -73,7 +70,6 @@ open class Locale: Service { converter: converter ) } - /// /// List of all continents. You can use the locale header to get the data in a /// supported language. @@ -81,15 +77,14 @@ open class Locale: Service { /// - Throws: Exception if the request fails /// - Returns: AppwriteModels.ContinentList /// - open func listContinents( - ) async throws -> AppwriteModels.ContinentList { + open func listContinents() async throws -> AppwriteModels.ContinentList { let apiPath: String = "/locale/continents" let apiParams: [String: Any] = [:] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.ContinentList = { response in @@ -104,7 +99,6 @@ open class Locale: Service { converter: converter ) } - /// /// List of all countries. You can use the locale header to get the data in a /// supported language. @@ -112,15 +106,14 @@ open class Locale: Service { /// - Throws: Exception if the request fails /// - Returns: AppwriteModels.CountryList /// - open func listCountries( - ) async throws -> AppwriteModels.CountryList { + open func listCountries() async throws -> AppwriteModels.CountryList { let apiPath: String = "/locale/countries" let apiParams: [String: Any] = [:] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.CountryList = { response in @@ -135,7 +128,6 @@ open class Locale: Service { converter: converter ) } - /// /// List of all countries that are currently members of the EU. You can use the /// locale header to get the data in a supported language. @@ -143,15 +135,14 @@ open class Locale: Service { /// - Throws: Exception if the request fails /// - Returns: AppwriteModels.CountryList /// - open func listCountriesEU( - ) async throws -> AppwriteModels.CountryList { + open func listCountriesEU() async throws -> AppwriteModels.CountryList { let apiPath: String = "/locale/countries/eu" let apiParams: [String: Any] = [:] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.CountryList = { response in @@ -166,7 +157,6 @@ open class Locale: Service { converter: converter ) } - /// /// List of all countries phone codes. You can use the locale header to get the /// data in a supported language. @@ -174,15 +164,14 @@ open class Locale: Service { /// - Throws: Exception if the request fails /// - Returns: AppwriteModels.PhoneList /// - open func listCountriesPhones( - ) async throws -> AppwriteModels.PhoneList { + open func listCountriesPhones() async throws -> AppwriteModels.PhoneList { let apiPath: String = "/locale/countries/phones" let apiParams: [String: Any] = [:] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.PhoneList = { response in @@ -197,7 +186,6 @@ open class Locale: Service { converter: converter ) } - /// /// List of all currencies, including currency symbol, name, plural, and /// decimal digits for all major and minor currencies. You can use the locale @@ -206,15 +194,14 @@ open class Locale: Service { /// - Throws: Exception if the request fails /// - Returns: AppwriteModels.CurrencyList /// - open func listCurrencies( - ) async throws -> AppwriteModels.CurrencyList { + open func listCurrencies() async throws -> AppwriteModels.CurrencyList { let apiPath: String = "/locale/currencies" let apiParams: [String: Any] = [:] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.CurrencyList = { response in @@ -229,7 +216,6 @@ open class Locale: Service { converter: converter ) } - /// /// List of all languages classified by ISO 639-1 including 2-letter code, name /// in English, and name in the respective language. @@ -237,15 +223,14 @@ open class Locale: Service { /// - Throws: Exception if the request fails /// - Returns: AppwriteModels.LanguageList /// - open func listLanguages( - ) async throws -> AppwriteModels.LanguageList { + open func listLanguages() async throws -> AppwriteModels.LanguageList { let apiPath: String = "/locale/languages" let apiParams: [String: Any] = [:] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.LanguageList = { response in @@ -260,6 +245,4 @@ open class Locale: Service { converter: converter ) } - - } diff --git a/Sources/Appwrite/Services/Messaging.swift b/Sources/Appwrite/Services/Messaging.swift index 79ba04e..972d363 100644 --- a/Sources/Appwrite/Services/Messaging.swift +++ b/Sources/Appwrite/Services/Messaging.swift @@ -1,9 +1,9 @@ -import AsyncHTTPClient -import Foundation -import NIO -import JSONCodable import AppwriteEnums import AppwriteModels +import AsyncHTTPClient +import Foundation +import JSONCodable +import NIO /// The Messaging service allows you to send messages to any provider type (SMTP, push notification, SMS, etc.). open class Messaging: Service { @@ -28,13 +28,13 @@ open class Messaging: Service { let apiParams: [String: Any?] = [ "subscriberId": subscriberId, - "targetId": targetId + "targetId": targetId, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Subscriber = { response in @@ -49,7 +49,6 @@ open class Messaging: Service { converter: converter ) } - /// /// Delete a subscriber by its unique ID. /// @@ -71,15 +70,14 @@ open class Messaging: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "content-type": "application/json" + "content-type": "application/json", ] return try await client.call( method: "DELETE", path: apiPath, headers: apiHeaders, - params: apiParams ) + params: apiParams + ) } - - } diff --git a/Sources/Appwrite/Services/Organization.swift b/Sources/Appwrite/Services/Organization.swift new file mode 100644 index 0000000..9939001 --- /dev/null +++ b/Sources/Appwrite/Services/Organization.swift @@ -0,0 +1,195 @@ +import AppwriteEnums +import AppwriteModels +import AsyncHTTPClient +import Foundation +import JSONCodable +import NIO + +/// The Organization service allows you to manage organization-level projects. +open class Organization: Service { + + /// + /// List app installations on the organization. Any organization member can + /// read installations. + /// + /// - Parameters: + /// - queries: [String] (optional) + /// - total: Bool (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.AppInstallationList + /// + open func listInstallations( + queries: [String]? = nil, + total: Bool? = nil + ) async throws -> AppwriteModels.AppInstallationList { + let apiPath: String = "/organization/installations" + + let apiParams: [String: Any?] = [ + "queries": queries, + "total": total, + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "accept": "application/json", + ] + + let converter: (Any) throws -> AppwriteModels.AppInstallationList = { response in + return AppwriteModels.AppInstallationList.from(map: response as! [String: Any]) + } + + return try await client.call( + method: "GET", + path: apiPath, + headers: apiHeaders, + params: apiParams, + converter: converter + ) + } + /// + /// Install an app on the organization. Only organization members with the + /// owner role can install apps. The installation is granted the scopes the app + /// currently requests. + /// + /// - Parameters: + /// - appId: String + /// - authorizationDetails: String (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.AppInstallation + /// + open func createInstallation( + appId: String, + authorizationDetails: String? = nil + ) async throws -> AppwriteModels.AppInstallation { + let apiPath: String = "/organization/installations" + + let apiParams: [String: Any?] = [ + "appId": appId, + "authorizationDetails": authorizationDetails, + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "content-type": "application/json", + "accept": "application/json", + ] + + let converter: (Any) throws -> AppwriteModels.AppInstallation = { response in + return AppwriteModels.AppInstallation.from(map: response as! [String: Any]) + } + + return try await client.call( + method: "POST", + path: apiPath, + headers: apiHeaders, + params: apiParams, + converter: converter + ) + } + /// + /// Get an app installation on the organization by its unique ID. Any + /// organization member can read installations. + /// + /// - Parameters: + /// - installationId: String + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.AppInstallation + /// + open func getInstallation( + installationId: String + ) async throws -> AppwriteModels.AppInstallation { + let apiPath: String = "/organization/installations/{installationId}" + .replacingOccurrences(of: "{installationId}", with: installationId) + + let apiParams: [String: Any] = [:] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "accept": "application/json", + ] + + let converter: (Any) throws -> AppwriteModels.AppInstallation = { response in + return AppwriteModels.AppInstallation.from(map: response as! [String: Any]) + } + + return try await client.call( + method: "GET", + path: apiPath, + headers: apiHeaders, + params: apiParams, + converter: converter + ) + } + /// + /// Update an app installation on the organization. Only organization members + /// with the owner role can update installations. The installation's granted + /// scopes are refreshed to the scopes the app currently requests; previously + /// issued installation access tokens are revoked. + /// + /// - Parameters: + /// - installationId: String + /// - authorizationDetails: String (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.AppInstallation + /// + open func updateInstallation( + installationId: String, + authorizationDetails: String? = nil + ) async throws -> AppwriteModels.AppInstallation { + let apiPath: String = "/organization/installations/{installationId}" + .replacingOccurrences(of: "{installationId}", with: installationId) + + let apiParams: [String: Any?] = [ + "authorizationDetails": authorizationDetails + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "content-type": "application/json", + "accept": "application/json", + ] + + let converter: (Any) throws -> AppwriteModels.AppInstallation = { response in + return AppwriteModels.AppInstallation.from(map: response as! [String: Any]) + } + + return try await client.call( + method: "PUT", + path: apiPath, + headers: apiHeaders, + params: apiParams, + converter: converter + ) + } + /// + /// Uninstall an app from the organization by its installation ID. Only + /// organization members with the owner role can remove installations. + /// Previously issued installation access tokens are revoked. + /// + /// - Parameters: + /// - installationId: String + /// - Throws: Exception if the request fails + /// - Returns: Any + /// + open func deleteInstallation( + installationId: String + ) async throws -> Any { + let apiPath: String = "/organization/installations/{installationId}" + .replacingOccurrences(of: "{installationId}", with: installationId) + + let apiParams: [String: Any] = [:] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "content-type": "application/json", + "accept": "application/json", + ] + + return try await client.call( + method: "DELETE", + path: apiPath, + headers: apiHeaders, + params: apiParams + ) + } +} diff --git a/Sources/Appwrite/Services/Presences.swift b/Sources/Appwrite/Services/Presences.swift index 16f7047..a2b57e4 100644 --- a/Sources/Appwrite/Services/Presences.swift +++ b/Sources/Appwrite/Services/Presences.swift @@ -1,16 +1,15 @@ -import AsyncHTTPClient -import Foundation -import NIO -import JSONCodable import AppwriteEnums import AppwriteModels +import AsyncHTTPClient +import Foundation +import JSONCodable +import NIO -/// +/// The Presences service allows you to track and manage real-time user presence in your project. open class Presences: Service { /// /// List presence logs. Expired entries are filtered out automatically. - /// /// /// - Parameters: /// - queries: [String] (optional) @@ -29,12 +28,12 @@ open class Presences: Service { let apiParams: [String: Any?] = [ "queries": queries, "total": total, - "ttl": ttl + "ttl": ttl, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.PresenceList = { response in @@ -49,11 +48,9 @@ open class Presences: Service { converter: converter ) } - /// /// Get a presence log by its unique ID. Entries whose `expiresAt` is in the /// past are treated as not found. - /// /// /// - Parameters: /// - presenceId: String @@ -70,7 +67,7 @@ open class Presences: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Presence = { response in @@ -85,10 +82,8 @@ open class Presences: Service { converter: converter ) } - /// /// Create or update a presence log by its user ID. - /// /// /// - Parameters: /// - presenceId: String @@ -113,13 +108,13 @@ open class Presences: Service { "status": status, "permissions": permissions, "expiresAt": expiresAt, - "metadata": metadata + "metadata": metadata, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Presence = { response in @@ -134,11 +129,9 @@ open class Presences: Service { converter: converter ) } - /// /// Update a presence log by its unique ID. Using the patch method you can pass /// only specific fields that will get updated. - /// /// /// - Parameters: /// - presenceId: String @@ -166,13 +159,13 @@ open class Presences: Service { "expiresAt": expiresAt, "metadata": metadata, "permissions": permissions, - "purge": purge + "purge": purge, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Presence = { response in @@ -187,10 +180,8 @@ open class Presences: Service { converter: converter ) } - /// /// Delete a presence log by its unique ID. - /// /// /// - Parameters: /// - presenceId: String @@ -207,15 +198,14 @@ open class Presences: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "content-type": "application/json" + "content-type": "application/json", ] return try await client.call( method: "DELETE", path: apiPath, headers: apiHeaders, - params: apiParams ) + params: apiParams + ) } - - } diff --git a/Sources/Appwrite/Services/Realtime.swift b/Sources/Appwrite/Services/Realtime.swift index e077dd6..f15c39f 100644 --- a/Sources/Appwrite/Services/Realtime.swift +++ b/Sources/Appwrite/Services/Realtime.swift @@ -1,9 +1,9 @@ -import Foundation import AsyncHTTPClient +import Foundation import NIO import NIOHTTP1 -open class Realtime : Service { +open class Realtime: Service { // Diagnostic messages go to stderr so they don't interleave with any stdout // the host process may be asserting on (e.g. SDK integration tests). @@ -15,7 +15,7 @@ open class Realtime : Service { private let TYPE_EVENT = "event" private let TYPE_PONG = "pong" private let DEBOUNCE_NANOS = 1_000_000 - private let HEARTBEAT_INTERVAL: UInt64 = 20_000_000_000 // 20 seconds in nanoseconds + private let HEARTBEAT_INTERVAL: UInt64 = 20_000_000_000 // 20 seconds in nanoseconds private var socketClient: WebSocketClient? = nil private var activeSubscriptions = [String: RealtimeCallback]() @@ -41,7 +41,7 @@ open class Realtime : Service { private var subCallDepth = 0 private var reconnectAttempts = 0 private var reconnect = true - + private var onErrorCallbacks: [((Swift.Error?, HTTPResponseStatus?) -> Void)] = [] private var onCloseCallbacks: [(() -> Void)] = [] private var onOpenCallbacks: [(() -> Void)] = [] @@ -49,11 +49,11 @@ open class Realtime : Service { public func onError(_ callback: @escaping (Swift.Error?, HTTPResponseStatus?) -> Void) { self.onErrorCallbacks.append(callback) } - + public func onClose(_ callback: @escaping () -> Void) { self.onCloseCallbacks.append(callback) } - + public func onOpen(_ callback: @escaping () -> Void) { self.onOpenCallbacks.append(callback) } @@ -124,7 +124,7 @@ open class Realtime : Service { let url = "\(client.endPointRealtime!)/realtime?\(queryParams)" - if (socketClient != nil) { + if socketClient != nil { reconnect = false try await closeSocket() } @@ -170,10 +170,11 @@ open class Realtime : Service { } let payload: [String: Any] = [ "type": "unsubscribe", - "data": ids.map { ["subscriptionId": $0] } + "data": ids.map { ["subscriptionId": $0] }, ] if let data = try? JSONSerialization.data(withJSONObject: payload), - let text = String(data: data, encoding: .utf8) { + let text = String(data: data, encoding: .utf8) + { ws.send(text: text) } } @@ -198,7 +199,7 @@ open class Realtime : Service { pendingSubscribes[subscriptionId] = [ "subscriptionId": subscriptionId, "channels": Array(subscription.channels), - "queries": subscription.queries + "queries": subscription.queries, ] } @@ -261,23 +262,25 @@ open class Realtime : Service { let payload: [String: Any] = [ "type": "subscribe", - "data": rows + "data": rows, ] if let data = try? JSONSerialization.data(withJSONObject: payload), - let text = String(data: data, encoding: .utf8) { + let text = String(data: data, encoding: .utf8) + { ws.send(text: text) } } private func closeSocket() async throws { stopHeartbeat() - + guard let client = socketClient, - let group = client.threadGroup else { + let group = client.threadGroup + else { return } - if (client.isConnected) { + if client.isConnected { let promise = group.any().makePromise(of: Void.self) client.close(promise: promise) try await promise.futureResult.get() @@ -295,10 +298,8 @@ open class Realtime : Service { } } - /** - * Convert channel value to string - * All Channel instances and String conform to ChannelValue - */ + /// Convert channel value to string + /// All Channel instances and String conform to ChannelValue private func channelToString(_ channel: ChannelValue) -> String { return channel.toString() } @@ -370,10 +371,11 @@ open class Realtime : Service { } let payload: [String: Any] = [ "type": "presence", - "data": payloadData + "data": payloadData, ] guard let jsonData = try? JSONSerialization.data(withJSONObject: payload), - let text = String(data: jsonData, encoding: .utf8) else { + let text = String(data: jsonData, encoding: .utf8) + else { throw AppwriteError(message: "Failed to encode presence payload") } ws.send(text: text) @@ -405,7 +407,7 @@ open class Realtime : Service { ) } - public func subscribe( + public func subscribe( channel: ChannelValue, payloadType: T.Type, callback: @escaping (RealtimeResponseEvent) -> Void, @@ -419,7 +421,7 @@ open class Realtime : Service { ) } - public func subscribe( + public func subscribe( channels: [ChannelValue], payloadType: T.Type, callback: @escaping (RealtimeResponseEvent) -> Void, @@ -433,7 +435,7 @@ open class Realtime : Service { ) } - public func subscribe( + public func subscribe( channels: Set, payloadType: T.Type, queries: [String] = [], @@ -547,7 +549,7 @@ extension Realtime: WebSocketClientDelegate { onOpenCallbacks.forEach { $0() } startHeartbeat() } - + private func handleResponseConnected(from json: [String: Any]) { guard json["data"] is [String: Any] else { return @@ -566,10 +568,11 @@ extension Realtime: WebSocketClientDelegate { public func onMessage(text: String) { let data = Data(text.utf8) guard let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any], - let type = json["type"] as? String else { + let type = json["type"] as? String + else { return } - + switch type { case TYPE_ERROR: do { @@ -594,7 +597,7 @@ extension Realtime: WebSocketClientDelegate { onCloseCallbacks.forEach { $0() } - if (!reconnect) { + if !reconnect { reconnect = true return } @@ -625,10 +628,11 @@ extension Realtime: WebSocketClientDelegate { func handleResponseEvent(from json: [String: Any]) { guard let data = json["data"] as? [String: Any], - let channels = data["channels"] as? [String], - let events = data["events"] as? [String], - let payload = data["payload"] as? [String: Any], - let subscriptions = data["subscriptions"] as? [String] else { + let channels = data["channels"] as? [String], + let events = data["events"] as? [String], + let payload = data["payload"] as? [String: Any], + let subscriptions = data["subscriptions"] as? [String] + else { return } diff --git a/Sources/Appwrite/Services/Service.swift b/Sources/Appwrite/Services/Service.swift index 3cf3d97..705e390 100644 --- a/Sources/Appwrite/Services/Service.swift +++ b/Sources/Appwrite/Services/Service.swift @@ -2,8 +2,7 @@ open class Service { internal var client: Client - public init(_ client: Client) - { + public init(_ client: Client) { self.client = client } } diff --git a/Sources/Appwrite/Services/Storage.swift b/Sources/Appwrite/Services/Storage.swift index b6c9706..d3f5fc6 100644 --- a/Sources/Appwrite/Services/Storage.swift +++ b/Sources/Appwrite/Services/Storage.swift @@ -1,9 +1,9 @@ -import AsyncHTTPClient -import Foundation -import NIO -import JSONCodable import AppwriteEnums import AppwriteModels +import AsyncHTTPClient +import Foundation +import JSONCodable +import NIO /// The Storage service allows you to manage your project files. open class Storage: Service { @@ -32,12 +32,12 @@ open class Storage: Service { let apiParams: [String: Any?] = [ "queries": queries, "search": search, - "total": total + "total": total, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.FileList = { response in @@ -52,32 +52,31 @@ open class Storage: Service { converter: converter ) } - /// /// Create a new file. Before using this route, you should create a new bucket /// resource using either a [server /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) /// API or directly from your Appwrite console. - /// + /// /// Larger files should be uploaded using multiple requests with the /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) /// header to send a partial request with a maximum supported chunk of `5MB`. /// The `content-range` header values should always be in bytes. - /// + /// /// When the first request is sent, the server will return the **File** object, /// and the subsequent part request must include the file's **id** in /// `x-appwrite-id` header to allow the server to know that the partial upload /// is for the existing file and not for a new one. - /// + /// /// If you're creating a new file using one of the Appwrite SDKs, all the /// chunking logic will be managed by the SDK internally. - /// /// /// - Parameters: /// - bucketId: String /// - fileId: String /// - file: InputFile /// - permissions: [String] (optional) + /// - folder: String (optional) /// - Throws: Exception if the request fails /// - Returns: AppwriteModels.File /// @@ -86,6 +85,7 @@ open class Storage: Service { fileId: String, file: InputFile, permissions: [String]? = nil, + folder: String? = nil, onProgress: ((UploadProgress) -> Void)? = nil ) async throws -> AppwriteModels.File { let apiPath: String = "/storage/buckets/{bucketId}/files" @@ -94,13 +94,14 @@ open class Storage: Service { var apiParams: [String: Any?] = [ "fileId": fileId, "file": file, - "permissions": permissions + "permissions": permissions, + "folder": folder, ] var apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "multipart/form-data", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.File = { response in @@ -119,7 +120,6 @@ open class Storage: Service { onProgress: onProgress ) } - /// /// Get a file by its unique ID. This endpoint response returns a JSON object /// with the file metadata. @@ -142,7 +142,7 @@ open class Storage: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.File = { response in @@ -157,7 +157,6 @@ open class Storage: Service { converter: converter ) } - /// /// Update a file by its unique ID. Only users with write permissions have /// access to update this resource. @@ -182,13 +181,13 @@ open class Storage: Service { let apiParams: [String: Any?] = [ "name": name, - "permissions": permissions + "permissions": permissions, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.File = { response in @@ -203,7 +202,6 @@ open class Storage: Service { converter: converter ) } - /// /// Delete a file by its unique ID. Only users with write permissions have /// access to delete this resource. @@ -226,16 +224,16 @@ open class Storage: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "content-type": "application/json" + "content-type": "application/json", ] return try await client.call( method: "DELETE", path: apiPath, headers: apiHeaders, - params: apiParams ) + params: apiParams + ) } - /// /// Get a file content by its unique ID. The endpoint response return with a /// 'Content-Disposition: attachment' header that tells the browser to start @@ -258,18 +256,21 @@ open class Storage: Service { .replacingOccurrences(of: "{fileId}", with: fileId) let apiParams: [String: Any?] = [ - "token": token, - "project": client.config["project"], - "impersonateuserid": client.config["impersonateuserid"] + "token": token + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "accept": "*/*", ] return try await client.call( method: "GET", path: apiPath, + headers: apiHeaders, params: apiParams ) } - /// /// Get a file preview image. Currently, this method supports preview for image /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, @@ -328,17 +329,20 @@ open class Storage: Service { "background": background, "output": output?.rawValue, "token": token, - "project": client.config["project"], - "impersonateuserid": client.config["impersonateuserid"] + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "accept": "image/*", ] return try await client.call( method: "GET", path: apiPath, + headers: apiHeaders, params: apiParams ) } - /// /// Get a file content by its unique ID. This endpoint is similar to the /// download method but returns with no 'Content-Disposition: attachment' @@ -361,17 +365,19 @@ open class Storage: Service { .replacingOccurrences(of: "{fileId}", with: fileId) let apiParams: [String: Any?] = [ - "token": token, - "project": client.config["project"], - "impersonateuserid": client.config["impersonateuserid"] + "token": token + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "accept": "*/*", ] return try await client.call( method: "GET", path: apiPath, + headers: apiHeaders, params: apiParams ) } - - } diff --git a/Sources/Appwrite/Services/TablesDB.swift b/Sources/Appwrite/Services/TablesDB.swift index a057333..8944bf3 100644 --- a/Sources/Appwrite/Services/TablesDB.swift +++ b/Sources/Appwrite/Services/TablesDB.swift @@ -1,11 +1,11 @@ -import AsyncHTTPClient -import Foundation -import NIO -import JSONCodable import AppwriteEnums import AppwriteModels +import AsyncHTTPClient +import Foundation +import JSONCodable +import NIO -/// +/// The TablesDB service allows you to create structured tables of columns, query and filter lists of rows open class TablesDB: Service { /// @@ -27,7 +27,7 @@ open class TablesDB: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.TransactionList = { response in @@ -42,7 +42,6 @@ open class TablesDB: Service { converter: converter ) } - /// /// Create a new transaction. /// @@ -63,7 +62,7 @@ open class TablesDB: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Transaction = { response in @@ -78,7 +77,6 @@ open class TablesDB: Service { converter: converter ) } - /// /// Get a transaction by its unique ID. /// @@ -97,7 +95,7 @@ open class TablesDB: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Transaction = { response in @@ -112,7 +110,6 @@ open class TablesDB: Service { converter: converter ) } - /// /// Update a transaction, to either commit or roll back its operations. /// @@ -133,13 +130,13 @@ open class TablesDB: Service { let apiParams: [String: Any?] = [ "commit": commit, - "rollback": rollback + "rollback": rollback, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Transaction = { response in @@ -154,7 +151,6 @@ open class TablesDB: Service { converter: converter ) } - /// /// Delete a transaction by its unique ID. /// @@ -173,28 +169,28 @@ open class TablesDB: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "content-type": "application/json" + "content-type": "application/json", ] return try await client.call( method: "DELETE", path: apiPath, headers: apiHeaders, - params: apiParams ) + params: apiParams + ) } - /// /// Create multiple operations in a single transaction. /// /// - Parameters: /// - transactionId: String - /// - operations: [Any] (optional) + /// - operations: [AnyCodable] (optional) /// - Throws: Exception if the request fails /// - Returns: AppwriteModels.Transaction /// open func createOperations( transactionId: String, - operations: [Any]? = nil + operations: [AnyCodable]? = nil ) async throws -> AppwriteModels.Transaction { let apiPath: String = "/tablesdb/transactions/{transactionId}/operations" .replacingOccurrences(of: "{transactionId}", with: transactionId) @@ -206,7 +202,7 @@ open class TablesDB: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Transaction = { response in @@ -221,7 +217,6 @@ open class TablesDB: Service { converter: converter ) } - /// /// Get a list of all the user's rows in a given table. You can use the query /// params to filter your results. @@ -253,12 +248,12 @@ open class TablesDB: Service { "queries": queries, "transactionId": transactionId, "total": total, - "ttl": ttl + "ttl": ttl, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.RowList = { response in @@ -306,7 +301,6 @@ open class TablesDB: Service { nestedType: [String: AnyCodable].self ) } - /// /// Create a new Row. Before using this route, you should create a new table /// resource using either a [server @@ -340,13 +334,13 @@ open class TablesDB: Service { "rowId": rowId, "data": data, "permissions": permissions, - "transactionId": transactionId + "transactionId": transactionId, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Row = { response in @@ -396,7 +390,6 @@ open class TablesDB: Service { nestedType: [String: AnyCodable].self ) } - /// /// Get a row by its unique ID. This endpoint response returns a JSON object /// with the row data. @@ -425,12 +418,12 @@ open class TablesDB: Service { let apiParams: [String: Any?] = [ "queries": queries, - "transactionId": transactionId + "transactionId": transactionId, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Row = { response in @@ -475,7 +468,6 @@ open class TablesDB: Service { nestedType: [String: AnyCodable].self ) } - /// /// Create or update a Row. Before using this route, you should create a new /// table resource using either a [server @@ -509,13 +501,13 @@ open class TablesDB: Service { let apiParams: [String: Any?] = [ "data": data, "permissions": permissions, - "transactionId": transactionId + "transactionId": transactionId, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Row = { response in @@ -565,7 +557,6 @@ open class TablesDB: Service { nestedType: [String: AnyCodable].self ) } - /// /// Update a row by its unique ID. Using the patch method you can pass only /// specific fields that will get updated. @@ -597,13 +588,13 @@ open class TablesDB: Service { let apiParams: [String: Any?] = [ "data": data, "permissions": permissions, - "transactionId": transactionId + "transactionId": transactionId, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Row = { response in @@ -651,7 +642,6 @@ open class TablesDB: Service { nestedType: [String: AnyCodable].self ) } - /// /// Delete a row by its unique ID. /// @@ -680,16 +670,16 @@ open class TablesDB: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "content-type": "application/json" + "content-type": "application/json", ] return try await client.call( method: "DELETE", path: apiPath, headers: apiHeaders, - params: apiParams ) + params: apiParams + ) } - /// /// Decrement a specific column of a row by a given value. /// @@ -723,13 +713,13 @@ open class TablesDB: Service { let apiParams: [String: Any?] = [ "value": value, "min": min, - "transactionId": transactionId + "transactionId": transactionId, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Row = { response in @@ -779,7 +769,6 @@ open class TablesDB: Service { nestedType: [String: AnyCodable].self ) } - /// /// Increment a specific column of a row by a given value. /// @@ -813,13 +802,13 @@ open class TablesDB: Service { let apiParams: [String: Any?] = [ "value": value, "max": max, - "transactionId": transactionId + "transactionId": transactionId, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Row = { response in @@ -869,6 +858,4 @@ open class TablesDB: Service { nestedType: [String: AnyCodable].self ) } - - } diff --git a/Sources/Appwrite/Services/Teams.swift b/Sources/Appwrite/Services/Teams.swift index 506d4ad..22fc9f4 100644 --- a/Sources/Appwrite/Services/Teams.swift +++ b/Sources/Appwrite/Services/Teams.swift @@ -1,9 +1,9 @@ -import AsyncHTTPClient -import Foundation -import NIO -import JSONCodable import AppwriteEnums import AppwriteModels +import AsyncHTTPClient +import Foundation +import JSONCodable +import NIO /// The Teams service allows you to group users of your project and to enable them to share read and write access to your project resources open class Teams: Service { @@ -30,12 +30,12 @@ open class Teams: Service { let apiParams: [String: Any?] = [ "queries": queries, "search": search, - "total": total + "total": total, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.TeamList = { response in @@ -74,7 +74,6 @@ open class Teams: Service { nestedType: [String: AnyCodable].self ) } - /// /// Create a new team. The user who creates the team will automatically be /// assigned as the owner of the team. Only the users with the owner role can @@ -98,13 +97,13 @@ open class Teams: Service { let apiParams: [String: Any?] = [ "teamId": teamId, "name": name, - "roles": roles + "roles": roles, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Team = { response in @@ -144,7 +143,6 @@ open class Teams: Service { nestedType: [String: AnyCodable].self ) } - /// /// Get a team by its ID. All team members have read access for this resource. /// @@ -164,7 +162,7 @@ open class Teams: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Team = { response in @@ -196,7 +194,6 @@ open class Teams: Service { nestedType: [String: AnyCodable].self ) } - /// /// Update the team's name by its unique ID. /// @@ -221,7 +218,7 @@ open class Teams: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Team = { response in @@ -256,7 +253,6 @@ open class Teams: Service { nestedType: [String: AnyCodable].self ) } - /// /// Delete a team using its ID. Only team members with the owner role can /// delete the team. @@ -276,16 +272,215 @@ open class Teams: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "content-type": "application/json" + "content-type": "application/json", ] return try await client.call( method: "DELETE", path: apiPath, headers: apiHeaders, - params: apiParams ) + params: apiParams + ) } + /// + /// List app installations on a team. Any team member can read installations. + /// + /// - Parameters: + /// - teamId: String + /// - queries: [String] (optional) + /// - total: Bool (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.AppInstallationList + /// + open func listInstallations( + teamId: String, + queries: [String]? = nil, + total: Bool? = nil + ) async throws -> AppwriteModels.AppInstallationList { + let apiPath: String = "/teams/{teamId}/installations" + .replacingOccurrences(of: "{teamId}", with: teamId) + let apiParams: [String: Any?] = [ + "queries": queries, + "total": total, + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "accept": "application/json", + ] + + let converter: (Any) throws -> AppwriteModels.AppInstallationList = { response in + return AppwriteModels.AppInstallationList.from(map: response as! [String: Any]) + } + + return try await client.call( + method: "GET", + path: apiPath, + headers: apiHeaders, + params: apiParams, + converter: converter + ) + } + /// + /// Install an app on a team. When authenticated as a user, only team members + /// with the owner role can install apps. Requests using an API key or in admin + /// mode can install apps on any team. The installation is granted the scopes + /// the app currently requests. + /// + /// - Parameters: + /// - teamId: String + /// - appId: String + /// - authorizationDetails: String (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.AppInstallation + /// + open func createInstallation( + teamId: String, + appId: String, + authorizationDetails: String? = nil + ) async throws -> AppwriteModels.AppInstallation { + let apiPath: String = "/teams/{teamId}/installations" + .replacingOccurrences(of: "{teamId}", with: teamId) + + let apiParams: [String: Any?] = [ + "appId": appId, + "authorizationDetails": authorizationDetails, + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "content-type": "application/json", + "accept": "application/json", + ] + + let converter: (Any) throws -> AppwriteModels.AppInstallation = { response in + return AppwriteModels.AppInstallation.from(map: response as! [String: Any]) + } + + return try await client.call( + method: "POST", + path: apiPath, + headers: apiHeaders, + params: apiParams, + converter: converter + ) + } + /// + /// Get an app installation on a team by its unique ID. Any team member can + /// read installations. + /// + /// - Parameters: + /// - teamId: String + /// - installationId: String + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.AppInstallation + /// + open func getInstallation( + teamId: String, + installationId: String + ) async throws -> AppwriteModels.AppInstallation { + let apiPath: String = "/teams/{teamId}/installations/{installationId}" + .replacingOccurrences(of: "{teamId}", with: teamId) + .replacingOccurrences(of: "{installationId}", with: installationId) + + let apiParams: [String: Any] = [:] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "accept": "application/json", + ] + + let converter: (Any) throws -> AppwriteModels.AppInstallation = { response in + return AppwriteModels.AppInstallation.from(map: response as! [String: Any]) + } + + return try await client.call( + method: "GET", + path: apiPath, + headers: apiHeaders, + params: apiParams, + converter: converter + ) + } + /// + /// Update an app installation on a team. Only team members with the owner role + /// can update installations. The installation's granted scopes are refreshed + /// to the scopes the app currently requests; previously issued installation + /// access tokens are revoked. + /// + /// - Parameters: + /// - teamId: String + /// - installationId: String + /// - authorizationDetails: String (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.AppInstallation + /// + open func updateInstallation( + teamId: String, + installationId: String, + authorizationDetails: String? = nil + ) async throws -> AppwriteModels.AppInstallation { + let apiPath: String = "/teams/{teamId}/installations/{installationId}" + .replacingOccurrences(of: "{teamId}", with: teamId) + .replacingOccurrences(of: "{installationId}", with: installationId) + + let apiParams: [String: Any?] = [ + "authorizationDetails": authorizationDetails + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "content-type": "application/json", + "accept": "application/json", + ] + + let converter: (Any) throws -> AppwriteModels.AppInstallation = { response in + return AppwriteModels.AppInstallation.from(map: response as! [String: Any]) + } + + return try await client.call( + method: "PUT", + path: apiPath, + headers: apiHeaders, + params: apiParams, + converter: converter + ) + } + /// + /// Uninstall an app from a team by its installation ID. Only team members with + /// the owner role can remove installations. Previously issued installation + /// access tokens are revoked. + /// + /// - Parameters: + /// - teamId: String + /// - installationId: String + /// - Throws: Exception if the request fails + /// - Returns: Any + /// + open func deleteInstallation( + teamId: String, + installationId: String + ) async throws -> Any { + let apiPath: String = "/teams/{teamId}/installations/{installationId}" + .replacingOccurrences(of: "{teamId}", with: teamId) + .replacingOccurrences(of: "{installationId}", with: installationId) + + let apiParams: [String: Any] = [:] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "content-type": "application/json", + "accept": "application/json", + ] + + return try await client.call( + method: "DELETE", + path: apiPath, + headers: apiHeaders, + params: apiParams + ) + } /// /// Use this endpoint to list a team's members using the team's ID. All team /// members have read access to this endpoint. Hide sensitive attributes from @@ -311,12 +506,12 @@ open class Teams: Service { let apiParams: [String: Any?] = [ "queries": queries, "search": search, - "total": total + "total": total, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.MembershipList = { response in @@ -331,7 +526,6 @@ open class Teams: Service { converter: converter ) } - /// /// Invite a new member to join your team. Provide an ID for existing users, or /// invite unregistered users using an email or phone number. If initiated from @@ -339,21 +533,20 @@ open class Teams: Service { /// team to the invited user, and an account will be created for them if one /// doesn't exist. If initiated from a Server SDK, the new member will be added /// automatically to the team. - /// + /// /// You only need to provide one of a user ID, email, or phone number. Appwrite /// will prioritize accepting the user ID > email > phone number if you provide /// more than one of these parameters. - /// + /// /// Use the `url` parameter to redirect the user from the invitation email to /// your app. After the user is redirected, use the [Update Team Membership /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) - /// endpoint to allow the user to accept the invitation to the team. - /// + /// endpoint to allow the user to accept the invitation to the team. + /// /// Please note that to avoid a [Redirect /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) /// Appwrite will accept the only redirect URLs under the domains you have /// added as a platform on the Appwrite Console. - /// /// /// - Parameters: /// - teamId: String @@ -384,13 +577,13 @@ open class Teams: Service { "phone": phone, "roles": roles, "url": url, - "name": name + "name": name, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Membership = { response in @@ -405,7 +598,6 @@ open class Teams: Service { converter: converter ) } - /// /// Get a team member by the membership unique id. All team members have read /// access for this resource. Hide sensitive attributes from the response by @@ -429,7 +621,7 @@ open class Teams: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Membership = { response in @@ -444,12 +636,10 @@ open class Teams: Service { converter: converter ) } - /// /// Modify the roles of a team member. Only team members with the owner role /// have access to this endpoint. Learn more about [roles and /// permissions](https://appwrite.io/docs/permissions). - /// /// /// - Parameters: /// - teamId: String @@ -474,7 +664,7 @@ open class Teams: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Membership = { response in @@ -489,7 +679,6 @@ open class Teams: Service { converter: converter ) } - /// /// This endpoint allows a user to leave a team or for a team owner to delete /// the membership of any other team member. You can also use this endpoint to @@ -513,24 +702,23 @@ open class Teams: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "content-type": "application/json" + "content-type": "application/json", ] return try await client.call( method: "DELETE", path: apiPath, headers: apiHeaders, - params: apiParams ) + params: apiParams + ) } - /// /// Use this endpoint to allow a user to accept an invitation to join a team /// after being redirected back to your app from the invitation email received /// by the user. - /// + /// /// If the request is successful, a session for the user is automatically /// created. - /// /// /// - Parameters: /// - teamId: String @@ -552,13 +740,13 @@ open class Teams: Service { let apiParams: [String: Any?] = [ "userId": userId, - "secret": secret + "secret": secret, ] let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Membership = { response in @@ -573,7 +761,6 @@ open class Teams: Service { converter: converter ) } - /// /// Get the team's shared preferences by its unique ID. If a preference doesn't /// need to be shared by all team members, prefer storing them in [user @@ -595,7 +782,7 @@ open class Teams: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Preferences = { response in @@ -629,7 +816,6 @@ open class Teams: Service { nestedType: [String: AnyCodable].self ) } - /// /// Update the team's preferences by its unique ID. The object you pass is /// stored as is and replaces any previous value. The maximum allowed prefs @@ -656,7 +842,7 @@ open class Teams: Service { let apiHeaders: [String: String] = [ "X-Appwrite-Project": client.config["project"] ?? "", "content-type": "application/json", - "accept": "application/json" + "accept": "application/json", ] let converter: (Any) throws -> AppwriteModels.Preferences = { response in @@ -693,6 +879,4 @@ open class Teams: Service { nestedType: [String: AnyCodable].self ) } - - } diff --git a/Sources/Appwrite/Services/VectorsDB.swift b/Sources/Appwrite/Services/VectorsDB.swift new file mode 100644 index 0000000..9d1224d --- /dev/null +++ b/Sources/Appwrite/Services/VectorsDB.swift @@ -0,0 +1,772 @@ +import AppwriteEnums +import AppwriteModels +import AsyncHTTPClient +import Foundation +import JSONCodable +import NIO + +/// +open class VectorsDB: Service { + + /// + /// List transactions across all databases. + /// + /// - Parameters: + /// - queries: [String] (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.TransactionList + /// + open func listTransactions( + queries: [String]? = nil + ) async throws -> AppwriteModels.TransactionList { + let apiPath: String = "/vectorsdb/transactions" + + let apiParams: [String: Any?] = [ + "queries": queries + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "accept": "application/json", + ] + + let converter: (Any) throws -> AppwriteModels.TransactionList = { response in + return AppwriteModels.TransactionList.from(map: response as! [String: Any]) + } + + return try await client.call( + method: "GET", + path: apiPath, + headers: apiHeaders, + params: apiParams, + converter: converter + ) + } + /// + /// Create a new transaction. + /// + /// - Parameters: + /// - ttl: Int (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.Transaction + /// + open func createTransaction( + ttl: Int? = nil + ) async throws -> AppwriteModels.Transaction { + let apiPath: String = "/vectorsdb/transactions" + + let apiParams: [String: Any?] = [ + "ttl": ttl + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "content-type": "application/json", + "accept": "application/json", + ] + + let converter: (Any) throws -> AppwriteModels.Transaction = { response in + return AppwriteModels.Transaction.from(map: response as! [String: Any]) + } + + return try await client.call( + method: "POST", + path: apiPath, + headers: apiHeaders, + params: apiParams, + converter: converter + ) + } + /// + /// Get a transaction by its unique ID. + /// + /// - Parameters: + /// - transactionId: String + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.Transaction + /// + open func getTransaction( + transactionId: String + ) async throws -> AppwriteModels.Transaction { + let apiPath: String = "/vectorsdb/transactions/{transactionId}" + .replacingOccurrences(of: "{transactionId}", with: transactionId) + + let apiParams: [String: Any] = [:] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "accept": "application/json", + ] + + let converter: (Any) throws -> AppwriteModels.Transaction = { response in + return AppwriteModels.Transaction.from(map: response as! [String: Any]) + } + + return try await client.call( + method: "GET", + path: apiPath, + headers: apiHeaders, + params: apiParams, + converter: converter + ) + } + /// + /// Update a transaction, to either commit or roll back its operations. + /// + /// - Parameters: + /// - transactionId: String + /// - commit: Bool (optional) + /// - rollback: Bool (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.Transaction + /// + open func updateTransaction( + transactionId: String, + commit: Bool? = nil, + rollback: Bool? = nil + ) async throws -> AppwriteModels.Transaction { + let apiPath: String = "/vectorsdb/transactions/{transactionId}" + .replacingOccurrences(of: "{transactionId}", with: transactionId) + + let apiParams: [String: Any?] = [ + "commit": commit, + "rollback": rollback, + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "content-type": "application/json", + "accept": "application/json", + ] + + let converter: (Any) throws -> AppwriteModels.Transaction = { response in + return AppwriteModels.Transaction.from(map: response as! [String: Any]) + } + + return try await client.call( + method: "PATCH", + path: apiPath, + headers: apiHeaders, + params: apiParams, + converter: converter + ) + } + /// + /// Delete a transaction by its unique ID. + /// + /// - Parameters: + /// - transactionId: String + /// - Throws: Exception if the request fails + /// - Returns: Any + /// + open func deleteTransaction( + transactionId: String + ) async throws -> Any { + let apiPath: String = "/vectorsdb/transactions/{transactionId}" + .replacingOccurrences(of: "{transactionId}", with: transactionId) + + let apiParams: [String: Any] = [:] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "content-type": "application/json", + ] + + return try await client.call( + method: "DELETE", + path: apiPath, + headers: apiHeaders, + params: apiParams + ) + } + /// + /// Create multiple operations in a single transaction. + /// + /// - Parameters: + /// - transactionId: String + /// - operations: [AnyCodable] (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.Transaction + /// + open func createOperations( + transactionId: String, + operations: [AnyCodable]? = nil + ) async throws -> AppwriteModels.Transaction { + let apiPath: String = "/vectorsdb/transactions/{transactionId}/operations" + .replacingOccurrences(of: "{transactionId}", with: transactionId) + + let apiParams: [String: Any?] = [ + "operations": operations + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "content-type": "application/json", + "accept": "application/json", + ] + + let converter: (Any) throws -> AppwriteModels.Transaction = { response in + return AppwriteModels.Transaction.from(map: response as! [String: Any]) + } + + return try await client.call( + method: "POST", + path: apiPath, + headers: apiHeaders, + params: apiParams, + converter: converter + ) + } + /// + /// Get a list of all the user's documents in a given collection. You can use + /// the query params to filter your results. + /// + /// - Parameters: + /// - databaseId: String + /// - collectionId: String + /// - queries: [String] (optional) + /// - transactionId: String (optional) + /// - total: Bool (optional) + /// - ttl: Int (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.DocumentList + /// + open func listDocuments( + databaseId: String, + collectionId: String, + queries: [String]? = nil, + transactionId: String? = nil, + total: Bool? = nil, + ttl: Int? = nil, + nestedType: T.Type + ) async throws -> AppwriteModels.DocumentList { + let apiPath: String = "/vectorsdb/{databaseId}/collections/{collectionId}/documents" + .replacingOccurrences(of: "{databaseId}", with: databaseId) + .replacingOccurrences(of: "{collectionId}", with: collectionId) + + let apiParams: [String: Any?] = [ + "queries": queries, + "transactionId": transactionId, + "total": total, + "ttl": ttl, + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "accept": "application/json", + ] + + let converter: (Any) throws -> AppwriteModels.DocumentList = { response in + return AppwriteModels.DocumentList.from(map: response as! [String: Any]) + } + + return try await client.call( + method: "GET", + path: apiPath, + headers: apiHeaders, + params: apiParams, + converter: converter + ) + } + + /// + /// Get a list of all the user's documents in a given collection. You can use + /// the query params to filter your results. + /// + /// - Parameters: + /// - databaseId: String + /// - collectionId: String + /// - queries: [String] (optional) + /// - transactionId: String (optional) + /// - total: Bool (optional) + /// - ttl: Int (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.DocumentList + /// + open func listDocuments( + databaseId: String, + collectionId: String, + queries: [String]? = nil, + transactionId: String? = nil, + total: Bool? = nil, + ttl: Int? = nil + ) async throws -> AppwriteModels.DocumentList<[String: AnyCodable]> { + return try await listDocuments( + databaseId: databaseId, + collectionId: collectionId, + queries: queries, + transactionId: transactionId, + total: total, + ttl: ttl, + nestedType: [String: AnyCodable].self + ) + } + /// + /// Create a new Document. Before using this route, you should create a new + /// collection resource using either a [server + /// integration](https://appwrite.io/docs/server/databases#documentsDBCreateCollection) + /// API or directly from your database console. + /// + /// - Parameters: + /// - databaseId: String + /// - collectionId: String + /// - documentId: String + /// - data: Any + /// - permissions: [String] (optional) + /// - transactionId: String (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.Document + /// + open func createDocument( + databaseId: String, + collectionId: String, + documentId: String, + data: Any, + permissions: [String]? = nil, + transactionId: String? = nil, + nestedType: T.Type + ) async throws -> AppwriteModels.Document { + let apiPath: String = "/vectorsdb/{databaseId}/collections/{collectionId}/documents" + .replacingOccurrences(of: "{databaseId}", with: databaseId) + .replacingOccurrences(of: "{collectionId}", with: collectionId) + + let apiParams: [String: Any?] = [ + "documentId": documentId, + "data": data, + "permissions": permissions, + "transactionId": transactionId, + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "content-type": "application/json", + "accept": "application/json", + ] + + let converter: (Any) throws -> AppwriteModels.Document = { response in + return AppwriteModels.Document.from(map: response as! [String: Any]) + } + + return try await client.call( + method: "POST", + path: apiPath, + headers: apiHeaders, + params: apiParams, + converter: converter + ) + } + + /// + /// Create a new Document. Before using this route, you should create a new + /// collection resource using either a [server + /// integration](https://appwrite.io/docs/server/databases#documentsDBCreateCollection) + /// API or directly from your database console. + /// + /// - Parameters: + /// - databaseId: String + /// - collectionId: String + /// - documentId: String + /// - data: Any + /// - permissions: [String] (optional) + /// - transactionId: String (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.Document + /// + open func createDocument( + databaseId: String, + collectionId: String, + documentId: String, + data: Any, + permissions: [String]? = nil, + transactionId: String? = nil + ) async throws -> AppwriteModels.Document<[String: AnyCodable]> { + return try await createDocument( + databaseId: databaseId, + collectionId: collectionId, + documentId: documentId, + data: data, + permissions: permissions, + transactionId: transactionId, + nestedType: [String: AnyCodable].self + ) + } + /// + /// Get a list of all the user's documents in a given collection using a POST + /// request. This behaves identically to the list documents endpoint but + /// accepts the queries in the request body, allowing much larger `queries` + /// arrays than can fit in a URL query string. + /// + /// - Parameters: + /// - databaseId: String + /// - collectionId: String + /// - queries: [String] (optional) + /// - transactionId: String (optional) + /// - total: Bool (optional) + /// - ttl: Int (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.DocumentList + /// + open func createQuery( + databaseId: String, + collectionId: String, + queries: [String]? = nil, + transactionId: String? = nil, + total: Bool? = nil, + ttl: Int? = nil, + nestedType: T.Type + ) async throws -> AppwriteModels.DocumentList { + let apiPath: String = "/vectorsdb/{databaseId}/collections/{collectionId}/documents/query" + .replacingOccurrences(of: "{databaseId}", with: databaseId) + .replacingOccurrences(of: "{collectionId}", with: collectionId) + + let apiParams: [String: Any?] = [ + "queries": queries, + "transactionId": transactionId, + "total": total, + "ttl": ttl, + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "content-type": "application/json", + "accept": "application/json", + ] + + let converter: (Any) throws -> AppwriteModels.DocumentList = { response in + return AppwriteModels.DocumentList.from(map: response as! [String: Any]) + } + + return try await client.call( + method: "POST", + path: apiPath, + headers: apiHeaders, + params: apiParams, + converter: converter + ) + } + + /// + /// Get a list of all the user's documents in a given collection using a POST + /// request. This behaves identically to the list documents endpoint but + /// accepts the queries in the request body, allowing much larger `queries` + /// arrays than can fit in a URL query string. + /// + /// - Parameters: + /// - databaseId: String + /// - collectionId: String + /// - queries: [String] (optional) + /// - transactionId: String (optional) + /// - total: Bool (optional) + /// - ttl: Int (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.DocumentList + /// + open func createQuery( + databaseId: String, + collectionId: String, + queries: [String]? = nil, + transactionId: String? = nil, + total: Bool? = nil, + ttl: Int? = nil + ) async throws -> AppwriteModels.DocumentList<[String: AnyCodable]> { + return try await createQuery( + databaseId: databaseId, + collectionId: collectionId, + queries: queries, + transactionId: transactionId, + total: total, + ttl: ttl, + nestedType: [String: AnyCodable].self + ) + } + /// + /// Get a document by its unique ID. This endpoint response returns a JSON + /// object with the document data. + /// + /// - Parameters: + /// - databaseId: String + /// - collectionId: String + /// - documentId: String + /// - queries: [String] (optional) + /// - transactionId: String (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.Document + /// + open func getDocument( + databaseId: String, + collectionId: String, + documentId: String, + queries: [String]? = nil, + transactionId: String? = nil, + nestedType: T.Type + ) async throws -> AppwriteModels.Document { + let apiPath: String = "/vectorsdb/{databaseId}/collections/{collectionId}/documents/{documentId}" + .replacingOccurrences(of: "{databaseId}", with: databaseId) + .replacingOccurrences(of: "{collectionId}", with: collectionId) + .replacingOccurrences(of: "{documentId}", with: documentId) + + let apiParams: [String: Any?] = [ + "queries": queries, + "transactionId": transactionId, + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "accept": "application/json", + ] + + let converter: (Any) throws -> AppwriteModels.Document = { response in + return AppwriteModels.Document.from(map: response as! [String: Any]) + } + + return try await client.call( + method: "GET", + path: apiPath, + headers: apiHeaders, + params: apiParams, + converter: converter + ) + } + + /// + /// Get a document by its unique ID. This endpoint response returns a JSON + /// object with the document data. + /// + /// - Parameters: + /// - databaseId: String + /// - collectionId: String + /// - documentId: String + /// - queries: [String] (optional) + /// - transactionId: String (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.Document + /// + open func getDocument( + databaseId: String, + collectionId: String, + documentId: String, + queries: [String]? = nil, + transactionId: String? = nil + ) async throws -> AppwriteModels.Document<[String: AnyCodable]> { + return try await getDocument( + databaseId: databaseId, + collectionId: collectionId, + documentId: documentId, + queries: queries, + transactionId: transactionId, + nestedType: [String: AnyCodable].self + ) + } + /// + /// Create or update a Document. Before using this route, you should create a + /// new collection resource using either a [server + /// integration](https://appwrite.io/docs/server/databases#documentsDBCreateCollection) + /// API or directly from your database console. + /// + /// - Parameters: + /// - databaseId: String + /// - collectionId: String + /// - documentId: String + /// - data: Any (optional) + /// - permissions: [String] (optional) + /// - transactionId: String (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.Document + /// + open func upsertDocument( + databaseId: String, + collectionId: String, + documentId: String, + data: Any? = nil, + permissions: [String]? = nil, + transactionId: String? = nil, + nestedType: T.Type + ) async throws -> AppwriteModels.Document { + let apiPath: String = "/vectorsdb/{databaseId}/collections/{collectionId}/documents/{documentId}" + .replacingOccurrences(of: "{databaseId}", with: databaseId) + .replacingOccurrences(of: "{collectionId}", with: collectionId) + .replacingOccurrences(of: "{documentId}", with: documentId) + + let apiParams: [String: Any?] = [ + "data": data, + "permissions": permissions, + "transactionId": transactionId, + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "content-type": "application/json", + "accept": "application/json", + ] + + let converter: (Any) throws -> AppwriteModels.Document = { response in + return AppwriteModels.Document.from(map: response as! [String: Any]) + } + + return try await client.call( + method: "PUT", + path: apiPath, + headers: apiHeaders, + params: apiParams, + converter: converter + ) + } + + /// + /// Create or update a Document. Before using this route, you should create a + /// new collection resource using either a [server + /// integration](https://appwrite.io/docs/server/databases#documentsDBCreateCollection) + /// API or directly from your database console. + /// + /// - Parameters: + /// - databaseId: String + /// - collectionId: String + /// - documentId: String + /// - data: Any (optional) + /// - permissions: [String] (optional) + /// - transactionId: String (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.Document + /// + open func upsertDocument( + databaseId: String, + collectionId: String, + documentId: String, + data: Any? = nil, + permissions: [String]? = nil, + transactionId: String? = nil + ) async throws -> AppwriteModels.Document<[String: AnyCodable]> { + return try await upsertDocument( + databaseId: databaseId, + collectionId: collectionId, + documentId: documentId, + data: data, + permissions: permissions, + transactionId: transactionId, + nestedType: [String: AnyCodable].self + ) + } + /// + /// Update a document by its unique ID. Using the patch method you can pass + /// only specific fields that will get updated. + /// + /// - Parameters: + /// - databaseId: String + /// - collectionId: String + /// - documentId: String + /// - data: Any (optional) + /// - permissions: [String] (optional) + /// - transactionId: String (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.Document + /// + open func updateDocument( + databaseId: String, + collectionId: String, + documentId: String, + data: Any? = nil, + permissions: [String]? = nil, + transactionId: String? = nil, + nestedType: T.Type + ) async throws -> AppwriteModels.Document { + let apiPath: String = "/vectorsdb/{databaseId}/collections/{collectionId}/documents/{documentId}" + .replacingOccurrences(of: "{databaseId}", with: databaseId) + .replacingOccurrences(of: "{collectionId}", with: collectionId) + .replacingOccurrences(of: "{documentId}", with: documentId) + + let apiParams: [String: Any?] = [ + "data": data, + "permissions": permissions, + "transactionId": transactionId, + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "content-type": "application/json", + "accept": "application/json", + ] + + let converter: (Any) throws -> AppwriteModels.Document = { response in + return AppwriteModels.Document.from(map: response as! [String: Any]) + } + + return try await client.call( + method: "PATCH", + path: apiPath, + headers: apiHeaders, + params: apiParams, + converter: converter + ) + } + + /// + /// Update a document by its unique ID. Using the patch method you can pass + /// only specific fields that will get updated. + /// + /// - Parameters: + /// - databaseId: String + /// - collectionId: String + /// - documentId: String + /// - data: Any (optional) + /// - permissions: [String] (optional) + /// - transactionId: String (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.Document + /// + open func updateDocument( + databaseId: String, + collectionId: String, + documentId: String, + data: Any? = nil, + permissions: [String]? = nil, + transactionId: String? = nil + ) async throws -> AppwriteModels.Document<[String: AnyCodable]> { + return try await updateDocument( + databaseId: databaseId, + collectionId: collectionId, + documentId: documentId, + data: data, + permissions: permissions, + transactionId: transactionId, + nestedType: [String: AnyCodable].self + ) + } + /// + /// Delete a document by its unique ID. + /// + /// - Parameters: + /// - databaseId: String + /// - collectionId: String + /// - documentId: String + /// - transactionId: String (optional) + /// - Throws: Exception if the request fails + /// - Returns: Any + /// + open func deleteDocument( + databaseId: String, + collectionId: String, + documentId: String, + transactionId: String? = nil + ) async throws -> Any { + let apiPath: String = "/vectorsdb/{databaseId}/collections/{collectionId}/documents/{documentId}" + .replacingOccurrences(of: "{databaseId}", with: databaseId) + .replacingOccurrences(of: "{collectionId}", with: collectionId) + .replacingOccurrences(of: "{documentId}", with: documentId) + + let apiParams: [String: Any?] = [ + "transactionId": transactionId + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "content-type": "application/json", + ] + + return try await client.call( + method: "DELETE", + path: apiPath, + headers: apiHeaders, + params: apiParams + ) + } +} diff --git a/Sources/Appwrite/StreamingDelegate.swift b/Sources/Appwrite/StreamingDelegate.swift index c80dc4e..a6332bf 100644 --- a/Sources/Appwrite/StreamingDelegate.swift +++ b/Sources/Appwrite/StreamingDelegate.swift @@ -1,6 +1,6 @@ +import AsyncHTTPClient import NIO import NIOHTTP1 -import AsyncHTTPClient class StreamingDelegate: HTTPClientResponseDelegate { @@ -46,7 +46,8 @@ class StreamingDelegate: HTTPClientResponseDelegate { func didSendRequestHead(task: HTTPClient.Task, _ head: HTTPRequestHead) { if let totalBytesString = head.headers.first(name: "Content-Length"), - let totalBytes = Int(totalBytesString) { + let totalBytes = Int(totalBytesString) + { progress.totalBytes = totalBytes } } @@ -64,7 +65,8 @@ class StreamingDelegate: HTTPClientResponseDelegate { case .idle: state = .head(head) if let totalBytesString = head.headers.first(name: "content-length"), - let totalBytes = Int(totalBytesString) { + let totalBytes = Int(totalBytesString) + { progress.totalBytes = totalBytes } case .head: @@ -107,9 +109,13 @@ class StreamingDelegate: HTTPClientResponseDelegate { case .idle: preconditionFailure("No head received before end") case .head(let head): - return Response(host: request.host, status: head.status, version: head.version, headers: head.headers, body: nil) + return Response( + host: request.host, status: head.status, version: head.version, + headers: head.headers, body: nil) case .body(let head): - return Response(host: request.host, status: head.status, version: head.version, headers: head.headers, body: nil) + return Response( + host: request.host, status: head.status, version: head.version, + headers: head.headers, body: nil) case .end: preconditionFailure("Request already processed") case .error(let error): @@ -121,4 +127,4 @@ class StreamingDelegate: HTTPClientResponseDelegate { state = .error(error) reportError?(AppwriteError(message: error.localizedDescription)) } -} \ No newline at end of file +} diff --git a/Sources/Appwrite/WebSockets/HTTPHandler.swift b/Sources/Appwrite/WebSockets/HTTPHandler.swift index 05b0b37..da50b65 100644 --- a/Sources/Appwrite/WebSockets/HTTPHandler.swift +++ b/Sources/Appwrite/WebSockets/HTTPHandler.swift @@ -1,6 +1,6 @@ +import Foundation import NIO import NIOHTTP1 -import Foundation /// Handles the HTTP pipeline for opening a WebSocket connection. /// @@ -8,7 +8,7 @@ import Foundation class HTTPHandler { unowned let client: WebSocketClient - + let headers: HTTPHeaders init(client: WebSocketClient, headers: HTTPHeaders) { @@ -39,14 +39,14 @@ class HTTPHandler { } } -extension HTTPHandler : ChannelInboundHandler, RemovableChannelHandler { - +extension HTTPHandler: ChannelInboundHandler, RemovableChannelHandler { + public typealias InboundIn = HTTPClientResponsePart public typealias OutboundOut = HTTPClientRequestPart - + func channelActive(context: ChannelHandlerContext) { var headers = HTTPHeaders() - + headers.add(name: "Host", value: "\(client.host):\(client.port)") headers.add(contentsOf: self.headers) headers.addDomainCookies(for: client.host) @@ -56,7 +56,7 @@ extension HTTPHandler : ChannelInboundHandler, RemovableChannelHandler { uri: "\(client.uri)?\(client.query)", headers: headers ) - + context.write(wrapOutboundOut(.head(requestHead)), promise: nil) context.writeAndFlush(wrapOutboundOut(.end(nil)), promise: nil) } diff --git a/Sources/Appwrite/WebSockets/MessageHandler.swift b/Sources/Appwrite/WebSockets/MessageHandler.swift index 89f1193..6968b1c 100644 --- a/Sources/Appwrite/WebSockets/MessageHandler.swift +++ b/Sources/Appwrite/WebSockets/MessageHandler.swift @@ -1,11 +1,12 @@ import Foundation import NIO -#if canImport(NIOFoundationCompat) -import NIOFoundationCompat -#endif import NIOHTTP1 import NIOWebSocket +#if canImport(NIOFoundationCompat) + import NIOFoundationCompat +#endif + /// Handles the HTTP pipeline for opening a WebSocket connection. /// /// Adds the required headers to the outbound upgrade connection request and handles success and failures responses. diff --git a/Sources/Appwrite/WebSockets/WebSocketClient.swift b/Sources/Appwrite/WebSockets/WebSocketClient.swift index 8e1b96e..5b84e65 100644 --- a/Sources/Appwrite/WebSockets/WebSocketClient.swift +++ b/Sources/Appwrite/WebSockets/WebSocketClient.swift @@ -1,12 +1,13 @@ +import Dispatch import Foundation import NIO -#if canImport(NIOFoundationCompat) -import NIOFoundationCompat -#endif import NIOHTTP1 -import NIOWebSocket -import Dispatch import NIOSSL +import NIOWebSocket + +#if canImport(NIOFoundationCompat) + import NIOFoundationCompat +#endif public let WEBSOCKET_LOCKER_QUEUE = "SyncLocker" public let WEBSOCKET_THREAD_QUEUE = "ThreadLocker" @@ -60,9 +61,9 @@ public class WebSocketClient { public var isConnected: Bool { channel?.isActive ?? false } - + // MARK: - Stored callbacks - + private var _openCallback: (NIOCore.Channel) -> Void = { _ in } var onOpen: (NIOCore.Channel) -> Void { get { @@ -76,8 +77,8 @@ public class WebSocketClient { } } } - - private var _closeCallback: (NIOCore.Channel, Data) -> Void = { _,_ in } + + private var _closeCallback: (NIOCore.Channel, Data) -> Void = { _, _ in } var onClose: (NIOCore.Channel, Data) -> Void { get { return locker.sync { @@ -104,7 +105,7 @@ public class WebSocketClient { } } } - + private var _binaryCallback: (Data) -> Void = { _ in } var onBinaryMessage: (Data) -> Void { get { @@ -118,8 +119,8 @@ public class WebSocketClient { } } } - - private var _errorCallBack: (Swift.Error?, HTTPResponseStatus?) -> Void = { _,_ in } + + private var _errorCallBack: (Swift.Error?, HTTPResponseStatus?) -> Void = { _, _ in } var onError: (Swift.Error?, HTTPResponseStatus?) -> Void { get { return locker.sync { @@ -132,9 +133,9 @@ public class WebSocketClient { } } } - + // MARK: - Callback setters - + /// Set a callback to be fired when a WebSocket connection is opened. /// /// - parameters: @@ -142,7 +143,7 @@ public class WebSocketClient { public func onOpen(_ callback: @escaping (NIOCore.Channel) -> Void) { onOpen = callback } - + /// Set a callback to be fired when a WebSocket text message is received. /// /// - parameters: @@ -174,9 +175,9 @@ public class WebSocketClient { public func onError(_ callback: @escaping (Swift.Error?, HTTPResponseStatus?) -> Void) { onError = callback } - + // MARK: - Constructors - + /// Create a new `WebSocketClient`. /// /// - parameters: @@ -249,7 +250,7 @@ public class WebSocketClient { SO_REUSEPORT ) - while(threadGroup == nil) { + while threadGroup == nil { try? await Task.sleep(nanoseconds: 10_000_000) } @@ -259,8 +260,9 @@ public class WebSocketClient { self.openChannel(channel: $0) } - _ = try await bootstrap - .connect(host: self.host,port: self.port) + _ = + try await bootstrap + .connect(host: self.host, port: self.port) .get() } @@ -274,16 +276,20 @@ public class WebSocketClient { } ) - let config: NIOHTTPClientUpgradeConfiguration = (upgraders: [basicUpgrader], completionHandler: { context in - context.channel.pipeline.removeHandler(httpHandler, promise: nil) - }) + let config: NIOHTTPClientUpgradeConfiguration = ( + upgraders: [basicUpgrader], + completionHandler: { context in + context.channel.pipeline.removeHandler(httpHandler, promise: nil) + } + ) return channel.pipeline.addHTTPClientHandlers(withClientUpgrade: config).flatMap { _ in return channel.pipeline.addHandler(httpHandler).flatMap { _ in if self.tlsEnabled { let tlsConfig = TLSConfiguration.makeClientConfiguration() let sslContext = try! NIOSSLContext(configuration: tlsConfig) - let sslHandler = try! NIOSSLClientHandler(context: sslContext, serverHostname: self.host) + let sslHandler = try! NIOSSLClientHandler( + context: sslContext, serverHostname: self.host) return channel.pipeline.addHandler(sslHandler, position: .first) } else { return channel.eventLoop.makeSucceededFuture(()) @@ -292,7 +298,9 @@ public class WebSocketClient { } } - private func upgradePipelineHandler(channel: NIOCore.Channel, response: HTTPResponseHead) -> EventLoopFuture { + private func upgradePipelineHandler(channel: NIOCore.Channel, response: HTTPResponseHead) + -> EventLoopFuture + { let handler = MessageHandler(client: self) if response.status == .switchingProtocols { diff --git a/Sources/Appwrite/WebSockets/WebSocketClientDelegate.swift b/Sources/Appwrite/WebSockets/WebSocketClientDelegate.swift index d6327e0..76eb4f6 100644 --- a/Sources/Appwrite/WebSockets/WebSocketClientDelegate.swift +++ b/Sources/Appwrite/WebSockets/WebSocketClientDelegate.swift @@ -3,9 +3,9 @@ import NIO import NIOHTTP1 /// Handles messages received by a connected WebSocket server. -public protocol WebSocketClientDelegate : AnyObject { +public protocol WebSocketClientDelegate: AnyObject { func onOpen(channel: NIOCore.Channel) - func onMessage(text: String) throws + func onMessage(text: String) throws func onMessage(data: Data) throws func onClose(channel: NIOCore.Channel, data: Data) func onError(error: Swift.Error?, status: HTTPResponseStatus?) throws diff --git a/Sources/AppwriteEnums/AuthenticationFactor.swift b/Sources/AppwriteEnums/AuthenticationFactor.swift index 10077a9..32426f8 100644 --- a/Sources/AppwriteEnums/AuthenticationFactor.swift +++ b/Sources/AppwriteEnums/AuthenticationFactor.swift @@ -5,6 +5,7 @@ public enum AuthenticationFactor: String, Codable, CustomStringConvertible { case phone = "phone" case totp = "totp" case recoverycode = "recoverycode" + case custom = "custom" public var description: String { return rawValue diff --git a/Sources/AppwriteEnums/ExecutionResourceType.swift b/Sources/AppwriteEnums/ExecutionResourceType.swift new file mode 100644 index 0000000..9dcf653 --- /dev/null +++ b/Sources/AppwriteEnums/ExecutionResourceType.swift @@ -0,0 +1,10 @@ +import Foundation + +public enum ExecutionResourceType: String, Codable, CustomStringConvertible { + case functions = "functions" + case sites = "sites" + + public var description: String { + return rawValue + } +} diff --git a/Sources/AppwriteEnums/ImageGravity.swift b/Sources/AppwriteEnums/ImageGravity.swift index 519f7cc..c008b5f 100644 --- a/Sources/AppwriteEnums/ImageGravity.swift +++ b/Sources/AppwriteEnums/ImageGravity.swift @@ -1,6 +1,7 @@ import Foundation public enum ImageGravity: String, Codable, CustomStringConvertible { + case auto = "auto" case center = "center" case topLeft = "top-left" case top = "top" diff --git a/Sources/AppwriteEnums/OAuthProvider.swift b/Sources/AppwriteEnums/OAuthProvider.swift index 0bb2486..86ae961 100644 --- a/Sources/AppwriteEnums/OAuthProvider.swift +++ b/Sources/AppwriteEnums/OAuthProvider.swift @@ -10,6 +10,7 @@ public enum OAuthProvider: String, Codable, CustomStringConvertible { case bitbucket = "bitbucket" case bitly = "bitly" case box = "box" + case cloudflare = "cloudflare" case dailymotion = "dailymotion" case discord = "discord" case disqus = "disqus" @@ -21,6 +22,7 @@ public enum OAuthProvider: String, Codable, CustomStringConvertible { case github = "github" case gitlab = "gitlab" case google = "google" + case huggingface = "huggingface" case keycloak = "keycloak" case kick = "kick" case linkedin = "linkedin" @@ -31,6 +33,7 @@ public enum OAuthProvider: String, Codable, CustomStringConvertible { case paypal = "paypal" case paypalSandbox = "paypalSandbox" case podio = "podio" + case resend = "resend" case salesforce = "salesforce" case slack = "slack" case spotify = "spotify" diff --git a/Sources/AppwriteModels/AlgoArgon2.swift b/Sources/AppwriteModels/AlgoArgon2.swift index b43668e..9eae6a5 100644 --- a/Sources/AppwriteModels/AlgoArgon2.swift +++ b/Sources/AppwriteModels/AlgoArgon2.swift @@ -55,11 +55,11 @@ open class AlgoArgon2: Codable { "type": type as Any, "memoryCost": memoryCost as Any, "timeCost": timeCost as Any, - "threads": threads as Any + "threads": threads as Any, ] } - public static func from(map: [String: Any] ) -> AlgoArgon2 { + public static func from(map: [String: Any]) -> AlgoArgon2 { return AlgoArgon2( type: map["type"] as! String, memoryCost: map["memoryCost"] as! Int, diff --git a/Sources/AppwriteModels/AlgoBcrypt.swift b/Sources/AppwriteModels/AlgoBcrypt.swift index 1da5027..484860e 100644 --- a/Sources/AppwriteModels/AlgoBcrypt.swift +++ b/Sources/AppwriteModels/AlgoBcrypt.swift @@ -35,7 +35,7 @@ open class AlgoBcrypt: Codable { ] } - public static func from(map: [String: Any] ) -> AlgoBcrypt { + public static func from(map: [String: Any]) -> AlgoBcrypt { return AlgoBcrypt( type: map["type"] as! String ) diff --git a/Sources/AppwriteModels/AlgoMd5.swift b/Sources/AppwriteModels/AlgoMd5.swift index 210e26f..d7e2613 100644 --- a/Sources/AppwriteModels/AlgoMd5.swift +++ b/Sources/AppwriteModels/AlgoMd5.swift @@ -35,7 +35,7 @@ open class AlgoMd5: Codable { ] } - public static func from(map: [String: Any] ) -> AlgoMd5 { + public static func from(map: [String: Any]) -> AlgoMd5 { return AlgoMd5( type: map["type"] as! String ) diff --git a/Sources/AppwriteModels/AlgoPhpass.swift b/Sources/AppwriteModels/AlgoPhpass.swift index b044d8e..90b31ce 100644 --- a/Sources/AppwriteModels/AlgoPhpass.swift +++ b/Sources/AppwriteModels/AlgoPhpass.swift @@ -35,7 +35,7 @@ open class AlgoPhpass: Codable { ] } - public static func from(map: [String: Any] ) -> AlgoPhpass { + public static func from(map: [String: Any]) -> AlgoPhpass { return AlgoPhpass( type: map["type"] as! String ) diff --git a/Sources/AppwriteModels/AlgoScrypt.swift b/Sources/AppwriteModels/AlgoScrypt.swift index 45289c6..c3323f3 100644 --- a/Sources/AppwriteModels/AlgoScrypt.swift +++ b/Sources/AppwriteModels/AlgoScrypt.swift @@ -63,11 +63,11 @@ open class AlgoScrypt: Codable { "costCpu": costCpu as Any, "costMemory": costMemory as Any, "costParallel": costParallel as Any, - "length": length as Any + "length": length as Any, ] } - public static func from(map: [String: Any] ) -> AlgoScrypt { + public static func from(map: [String: Any]) -> AlgoScrypt { return AlgoScrypt( type: map["type"] as! String, costCpu: map["costCpu"] as! Int, diff --git a/Sources/AppwriteModels/AlgoScryptModified.swift b/Sources/AppwriteModels/AlgoScryptModified.swift index 5e64b11..71fb8b6 100644 --- a/Sources/AppwriteModels/AlgoScryptModified.swift +++ b/Sources/AppwriteModels/AlgoScryptModified.swift @@ -55,11 +55,11 @@ open class AlgoScryptModified: Codable { "type": type as Any, "salt": salt as Any, "saltSeparator": saltSeparator as Any, - "signerKey": signerKey as Any + "signerKey": signerKey as Any, ] } - public static func from(map: [String: Any] ) -> AlgoScryptModified { + public static func from(map: [String: Any]) -> AlgoScryptModified { return AlgoScryptModified( type: map["type"] as! String, salt: map["salt"] as! String, diff --git a/Sources/AppwriteModels/AlgoSha.swift b/Sources/AppwriteModels/AlgoSha.swift index 399ab8b..54b4831 100644 --- a/Sources/AppwriteModels/AlgoSha.swift +++ b/Sources/AppwriteModels/AlgoSha.swift @@ -35,7 +35,7 @@ open class AlgoSha: Codable { ] } - public static func from(map: [String: Any] ) -> AlgoSha { + public static func from(map: [String: Any]) -> AlgoSha { return AlgoSha( type: map["type"] as! String ) diff --git a/Sources/AppwriteModels/AppInstallation.swift b/Sources/AppwriteModels/AppInstallation.swift new file mode 100644 index 0000000..140feb1 --- /dev/null +++ b/Sources/AppwriteModels/AppInstallation.swift @@ -0,0 +1,124 @@ +import Foundation +import JSONCodable + +/// AppInstallation +open class AppInstallation: Codable { + + enum CodingKeys: String, CodingKey { + case id = "$id" + case createdAt = "$createdAt" + case updatedAt = "$updatedAt" + case appId = "appId" + case teamId = "teamId" + case scopes = "scopes" + case authorizationDetails = "authorizationDetails" + case createdById = "createdById" + case createdByName = "createdByName" + case lastAccessedAt = "lastAccessedAt" + } + + /// Installation ID. + public let id: String + /// Installation creation time in ISO 8601 format. + public let createdAt: String + /// Installation update time in ISO 8601 format. + public let updatedAt: String + /// ID of the installed application. + public let appId: String + /// ID of the team the application is installed on. + public let teamId: String + /// Scopes granted to the application. Snapshot of the application's installation scopes taken when the installation was created or last updated. + public let scopes: [String] + /// Authorization details granted to the application. Rich authorization request (RFC 9396) style entries; the Appwrite Console stores authorized project IDs here. + public let authorizationDetails: [AnyCodable] + /// ID of the user who created the installation. + public let createdById: String + /// Name of the user who created the installation. + public let createdByName: String + /// Time an access token was last issued for the installation in ISO 8601 format. Null if never used. + public let lastAccessedAt: String? + + init( + id: String, + createdAt: String, + updatedAt: String, + appId: String, + teamId: String, + scopes: [String], + authorizationDetails: [AnyCodable], + createdById: String, + createdByName: String, + lastAccessedAt: String? + ) { + self.id = id + self.createdAt = createdAt + self.updatedAt = updatedAt + self.appId = appId + self.teamId = teamId + self.scopes = scopes + self.authorizationDetails = authorizationDetails + self.createdById = createdById + self.createdByName = createdByName + self.lastAccessedAt = lastAccessedAt + } + + public required init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.id = try container.decode(String.self, forKey: .id) + self.createdAt = try container.decode(String.self, forKey: .createdAt) + self.updatedAt = try container.decode(String.self, forKey: .updatedAt) + self.appId = try container.decode(String.self, forKey: .appId) + self.teamId = try container.decode(String.self, forKey: .teamId) + self.scopes = try container.decode([String].self, forKey: .scopes) + self.authorizationDetails = try container.decode([AnyCodable].self, forKey: .authorizationDetails) + self.createdById = try container.decode(String.self, forKey: .createdById) + self.createdByName = try container.decode(String.self, forKey: .createdByName) + self.lastAccessedAt = try container.decodeIfPresent(String.self, forKey: .lastAccessedAt) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(id, forKey: .id) + try container.encode(createdAt, forKey: .createdAt) + try container.encode(updatedAt, forKey: .updatedAt) + try container.encode(appId, forKey: .appId) + try container.encode(teamId, forKey: .teamId) + try container.encode(scopes, forKey: .scopes) + try container.encode(authorizationDetails, forKey: .authorizationDetails) + try container.encode(createdById, forKey: .createdById) + try container.encode(createdByName, forKey: .createdByName) + try container.encodeIfPresent(lastAccessedAt, forKey: .lastAccessedAt) + } + + public func toMap() -> [String: Any] { + return [ + "$id": id as Any, + "$createdAt": createdAt as Any, + "$updatedAt": updatedAt as Any, + "appId": appId as Any, + "teamId": teamId as Any, + "scopes": scopes as Any, + "authorizationDetails": authorizationDetails as Any, + "createdById": createdById as Any, + "createdByName": createdByName as Any, + "lastAccessedAt": lastAccessedAt as Any, + ] + } + + public static func from(map: [String: Any]) -> AppInstallation { + return AppInstallation( + id: map["$id"] as! String, + createdAt: map["$createdAt"] as! String, + updatedAt: map["$updatedAt"] as! String, + appId: map["appId"] as! String, + teamId: map["teamId"] as! String, + scopes: map["scopes"] as! [String], + authorizationDetails: (map["authorizationDetails"] as! [Any]).map { AnyCodable($0) }, + createdById: map["createdById"] as! String, + createdByName: map["createdByName"] as! String, + lastAccessedAt: map["lastAccessedAt"] as? String + ) + } +} diff --git a/Sources/AppwriteModels/AppInstallationList.swift b/Sources/AppwriteModels/AppInstallationList.swift new file mode 100644 index 0000000..63e9835 --- /dev/null +++ b/Sources/AppwriteModels/AppInstallationList.swift @@ -0,0 +1,52 @@ +import Foundation +import JSONCodable + +/// App installations list +open class AppInstallationList: Codable { + + enum CodingKeys: String, CodingKey { + case total = "total" + case installations = "installations" + } + + /// Total number of installations that matched your query. + public let total: Int + /// List of installations. + public let installations: [AppInstallation] + + init( + total: Int, + installations: [AppInstallation] + ) { + self.total = total + self.installations = installations + } + + public required init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.total = try container.decode(Int.self, forKey: .total) + self.installations = try container.decode([AppInstallation].self, forKey: .installations) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(total, forKey: .total) + try container.encode(installations, forKey: .installations) + } + + public func toMap() -> [String: Any] { + return [ + "total": total as Any, + "installations": installations.map { $0.toMap() } as Any, + ] + } + + public static func from(map: [String: Any]) -> AppInstallationList { + return AppInstallationList( + total: map["total"] as! Int, + installations: (map["installations"] as! [[String: Any]]).map { AppInstallation.from(map: $0) } + ) + } +} diff --git a/Sources/AppwriteModels/Continent.swift b/Sources/AppwriteModels/Continent.swift index a310304..d0434ad 100644 --- a/Sources/AppwriteModels/Continent.swift +++ b/Sources/AppwriteModels/Continent.swift @@ -39,11 +39,11 @@ open class Continent: Codable { public func toMap() -> [String: Any] { return [ "name": name as Any, - "code": code as Any + "code": code as Any, ] } - public static func from(map: [String: Any] ) -> Continent { + public static func from(map: [String: Any]) -> Continent { return Continent( name: map["name"] as! String, code: map["code"] as! String diff --git a/Sources/AppwriteModels/ContinentList.swift b/Sources/AppwriteModels/ContinentList.swift index 2279b9b..3738f48 100644 --- a/Sources/AppwriteModels/ContinentList.swift +++ b/Sources/AppwriteModels/ContinentList.swift @@ -39,11 +39,11 @@ open class ContinentList: Codable { public func toMap() -> [String: Any] { return [ "total": total as Any, - "continents": continents.map { $0.toMap() } as Any + "continents": continents.map { $0.toMap() } as Any, ] } - public static func from(map: [String: Any] ) -> ContinentList { + public static func from(map: [String: Any]) -> ContinentList { return ContinentList( total: map["total"] as! Int, continents: (map["continents"] as! [[String: Any]]).map { Continent.from(map: $0) } diff --git a/Sources/AppwriteModels/Country.swift b/Sources/AppwriteModels/Country.swift index f5a7a10..90daca1 100644 --- a/Sources/AppwriteModels/Country.swift +++ b/Sources/AppwriteModels/Country.swift @@ -39,11 +39,11 @@ open class Country: Codable { public func toMap() -> [String: Any] { return [ "name": name as Any, - "code": code as Any + "code": code as Any, ] } - public static func from(map: [String: Any] ) -> Country { + public static func from(map: [String: Any]) -> Country { return Country( name: map["name"] as! String, code: map["code"] as! String diff --git a/Sources/AppwriteModels/CountryList.swift b/Sources/AppwriteModels/CountryList.swift index 4d83832..252fa68 100644 --- a/Sources/AppwriteModels/CountryList.swift +++ b/Sources/AppwriteModels/CountryList.swift @@ -39,11 +39,11 @@ open class CountryList: Codable { public func toMap() -> [String: Any] { return [ "total": total as Any, - "countries": countries.map { $0.toMap() } as Any + "countries": countries.map { $0.toMap() } as Any, ] } - public static func from(map: [String: Any] ) -> CountryList { + public static func from(map: [String: Any]) -> CountryList { return CountryList( total: map["total"] as! Int, countries: (map["countries"] as! [[String: Any]]).map { Country.from(map: $0) } diff --git a/Sources/AppwriteModels/Currency.swift b/Sources/AppwriteModels/Currency.swift index 6e546f1..ebfe800 100644 --- a/Sources/AppwriteModels/Currency.swift +++ b/Sources/AppwriteModels/Currency.swift @@ -79,11 +79,11 @@ open class Currency: Codable { "decimalDigits": decimalDigits as Any, "rounding": rounding as Any, "code": code as Any, - "namePlural": namePlural as Any + "namePlural": namePlural as Any, ] } - public static func from(map: [String: Any] ) -> Currency { + public static func from(map: [String: Any]) -> Currency { return Currency( symbol: map["symbol"] as! String, name: map["name"] as! String, diff --git a/Sources/AppwriteModels/CurrencyList.swift b/Sources/AppwriteModels/CurrencyList.swift index 3d8cdcd..64b7841 100644 --- a/Sources/AppwriteModels/CurrencyList.swift +++ b/Sources/AppwriteModels/CurrencyList.swift @@ -39,11 +39,11 @@ open class CurrencyList: Codable { public func toMap() -> [String: Any] { return [ "total": total as Any, - "currencies": currencies.map { $0.toMap() } as Any + "currencies": currencies.map { $0.toMap() } as Any, ] } - public static func from(map: [String: Any] ) -> CurrencyList { + public static func from(map: [String: Any]) -> CurrencyList { return CurrencyList( total: map["total"] as! Int, currencies: (map["currencies"] as! [[String: Any]]).map { Currency.from(map: $0) } diff --git a/Sources/AppwriteModels/Document.swift b/Sources/AppwriteModels/Document.swift index a3cba78..d551bd1 100644 --- a/Sources/AppwriteModels/Document.swift +++ b/Sources/AppwriteModels/Document.swift @@ -2,7 +2,7 @@ import Foundation import JSONCodable /// Document -open class Document: Codable { +open class Document: Codable { enum CodingKeys: String, CodingKey { case id = "$id" @@ -87,11 +87,11 @@ open class Document: Codable { "$createdAt": createdAt as Any, "$updatedAt": updatedAt as Any, "$permissions": permissions as Any, - "data": (try! JSONSerialization.jsonObject(with: JSONEncoder().encode(data))) as? [String: Any] ?? [:] + "data": (try! JSONSerialization.jsonObject(with: JSONEncoder().encode(data))) as? [String: Any] ?? [:], ] } - public static func from(map: [String: Any] ) -> Document { + public static func from(map: [String: Any]) -> Document { return Document( id: map["$id"] as? String ?? "", sequence: map["$sequence"] as? String ?? "", diff --git a/Sources/AppwriteModels/DocumentList.swift b/Sources/AppwriteModels/DocumentList.swift index 4f55579..ea3f589 100644 --- a/Sources/AppwriteModels/DocumentList.swift +++ b/Sources/AppwriteModels/DocumentList.swift @@ -2,7 +2,7 @@ import Foundation import JSONCodable /// Documents List -open class DocumentList: Codable { +open class DocumentList: Codable { enum CodingKeys: String, CodingKey { case total = "total" @@ -39,11 +39,11 @@ open class DocumentList: Codable { public func toMap() -> [String: Any] { return [ "total": total as Any, - "documents": documents.map { $0.toMap() } as Any + "documents": documents.map { $0.toMap() } as Any, ] } - public static func from(map: [String: Any] ) -> DocumentList { + public static func from(map: [String: Any]) -> DocumentList { return DocumentList( total: map["total"] as! Int, documents: (map["documents"] as! [[String: Any]]).map { Document.from(map: $0) } diff --git a/Sources/AppwriteModels/Execution.swift b/Sources/AppwriteModels/Execution.swift index c4ee4ea..e02bb69 100644 --- a/Sources/AppwriteModels/Execution.swift +++ b/Sources/AppwriteModels/Execution.swift @@ -1,6 +1,6 @@ +import AppwriteEnums import Foundation import JSONCodable -import AppwriteEnums /// Execution open class Execution: Codable { @@ -10,7 +10,8 @@ open class Execution: Codable { case createdAt = "$createdAt" case updatedAt = "$updatedAt" case permissions = "$permissions" - case functionId = "functionId" + case resourceId = "resourceId" + case resourceType = "resourceType" case deploymentId = "deploymentId" case trigger = "trigger" case status = "status" @@ -34,13 +35,15 @@ open class Execution: Codable { public let updatedAt: String /// Execution roles. public let permissions: [String] - /// Function ID. - public let functionId: String - /// Function's deployment ID used to create the execution. + /// Function or site ID. + public let resourceId: String + /// Execution resource type. + public let resourceType: AppwriteEnums.ExecutionResourceType + /// Deployment ID used to create the execution. public let deploymentId: String - /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. + /// The trigger that caused the resource to execute. Possible values can be: `http`, `schedule`, or `event`. public let trigger: AppwriteEnums.ExecutionTrigger - /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, `failed`, or `scheduled`. + /// The status of the resource execution. Possible values can be: `waiting`, `processing`, `completed`, `failed`, or `scheduled`. public let status: AppwriteEnums.ExecutionStatus /// HTTP request method type. public let requestMethod: String @@ -54,9 +57,9 @@ open class Execution: Codable { public let responseBody: String /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. public let responseHeaders: [Headers] - /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + /// Resource logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. public let logs: String - /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + /// Resource errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. public let errors: String /// Resource(function/site) execution duration in seconds. public let duration: Double @@ -68,7 +71,8 @@ open class Execution: Codable { createdAt: String, updatedAt: String, permissions: [String], - functionId: String, + resourceId: String, + resourceType: AppwriteEnums.ExecutionResourceType, deploymentId: String, trigger: AppwriteEnums.ExecutionTrigger, status: AppwriteEnums.ExecutionStatus, @@ -87,7 +91,8 @@ open class Execution: Codable { self.createdAt = createdAt self.updatedAt = updatedAt self.permissions = permissions - self.functionId = functionId + self.resourceId = resourceId + self.resourceType = resourceType self.deploymentId = deploymentId self.trigger = trigger self.status = status @@ -110,7 +115,8 @@ open class Execution: Codable { self.createdAt = try container.decode(String.self, forKey: .createdAt) self.updatedAt = try container.decode(String.self, forKey: .updatedAt) self.permissions = try container.decode([String].self, forKey: .permissions) - self.functionId = try container.decode(String.self, forKey: .functionId) + self.resourceId = try container.decode(String.self, forKey: .resourceId) + self.resourceType = AppwriteEnums.ExecutionResourceType(rawValue: try container.decode(String.self, forKey: .resourceType))! self.deploymentId = try container.decode(String.self, forKey: .deploymentId) self.trigger = AppwriteEnums.ExecutionTrigger(rawValue: try container.decode(String.self, forKey: .trigger))! self.status = AppwriteEnums.ExecutionStatus(rawValue: try container.decode(String.self, forKey: .status))! @@ -133,7 +139,8 @@ open class Execution: Codable { try container.encode(createdAt, forKey: .createdAt) try container.encode(updatedAt, forKey: .updatedAt) try container.encode(permissions, forKey: .permissions) - try container.encode(functionId, forKey: .functionId) + try container.encode(resourceId, forKey: .resourceId) + try container.encode(resourceType.rawValue, forKey: .resourceType) try container.encode(deploymentId, forKey: .deploymentId) try container.encode(trigger.rawValue, forKey: .trigger) try container.encode(status.rawValue, forKey: .status) @@ -155,7 +162,8 @@ open class Execution: Codable { "$createdAt": createdAt as Any, "$updatedAt": updatedAt as Any, "$permissions": permissions as Any, - "functionId": functionId as Any, + "resourceId": resourceId as Any, + "resourceType": resourceType.rawValue as Any, "deploymentId": deploymentId as Any, "trigger": trigger.rawValue as Any, "status": status.rawValue as Any, @@ -168,20 +176,21 @@ open class Execution: Codable { "logs": logs as Any, "errors": errors as Any, "duration": duration as Any, - "scheduledAt": scheduledAt as Any + "scheduledAt": scheduledAt as Any, ] } - public static func from(map: [String: Any] ) -> Execution { + public static func from(map: [String: Any]) -> Execution { return Execution( id: map["$id"] as! String, createdAt: map["$createdAt"] as! String, updatedAt: map["$updatedAt"] as! String, permissions: map["$permissions"] as! [String], - functionId: map["functionId"] as! String, + resourceId: map["resourceId"] as! String, + resourceType: AppwriteEnums.ExecutionResourceType(rawValue: map["resourceType"] as! String)!, deploymentId: map["deploymentId"] as! String, - trigger: ExecutionTrigger(rawValue: map["trigger"] as! String)!, - status: ExecutionStatus(rawValue: map["status"] as! String)!, + trigger: AppwriteEnums.ExecutionTrigger(rawValue: map["trigger"] as! String)!, + status: AppwriteEnums.ExecutionStatus(rawValue: map["status"] as! String)!, requestMethod: map["requestMethod"] as! String, requestPath: map["requestPath"] as! String, requestHeaders: (map["requestHeaders"] as! [[String: Any]]).map { Headers.from(map: $0) }, diff --git a/Sources/AppwriteModels/ExecutionList.swift b/Sources/AppwriteModels/ExecutionList.swift index 4e09927..e26b285 100644 --- a/Sources/AppwriteModels/ExecutionList.swift +++ b/Sources/AppwriteModels/ExecutionList.swift @@ -39,11 +39,11 @@ open class ExecutionList: Codable { public func toMap() -> [String: Any] { return [ "total": total as Any, - "executions": executions.map { $0.toMap() } as Any + "executions": executions.map { $0.toMap() } as Any, ] } - public static func from(map: [String: Any] ) -> ExecutionList { + public static func from(map: [String: Any]) -> ExecutionList { return ExecutionList( total: map["total"] as! Int, executions: (map["executions"] as! [[String: Any]]).map { Execution.from(map: $0) } diff --git a/Sources/AppwriteModels/File.swift b/Sources/AppwriteModels/File.swift index 672dd3b..e97e48a 100644 --- a/Sources/AppwriteModels/File.swift +++ b/Sources/AppwriteModels/File.swift @@ -11,6 +11,8 @@ open class File: Codable { case updatedAt = "$updatedAt" case permissions = "$permissions" case name = "name" + case folder = "folder" + case key = "key" case signature = "signature" case mimeType = "mimeType" case sizeOriginal = "sizeOriginal" @@ -33,6 +35,10 @@ open class File: Codable { public let permissions: [String] /// File name. public let name: String + /// Virtual folder containing the file, with a trailing slash. Empty for the bucket root. + public let folder: String + /// Full virtual path of the file: the folder followed by the file name. + public let key: String /// File MD5 signature. public let signature: String /// File mime type. @@ -57,6 +63,8 @@ open class File: Codable { updatedAt: String, permissions: [String], name: String, + folder: String, + key: String, signature: String, mimeType: String, sizeOriginal: Int, @@ -72,6 +80,8 @@ open class File: Codable { self.updatedAt = updatedAt self.permissions = permissions self.name = name + self.folder = folder + self.key = key self.signature = signature self.mimeType = mimeType self.sizeOriginal = sizeOriginal @@ -91,6 +101,8 @@ open class File: Codable { self.updatedAt = try container.decode(String.self, forKey: .updatedAt) self.permissions = try container.decode([String].self, forKey: .permissions) self.name = try container.decode(String.self, forKey: .name) + self.folder = try container.decode(String.self, forKey: .folder) + self.key = try container.decode(String.self, forKey: .key) self.signature = try container.decode(String.self, forKey: .signature) self.mimeType = try container.decode(String.self, forKey: .mimeType) self.sizeOriginal = try container.decode(Int.self, forKey: .sizeOriginal) @@ -110,6 +122,8 @@ open class File: Codable { try container.encode(updatedAt, forKey: .updatedAt) try container.encode(permissions, forKey: .permissions) try container.encode(name, forKey: .name) + try container.encode(folder, forKey: .folder) + try container.encode(key, forKey: .key) try container.encode(signature, forKey: .signature) try container.encode(mimeType, forKey: .mimeType) try container.encode(sizeOriginal, forKey: .sizeOriginal) @@ -128,6 +142,8 @@ open class File: Codable { "$updatedAt": updatedAt as Any, "$permissions": permissions as Any, "name": name as Any, + "folder": folder as Any, + "key": key as Any, "signature": signature as Any, "mimeType": mimeType as Any, "sizeOriginal": sizeOriginal as Any, @@ -135,11 +151,11 @@ open class File: Codable { "chunksTotal": chunksTotal as Any, "chunksUploaded": chunksUploaded as Any, "encryption": encryption as Any, - "compression": compression as Any + "compression": compression as Any, ] } - public static func from(map: [String: Any] ) -> File { + public static func from(map: [String: Any]) -> File { return File( id: map["$id"] as! String, bucketId: map["bucketId"] as! String, @@ -147,6 +163,8 @@ open class File: Codable { updatedAt: map["$updatedAt"] as! String, permissions: map["$permissions"] as! [String], name: map["name"] as! String, + folder: map["folder"] as! String, + key: map["key"] as! String, signature: map["signature"] as! String, mimeType: map["mimeType"] as! String, sizeOriginal: map["sizeOriginal"] as! Int, diff --git a/Sources/AppwriteModels/FileList.swift b/Sources/AppwriteModels/FileList.swift index b265a6e..6565130 100644 --- a/Sources/AppwriteModels/FileList.swift +++ b/Sources/AppwriteModels/FileList.swift @@ -39,11 +39,11 @@ open class FileList: Codable { public func toMap() -> [String: Any] { return [ "total": total as Any, - "files": files.map { $0.toMap() } as Any + "files": files.map { $0.toMap() } as Any, ] } - public static func from(map: [String: Any] ) -> FileList { + public static func from(map: [String: Any]) -> FileList { return FileList( total: map["total"] as! Int, files: (map["files"] as! [[String: Any]]).map { File.from(map: $0) } diff --git a/Sources/AppwriteModels/Headers.swift b/Sources/AppwriteModels/Headers.swift index 0d344fc..a409e07 100644 --- a/Sources/AppwriteModels/Headers.swift +++ b/Sources/AppwriteModels/Headers.swift @@ -39,11 +39,11 @@ open class Headers: Codable { public func toMap() -> [String: Any] { return [ "name": name as Any, - "value": value as Any + "value": value as Any, ] } - public static func from(map: [String: Any] ) -> Headers { + public static func from(map: [String: Any]) -> Headers { return Headers( name: map["name"] as! String, value: map["value"] as! String diff --git a/Sources/AppwriteModels/Identity.swift b/Sources/AppwriteModels/Identity.swift index a0a565c..d8e6b6e 100644 --- a/Sources/AppwriteModels/Identity.swift +++ b/Sources/AppwriteModels/Identity.swift @@ -103,11 +103,11 @@ open class Identity: Codable { "providerEmail": providerEmail as Any, "providerAccessToken": providerAccessToken as Any, "providerAccessTokenExpiry": providerAccessTokenExpiry as Any, - "providerRefreshToken": providerRefreshToken as Any + "providerRefreshToken": providerRefreshToken as Any, ] } - public static func from(map: [String: Any] ) -> Identity { + public static func from(map: [String: Any]) -> Identity { return Identity( id: map["$id"] as! String, createdAt: map["$createdAt"] as! String, diff --git a/Sources/AppwriteModels/IdentityList.swift b/Sources/AppwriteModels/IdentityList.swift index 0ff998d..2e3f874 100644 --- a/Sources/AppwriteModels/IdentityList.swift +++ b/Sources/AppwriteModels/IdentityList.swift @@ -39,11 +39,11 @@ open class IdentityList: Codable { public func toMap() -> [String: Any] { return [ "total": total as Any, - "identities": identities.map { $0.toMap() } as Any + "identities": identities.map { $0.toMap() } as Any, ] } - public static func from(map: [String: Any] ) -> IdentityList { + public static func from(map: [String: Any]) -> IdentityList { return IdentityList( total: map["total"] as! Int, identities: (map["identities"] as! [[String: Any]]).map { Identity.from(map: $0) } diff --git a/Sources/AppwriteModels/Jwt.swift b/Sources/AppwriteModels/Jwt.swift index 22c5be2..78160e4 100644 --- a/Sources/AppwriteModels/Jwt.swift +++ b/Sources/AppwriteModels/Jwt.swift @@ -35,7 +35,7 @@ open class Jwt: Codable { ] } - public static func from(map: [String: Any] ) -> Jwt { + public static func from(map: [String: Any]) -> Jwt { return Jwt( jwt: map["jwt"] as! String ) diff --git a/Sources/AppwriteModels/Language.swift b/Sources/AppwriteModels/Language.swift index 6b12959..9c9d0dc 100644 --- a/Sources/AppwriteModels/Language.swift +++ b/Sources/AppwriteModels/Language.swift @@ -47,11 +47,11 @@ open class Language: Codable { return [ "name": name as Any, "code": code as Any, - "nativeName": nativeName as Any + "nativeName": nativeName as Any, ] } - public static func from(map: [String: Any] ) -> Language { + public static func from(map: [String: Any]) -> Language { return Language( name: map["name"] as! String, code: map["code"] as! String, diff --git a/Sources/AppwriteModels/LanguageList.swift b/Sources/AppwriteModels/LanguageList.swift index 0d57fdd..861ee63 100644 --- a/Sources/AppwriteModels/LanguageList.swift +++ b/Sources/AppwriteModels/LanguageList.swift @@ -39,11 +39,11 @@ open class LanguageList: Codable { public func toMap() -> [String: Any] { return [ "total": total as Any, - "languages": languages.map { $0.toMap() } as Any + "languages": languages.map { $0.toMap() } as Any, ] } - public static func from(map: [String: Any] ) -> LanguageList { + public static func from(map: [String: Any]) -> LanguageList { return LanguageList( total: map["total"] as! Int, languages: (map["languages"] as! [[String: Any]]).map { Language.from(map: $0) } diff --git a/Sources/AppwriteModels/Locale.swift b/Sources/AppwriteModels/Locale.swift index 9d10538..cf26870 100644 --- a/Sources/AppwriteModels/Locale.swift +++ b/Sources/AppwriteModels/Locale.swift @@ -167,11 +167,11 @@ open class Locale: Codable { "isp": isp as Any, "connectionType": connectionType as Any, "connectionUsageType": connectionUsageType as Any, - "connectionOrganization": connectionOrganization as Any + "connectionOrganization": connectionOrganization as Any, ] } - public static func from(map: [String: Any] ) -> Locale { + public static func from(map: [String: Any]) -> Locale { return Locale( ip: map["ip"] as! String, countryCode: map["countryCode"] as! String, diff --git a/Sources/AppwriteModels/LocaleCode.swift b/Sources/AppwriteModels/LocaleCode.swift index f4ac0fc..beaa5a1 100644 --- a/Sources/AppwriteModels/LocaleCode.swift +++ b/Sources/AppwriteModels/LocaleCode.swift @@ -39,11 +39,11 @@ open class LocaleCode: Codable { public func toMap() -> [String: Any] { return [ "code": code as Any, - "name": name as Any + "name": name as Any, ] } - public static func from(map: [String: Any] ) -> LocaleCode { + public static func from(map: [String: Any]) -> LocaleCode { return LocaleCode( code: map["code"] as! String, name: map["name"] as! String diff --git a/Sources/AppwriteModels/LocaleCodeList.swift b/Sources/AppwriteModels/LocaleCodeList.swift index 5a655bc..2556128 100644 --- a/Sources/AppwriteModels/LocaleCodeList.swift +++ b/Sources/AppwriteModels/LocaleCodeList.swift @@ -39,11 +39,11 @@ open class LocaleCodeList: Codable { public func toMap() -> [String: Any] { return [ "total": total as Any, - "localeCodes": localeCodes.map { $0.toMap() } as Any + "localeCodes": localeCodes.map { $0.toMap() } as Any, ] } - public static func from(map: [String: Any] ) -> LocaleCodeList { + public static func from(map: [String: Any]) -> LocaleCodeList { return LocaleCodeList( total: map["total"] as! Int, localeCodes: (map["localeCodes"] as! [[String: Any]]).map { LocaleCode.from(map: $0) } diff --git a/Sources/AppwriteModels/Log.swift b/Sources/AppwriteModels/Log.swift index 5b54e30..9e91844 100644 --- a/Sources/AppwriteModels/Log.swift +++ b/Sources/AppwriteModels/Log.swift @@ -199,11 +199,11 @@ open class Log: Codable { "deviceBrand": deviceBrand as Any, "deviceModel": deviceModel as Any, "countryCode": countryCode as Any, - "countryName": countryName as Any + "countryName": countryName as Any, ] } - public static func from(map: [String: Any] ) -> Log { + public static func from(map: [String: Any]) -> Log { return Log( event: map["event"] as! String, userId: map["userId"] as! String, diff --git a/Sources/AppwriteModels/LogList.swift b/Sources/AppwriteModels/LogList.swift index ac545e2..c776bc3 100644 --- a/Sources/AppwriteModels/LogList.swift +++ b/Sources/AppwriteModels/LogList.swift @@ -39,11 +39,11 @@ open class LogList: Codable { public func toMap() -> [String: Any] { return [ "total": total as Any, - "logs": logs.map { $0.toMap() } as Any + "logs": logs.map { $0.toMap() } as Any, ] } - public static func from(map: [String: Any] ) -> LogList { + public static func from(map: [String: Any]) -> LogList { return LogList( total: map["total"] as! Int, logs: (map["logs"] as! [[String: Any]]).map { Log.from(map: $0) } diff --git a/Sources/AppwriteModels/Membership.swift b/Sources/AppwriteModels/Membership.swift index 79228ee..70db9cf 100644 --- a/Sources/AppwriteModels/Membership.swift +++ b/Sources/AppwriteModels/Membership.swift @@ -143,11 +143,11 @@ open class Membership: Codable { "confirm": confirm as Any, "mfa": mfa as Any, "userAccessedAt": userAccessedAt as Any, - "roles": roles as Any + "roles": roles as Any, ] } - public static func from(map: [String: Any] ) -> Membership { + public static func from(map: [String: Any]) -> Membership { return Membership( id: map["$id"] as! String, createdAt: map["$createdAt"] as! String, diff --git a/Sources/AppwriteModels/MembershipList.swift b/Sources/AppwriteModels/MembershipList.swift index 283abae..8d738cd 100644 --- a/Sources/AppwriteModels/MembershipList.swift +++ b/Sources/AppwriteModels/MembershipList.swift @@ -39,11 +39,11 @@ open class MembershipList: Codable { public func toMap() -> [String: Any] { return [ "total": total as Any, - "memberships": memberships.map { $0.toMap() } as Any + "memberships": memberships.map { $0.toMap() } as Any, ] } - public static func from(map: [String: Any] ) -> MembershipList { + public static func from(map: [String: Any]) -> MembershipList { return MembershipList( total: map["total"] as! Int, memberships: (map["memberships"] as! [[String: Any]]).map { Membership.from(map: $0) } diff --git a/Sources/AppwriteModels/MfaChallenge.swift b/Sources/AppwriteModels/MfaChallenge.swift index 55d82ab..de83aa6 100644 --- a/Sources/AppwriteModels/MfaChallenge.swift +++ b/Sources/AppwriteModels/MfaChallenge.swift @@ -55,11 +55,11 @@ open class MfaChallenge: Codable { "$id": id as Any, "$createdAt": createdAt as Any, "userId": userId as Any, - "expire": expire as Any + "expire": expire as Any, ] } - public static func from(map: [String: Any] ) -> MfaChallenge { + public static func from(map: [String: Any]) -> MfaChallenge { return MfaChallenge( id: map["$id"] as! String, createdAt: map["$createdAt"] as! String, diff --git a/Sources/AppwriteModels/MfaFactors.swift b/Sources/AppwriteModels/MfaFactors.swift index fb8f35c..65a293b 100644 --- a/Sources/AppwriteModels/MfaFactors.swift +++ b/Sources/AppwriteModels/MfaFactors.swift @@ -9,6 +9,7 @@ open class MfaFactors: Codable { case phone = "phone" case email = "email" case recoveryCode = "recoveryCode" + case custom = "custom" } /// Can TOTP be used for MFA challenge for this account. @@ -19,17 +20,21 @@ open class MfaFactors: Codable { public let email: Bool /// Can recovery code be used for MFA challenge for this account. public let recoveryCode: Bool + /// Can custom factor be used for MFA challenge for this account. + public let custom: Bool init( totp: Bool, phone: Bool, email: Bool, - recoveryCode: Bool + recoveryCode: Bool, + custom: Bool ) { self.totp = totp self.phone = phone self.email = email self.recoveryCode = recoveryCode + self.custom = custom } public required init(from decoder: Decoder) throws { @@ -39,6 +44,7 @@ open class MfaFactors: Codable { self.phone = try container.decode(Bool.self, forKey: .phone) self.email = try container.decode(Bool.self, forKey: .email) self.recoveryCode = try container.decode(Bool.self, forKey: .recoveryCode) + self.custom = try container.decode(Bool.self, forKey: .custom) } public func encode(to encoder: Encoder) throws { @@ -48,6 +54,7 @@ open class MfaFactors: Codable { try container.encode(phone, forKey: .phone) try container.encode(email, forKey: .email) try container.encode(recoveryCode, forKey: .recoveryCode) + try container.encode(custom, forKey: .custom) } public func toMap() -> [String: Any] { @@ -55,16 +62,18 @@ open class MfaFactors: Codable { "totp": totp as Any, "phone": phone as Any, "email": email as Any, - "recoveryCode": recoveryCode as Any + "recoveryCode": recoveryCode as Any, + "custom": custom as Any, ] } - public static func from(map: [String: Any] ) -> MfaFactors { + public static func from(map: [String: Any]) -> MfaFactors { return MfaFactors( totp: map["totp"] as! Bool, phone: map["phone"] as! Bool, email: map["email"] as! Bool, - recoveryCode: map["recoveryCode"] as! Bool + recoveryCode: map["recoveryCode"] as! Bool, + custom: map["custom"] as! Bool ) } } diff --git a/Sources/AppwriteModels/MfaRecoveryCodes.swift b/Sources/AppwriteModels/MfaRecoveryCodes.swift index 47c80ab..43a5675 100644 --- a/Sources/AppwriteModels/MfaRecoveryCodes.swift +++ b/Sources/AppwriteModels/MfaRecoveryCodes.swift @@ -35,7 +35,7 @@ open class MfaRecoveryCodes: Codable { ] } - public static func from(map: [String: Any] ) -> MfaRecoveryCodes { + public static func from(map: [String: Any]) -> MfaRecoveryCodes { return MfaRecoveryCodes( recoveryCodes: map["recoveryCodes"] as! [String] ) diff --git a/Sources/AppwriteModels/MfaType.swift b/Sources/AppwriteModels/MfaType.swift index 2aaca85..68d3ae2 100644 --- a/Sources/AppwriteModels/MfaType.swift +++ b/Sources/AppwriteModels/MfaType.swift @@ -39,11 +39,11 @@ open class MfaType: Codable { public func toMap() -> [String: Any] { return [ "secret": secret as Any, - "uri": uri as Any + "uri": uri as Any, ] } - public static func from(map: [String: Any] ) -> MfaType { + public static func from(map: [String: Any]) -> MfaType { return MfaType( secret: map["secret"] as! String, uri: map["uri"] as! String diff --git a/Sources/AppwriteModels/Oauth2Consent.swift b/Sources/AppwriteModels/Oauth2Consent.swift new file mode 100644 index 0000000..79d97f9 --- /dev/null +++ b/Sources/AppwriteModels/Oauth2Consent.swift @@ -0,0 +1,124 @@ +import Foundation +import JSONCodable + +/// OAuth2 Consent +open class Oauth2Consent: Codable { + + enum CodingKeys: String, CodingKey { + case id = "$id" + case createdAt = "$createdAt" + case updatedAt = "$updatedAt" + case userId = "userId" + case appId = "appId" + case cimdUrl = "cimdUrl" + case scopes = "scopes" + case resources = "resources" + case authorizationDetails = "authorizationDetails" + case expire = "expire" + } + + /// Consent ID. + public let id: String + /// Consent creation time in ISO 8601 format. + public let createdAt: String + /// Consent update date in ISO 8601 format. + public let updatedAt: String + /// ID of the user the consent belongs to. + public let userId: String + /// ID of the registered app the consent was given to. Empty for URL-form (CIMD) clients. + public let appId: String + /// Client ID metadata document URL of the client the consent was given to. Empty for registered apps. + public let cimdUrl: String + /// OAuth2 scopes the user consented to. + public let scopes: [String] + /// RFC 8707 resource indicators the user consented to. + public let resources: [String] + /// Authorization details the user consented to, as a JSON string. Each entry has a `type` plus project-defined fields. + public let authorizationDetails: String + /// Consent expiration time in ISO 8601 format. Empty when the consent has no token-bound expiry yet. + public let expire: String + + init( + id: String, + createdAt: String, + updatedAt: String, + userId: String, + appId: String, + cimdUrl: String, + scopes: [String], + resources: [String], + authorizationDetails: String, + expire: String + ) { + self.id = id + self.createdAt = createdAt + self.updatedAt = updatedAt + self.userId = userId + self.appId = appId + self.cimdUrl = cimdUrl + self.scopes = scopes + self.resources = resources + self.authorizationDetails = authorizationDetails + self.expire = expire + } + + public required init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.id = try container.decode(String.self, forKey: .id) + self.createdAt = try container.decode(String.self, forKey: .createdAt) + self.updatedAt = try container.decode(String.self, forKey: .updatedAt) + self.userId = try container.decode(String.self, forKey: .userId) + self.appId = try container.decode(String.self, forKey: .appId) + self.cimdUrl = try container.decode(String.self, forKey: .cimdUrl) + self.scopes = try container.decode([String].self, forKey: .scopes) + self.resources = try container.decode([String].self, forKey: .resources) + self.authorizationDetails = try container.decode(String.self, forKey: .authorizationDetails) + self.expire = try container.decode(String.self, forKey: .expire) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(id, forKey: .id) + try container.encode(createdAt, forKey: .createdAt) + try container.encode(updatedAt, forKey: .updatedAt) + try container.encode(userId, forKey: .userId) + try container.encode(appId, forKey: .appId) + try container.encode(cimdUrl, forKey: .cimdUrl) + try container.encode(scopes, forKey: .scopes) + try container.encode(resources, forKey: .resources) + try container.encode(authorizationDetails, forKey: .authorizationDetails) + try container.encode(expire, forKey: .expire) + } + + public func toMap() -> [String: Any] { + return [ + "$id": id as Any, + "$createdAt": createdAt as Any, + "$updatedAt": updatedAt as Any, + "userId": userId as Any, + "appId": appId as Any, + "cimdUrl": cimdUrl as Any, + "scopes": scopes as Any, + "resources": resources as Any, + "authorizationDetails": authorizationDetails as Any, + "expire": expire as Any, + ] + } + + public static func from(map: [String: Any]) -> Oauth2Consent { + return Oauth2Consent( + id: map["$id"] as! String, + createdAt: map["$createdAt"] as! String, + updatedAt: map["$updatedAt"] as! String, + userId: map["userId"] as! String, + appId: map["appId"] as! String, + cimdUrl: map["cimdUrl"] as! String, + scopes: map["scopes"] as! [String], + resources: map["resources"] as! [String], + authorizationDetails: map["authorizationDetails"] as! String, + expire: map["expire"] as! String + ) + } +} diff --git a/Sources/AppwriteModels/Oauth2ConsentList.swift b/Sources/AppwriteModels/Oauth2ConsentList.swift new file mode 100644 index 0000000..03678d3 --- /dev/null +++ b/Sources/AppwriteModels/Oauth2ConsentList.swift @@ -0,0 +1,52 @@ +import Foundation +import JSONCodable + +/// OAuth2 consents list +open class Oauth2ConsentList: Codable { + + enum CodingKeys: String, CodingKey { + case total = "total" + case consents = "consents" + } + + /// Total number of consents that matched your query. + public let total: Int + /// List of consents. + public let consents: [Oauth2Consent] + + init( + total: Int, + consents: [Oauth2Consent] + ) { + self.total = total + self.consents = consents + } + + public required init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.total = try container.decode(Int.self, forKey: .total) + self.consents = try container.decode([Oauth2Consent].self, forKey: .consents) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(total, forKey: .total) + try container.encode(consents, forKey: .consents) + } + + public func toMap() -> [String: Any] { + return [ + "total": total as Any, + "consents": consents.map { $0.toMap() } as Any, + ] + } + + public static func from(map: [String: Any]) -> Oauth2ConsentList { + return Oauth2ConsentList( + total: map["total"] as! Int, + consents: (map["consents"] as! [[String: Any]]).map { Oauth2Consent.from(map: $0) } + ) + } +} diff --git a/Sources/AppwriteModels/Oauth2ConsentToken.swift b/Sources/AppwriteModels/Oauth2ConsentToken.swift new file mode 100644 index 0000000..04ab05c --- /dev/null +++ b/Sources/AppwriteModels/Oauth2ConsentToken.swift @@ -0,0 +1,133 @@ +import Foundation +import JSONCodable + +/// OAuth2 Consent Token +open class Oauth2ConsentToken: Codable { + + enum CodingKeys: String, CodingKey { + case id = "$id" + case createdAt = "$createdAt" + case updatedAt = "$updatedAt" + case consentId = "consentId" + case userId = "userId" + case appId = "appId" + case cimdUrl = "cimdUrl" + case scopes = "scopes" + case resources = "resources" + case authorizationDetails = "authorizationDetails" + case expire = "expire" + } + + /// Token family ID. + public let id: String + /// Token creation time in ISO 8601 format. + public let createdAt: String + /// Token update date in ISO 8601 format. Refreshing the token family updates this. + public let updatedAt: String + /// ID of the consent the token family was issued under. + public let consentId: String + /// ID of the user the token family belongs to. + public let userId: String + /// ID of the registered app the token family was issued to. Empty for URL-form (CIMD) clients. + public let appId: String + /// Client ID metadata document URL of the client the token family was issued to. Empty for registered apps. + public let cimdUrl: String + /// OAuth2 scopes granted on the token family. + public let scopes: [String] + /// RFC 8707 resource indicators granted on the token family. + public let resources: [String] + /// Authorization details granted on the token family, as a JSON string. Each entry has a `type` plus project-defined fields. + public let authorizationDetails: String + /// Expiration time of the current access token of this family in ISO 8601 format. + public let expire: String + + init( + id: String, + createdAt: String, + updatedAt: String, + consentId: String, + userId: String, + appId: String, + cimdUrl: String, + scopes: [String], + resources: [String], + authorizationDetails: String, + expire: String + ) { + self.id = id + self.createdAt = createdAt + self.updatedAt = updatedAt + self.consentId = consentId + self.userId = userId + self.appId = appId + self.cimdUrl = cimdUrl + self.scopes = scopes + self.resources = resources + self.authorizationDetails = authorizationDetails + self.expire = expire + } + + public required init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.id = try container.decode(String.self, forKey: .id) + self.createdAt = try container.decode(String.self, forKey: .createdAt) + self.updatedAt = try container.decode(String.self, forKey: .updatedAt) + self.consentId = try container.decode(String.self, forKey: .consentId) + self.userId = try container.decode(String.self, forKey: .userId) + self.appId = try container.decode(String.self, forKey: .appId) + self.cimdUrl = try container.decode(String.self, forKey: .cimdUrl) + self.scopes = try container.decode([String].self, forKey: .scopes) + self.resources = try container.decode([String].self, forKey: .resources) + self.authorizationDetails = try container.decode(String.self, forKey: .authorizationDetails) + self.expire = try container.decode(String.self, forKey: .expire) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(id, forKey: .id) + try container.encode(createdAt, forKey: .createdAt) + try container.encode(updatedAt, forKey: .updatedAt) + try container.encode(consentId, forKey: .consentId) + try container.encode(userId, forKey: .userId) + try container.encode(appId, forKey: .appId) + try container.encode(cimdUrl, forKey: .cimdUrl) + try container.encode(scopes, forKey: .scopes) + try container.encode(resources, forKey: .resources) + try container.encode(authorizationDetails, forKey: .authorizationDetails) + try container.encode(expire, forKey: .expire) + } + + public func toMap() -> [String: Any] { + return [ + "$id": id as Any, + "$createdAt": createdAt as Any, + "$updatedAt": updatedAt as Any, + "consentId": consentId as Any, + "userId": userId as Any, + "appId": appId as Any, + "cimdUrl": cimdUrl as Any, + "scopes": scopes as Any, + "resources": resources as Any, + "authorizationDetails": authorizationDetails as Any, + "expire": expire as Any, + ] + } + + public static func from(map: [String: Any]) -> Oauth2ConsentToken { + return Oauth2ConsentToken( + id: map["$id"] as! String, + createdAt: map["$createdAt"] as! String, + updatedAt: map["$updatedAt"] as! String, + consentId: map["consentId"] as! String, + userId: map["userId"] as! String, + appId: map["appId"] as! String, + cimdUrl: map["cimdUrl"] as! String, + scopes: map["scopes"] as! [String], + resources: map["resources"] as! [String], + authorizationDetails: map["authorizationDetails"] as! String, + expire: map["expire"] as! String + ) + } +} diff --git a/Sources/AppwriteModels/Oauth2ConsentTokenList.swift b/Sources/AppwriteModels/Oauth2ConsentTokenList.swift new file mode 100644 index 0000000..45a6dae --- /dev/null +++ b/Sources/AppwriteModels/Oauth2ConsentTokenList.swift @@ -0,0 +1,52 @@ +import Foundation +import JSONCodable + +/// OAuth2 consent tokens list +open class Oauth2ConsentTokenList: Codable { + + enum CodingKeys: String, CodingKey { + case total = "total" + case tokens = "tokens" + } + + /// Total number of tokens that matched your query. + public let total: Int + /// List of tokens. + public let tokens: [Oauth2ConsentToken] + + init( + total: Int, + tokens: [Oauth2ConsentToken] + ) { + self.total = total + self.tokens = tokens + } + + public required init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.total = try container.decode(Int.self, forKey: .total) + self.tokens = try container.decode([Oauth2ConsentToken].self, forKey: .tokens) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(total, forKey: .total) + try container.encode(tokens, forKey: .tokens) + } + + public func toMap() -> [String: Any] { + return [ + "total": total as Any, + "tokens": tokens.map { $0.toMap() } as Any, + ] + } + + public static func from(map: [String: Any]) -> Oauth2ConsentTokenList { + return Oauth2ConsentTokenList( + total: map["total"] as! Int, + tokens: (map["tokens"] as! [[String: Any]]).map { Oauth2ConsentToken.from(map: $0) } + ) + } +} diff --git a/Sources/AppwriteModels/Phone.swift b/Sources/AppwriteModels/Phone.swift index 41f6818..b765f5d 100644 --- a/Sources/AppwriteModels/Phone.swift +++ b/Sources/AppwriteModels/Phone.swift @@ -47,11 +47,11 @@ open class Phone: Codable { return [ "code": code as Any, "countryCode": countryCode as Any, - "countryName": countryName as Any + "countryName": countryName as Any, ] } - public static func from(map: [String: Any] ) -> Phone { + public static func from(map: [String: Any]) -> Phone { return Phone( code: map["code"] as! String, countryCode: map["countryCode"] as! String, diff --git a/Sources/AppwriteModels/PhoneList.swift b/Sources/AppwriteModels/PhoneList.swift index 5a824e1..b4da5d4 100644 --- a/Sources/AppwriteModels/PhoneList.swift +++ b/Sources/AppwriteModels/PhoneList.swift @@ -39,11 +39,11 @@ open class PhoneList: Codable { public func toMap() -> [String: Any] { return [ "total": total as Any, - "phones": phones.map { $0.toMap() } as Any + "phones": phones.map { $0.toMap() } as Any, ] } - public static func from(map: [String: Any] ) -> PhoneList { + public static func from(map: [String: Any]) -> PhoneList { return PhoneList( total: map["total"] as! Int, phones: (map["phones"] as! [[String: Any]]).map { Phone.from(map: $0) } diff --git a/Sources/AppwriteModels/Preferences.swift b/Sources/AppwriteModels/Preferences.swift index 1bb00f7..cc22d06 100644 --- a/Sources/AppwriteModels/Preferences.swift +++ b/Sources/AppwriteModels/Preferences.swift @@ -2,7 +2,7 @@ import Foundation import JSONCodable /// Preferences -open class Preferences: Codable { +open class Preferences: Codable { enum CodingKeys: String, CodingKey { case data = "data" @@ -35,7 +35,7 @@ open class Preferences: Codable { ] } - public static func from(map: [String: Any] ) -> Preferences { + public static func from(map: [String: Any]) -> Preferences { return Preferences( data: try! JSONDecoder().decode(T.self, from: JSONSerialization.data(withJSONObject: map["data"] as? [String: Any] ?? map, options: [])) ) diff --git a/Sources/AppwriteModels/Presence.swift b/Sources/AppwriteModels/Presence.swift index da34ff0..1876a3e 100644 --- a/Sources/AppwriteModels/Presence.swift +++ b/Sources/AppwriteModels/Presence.swift @@ -95,11 +95,11 @@ open class Presence: Codable { "status": status as Any, "source": source as Any, "expiresAt": expiresAt as Any, - "metadata": metadata as Any + "metadata": metadata as Any, ] } - public static func from(map: [String: Any] ) -> Presence { + public static func from(map: [String: Any]) -> Presence { return Presence( id: map["$id"] as! String, createdAt: map["$createdAt"] as! String, diff --git a/Sources/AppwriteModels/PresenceList.swift b/Sources/AppwriteModels/PresenceList.swift index 6d149fb..5b06a5e 100644 --- a/Sources/AppwriteModels/PresenceList.swift +++ b/Sources/AppwriteModels/PresenceList.swift @@ -39,11 +39,11 @@ open class PresenceList: Codable { public func toMap() -> [String: Any] { return [ "total": total as Any, - "presences": presences.map { $0.toMap() } as Any + "presences": presences.map { $0.toMap() } as Any, ] } - public static func from(map: [String: Any] ) -> PresenceList { + public static func from(map: [String: Any]) -> PresenceList { return PresenceList( total: map["total"] as! Int, presences: (map["presences"] as! [[String: Any]]).map { Presence.from(map: $0) } diff --git a/Sources/AppwriteModels/Row.swift b/Sources/AppwriteModels/Row.swift index 2ee0565..81e24e5 100644 --- a/Sources/AppwriteModels/Row.swift +++ b/Sources/AppwriteModels/Row.swift @@ -2,7 +2,7 @@ import Foundation import JSONCodable /// Row -open class Row: Codable { +open class Row: Codable { enum CodingKeys: String, CodingKey { case id = "$id" @@ -87,11 +87,11 @@ open class Row: Codable { "$createdAt": createdAt as Any, "$updatedAt": updatedAt as Any, "$permissions": permissions as Any, - "data": (try! JSONSerialization.jsonObject(with: JSONEncoder().encode(data))) as? [String: Any] ?? [:] + "data": (try! JSONSerialization.jsonObject(with: JSONEncoder().encode(data))) as? [String: Any] ?? [:], ] } - public static func from(map: [String: Any] ) -> Row { + public static func from(map: [String: Any]) -> Row { return Row( id: map["$id"] as! String, sequence: map["$sequence"] as! String, diff --git a/Sources/AppwriteModels/RowList.swift b/Sources/AppwriteModels/RowList.swift index 8562ef2..bfc96d3 100644 --- a/Sources/AppwriteModels/RowList.swift +++ b/Sources/AppwriteModels/RowList.swift @@ -2,7 +2,7 @@ import Foundation import JSONCodable /// Rows List -open class RowList: Codable { +open class RowList: Codable { enum CodingKeys: String, CodingKey { case total = "total" @@ -39,11 +39,11 @@ open class RowList: Codable { public func toMap() -> [String: Any] { return [ "total": total as Any, - "rows": rows.map { $0.toMap() } as Any + "rows": rows.map { $0.toMap() } as Any, ] } - public static func from(map: [String: Any] ) -> RowList { + public static func from(map: [String: Any]) -> RowList { return RowList( total: map["total"] as! Int, rows: (map["rows"] as! [[String: Any]]).map { Row.from(map: $0) } diff --git a/Sources/AppwriteModels/Session.swift b/Sources/AppwriteModels/Session.swift index 1da34cc..799901c 100644 --- a/Sources/AppwriteModels/Session.swift +++ b/Sources/AppwriteModels/Session.swift @@ -255,11 +255,11 @@ open class Session: Codable { "current": current as Any, "factors": factors as Any, "secret": secret as Any, - "mfaUpdatedAt": mfaUpdatedAt as Any + "mfaUpdatedAt": mfaUpdatedAt as Any, ] } - public static func from(map: [String: Any] ) -> Session { + public static func from(map: [String: Any]) -> Session { return Session( id: map["$id"] as! String, createdAt: map["$createdAt"] as! String, diff --git a/Sources/AppwriteModels/SessionList.swift b/Sources/AppwriteModels/SessionList.swift index 81e9d1a..ccc8c18 100644 --- a/Sources/AppwriteModels/SessionList.swift +++ b/Sources/AppwriteModels/SessionList.swift @@ -39,11 +39,11 @@ open class SessionList: Codable { public func toMap() -> [String: Any] { return [ "total": total as Any, - "sessions": sessions.map { $0.toMap() } as Any + "sessions": sessions.map { $0.toMap() } as Any, ] } - public static func from(map: [String: Any] ) -> SessionList { + public static func from(map: [String: Any]) -> SessionList { return SessionList( total: map["total"] as! Int, sessions: (map["sessions"] as! [[String: Any]]).map { Session.from(map: $0) } diff --git a/Sources/AppwriteModels/Subscriber.swift b/Sources/AppwriteModels/Subscriber.swift index 8dc1c13..4aa2e11 100644 --- a/Sources/AppwriteModels/Subscriber.swift +++ b/Sources/AppwriteModels/Subscriber.swift @@ -95,11 +95,11 @@ open class Subscriber: Codable { "userId": userId as Any, "userName": userName as Any, "topicId": topicId as Any, - "providerType": providerType as Any + "providerType": providerType as Any, ] } - public static func from(map: [String: Any] ) -> Subscriber { + public static func from(map: [String: Any]) -> Subscriber { return Subscriber( id: map["$id"] as! String, createdAt: map["$createdAt"] as! String, diff --git a/Sources/AppwriteModels/Target.swift b/Sources/AppwriteModels/Target.swift index 4be8f67..c27d03b 100644 --- a/Sources/AppwriteModels/Target.swift +++ b/Sources/AppwriteModels/Target.swift @@ -95,11 +95,11 @@ open class Target: Codable { "providerId": providerId as Any, "providerType": providerType as Any, "identifier": identifier as Any, - "expired": expired as Any + "expired": expired as Any, ] } - public static func from(map: [String: Any] ) -> Target { + public static func from(map: [String: Any]) -> Target { return Target( id: map["$id"] as! String, createdAt: map["$createdAt"] as! String, diff --git a/Sources/AppwriteModels/Team.swift b/Sources/AppwriteModels/Team.swift index 232f36c..8a054db 100644 --- a/Sources/AppwriteModels/Team.swift +++ b/Sources/AppwriteModels/Team.swift @@ -2,7 +2,7 @@ import Foundation import JSONCodable /// Team -open class Team: Codable { +open class Team: Codable { enum CodingKeys: String, CodingKey { case id = "$id" @@ -71,11 +71,11 @@ open class Team: Codable { "$updatedAt": updatedAt as Any, "name": name as Any, "total": total as Any, - "prefs": prefs.toMap() as Any + "prefs": prefs.toMap() as Any, ] } - public static func from(map: [String: Any] ) -> Team { + public static func from(map: [String: Any]) -> Team { return Team( id: map["$id"] as! String, createdAt: map["$createdAt"] as! String, diff --git a/Sources/AppwriteModels/TeamList.swift b/Sources/AppwriteModels/TeamList.swift index 60dfaf3..f50cf54 100644 --- a/Sources/AppwriteModels/TeamList.swift +++ b/Sources/AppwriteModels/TeamList.swift @@ -2,7 +2,7 @@ import Foundation import JSONCodable /// Teams List -open class TeamList: Codable { +open class TeamList: Codable { enum CodingKeys: String, CodingKey { case total = "total" @@ -39,11 +39,11 @@ open class TeamList: Codable { public func toMap() -> [String: Any] { return [ "total": total as Any, - "teams": teams.map { $0.toMap() } as Any + "teams": teams.map { $0.toMap() } as Any, ] } - public static func from(map: [String: Any] ) -> TeamList { + public static func from(map: [String: Any]) -> TeamList { return TeamList( total: map["total"] as! Int, teams: (map["teams"] as! [[String: Any]]).map { Team.from(map: $0) } diff --git a/Sources/AppwriteModels/Token.swift b/Sources/AppwriteModels/Token.swift index e6716cd..18a92a9 100644 --- a/Sources/AppwriteModels/Token.swift +++ b/Sources/AppwriteModels/Token.swift @@ -71,11 +71,11 @@ open class Token: Codable { "userId": userId as Any, "secret": secret as Any, "expire": expire as Any, - "phrase": phrase as Any + "phrase": phrase as Any, ] } - public static func from(map: [String: Any] ) -> Token { + public static func from(map: [String: Any]) -> Token { return Token( id: map["$id"] as! String, createdAt: map["$createdAt"] as! String, diff --git a/Sources/AppwriteModels/Transaction.swift b/Sources/AppwriteModels/Transaction.swift index fcc7f0d..4032caa 100644 --- a/Sources/AppwriteModels/Transaction.swift +++ b/Sources/AppwriteModels/Transaction.swift @@ -71,11 +71,11 @@ open class Transaction: Codable { "$updatedAt": updatedAt as Any, "status": status as Any, "operations": operations as Any, - "expiresAt": expiresAt as Any + "expiresAt": expiresAt as Any, ] } - public static func from(map: [String: Any] ) -> Transaction { + public static func from(map: [String: Any]) -> Transaction { return Transaction( id: map["$id"] as! String, createdAt: map["$createdAt"] as! String, diff --git a/Sources/AppwriteModels/TransactionList.swift b/Sources/AppwriteModels/TransactionList.swift index 93915a9..657d19e 100644 --- a/Sources/AppwriteModels/TransactionList.swift +++ b/Sources/AppwriteModels/TransactionList.swift @@ -39,11 +39,11 @@ open class TransactionList: Codable { public func toMap() -> [String: Any] { return [ "total": total as Any, - "transactions": transactions.map { $0.toMap() } as Any + "transactions": transactions.map { $0.toMap() } as Any, ] } - public static func from(map: [String: Any] ) -> TransactionList { + public static func from(map: [String: Any]) -> TransactionList { return TransactionList( total: map["total"] as! Int, transactions: (map["transactions"] as! [[String: Any]]).map { Transaction.from(map: $0) } diff --git a/Sources/AppwriteModels/User.swift b/Sources/AppwriteModels/User.swift index a3ae446..2401ea4 100644 --- a/Sources/AppwriteModels/User.swift +++ b/Sources/AppwriteModels/User.swift @@ -2,7 +2,7 @@ import Foundation import JSONCodable /// User -open class User: Codable { +open class User: Codable { enum CodingKeys: String, CodingKey { case id = "$id" @@ -231,11 +231,11 @@ open class User: Codable { "targets": targets.map { $0.toMap() } as Any, "accessedAt": accessedAt as Any, "impersonator": impersonator as Any, - "impersonatorUserId": impersonatorUserId as Any + "impersonatorUserId": impersonatorUserId as Any, ] } - public static func from(map: [String: Any] ) -> User { + public static func from(map: [String: Any]) -> User { return User( id: map["$id"] as! String, createdAt: map["$createdAt"] as! String, diff --git a/Sources/JSONCodable/Codable+JSON.swift b/Sources/JSONCodable/Codable+JSON.swift index e08de62..4ddb792 100644 --- a/Sources/JSONCodable/Codable+JSON.swift +++ b/Sources/JSONCodable/Codable+JSON.swift @@ -9,20 +9,27 @@ extension Encodable { public func toJson() throws -> String { return String(data: try jsonEncoder.encode(self), encoding: .utf8)! } + + /// Encodes the value into a Foundation JSON object so it can be nested in + /// a larger `JSONSerialization` payload without being double-encoded. + public func toJsonObject() throws -> Any { + return try JSONSerialization.jsonObject( + with: jsonEncoder.encode(self), options: [.fragmentsAllowed]) + } } extension String { - public func fromJson(to model: T.Type) throws -> T { + public func fromJson(to model: T.Type) throws -> T { return try jsonDecoder.decode(model, from: self.data(using: .utf8)!) } } -protocol JsonConvert : Encodable { +protocol JsonConvert: Encodable { func jsonCast() -> T } extension JsonConvert { - public func jsonCast(to model: T.Type) throws -> T { + public func jsonCast(to model: T.Type) throws -> T { let string = try (self as Encodable).toJson() return try string.fromJson(to: model) } @@ -205,7 +212,8 @@ extension _AnyDecodable { } else if let dictionary = try? container.decode([String: AnyDecodable].self) { self.init(dictionary.mapValues { $0.value }) } else { - throw DecodingError.dataCorruptedError(in: container, debugDescription: "AnyDecodable value cannot be decoded") + throw DecodingError.dataCorruptedError( + in: container, debugDescription: "AnyDecodable value cannot be decoded") } } } @@ -213,10 +221,10 @@ extension _AnyDecodable { extension AnyDecodable: Equatable { public static func == (lhs: AnyDecodable, rhs: AnyDecodable) -> Bool { switch (lhs.value, rhs.value) { -#if canImport(Foundation) - case is (NSNull, NSNull), is (Void, Void): - return true -#endif + #if canImport(Foundation) + case is (NSNull, NSNull), is (Void, Void): + return true + #endif case let (lhs as Bool, rhs as Bool): return lhs == rhs case let (lhs as Int, rhs as Int): @@ -346,8 +354,8 @@ extension _AnyEncodable { switch value { #if canImport(Foundation) - case is NSNull: - try container.encodeNil() + case is NSNull: + try container.encodeNil() #endif case is Void: try container.encodeNil() @@ -380,12 +388,12 @@ extension _AnyEncodable { case let string as String: try container.encode(string) #if canImport(Foundation) - case let number as NSNumber: - try encode(nsnumber: number, into: &container) - case let date as Date: - try container.encode(date) - case let url as URL: - try container.encode(url) + case let number as NSNumber: + try encode(nsnumber: number, into: &container) + case let date as Date: + try container.encode(date) + case let url as URL: + try container.encode(url) #endif case let array as [Any?]: try container.encode(array.map { AnyEncodable($0) }) @@ -394,41 +402,47 @@ extension _AnyEncodable { case let encodable as Encodable: try encodable.encode(to: encoder) default: - let context = EncodingError.Context(codingPath: container.codingPath, debugDescription: "AnyEncodable value cannot be encoded") + let context = EncodingError.Context( + codingPath: container.codingPath, + debugDescription: "AnyEncodable value cannot be encoded") throw EncodingError.invalidValue(value, context) } } #if canImport(Foundation) - private func encode(nsnumber: NSNumber, into container: inout SingleValueEncodingContainer) throws { - switch Character(Unicode.Scalar(UInt8(nsnumber.objCType.pointee))) { - case "B": - try container.encode(nsnumber.boolValue) - case "c": - try container.encode(nsnumber.int8Value) - case "s": - try container.encode(nsnumber.int16Value) - case "i", "l": - try container.encode(nsnumber.int32Value) - case "q": - try container.encode(nsnumber.int64Value) - case "C": - try container.encode(nsnumber.uint8Value) - case "S": - try container.encode(nsnumber.uint16Value) - case "I", "L": - try container.encode(nsnumber.uint32Value) - case "Q": - try container.encode(nsnumber.uint64Value) - case "f": - try container.encode(nsnumber.floatValue) - case "d": - try container.encode(nsnumber.doubleValue) - default: - let context = EncodingError.Context(codingPath: container.codingPath, debugDescription: "NSNumber cannot be encoded because its type is not handled") - throw EncodingError.invalidValue(nsnumber, context) + private func encode(nsnumber: NSNumber, into container: inout SingleValueEncodingContainer) + throws + { + switch Character(Unicode.Scalar(UInt8(nsnumber.objCType.pointee))) { + case "B": + try container.encode(nsnumber.boolValue) + case "c": + try container.encode(nsnumber.int8Value) + case "s": + try container.encode(nsnumber.int16Value) + case "i", "l": + try container.encode(nsnumber.int32Value) + case "q": + try container.encode(nsnumber.int64Value) + case "C": + try container.encode(nsnumber.uint8Value) + case "S": + try container.encode(nsnumber.uint16Value) + case "I", "L": + try container.encode(nsnumber.uint32Value) + case "Q": + try container.encode(nsnumber.uint64Value) + case "f": + try container.encode(nsnumber.floatValue) + case "d": + try container.encode(nsnumber.doubleValue) + default: + let context = EncodingError.Context( + codingPath: container.codingPath, + debugDescription: "NSNumber cannot be encoded because its type is not handled") + throw EncodingError.invalidValue(nsnumber, context) + } } - } #endif } diff --git a/Tests/AppwriteTests/Tests.swift b/Tests/AppwriteTests/Tests.swift index 80a577e..89e8657 100644 --- a/Tests/AppwriteTests/Tests.swift +++ b/Tests/AppwriteTests/Tests.swift @@ -2,4 +2,4 @@ import XCTest class Tests: XCTestCase { -} \ No newline at end of file +} diff --git a/docs/examples/account/delete-consent-token.md b/docs/examples/account/delete-consent-token.md new file mode 100644 index 0000000..ef9b8a2 --- /dev/null +++ b/docs/examples/account/delete-consent-token.md @@ -0,0 +1,15 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let account = Account(client) + +let result = try await account.deleteConsentToken( + consentId: "", + tokenId: "" +) + +``` diff --git a/docs/examples/account/delete-consent.md b/docs/examples/account/delete-consent.md new file mode 100644 index 0000000..862b1e3 --- /dev/null +++ b/docs/examples/account/delete-consent.md @@ -0,0 +1,14 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let account = Account(client) + +let result = try await account.deleteConsent( + consentId: "" +) + +``` diff --git a/docs/examples/account/get-consent-token.md b/docs/examples/account/get-consent-token.md new file mode 100644 index 0000000..502f79e --- /dev/null +++ b/docs/examples/account/get-consent-token.md @@ -0,0 +1,15 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let account = Account(client) + +let oauth2ConsentToken = try await account.getConsentToken( + consentId: "", + tokenId: "" +) + +``` diff --git a/docs/examples/account/get-consent.md b/docs/examples/account/get-consent.md new file mode 100644 index 0000000..a7380c4 --- /dev/null +++ b/docs/examples/account/get-consent.md @@ -0,0 +1,14 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let account = Account(client) + +let oauth2Consent = try await account.getConsent( + consentId: "" +) + +``` diff --git a/docs/examples/account/list-consent-tokens.md b/docs/examples/account/list-consent-tokens.md new file mode 100644 index 0000000..bc32316 --- /dev/null +++ b/docs/examples/account/list-consent-tokens.md @@ -0,0 +1,16 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let account = Account(client) + +let oauth2ConsentTokenList = try await account.listConsentTokens( + consentId: "", + queries: [], // optional + total: false // optional +) + +``` diff --git a/docs/examples/account/list-consents.md b/docs/examples/account/list-consents.md new file mode 100644 index 0000000..25b50d5 --- /dev/null +++ b/docs/examples/account/list-consents.md @@ -0,0 +1,15 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let account = Account(client) + +let oauth2ConsentList = try await account.listConsents( + queries: [], // optional + total: false // optional +) + +``` diff --git a/docs/examples/avatars/get-initials.md b/docs/examples/avatars/get-initials.md index d1f6d7c..44fca8f 100644 --- a/docs/examples/avatars/get-initials.md +++ b/docs/examples/avatars/get-initials.md @@ -11,7 +11,7 @@ let bytes = try await avatars.getInitials( name: "", // optional width: 0, // optional height: 0, // optional - background: "" // optional + background: "FFFFFF" // optional ) ``` diff --git a/docs/examples/avatars/get-photo.md b/docs/examples/avatars/get-photo.md new file mode 100644 index 0000000..d5a1982 --- /dev/null +++ b/docs/examples/avatars/get-photo.md @@ -0,0 +1,21 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let avatars = Avatars(client) + +let bytes = try await avatars.getPhoto( + width: 0, // optional + height: 0, // optional + quality: 0, // optional + output: "png", // optional + rating: "g", // optional + userId: "current()", // optional + emailHash: "", // optional + name: "" // optional +) + +``` diff --git a/docs/examples/databases/create-operations.md b/docs/examples/databases/create-operations.md index c9d5997..f669acb 100644 --- a/docs/examples/databases/create-operations.md +++ b/docs/examples/databases/create-operations.md @@ -10,16 +10,16 @@ let databases = Databases(client) let transaction = try await databases.createOperations( transactionId: "", operations: [ - { - "action": "create", - "databaseId": "", - "collectionId": "", - "documentId": "", - "data": { - "name": "Walter O'Brien" - } - } - ] // optional + [ + "action": "create", + "databaseId": "", + "collectionId": "", + "documentId": "", + "data": [ + "name": "Walter O'Brien" + ] + ] + ] // optional ) ``` diff --git a/docs/examples/databases/decrement-document-attribute.md b/docs/examples/databases/decrement-document-attribute.md index 0e08625..8f7746e 100644 --- a/docs/examples/databases/decrement-document-attribute.md +++ b/docs/examples/databases/decrement-document-attribute.md @@ -11,8 +11,8 @@ let document = try await databases.decrementDocumentAttribute( databaseId: "", collectionId: "", documentId: "", - attribute: "", - value: 0, // optional + attribute: "", + value: 1, // optional min: 0, // optional transactionId: "" // optional ) diff --git a/docs/examples/databases/increment-document-attribute.md b/docs/examples/databases/increment-document-attribute.md index 0228b21..3bd2474 100644 --- a/docs/examples/databases/increment-document-attribute.md +++ b/docs/examples/databases/increment-document-attribute.md @@ -11,9 +11,9 @@ let document = try await databases.incrementDocumentAttribute( databaseId: "", collectionId: "", documentId: "", - attribute: "", - value: 0, // optional - max: 0, // optional + attribute: "", + value: 1, // optional + max: 100, // optional transactionId: "" // optional ) diff --git a/docs/examples/documentsdb/create-document.md b/docs/examples/documentsdb/create-document.md new file mode 100644 index 0000000..a0d6a69 --- /dev/null +++ b/docs/examples/documentsdb/create-document.md @@ -0,0 +1,25 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let documentsDB = DocumentsDB(client) + +let document = try await documentsDB.createDocument( + databaseId: "", + collectionId: "", + documentId: "", + data: [ + "username": "walter.obrien", + "email": "walter.obrien@example.com", + "fullName": "Walter O'Brien", + "age": 30, + "isAdmin": false + ], + permissions: [Permission.read(Role.any())], // optional + transactionId: "" // optional +) + +``` diff --git a/docs/examples/documentsdb/create-documents.md b/docs/examples/documentsdb/create-documents.md new file mode 100644 index 0000000..c170200 --- /dev/null +++ b/docs/examples/documentsdb/create-documents.md @@ -0,0 +1,17 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let documentsDB = DocumentsDB(client) + +let documentList = try await documentsDB.createDocuments( + databaseId: "", + collectionId: "", + documents: [], + transactionId: "" // optional +) + +``` diff --git a/docs/examples/documentsdb/create-operations.md b/docs/examples/documentsdb/create-operations.md new file mode 100644 index 0000000..1255f66 --- /dev/null +++ b/docs/examples/documentsdb/create-operations.md @@ -0,0 +1,25 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let documentsDB = DocumentsDB(client) + +let transaction = try await documentsDB.createOperations( + transactionId: "", + operations: [ + [ + "action": "create", + "databaseId": "", + "collectionId": "", + "documentId": "", + "data": [ + "name": "Walter O'Brien" + ] + ] + ] // optional +) + +``` diff --git a/docs/examples/documentsdb/create-transaction.md b/docs/examples/documentsdb/create-transaction.md new file mode 100644 index 0000000..88030b7 --- /dev/null +++ b/docs/examples/documentsdb/create-transaction.md @@ -0,0 +1,14 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let documentsDB = DocumentsDB(client) + +let transaction = try await documentsDB.createTransaction( + ttl: 60 // optional +) + +``` diff --git a/docs/examples/documentsdb/decrement-document-attribute.md b/docs/examples/documentsdb/decrement-document-attribute.md new file mode 100644 index 0000000..11d2ed3 --- /dev/null +++ b/docs/examples/documentsdb/decrement-document-attribute.md @@ -0,0 +1,20 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let documentsDB = DocumentsDB(client) + +let document = try await documentsDB.decrementDocumentAttribute( + databaseId: "", + collectionId: "", + documentId: "", + attribute: "", + value: 1, // optional + min: 0, // optional + transactionId: "" // optional +) + +``` diff --git a/docs/examples/documentsdb/delete-document.md b/docs/examples/documentsdb/delete-document.md new file mode 100644 index 0000000..10eef17 --- /dev/null +++ b/docs/examples/documentsdb/delete-document.md @@ -0,0 +1,17 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let documentsDB = DocumentsDB(client) + +let result = try await documentsDB.deleteDocument( + databaseId: "", + collectionId: "", + documentId: "", + transactionId: "" // optional +) + +``` diff --git a/docs/examples/documentsdb/delete-transaction.md b/docs/examples/documentsdb/delete-transaction.md new file mode 100644 index 0000000..ca1c9bb --- /dev/null +++ b/docs/examples/documentsdb/delete-transaction.md @@ -0,0 +1,14 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let documentsDB = DocumentsDB(client) + +let result = try await documentsDB.deleteTransaction( + transactionId: "" +) + +``` diff --git a/docs/examples/documentsdb/get-document.md b/docs/examples/documentsdb/get-document.md new file mode 100644 index 0000000..504bbf1 --- /dev/null +++ b/docs/examples/documentsdb/get-document.md @@ -0,0 +1,18 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let documentsDB = DocumentsDB(client) + +let document = try await documentsDB.getDocument( + databaseId: "", + collectionId: "", + documentId: "", + queries: [], // optional + transactionId: "" // optional +) + +``` diff --git a/docs/examples/documentsdb/get-transaction.md b/docs/examples/documentsdb/get-transaction.md new file mode 100644 index 0000000..4435dce --- /dev/null +++ b/docs/examples/documentsdb/get-transaction.md @@ -0,0 +1,14 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let documentsDB = DocumentsDB(client) + +let transaction = try await documentsDB.getTransaction( + transactionId: "" +) + +``` diff --git a/docs/examples/documentsdb/increment-document-attribute.md b/docs/examples/documentsdb/increment-document-attribute.md new file mode 100644 index 0000000..4164895 --- /dev/null +++ b/docs/examples/documentsdb/increment-document-attribute.md @@ -0,0 +1,20 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let documentsDB = DocumentsDB(client) + +let document = try await documentsDB.incrementDocumentAttribute( + databaseId: "", + collectionId: "", + documentId: "", + attribute: "", + value: 1, // optional + max: 100, // optional + transactionId: "" // optional +) + +``` diff --git a/docs/examples/documentsdb/list-documents.md b/docs/examples/documentsdb/list-documents.md new file mode 100644 index 0000000..81768bc --- /dev/null +++ b/docs/examples/documentsdb/list-documents.md @@ -0,0 +1,19 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let documentsDB = DocumentsDB(client) + +let documentList = try await documentsDB.listDocuments( + databaseId: "", + collectionId: "", + queries: [], // optional + transactionId: "", // optional + total: false, // optional + ttl: 0 // optional +) + +``` diff --git a/docs/examples/documentsdb/list-transactions.md b/docs/examples/documentsdb/list-transactions.md new file mode 100644 index 0000000..0fe1ca7 --- /dev/null +++ b/docs/examples/documentsdb/list-transactions.md @@ -0,0 +1,14 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let documentsDB = DocumentsDB(client) + +let transactionList = try await documentsDB.listTransactions( + queries: [] // optional +) + +``` diff --git a/docs/examples/documentsdb/update-document.md b/docs/examples/documentsdb/update-document.md new file mode 100644 index 0000000..250ecd7 --- /dev/null +++ b/docs/examples/documentsdb/update-document.md @@ -0,0 +1,19 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let documentsDB = DocumentsDB(client) + +let document = try await documentsDB.updateDocument( + databaseId: "", + collectionId: "", + documentId: "", + data: [:], // optional + permissions: [Permission.read(Role.any())], // optional + transactionId: "" // optional +) + +``` diff --git a/docs/examples/documentsdb/update-transaction.md b/docs/examples/documentsdb/update-transaction.md new file mode 100644 index 0000000..1ea869b --- /dev/null +++ b/docs/examples/documentsdb/update-transaction.md @@ -0,0 +1,16 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let documentsDB = DocumentsDB(client) + +let transaction = try await documentsDB.updateTransaction( + transactionId: "", + commit: false, // optional + rollback: false // optional +) + +``` diff --git a/docs/examples/documentsdb/upsert-document.md b/docs/examples/documentsdb/upsert-document.md new file mode 100644 index 0000000..cede61c --- /dev/null +++ b/docs/examples/documentsdb/upsert-document.md @@ -0,0 +1,19 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let documentsDB = DocumentsDB(client) + +let document = try await documentsDB.upsertDocument( + databaseId: "", + collectionId: "", + documentId: "", + data: [:], // optional + permissions: [Permission.read(Role.any())], // optional + transactionId: "" // optional +) + +``` diff --git a/docs/examples/organization/create-installation.md b/docs/examples/organization/create-installation.md new file mode 100644 index 0000000..b2eb34a --- /dev/null +++ b/docs/examples/organization/create-installation.md @@ -0,0 +1,15 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let organization = Organization(client) + +let appInstallation = try await organization.createInstallation( + appId: "", + authorizationDetails: "" // optional +) + +``` diff --git a/docs/examples/organization/delete-installation.md b/docs/examples/organization/delete-installation.md new file mode 100644 index 0000000..3124453 --- /dev/null +++ b/docs/examples/organization/delete-installation.md @@ -0,0 +1,14 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let organization = Organization(client) + +let result = try await organization.deleteInstallation( + installationId: "" +) + +``` diff --git a/docs/examples/organization/get-installation.md b/docs/examples/organization/get-installation.md new file mode 100644 index 0000000..f9bbcab --- /dev/null +++ b/docs/examples/organization/get-installation.md @@ -0,0 +1,14 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let organization = Organization(client) + +let appInstallation = try await organization.getInstallation( + installationId: "" +) + +``` diff --git a/docs/examples/organization/list-installations.md b/docs/examples/organization/list-installations.md new file mode 100644 index 0000000..56c8b05 --- /dev/null +++ b/docs/examples/organization/list-installations.md @@ -0,0 +1,15 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let organization = Organization(client) + +let appInstallationList = try await organization.listInstallations( + queries: [], // optional + total: false // optional +) + +``` diff --git a/docs/examples/organization/update-installation.md b/docs/examples/organization/update-installation.md new file mode 100644 index 0000000..e0be7ad --- /dev/null +++ b/docs/examples/organization/update-installation.md @@ -0,0 +1,15 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let organization = Organization(client) + +let appInstallation = try await organization.updateInstallation( + installationId: "", + authorizationDetails: "" // optional +) + +``` diff --git a/docs/examples/storage/create-file.md b/docs/examples/storage/create-file.md index c446077..bfa3197 100644 --- a/docs/examples/storage/create-file.md +++ b/docs/examples/storage/create-file.md @@ -11,7 +11,8 @@ let file = try await storage.createFile( bucketId: "", fileId: "", file: InputFile.fromPath("file.png"), - permissions: [Permission.read(Role.any())] // optional + permissions: [Permission.read(Role.any())], // optional + folder: "photos/2026" // optional ) ``` diff --git a/docs/examples/storage/get-file-preview.md b/docs/examples/storage/get-file-preview.md index 5ba4032..ea1df78 100644 --- a/docs/examples/storage/get-file-preview.md +++ b/docs/examples/storage/get-file-preview.md @@ -13,14 +13,14 @@ let bytes = try await storage.getFilePreview( fileId: "", width: 0, // optional height: 0, // optional - gravity: .center, // optional + gravity: .auto, // optional quality: -1, // optional borderWidth: 0, // optional - borderColor: "", // optional + borderColor: "FFFFFF", // optional borderRadius: 0, // optional opacity: 0, // optional rotation: -360, // optional - background: "", // optional + background: "FFFFFF", // optional output: .jpg, // optional token: "" // optional ) diff --git a/docs/examples/tablesdb/create-operations.md b/docs/examples/tablesdb/create-operations.md index ee3d6ce..edebcee 100644 --- a/docs/examples/tablesdb/create-operations.md +++ b/docs/examples/tablesdb/create-operations.md @@ -10,16 +10,16 @@ let tablesDB = TablesDB(client) let transaction = try await tablesDB.createOperations( transactionId: "", operations: [ - { - "action": "create", - "databaseId": "", - "tableId": "", - "rowId": "", - "data": { - "name": "Walter O'Brien" - } - } - ] // optional + [ + "action": "create", + "databaseId": "", + "tableId": "", + "rowId": "", + "data": [ + "name": "Walter O'Brien" + ] + ] + ] // optional ) ``` diff --git a/docs/examples/tablesdb/decrement-row-column.md b/docs/examples/tablesdb/decrement-row-column.md index 2c3cfb3..bef6d34 100644 --- a/docs/examples/tablesdb/decrement-row-column.md +++ b/docs/examples/tablesdb/decrement-row-column.md @@ -11,8 +11,8 @@ let row = try await tablesDB.decrementRowColumn( databaseId: "", tableId: "", rowId: "", - column: "", - value: 0, // optional + column: "", + value: 1, // optional min: 0, // optional transactionId: "" // optional ) diff --git a/docs/examples/tablesdb/increment-row-column.md b/docs/examples/tablesdb/increment-row-column.md index a2b14f8..f829852 100644 --- a/docs/examples/tablesdb/increment-row-column.md +++ b/docs/examples/tablesdb/increment-row-column.md @@ -11,9 +11,9 @@ let row = try await tablesDB.incrementRowColumn( databaseId: "", tableId: "", rowId: "", - column: "", - value: 0, // optional - max: 0, // optional + column: "", + value: 1, // optional + max: 100, // optional transactionId: "" // optional ) diff --git a/docs/examples/teams/create-installation.md b/docs/examples/teams/create-installation.md new file mode 100644 index 0000000..71f64aa --- /dev/null +++ b/docs/examples/teams/create-installation.md @@ -0,0 +1,16 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let teams = Teams(client) + +let appInstallation = try await teams.createInstallation( + teamId: "", + appId: "", + authorizationDetails: "" // optional +) + +``` diff --git a/docs/examples/teams/delete-installation.md b/docs/examples/teams/delete-installation.md new file mode 100644 index 0000000..66ef934 --- /dev/null +++ b/docs/examples/teams/delete-installation.md @@ -0,0 +1,15 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let teams = Teams(client) + +let result = try await teams.deleteInstallation( + teamId: "", + installationId: "" +) + +``` diff --git a/docs/examples/teams/get-installation.md b/docs/examples/teams/get-installation.md new file mode 100644 index 0000000..c442011 --- /dev/null +++ b/docs/examples/teams/get-installation.md @@ -0,0 +1,15 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let teams = Teams(client) + +let appInstallation = try await teams.getInstallation( + teamId: "", + installationId: "" +) + +``` diff --git a/docs/examples/teams/list-installations.md b/docs/examples/teams/list-installations.md new file mode 100644 index 0000000..c64ae7d --- /dev/null +++ b/docs/examples/teams/list-installations.md @@ -0,0 +1,16 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let teams = Teams(client) + +let appInstallationList = try await teams.listInstallations( + teamId: "", + queries: [], // optional + total: false // optional +) + +``` diff --git a/docs/examples/teams/update-installation.md b/docs/examples/teams/update-installation.md new file mode 100644 index 0000000..7b50293 --- /dev/null +++ b/docs/examples/teams/update-installation.md @@ -0,0 +1,16 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let teams = Teams(client) + +let appInstallation = try await teams.updateInstallation( + teamId: "", + installationId: "", + authorizationDetails: "" // optional +) + +``` diff --git a/docs/examples/vectorsdb/create-document.md b/docs/examples/vectorsdb/create-document.md new file mode 100644 index 0000000..b134090 --- /dev/null +++ b/docs/examples/vectorsdb/create-document.md @@ -0,0 +1,29 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let vectorsDB = VectorsDB(client) + +let document = try await vectorsDB.createDocument( + databaseId: "", + collectionId: "", + documentId: "", + data: [ + "embeddings": [ + 0.12, + -0.55, + 0.88, + 1.02 + ], + "metadata": [ + "key": "value" + ] + ], + permissions: [Permission.read(Role.any())], // optional + transactionId: "" // optional +) + +``` diff --git a/docs/examples/vectorsdb/create-operations.md b/docs/examples/vectorsdb/create-operations.md new file mode 100644 index 0000000..b48c459 --- /dev/null +++ b/docs/examples/vectorsdb/create-operations.md @@ -0,0 +1,25 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let vectorsDB = VectorsDB(client) + +let transaction = try await vectorsDB.createOperations( + transactionId: "", + operations: [ + [ + "action": "create", + "databaseId": "", + "collectionId": "", + "documentId": "", + "data": [ + "name": "Walter O'Brien" + ] + ] + ] // optional +) + +``` diff --git a/docs/examples/vectorsdb/create-query.md b/docs/examples/vectorsdb/create-query.md new file mode 100644 index 0000000..e80be9b --- /dev/null +++ b/docs/examples/vectorsdb/create-query.md @@ -0,0 +1,19 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let vectorsDB = VectorsDB(client) + +let documentList = try await vectorsDB.createQuery( + databaseId: "", + collectionId: "", + queries: [], // optional + transactionId: "", // optional + total: false, // optional + ttl: 0 // optional +) + +``` diff --git a/docs/examples/vectorsdb/create-transaction.md b/docs/examples/vectorsdb/create-transaction.md new file mode 100644 index 0000000..4cdabc2 --- /dev/null +++ b/docs/examples/vectorsdb/create-transaction.md @@ -0,0 +1,14 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let vectorsDB = VectorsDB(client) + +let transaction = try await vectorsDB.createTransaction( + ttl: 60 // optional +) + +``` diff --git a/docs/examples/vectorsdb/delete-document.md b/docs/examples/vectorsdb/delete-document.md new file mode 100644 index 0000000..dd80e83 --- /dev/null +++ b/docs/examples/vectorsdb/delete-document.md @@ -0,0 +1,17 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let vectorsDB = VectorsDB(client) + +let result = try await vectorsDB.deleteDocument( + databaseId: "", + collectionId: "", + documentId: "", + transactionId: "" // optional +) + +``` diff --git a/docs/examples/vectorsdb/delete-transaction.md b/docs/examples/vectorsdb/delete-transaction.md new file mode 100644 index 0000000..ff7538a --- /dev/null +++ b/docs/examples/vectorsdb/delete-transaction.md @@ -0,0 +1,14 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let vectorsDB = VectorsDB(client) + +let result = try await vectorsDB.deleteTransaction( + transactionId: "" +) + +``` diff --git a/docs/examples/vectorsdb/get-document.md b/docs/examples/vectorsdb/get-document.md new file mode 100644 index 0000000..e181437 --- /dev/null +++ b/docs/examples/vectorsdb/get-document.md @@ -0,0 +1,18 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let vectorsDB = VectorsDB(client) + +let document = try await vectorsDB.getDocument( + databaseId: "", + collectionId: "", + documentId: "", + queries: [], // optional + transactionId: "" // optional +) + +``` diff --git a/docs/examples/vectorsdb/get-transaction.md b/docs/examples/vectorsdb/get-transaction.md new file mode 100644 index 0000000..4b8fd1a --- /dev/null +++ b/docs/examples/vectorsdb/get-transaction.md @@ -0,0 +1,14 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let vectorsDB = VectorsDB(client) + +let transaction = try await vectorsDB.getTransaction( + transactionId: "" +) + +``` diff --git a/docs/examples/vectorsdb/list-documents.md b/docs/examples/vectorsdb/list-documents.md new file mode 100644 index 0000000..c082c81 --- /dev/null +++ b/docs/examples/vectorsdb/list-documents.md @@ -0,0 +1,19 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let vectorsDB = VectorsDB(client) + +let documentList = try await vectorsDB.listDocuments( + databaseId: "", + collectionId: "", + queries: [], // optional + transactionId: "", // optional + total: false, // optional + ttl: 0 // optional +) + +``` diff --git a/docs/examples/vectorsdb/list-transactions.md b/docs/examples/vectorsdb/list-transactions.md new file mode 100644 index 0000000..26aa4f4 --- /dev/null +++ b/docs/examples/vectorsdb/list-transactions.md @@ -0,0 +1,14 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let vectorsDB = VectorsDB(client) + +let transactionList = try await vectorsDB.listTransactions( + queries: [] // optional +) + +``` diff --git a/docs/examples/vectorsdb/update-document.md b/docs/examples/vectorsdb/update-document.md new file mode 100644 index 0000000..f96706f --- /dev/null +++ b/docs/examples/vectorsdb/update-document.md @@ -0,0 +1,19 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let vectorsDB = VectorsDB(client) + +let document = try await vectorsDB.updateDocument( + databaseId: "", + collectionId: "", + documentId: "", + data: [:], // optional + permissions: [Permission.read(Role.any())], // optional + transactionId: "" // optional +) + +``` diff --git a/docs/examples/vectorsdb/update-transaction.md b/docs/examples/vectorsdb/update-transaction.md new file mode 100644 index 0000000..f254540 --- /dev/null +++ b/docs/examples/vectorsdb/update-transaction.md @@ -0,0 +1,16 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let vectorsDB = VectorsDB(client) + +let transaction = try await vectorsDB.updateTransaction( + transactionId: "", + commit: false, // optional + rollback: false // optional +) + +``` diff --git a/docs/examples/vectorsdb/upsert-document.md b/docs/examples/vectorsdb/upsert-document.md new file mode 100644 index 0000000..4fd8576 --- /dev/null +++ b/docs/examples/vectorsdb/upsert-document.md @@ -0,0 +1,19 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let vectorsDB = VectorsDB(client) + +let document = try await vectorsDB.upsertDocument( + databaseId: "", + collectionId: "", + documentId: "", + data: [:], // optional + permissions: [Permission.read(Role.any())], // optional + transactionId: "" // optional +) + +``` diff --git a/example-swiftui/Shared/ExampleApp.swift b/example-swiftui/Shared/ExampleApp.swift index 15ff0c9..bb4e8db 100644 --- a/example-swiftui/Shared/ExampleApp.swift +++ b/example-swiftui/Shared/ExampleApp.swift @@ -1,8 +1,8 @@ -import SwiftUI import Appwrite -import NIO import Firebase import FirebaseMessaging +import NIO +import SwiftUI let host = "https://cloud.appwrite.io/v1" let projectId = "[YOUR_PROJECT_ID]" @@ -15,11 +15,13 @@ let account = Account(client) let storage = Storage(client) let realtime = Realtime(client) -class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate { +class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate, + MessagingDelegate +{ func application( _ application: UIApplication, - didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil ) -> Bool { FirebaseApp.configure() @@ -29,14 +31,14 @@ class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDele let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound] UNUserNotificationCenter.current().requestAuthorization( - options: authOptions, - completionHandler: { granted, error in - DispatchQueue.main.async { - if granted { - application.registerForRemoteNotifications() - } - } - } + options: authOptions, + completionHandler: { granted, error in + DispatchQueue.main.async { + if granted { + application.registerForRemoteNotifications() + } + } + } ) return true @@ -50,7 +52,7 @@ class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDele return } - UserDefaults.standard.set(fcmToken , forKey: "fcmToken") + UserDefaults.standard.set(fcmToken, forKey: "fcmToken") let targetId = UserDefaults.standard.string(forKey: "targetId") @@ -67,7 +69,7 @@ class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDele identifier: fcmToken ) - UserDefaults.standard.set(target?.id , forKey: "targetId") + UserDefaults.standard.set(target?.id, forKey: "targetId") } else { _ = try? await account.updatePushTarget( targetId: targetId!, diff --git a/example-swiftui/Shared/ExampleView.swift b/example-swiftui/Shared/ExampleView.swift index 0c3d2de..cb88fcf 100644 --- a/example-swiftui/Shared/ExampleView.swift +++ b/example-swiftui/Shared/ExampleView.swift @@ -1,15 +1,15 @@ -import SwiftUI import Appwrite import NIO +import SwiftUI struct ExampleView: View { - + @ObservedObject var viewModel: ViewModel - + @State var imageToUpload = OSImage() - + var body: some View { - + VStack(spacing: 8) { viewModel.downloadedImage? @@ -38,24 +38,24 @@ struct ExampleView: View { Button("Download image") { Task { await viewModel.download() } } - + Button("Upload image") { viewModel.isShowPhotoLibrary = true } - + Button("Subscribe") { Task { await viewModel.subscribe() } } } #if os(macOS) - .onChange(of: viewModel.isShowPhotoLibrary) { showing in - ImagePicker.present() - } + .onChange(of: viewModel.isShowPhotoLibrary) { showing in + ImagePicker.present() + } #endif #if os(iOS) || os(visionOS) - .sheet(isPresented: $viewModel.isShowPhotoLibrary) { - ImagePicker(selectedImage: $imageToUpload) - } + .sheet(isPresented: $viewModel.isShowPhotoLibrary) { + ImagePicker(selectedImage: $imageToUpload) + } #endif .onChange(of: imageToUpload) { img in Task { await viewModel.upload(image: img) } diff --git a/example-swiftui/Shared/ExampleViewModel.swift b/example-swiftui/Shared/ExampleViewModel.swift index aa3f4af..b243b77 100644 --- a/example-swiftui/Shared/ExampleViewModel.swift +++ b/example-swiftui/Shared/ExampleViewModel.swift @@ -1,11 +1,11 @@ -import Foundation -import SwiftUI import Appwrite +import Foundation import NIO +import SwiftUI extension ExampleView { - class ViewModel : ObservableObject { + class ViewModel: ObservableObject { @Published var downloadedImage: Image? = nil @Published public var username: String = "test@test.test" @@ -50,10 +50,12 @@ extension ExampleView { return } - guard let target = try? await account.createPushTarget( - targetId: ID.unique(), - identifier: token - ) else { + guard + let target = try? await account.createPushTarget( + targetId: ID.unique(), + identifier: token + ) + else { return } @@ -101,11 +103,11 @@ extension ExampleView { func upload(image: OSImage) async { #if os(macOS) - let fileName = "file.tiff" - let mime = "image/tiff" + let fileName = "file.tiff" + let mime = "image/tiff" #else - let fileName = "file.png" - let mime = "image/png" + let fileName = "file.png" + let mime = "image/png" #endif let file = InputFile.fromData( @@ -131,7 +133,9 @@ extension ExampleView { } func subscribe() async { - let sub1 = try? await realtime.subscribe(channels: ["databases.\(databaseId).collections.\(collectionId).documents"]) { event in + let sub1 = try? await realtime.subscribe(channels: [ + "databases.\(databaseId).collections.\(collectionId).documents" + ]) { event in DispatchQueue.main.async { self.response = String(describing: event.payload!) } @@ -139,7 +143,9 @@ extension ExampleView { try? await Task.sleep(nanoseconds: UInt64(500_000_000)) - _ = try? await realtime.subscribe(channels: ["databases.\(databaseId).collections.\(collectionId2).documents"]) { event in + _ = try? await realtime.subscribe(channels: [ + "databases.\(databaseId).collections.\(collectionId2).documents" + ]) { event in DispatchQueue.main.async { self.response2 = String(describing: event.payload!) } diff --git a/example-swiftui/Shared/Image/OSImage.swift b/example-swiftui/Shared/Image/OSImage.swift index c09aa6f..6270c57 100644 --- a/example-swiftui/Shared/Image/OSImage.swift +++ b/example-swiftui/Shared/Image/OSImage.swift @@ -7,19 +7,19 @@ import SwiftUI #if os(macOS) -import AppKit -public typealias OSImage = NSImage + import AppKit + public typealias OSImage = NSImage #elseif os(iOS) || os(tvOS) || os(watchOS) || os(visionOS) -import UIKit -public typealias OSImage = UIImage + import UIKit + public typealias OSImage = UIImage #endif extension Image { public init(data: Data) { #if os(macOS) - self.init(nsImage: NSImage(data: data)!) + self.init(nsImage: NSImage(data: data)!) #elseif os(iOS) || os(tvOS) || os(watchOS) || os(visionOS) - self.init(uiImage: UIImage(data: data)!) + self.init(uiImage: UIImage(data: data)!) #endif } } @@ -27,9 +27,9 @@ extension Image { extension OSImage { public var data: Data { #if os(macOS) - return self.tiffRepresentation! + return self.tiffRepresentation! #elseif os(iOS) || os(tvOS) || os(watchOS) || os(visionOS) - return self.pngData()! + return self.pngData()! #endif } } diff --git a/example-swiftui/Shared/ImagePicker.swift b/example-swiftui/Shared/ImagePicker.swift index 827356f..f27c65f 100644 --- a/example-swiftui/Shared/ImagePicker.swift +++ b/example-swiftui/Shared/ImagePicker.swift @@ -2,6 +2,6 @@ import SwiftUI struct ImagePicker { @Binding var selectedImage: OSImage - + @Environment(\.presentationMode) var presentationMode } diff --git a/example-swiftui/iOS/ImagePicker+iOS.swift b/example-swiftui/iOS/ImagePicker+iOS.swift index afa7316..262d6b9 100644 --- a/example-swiftui/iOS/ImagePicker+iOS.swift +++ b/example-swiftui/iOS/ImagePicker+iOS.swift @@ -1,45 +1,53 @@ -import UIKit import SwiftUI +import UIKit + +extension ImagePicker: UIViewControllerRepresentable { -extension ImagePicker : UIViewControllerRepresentable { - var sourceType: UIImagePickerController.SourceType { - get { - return .photoLibrary - } + return .photoLibrary } - func makeUIViewController(context: UIViewControllerRepresentableContext) -> UIImagePickerController { - + func makeUIViewController(context: UIViewControllerRepresentableContext) + -> UIImagePickerController + { + let imagePicker = UIImagePickerController() imagePicker.allowsEditing = false imagePicker.sourceType = sourceType imagePicker.delegate = context.coordinator - + return imagePicker } - - func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext) { + + func updateUIViewController( + _ uiViewController: UIImagePickerController, + context: UIViewControllerRepresentableContext + ) { } - + func makeCoordinator() -> Coordinator { Coordinator(self) } - - final class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate { - + + final class Coordinator: NSObject, UIImagePickerControllerDelegate, + UINavigationControllerDelegate + { + var parent: ImagePicker - + init(_ parent: ImagePicker) { self.parent = parent } - - func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { - + + func imagePickerController( + _ picker: UIImagePickerController, + didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any] + ) { + if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage { parent.selectedImage = image } - + parent.presentationMode.wrappedValue.dismiss() } } diff --git a/example-swiftui/iOS/Keyboard.swift b/example-swiftui/iOS/Keyboard.swift index 037ffad..d1bb722 100644 --- a/example-swiftui/iOS/Keyboard.swift +++ b/example-swiftui/iOS/Keyboard.swift @@ -2,8 +2,8 @@ // Created by Jake Barnby on 4/08/21. // -import SwiftUI import Combine +import SwiftUI final class Keyboard: ObservableObject { @@ -14,7 +14,10 @@ final class Keyboard: ObservableObject { init() { NotificationCenter.default.publisher(for: UIResponder.keyboardWillChangeFrameNotification) .compactMap({ (notification) -> CGFloat? in - guard let frame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { + guard + let frame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] + as? CGRect + else { return nil } if frame.origin.y == UIScreen.main.bounds.height { @@ -31,4 +34,4 @@ final class Keyboard: ObservableObject { $0.cancel() } } -} \ No newline at end of file +} diff --git a/example-swiftui/macOS/ImagePicker+macOS.swift b/example-swiftui/macOS/ImagePicker+macOS.swift index 114c7e0..ca8a9d9 100644 --- a/example-swiftui/macOS/ImagePicker+macOS.swift +++ b/example-swiftui/macOS/ImagePicker+macOS.swift @@ -2,24 +2,23 @@ import AppKit extension ImagePicker { static func present() { - let dialog = NSOpenPanel(); + let dialog = NSOpenPanel() - dialog.title = "Choose an image" - dialog.showsResizeIndicator = true - dialog.showsHiddenFiles = false + dialog.title = "Choose an image" + dialog.showsResizeIndicator = true + dialog.showsHiddenFiles = false dialog.allowsMultipleSelection = false - dialog.canChooseDirectories = false - dialog.allowedFileTypes = ["png", "jpg", "jpeg", "gif", "tiff"] + dialog.canChooseDirectories = false + dialog.allowedFileTypes = ["png", "jpg", "jpeg", "gif", "tiff"] - if (dialog.runModal() == NSApplication.ModalResponse.OK) { + if dialog.runModal() == NSApplication.ModalResponse.OK { guard let result = dialog.url else { return } - - + // path contains the file path e.g // /Users/ourcodeworld/Desktop/tiger.jpeg - + } else { // User clicked on "Cancel" return diff --git a/example-uikit/UIKitExample/AppDelegate.swift b/example-uikit/UIKitExample/AppDelegate.swift index 597ee24..d199b98 100644 --- a/example-uikit/UIKitExample/AppDelegate.swift +++ b/example-uikit/UIKitExample/AppDelegate.swift @@ -1,28 +1,35 @@ import Appwrite import UIKit - @main class AppDelegate: UIResponder, UIApplicationDelegate { - func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { - // Override point for customization after application launch. - return true + func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + // Override point for customization after application launch. + return true } // MARK: UISceneSession Lifecycle - - func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { - // Called when a new scene session is being created. - // Use this method to select a configuration to create the new scene with. - return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) + func application( + _ application: UIApplication, + configurationForConnecting connectingSceneSession: UISceneSession, + options: UIScene.ConnectionOptions + ) -> UISceneConfiguration { + // Called when a new scene session is being created. + // Use this method to select a configuration to create the new scene with. + return UISceneConfiguration( + name: "Default Configuration", sessionRole: connectingSceneSession.role) } - - func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set) { - // Called when the user discards a scene session. - // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. - // Use this method to release any resources that were specific to the discarded scenes, as they will not return. + func application( + _ application: UIApplication, didDiscardSceneSessions sceneSessions: Set + ) { + // Called when the user discards a scene session. + // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. + // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } } diff --git a/example-uikit/UIKitExample/ImagePicker.swift b/example-uikit/UIKitExample/ImagePicker.swift index db1324f..9ddb4c7 100644 --- a/example-uikit/UIKitExample/ImagePicker.swift +++ b/example-uikit/UIKitExample/ImagePicker.swift @@ -43,8 +43,10 @@ extension ImagePicker: UIImagePickerControllerDelegate { self.pickerController(picker, didSelect: nil) } - public func imagePickerController(_ picker: UIImagePickerController, - didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) { + public func imagePickerController( + _ picker: UIImagePickerController, + didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any] + ) { guard let image = info[.originalImage] as? UIImage else { return self.pickerController(picker, didSelect: nil) } diff --git a/example-uikit/UIKitExample/SceneDelegate.swift b/example-uikit/UIKitExample/SceneDelegate.swift index 525b434..bd2a16c 100644 --- a/example-uikit/UIKitExample/SceneDelegate.swift +++ b/example-uikit/UIKitExample/SceneDelegate.swift @@ -1,14 +1,14 @@ import Appwrite import UIKit - class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? - + func scene(_ scene: UIScene, openURLContexts URLContexts: Set) { guard let url = URLContexts.first?.url, - url.absoluteString.contains("appwrite-callback") else { + url.absoluteString.contains("appwrite-callback") + else { return } WebAuthComponent.handleIncomingCookie(from: url) diff --git a/example-uikit/UIKitExample/ViewController.swift b/example-uikit/UIKitExample/ViewController.swift index 73374a6..b90a786 100644 --- a/example-uikit/UIKitExample/ViewController.swift +++ b/example-uikit/UIKitExample/ViewController.swift @@ -1,6 +1,6 @@ -import UIKit -import NIO import Appwrite +import NIO +import UIKit let host = "https://cloud.appwrite.io/v1" @@ -13,33 +13,33 @@ class ViewController: UIViewController { @IBOutlet weak var downloadButton: UIButton! @IBOutlet weak var uploadButton: UIButton! @IBOutlet weak var image: UIImageView! - + let client = Client() .setEndpoint(host) .setProject("test") let collectionId = "test" var bucketId = "test" - + var fileId = "unique()" var documentId = "unique()" - + lazy var account = Account(client) lazy var storage = Storage(client) lazy var realtime = Realtime(client) lazy var database = Database(client) - + var response = "" - + var picker: ImagePicker? - + required init?(coder: NSCoder) { super.init(coder: coder) } - + override func viewDidLoad() { super.viewDidLoad() - + picker = ImagePicker(presentationController: self, delegate: self) } @@ -55,7 +55,7 @@ class ViewController: UIViewController { self.response = String(describing: error) } } - + @IBAction func loginClick(_ sender: Any) async { do { let response = try await account.createEmailSession( @@ -67,7 +67,7 @@ class ViewController: UIViewController { self.response = String(describing: error) } } - + @IBAction func loginWithFacebook(_ sender: UIButton) async { do { let response = try await account.createOAuth2Session( @@ -80,7 +80,7 @@ class ViewController: UIViewController { self.response = String(describing: error) } } - + @IBAction func download(_ sender: Any) async { do { let response = try await storage.getFileDownload( @@ -93,20 +93,20 @@ class ViewController: UIViewController { self.response = String(describing: error) } } - + @IBAction func upload(_ sender: Any) { picker?.present() - + } - + @IBAction func subscribe(_ sender: Any) { - _ = realtime.subscribe(channel:"collections.\(collectionId).documents") { message in + _ = realtime.subscribe(channel: "collections.\(collectionId).documents") { message in DispatchQueue.main.async { self.text.text = String(describing: message) } } } - + @IBAction func createDocument(_ sender: Any) async { do { let response = try await database.createDocument( @@ -114,7 +114,7 @@ class ViewController: UIViewController { documentId: documentId, data: [ "name": "Name \(Int.random(in: 0...Int.max))", - "description": "Description \(Int.random(in: 0...Int.max))" + "description": "Description \(Int.random(in: 0...Int.max))", ], read: ["role:all"], write: [] @@ -124,16 +124,16 @@ class ViewController: UIViewController { self.response = String(describing: error) } } - + } extension ViewController: ImagePickerDelegate { func didSelect(image: UIImage?) async { let buffer = ByteBufferAllocator() .buffer(data: image!.jpegData(compressionQuality: 1)!) - + let file = File(name: "my_image.jpg", buffer: buffer) - + do { let response = try await storage.createFile( bucketId: bucketId, diff --git a/example-uikit/UIKitExampleTests/UIKitExampleTests.swift b/example-uikit/UIKitExampleTests/UIKitExampleTests.swift index 62302c4..d8185fa 100644 --- a/example-uikit/UIKitExampleTests/UIKitExampleTests.swift +++ b/example-uikit/UIKitExampleTests/UIKitExampleTests.swift @@ -7,6 +7,7 @@ // import XCTest + @testable import UIKitExample class UIKitExampleTests: XCTestCase {