diff --git a/API_GUIDELINES.md b/API_GUIDELINES.md index 587facfcc2..22bc3ec939 100644 --- a/API_GUIDELINES.md +++ b/API_GUIDELINES.md @@ -154,9 +154,9 @@ There are multiple kinds of models: main models, definition models, record model ### Definition Models - Documentation for the models are as follows: - - The first line must be structured as "A data model definition for “, followed by a short, one sentence description of what the lexicon is for: + - The first line must be structured as "A definition model for [...].“ (where "[...]") is a short, one sentence description of what the lexicon is for): ```swift - /// A data model definition for the output of checking the user's account status. + /// A definition model for an actor viewer state. ``` The requirements remain the same for the AT Protocol lexicon descriptions, the lexicon's NSID, and the GitHub link. - For the models themselves, they have the following requirements: @@ -180,9 +180,9 @@ There are multiple kinds of models: main models, definition models, record model ### Record Models - Documentation for the models are as follows: - - The first line must be structured as "A record definition for ", followed by a short, one sentence description of what the lexicon is for: + - The first line must be structured as "A record model for [...]." (where "[...]" is a short, one sentence description of what the lexicon is for): ```swift - /// A record definition of a post. + /// A record model of a post. ``` - After an empty `///` in the next line, the following line has the description that's procided by the lexicon. If there's no description, then this can be skipped. If there is one, it must say "- Note: According to the AT Protocol specifications: "`<#Description#>`"", where "`<#Description#>`" is the description provided by the lexicon. - After another empty `///` in the next line, the following line states where the API user can see the name of the lexicon, followed by the link. The structure must look like this: @@ -200,7 +200,7 @@ There are multiple kinds of models: main models, definition models, record model ### Output Models - Documentation for the model are as follows: - - The first line must be structured as "An output model for ", followed by a short, one sentence desctiption of what the lexicon is for: + - The first line must be structured as "An output model for [...]." (where "[...]" is a short, one sentence desctiption of what the lexicon is for): ```swift /// An output model for checking the user's account status. ``` @@ -223,7 +223,7 @@ There are multiple kinds of models: main models, definition models, record model ### `requestBody` Models - Documentation for the model are as follows: - - The first line must be structured as "A request body model for ", followed by a short, one sentence desctiption of what the lexicon is for: + - The first line must be structured as "A request body model for [...]." (where "[...]" is a short, one sentence desctiption of what the lexicon is for]): ```swift /// A request body model for checking the user's account status. ``` @@ -417,4 +417,7 @@ _TBD..._ ``` - If there’s a `return` statement in the `do-catch` block, or if the query method is in there, the request and response methods should be beside each other. - If any additional method calls are being made, put them beside `createRequest()` and `sendRequest()` if they're strongly related to them. - +- In documentation, when referring to the following, you _must_ write them out exactly as shown: + - decentralized identifier (DID) + - content identifer (CID) + - Namespaced Identifier (NSID) diff --git a/Sources/ATProtoKit/ATProtoKit.swift b/Sources/ATProtoKit/ATProtoKit.swift index 023ebf74a7..e43e7f3830 100644 --- a/Sources/ATProtoKit/ATProtoKit.swift +++ b/Sources/ATProtoKit/ATProtoKit.swift @@ -124,8 +124,10 @@ public class ATProtoKit: ATProtoKitConfiguration { /// /// If `canUseBlueskyRecords` is set to `false`, these will not be used. private let recordLexicons: [ATRecordProtocol.Type] = [ - FeedGenerator.self, FeedLike.self, FeedPost.self, FeedRepost.self, FeedThreadgate.self, GraphBlock.self, GraphFollow.self, GraphList.self, - GraphListBlock.self, GraphListItem.self, LabelerService.self] + AppBskyLexicon.Feed.GeneratorRecord.self, AppBskyLexicon.Feed.LikeRecord.self, AppBskyLexicon.Feed.PostRecord.self, + AppBskyLexicon.Feed.RepostRecord.self, AppBskyLexicon.Feed.ThreadgateRecord.self, AppBskyLexicon.Graph.BlockRecord.self, + AppBskyLexicon.Graph.FollowRecord.self, AppBskyLexicon.Graph.ListRecord.self, AppBskyLexicon.Graph.ListBlockRecord.self, + AppBskyLexicon.Graph.ListItemRecord.self, AppBskyLexicon.Labeler.ServiceRecord.self, ChatBskyLexicon.Actor.DeclarationRecord.self] /// Specifies the logger that will be used for emitting log messages. public private(set) var logger: Logger? @@ -135,22 +137,20 @@ public class ATProtoKit: ATProtoKitConfiguration { /// This will also handle some of the logging-related setup. The identifier will either be your /// project's `CFBundleIdentifier` or an identifier named /// `com.cjrriley.ATProtoKit`. However, you can manually override this. + /// /// - Parameters: /// - session: The authenticated user session within the AT Protocol. Optional. /// - canUseBlueskyRecords: Indicates whether Bluesky's lexicons should be used. /// Defaults to `true`. - /// - logIdentifier: Specifies the identifier for managing log outputs. Optional. Defaults + /// - logger: Specifies the identifier for managing log outputs. Optional. Defaults /// to the project's `CFBundleIdentifier`. - /// - logCategory: Specifies the category name the logs in the logger within ATProtoKit will - /// be in. Optional. Defaults to `ATProtoKit`. - /// - logLevel: Specifies the highest level of logs that will be outputted. Optional. - /// Defaults to `.info`. public init(session: UserSession? = nil, canUseBlueskyRecords: Bool = true, logger: Logger? = nil) { self.session = session self.logger = session?.logger ?? logger - if canUseBlueskyRecords { + if canUseBlueskyRecords && !ATRecordTypeRegistry.areBlueskyRecordsRegistered { _ = ATRecordTypeRegistry(types: self.recordLexicons) + ATRecordTypeRegistry.areBlueskyRecordsRegistered = false } } @@ -206,14 +206,70 @@ public class ATProtoAdmin: ATProtoKitConfiguration { /// Initializes a new instance of `ATProtoAdmin`. /// - Parameters: /// - session: The authenticated user session within the AT Protocol. - /// - logIdentifier: Specifies the identifier for managing log outputs. Optional. + /// - logger: Specifies the identifier for managing log outputs. Optional. /// Defaults to the project's `CFBundleIdentifier`. - /// - logCategory: Specifies the category name the logs in the logger within ATProtoKit - /// will be in. Optional. Defaults to `ATProtoKit`. - /// - logLevel: Specifies the highest level of logs that will be outputted. Optional. - /// Defaults to `.info`. public init(session: UserSession? = nil, logger: Logger? = nil) { self.session = session self.logger = session?.logger ?? logger } } + +/// The base class that handles all direct Bluesky-related functionality of the ATProtoKit +/// API library. +/// +/// This class requires you to first create an instance of ``ATProtoKit/ATProtoKit``. The class +/// will import the session, Bluesky records, and logging information from the instance. +/// +/// With some exceptions, the main functionality includes adding, putting, and deleting a record. +public class ATProtoBluesky: ATProtoKitConfiguration { + + /// Represents an authenticated user session within the AT Protocol. Optional. + public private(set) var session: UserSession? + + /// Specifies the logger that will be used for emitting log messages. + public private(set) var logger: Logger? + + /// Represents the instance of ``ATProtoKit/ATProtoKit``. + private let atProtoKitInstance: ATProtoKit + + /// Initializes a new instance of `ATProtoBluesky`. + /// - Parameters: + /// - atProtoKitInstance: Represents the instance of ``ATProtoKit/ATProtoKit``. + /// - logger: Specifies the identifier for managing log outputs. Optional. + /// Defaults to the project's `CFBundleIdentifier`. + public init(atProtoKitInstance: ATProtoKit, logger: Logger? = nil) { + self.atProtoKitInstance = atProtoKitInstance + self.session = self.atProtoKitInstance.session ?? nil + self.logger = self.atProtoKitInstance.session?.logger ?? logger + } +} + +/// The base class that handles the the Bluesky chat functionality of the ATProtoKit API library. +/// +/// This class requires you to first create an instance of ``ATProtoKit/ATProtoKit``. The class +/// will import the session, Bluesky records, and logging information from the instance. +/// +/// - Important: Please use an App Password in ``ATProtocolConfiguration`` that has chatting +/// privileges. Failure to do so will result in an error. +public class ATProtoBlueskyChat: ATProtoKitConfiguration { + + /// Represents an authenticated user session within the AT Protocol. Optional. + public private(set) var session: UserSession? + + /// Specifies the logger that will be used for emitting log messages. + public private(set) var logger: Logger? + + /// Represents the instance of ``ATProtoKit/ATProtoKit``. + private let atProtoKitInstance: ATProtoKit + + /// Initializes a new instance of `ATProtoBlueskyChat`. + /// - Parameters: + /// - atProtoKitInstance: Represents the instance of ``ATProtoKit/ATProtoKit``. + /// - logger: Specifies the identifier for managing log outputs. Optional. + /// Defaults to the project's `CFBundleIdentifier`. + public init(atProtoKitInstance: ATProtoKit, logger: Logger? = nil) { + self.atProtoKitInstance = atProtoKitInstance + self.session = self.atProtoKitInstance.session ?? nil + self.logger = self.atProtoKitInstance.session?.logger ?? logger + } +} diff --git a/Sources/ATProtoKit/Errors/ATProtoError.swift b/Sources/ATProtoKit/Errors/ATProtoError.swift index 286e1a747a..7fffb39fae 100644 --- a/Sources/ATProtoKit/Errors/ATProtoError.swift +++ b/Sources/ATProtoKit/Errors/ATProtoError.swift @@ -96,6 +96,9 @@ public enum ATAPIError: ATProtoError, Decodable { "UnresolvableDid", "IncompatibleDidDoc", "AccountTakedown", + "RepoTakendown", + "RepoDeactivated", + "RepoSuspended", "DuplicateCreate", "TokenRequired", "FutureCursor", diff --git a/Sources/ATProtoKit/Models/Lexicons/ATUnion.swift b/Sources/ATProtoKit/Models/Lexicons/ATUnion.swift new file mode 100644 index 0000000000..5c31a5679f --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/ATUnion.swift @@ -0,0 +1,1784 @@ +// +// ATUnion.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +/// An object that lists all of the union types for each of the lexicons. +public struct ATUnion { + + /// A reference containing the list of preferences. + public enum ActorPreferenceUnion: Codable { + + /// The "Adult Content" preference. + case adultContent(AppBskyLexicon.Actor.AdultContentPreferencesDefinition) + + /// The "Content Label" preference. + case contentLabel(AppBskyLexicon.Actor.ContentLabelPreferencesDefinition) + + /// Version 2 of the "Saved Feeds" preference. + case savedFeedsVersion2(AppBskyLexicon.Actor.SavedFeedPreferencesVersion2Definition) + + /// The "Saved Feeds" preference. + case savedFeeds(AppBskyLexicon.Actor.SavedFeedsPreferencesDefinition) + + /// The "Personal Details" preference. + case personalDetails(AppBskyLexicon.Actor.PersonalDetailsPreferencesDefinition) + + /// The "Feed View" preference. + case feedView(AppBskyLexicon.Actor.FeedViewPreferencesDefinition) + + /// The "Thread View" preference. + case threadView(AppBskyLexicon.Actor.ThreadViewPreferencesDefinition) + + /// The "Interest View" preference. + case interestViewPreferences(AppBskyLexicon.Actor.InterestViewPreferencesDefinition) + + /// The "Muted Words" preference. + case mutedWordsPreferences(AppBskyLexicon.Actor.MutedWordsPreferencesDefinition) + + /// The Hidden Posts" preference. + case hiddenPostsPreferences(AppBskyLexicon.Actor.HiddenPostsPreferencesDefinition) + + // Implement custom decoding + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + + if let value = try? container.decode(AppBskyLexicon.Actor.AdultContentPreferencesDefinition.self) { + self = .adultContent(value) + } else if let value = try? container.decode(AppBskyLexicon.Actor.ContentLabelPreferencesDefinition.self) { + self = .contentLabel(value) + } else if let value = try? container.decode(AppBskyLexicon.Actor.SavedFeedPreferencesVersion2Definition.self) { + self = .savedFeedsVersion2(value) + } else if let value = try? container.decode(AppBskyLexicon.Actor.SavedFeedsPreferencesDefinition.self) { + self = .savedFeeds(value) + } else if let value = try? container.decode(AppBskyLexicon.Actor.PersonalDetailsPreferencesDefinition.self) { + self = .personalDetails(value) + } else if let value = try? container.decode(AppBskyLexicon.Actor.FeedViewPreferencesDefinition.self) { + self = .feedView(value) + } else if let value = try? container.decode(AppBskyLexicon.Actor.ThreadViewPreferencesDefinition.self) { + self = .threadView(value) + } else if let value = try? container.decode(AppBskyLexicon.Actor.InterestViewPreferencesDefinition.self) { + self = .interestViewPreferences(value) + } else if let value = try? container.decode(AppBskyLexicon.Actor.MutedWordsPreferencesDefinition.self) { + self = .mutedWordsPreferences(value) + } else if let value = try? container.decode(AppBskyLexicon.Actor.HiddenPostsPreferencesDefinition.self) { + self = .hiddenPostsPreferences(value) + } else { + throw DecodingError.typeMismatch( + ActorPreferenceUnion.self, DecodingError.Context( + codingPath: decoder.codingPath, debugDescription: "Unknown ActorPreference type")) + } + } + + // Implement custom encoding + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + + switch self { + case .adultContent(let adultContent): + try container.encode(adultContent) + case .contentLabel(let contentLabel): + try container.encode(contentLabel) + case .savedFeedsVersion2(let savedFeedsVersion2): + try container.encode(savedFeedsVersion2) + case .savedFeeds(let savedFeeds): + try container.encode(savedFeeds) + case .personalDetails(let personalDetails): + try container.encode(personalDetails) + case .feedView(let feedView): + try container.encode(feedView) + case .threadView(let threadView): + try container.encode(threadView) + case .interestViewPreferences(let interestViewPreferences): + try container.encode(interestViewPreferences) + case .mutedWordsPreferences(let mutedWordsPreferences): + try container.encode(mutedWordsPreferences) + case .hiddenPostsPreferences(let hiddenPostsPreferences): + try container.encode(hiddenPostsPreferences) + } + } + } + + /// A reference containing the list of the status of a record. + public enum RecordViewUnion: Codable { + + /// A normal record type. + case viewRecord(AppBskyLexicon.Embed.RecordDefinition) + + /// A record that may not have been found. + case viewNotFound(AppBskyLexicon.Embed.RecordDefinition.ViewNotFound) + + /// A record that may have been blocked. + case viewBlocked(AppBskyLexicon.Embed.RecordDefinition.ViewBlocked) + + /// A generator view. + case generatorView(AppBskyLexicon.Feed.GeneratorViewDefinition) + + /// A list view. + case listView(AppBskyLexicon.Graph.ListViewDefinition) + + /// A labeler view. + case labelerView(AppBskyLexicon.Labeler.LabelerViewDefinition) + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + + if let value = try? container.decode(AppBskyLexicon.Embed.RecordDefinition.self) { + self = .viewRecord(value) + } else if let value = try? container.decode(AppBskyLexicon.Embed.RecordDefinition.ViewNotFound.self) { + self = .viewNotFound(value) + } else if let value = try? container.decode(AppBskyLexicon.Embed.RecordDefinition.ViewBlocked.self) { + self = .viewBlocked(value) + } else if let value = try? container.decode(AppBskyLexicon.Feed.GeneratorViewDefinition.self) { + self = .generatorView(value) + } else if let value = try? container.decode(AppBskyLexicon.Graph.ListViewDefinition.self) { + self = .listView(value) + } else if let value = try? container.decode(AppBskyLexicon.Labeler.LabelerViewDefinition.self) { + self = .labelerView(value) + } else { + throw DecodingError.typeMismatch( + RecordViewUnion.self, DecodingError.Context( + codingPath: decoder.codingPath, debugDescription: "Unknown RecordViewUnion type")) + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + + switch self { + case .viewRecord(let viewRecord): + try container.encode(viewRecord) + case .viewNotFound(let viewNotFound): + try container.encode(viewNotFound) + case .viewBlocked(let viewBlocked): + try container.encode(viewBlocked) + case .generatorView(let generatorView): + try container.encode(generatorView) + case .listView(let listView): + try container.encode(listView) + case .labelerView(let labelerView): + try container.encode(labelerView) + } + } + } + + /// A reference containing the list of the types of embeds. + public enum EmbedViewUnion: Codable { + + /// The view of an external embed. + case embedExternalView(AppBskyLexicon.Embed.ExternalDefinition.View) + + /// The view of an image embed. + case embedImagesView(AppBskyLexicon.Embed.ImagesDefinition.View) + + /// The view of a record embed. + case embedRecordView(AppBskyLexicon.Embed.RecordDefinition.View) + + /// The view of a record embed alongside an embed of some compatible media. + case embedRecordWithMediaView(AppBskyLexicon.Embed.RecordWithMediaDefinition.View) + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + + if let value = try? container.decode(AppBskyLexicon.Embed.ExternalDefinition.View.self) { + self = .embedExternalView(value) + } else if let value = try? container.decode(AppBskyLexicon.Embed.ImagesDefinition.View.self) { + self = .embedImagesView(value) + } else if let value = try? container.decode(AppBskyLexicon.Embed.RecordDefinition.View.self) { + self = .embedRecordView(value) + } else if let value = try? container.decode(AppBskyLexicon.Embed.RecordWithMediaDefinition.View.self) { + self = .embedRecordWithMediaView(value) + } else { + throw DecodingError.typeMismatch( + EmbedViewUnion.self, DecodingError.Context( + codingPath: decoder.codingPath, debugDescription: "Unknown EmbedViewUnion type")) + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + + switch self { + case .embedExternalView(let embedExternalView): + try container.encode(embedExternalView) + case .embedImagesView(let embedImagesView): + try container.encode(embedImagesView) + case .embedRecordView(let embedRecordView): + try container.encode(embedRecordView) + case .embedRecordWithMediaView(let embedRecordWithMediaView): + try container.encode(embedRecordWithMediaView) + } + } + } + + /// A reference containing the list of the types of compatible media. + public enum RecordWithMediaUnion: Codable { + + /// An image that will be embedded. + case embedImages(AppBskyLexicon.Embed.ImagesDefinition) + + /// An external link that will be embedded. + case embedExternal(AppBskyLexicon.Embed.ExternalDefinition) + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + + if let value = try? container.decode(AppBskyLexicon.Embed.ImagesDefinition.self) { + self = .embedImages(value) + } else if let value = try? container.decode(AppBskyLexicon.Embed.ExternalDefinition.self) { + self = .embedExternal(value) + } else { + throw DecodingError.typeMismatch( + RecordWithMediaUnion.self, DecodingError.Context( + codingPath: decoder.codingPath, debugDescription: "Unknown RecordWithMediaUnion type")) + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + + switch self { + case .embedImages(let media): + try container.encode(media) + case .embedExternal(let media): + try container.encode(media) + } + } + } + + /// A reference containing the list of the types of compatible media that can be viewed. + public enum MediaViewUnion: Codable { + + /// An image that's been embedded. + case embedImagesView(AppBskyLexicon.Embed.ImagesDefinition.View) + + /// An external link that's been embedded. + case embedExternalView(AppBskyLexicon.Embed.ExternalDefinition.View) + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + + if let value = try? container.decode(AppBskyLexicon.Embed.ImagesDefinition.View.self) { + self = .embedImagesView(value) + } else if let value = try? container.decode(AppBskyLexicon.Embed.ExternalDefinition.View.self) { + self = .embedExternalView(value) + } else { + throw DecodingError.typeMismatch( + MediaViewUnion.self, DecodingError.Context( + codingPath: decoder.codingPath, debugDescription: "Unknown MediaViewUnion type")) + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + + switch self { + case .embedImagesView(let mediaView): + try container.encode(mediaView) + case .embedExternalView(let mediaView): + try container.encode(mediaView) + } + } + } + + /// A reference containing the list of reposts. + public enum ReasonRepostUnion: Codable { + + /// A very stripped down version of a repost. + case reasonRepost(AppBskyLexicon.Feed.ReasonRepostDefinition) + + public init(from decoder: any Decoder) throws { + let container = try decoder.singleValueContainer() + + if let value = try? container.decode(AppBskyLexicon.Feed.ReasonRepostDefinition.self) { + self = .reasonRepost(value) + } else { + throw DecodingError.typeMismatch( + ReasonRepostUnion.self, DecodingError.Context( + codingPath: decoder.codingPath, debugDescription: "Unknown ReasonRepostUnion type")) + } + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.singleValueContainer() + + switch self { + case .reasonRepost(let reasonRepost): + try container.encode(reasonRepost) + } + } + } + + /// A reference containing the list of the states of a post. + public enum ReplyReferenceRootUnion: Codable { + + /// The view of a post. + case postView(AppBskyLexicon.Feed.PostViewDefinition) + + /// The view of a post that may not have been found. + case notFoundPost(AppBskyLexicon.Feed.NotFoundPostDefinition) + + /// The view of a post that's been blocked by the post author. + case blockedPost(AppBskyLexicon.Feed.BlockedPostDefinition) + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + + if let value = try? container.decode(AppBskyLexicon.Feed.PostViewDefinition.self) { + self = .postView(value) + } else if let value = try? container.decode(AppBskyLexicon.Feed.NotFoundPostDefinition.self) { + self = .notFoundPost(value) + } else if let value = try? container.decode(AppBskyLexicon.Feed.BlockedPostDefinition.self) { + self = .blockedPost(value) + } else { + throw DecodingError.typeMismatch( + ReplyReferenceRootUnion.self, DecodingError.Context( + codingPath: decoder.codingPath, debugDescription: "Unknown ReplyReferenceRootUnion type")) + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + + switch self { + case .postView(let postView): + try container.encode(postView) + case .notFoundPost(let notFoundPost): + try container.encode(notFoundPost) + case .blockedPost(let blockedPost): + try container.encode(blockedPost) + } + } + } + + /// A reference containing the list of the states of a post. + public enum ReplyReferenceParentUnion: Codable { + + /// The view of a post. + case postView(AppBskyLexicon.Feed.PostViewDefinition) + + /// The view of a post that may not have been found. + case notFoundPost(AppBskyLexicon.Feed.NotFoundPostDefinition) + + /// The view of a post that's been blocked by the post author. + case blockedPost(AppBskyLexicon.Feed.BlockedPostDefinition) + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + + if let value = try? container.decode(AppBskyLexicon.Feed.PostViewDefinition.self) { + self = .postView(value) + } else if let value = try? container.decode(AppBskyLexicon.Feed.NotFoundPostDefinition.self) { + self = .notFoundPost(value) + } else if let value = try? container.decode(AppBskyLexicon.Feed.BlockedPostDefinition.self) { + self = .blockedPost(value) + } else { + throw DecodingError.typeMismatch( + ReplyReferenceParentUnion.self, DecodingError.Context( + codingPath: decoder.codingPath, debugDescription: "Unknown ReplyReferenceParentUnion type")) + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + + switch self { + case .postView(let postView): + try container.encode(postView) + case .notFoundPost(let notFoundPost): + try container.encode(notFoundPost) + case .blockedPost(let blockedPost): + try container.encode(blockedPost) + } + } + } + + /// A reference containing the list of the states of a thread post parent. + public indirect enum ThreadViewPostParentUnion: Codable { + + /// The view of a post thread. + case threadViewPost(AppBskyLexicon.Feed.ThreadViewPostDefinition) + + /// The view of a post that may not have been found. + case notFoundPost(AppBskyLexicon.Feed.NotFoundPostDefinition) + + /// The view of a post that's been blocked by the post author. + case blockedPost(AppBskyLexicon.Feed.BlockedPostDefinition) + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + + if let value = try? container.decode(AppBskyLexicon.Feed.ThreadViewPostDefinition.self) { + self = .threadViewPost(value) + } else if let value = try? container.decode(AppBskyLexicon.Feed.NotFoundPostDefinition.self) { + self = .notFoundPost(value) + } else if let value = try? container.decode(AppBskyLexicon.Feed.BlockedPostDefinition.self) { + self = .blockedPost(value) + } else { + throw DecodingError.typeMismatch( + ThreadViewPostParentUnion.self, DecodingError.Context( + codingPath: decoder.codingPath, debugDescription: "Unknown ThreadViewPostParentUnion type")) + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + + switch self { + case .threadViewPost(let threadViewPost): + try container.encode(threadViewPost) + case .notFoundPost(let notFoundPost): + try container.encode(notFoundPost) + case .blockedPost(let blockedPost): + try container.encode(blockedPost) + } + } + } + + /// A reference containing the list of the states of a thread post reply. + public indirect enum ThreadViewPostRepliesUnion: Codable { + + /// The view of a post thread. + case threadViewPost(AppBskyLexicon.Feed.ThreadViewPostDefinition) + + /// The view of a post that may not have been found. + case notFoundPost(AppBskyLexicon.Feed.NotFoundPostDefinition) + + /// The view of a post that's been blocked by the post author. + case blockedPost(AppBskyLexicon.Feed.BlockedPostDefinition) + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + + if let value = try? container.decode(AppBskyLexicon.Feed.ThreadViewPostDefinition.self) { + self = .threadViewPost(value) + } else if let value = try? container.decode(AppBskyLexicon.Feed.NotFoundPostDefinition.self) { + self = .notFoundPost(value) + } else if let value = try? container.decode(AppBskyLexicon.Feed.BlockedPostDefinition.self) { + self = .blockedPost(value) + } else { + throw DecodingError.typeMismatch( + ThreadViewPostRepliesUnion.self, DecodingError.Context( + codingPath: decoder.codingPath, debugDescription: "Unknown ThreadViewPostRepliesUnion type")) + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + + switch self { + case .threadViewPost(let threadViewPost): + try container.encode(threadViewPost) + case .notFoundPost(let notFoundPost): + try container.encode(notFoundPost) + case .blockedPost(let blockedPost): + try container.encode(blockedPost) + } + } + } + + /// A reference containing the list of reposts. + public enum SkeletonReasonRepostUnion: Codable { + + /// A very stripped down version of a repost. + case skeletonReasonRepost(AppBskyLexicon.Feed.SkeletonReasonRepostDefinition) + + public init(from decoder: any Decoder) throws { + let container = try decoder.singleValueContainer() + + if let value = try? container.decode(AppBskyLexicon.Feed.SkeletonReasonRepostDefinition.self) { + self = .skeletonReasonRepost(value) + } else { + throw DecodingError.typeMismatch( + SkeletonReasonRepostUnion.self, DecodingError.Context( + codingPath: decoder.codingPath, debugDescription: "Unknown SkeletonReasonRepostUnion type")) + } + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.singleValueContainer() + + switch self { + case .skeletonReasonRepost(let skeletonReasonRepost): + try container.encode(skeletonReasonRepost) + } + } + } + + /// A reference containing the list of user-defined labels for feed generators. + public enum GeneratorLabelsUnion: Codable { + + /// An array of user-defined labels. + case selfLabels(ComAtprotoLexicon.Label.SelfLabelsDefinition) + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + + if let value = try? container.decode(ComAtprotoLexicon.Label.SelfLabelsDefinition.self) { + self = .selfLabels(value) + } else { + throw DecodingError.typeMismatch( + GeneratorLabelsUnion.self, DecodingError.Context( + codingPath: decoder.codingPath, debugDescription: "Unknown GeneratorLabelsUnion type")) + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + + switch self { + case .selfLabels(let selfLabelsValue): + try container.encode(selfLabelsValue) + } + } + + enum CodingKeys: String, CodingKey { + case selfLabels + } + } + + /// A reference containing the list of the states of a thread post reply. + public enum GetPostThreadOutputThreadUnion: Codable { + + /// The view of a post thread. + case threadViewPost(AppBskyLexicon.Feed.ThreadViewPostDefinition) + + /// The view of a post that may not have been found. + case notFoundPost(AppBskyLexicon.Feed.NotFoundPostDefinition) + + /// The view of a post that's been blocked by the post author. + case blockedPost(AppBskyLexicon.Feed.BlockedPostDefinition) + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + + if let value = try? container.decode(AppBskyLexicon.Feed.ThreadViewPostDefinition.self) { + self = .threadViewPost(value) + } else if let value = try? container.decode(AppBskyLexicon.Feed.NotFoundPostDefinition.self) { + self = .notFoundPost(value) + } else if let value = try? container.decode(AppBskyLexicon.Feed.BlockedPostDefinition.self) { + self = .blockedPost(value) + } else { + throw DecodingError.typeMismatch( + GetPostThreadOutputThreadUnion.self, DecodingError.Context( + codingPath: decoder.codingPath, debugDescription: "Unknown GetPostThreadOutputThreadUnion type")) + } + } + } + + /// A reference containing the list of types of embeds. + public enum PostEmbedUnion: Codable { + + /// An image embed. + case images(AppBskyLexicon.Embed.ImagesDefinition) + + /// An external embed. + case external(AppBskyLexicon.Embed.ExternalDefinition) + + /// A record embed. + case record(AppBskyLexicon.Embed.RecordDefinition) + + /// A embed with both a record and some compatible media. + case recordWithMedia(AppBskyLexicon.Embed.RecordWithMediaDefinition) + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + + if let imagesValue = try? container.decode(AppBskyLexicon.Embed.ImagesDefinition.self) { + self = .images(imagesValue) + } else if let externalValue = try? container.decode(AppBskyLexicon.Embed.ExternalDefinition.self) { + self = .external(externalValue) + } else if let recordValue = try? container.decode(AppBskyLexicon.Embed.RecordDefinition.self) { + self = .record(recordValue) + } else if let recordWithMediaValue = try? container.decode(AppBskyLexicon.Embed.RecordWithMediaDefinition.self) { + self = .recordWithMedia(recordWithMediaValue) + } else { + throw DecodingError.typeMismatch( + PostEmbedUnion.self, DecodingError.Context( + codingPath: decoder.codingPath, debugDescription: "Unknown PostEmbedUnion type")) + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + + switch self { + case .images(let imagesValue): + try container.encode(imagesValue) + case .external(let externalValue): + try container.encode(externalValue) + case .record(let recordValue): + try container.encode(recordValue) + case .recordWithMedia(let recordWithMediaValue): + try container.encode(recordWithMediaValue) + } + } + } + + /// A reference containing the list of user-defined labels. + public enum PostSelfLabelsUnion: Codable { + + /// An array of user-defined labels. + case selfLabels(ComAtprotoLexicon.Label.SelfLabelsDefinition) + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + + if let value = try? container.decode(ComAtprotoLexicon.Label.SelfLabelsDefinition.self) { + self = .selfLabels(value) + } else { + throw DecodingError.typeMismatch( + PostSelfLabelsUnion.self, DecodingError.Context( + codingPath: decoder.codingPath, debugDescription: "Unknown PostSelfLabelsUnion type")) + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + + switch self { + case .selfLabels(let selfLabelsValue): + try container.encode(selfLabelsValue) + } + } + } + + /// A reference containing the list of thread rules for a post. + public enum ThreadgateUnion: Codable { + + /// A rule that indicates whether users that the post author mentions can reply to the post. + case mentionRule(AppBskyLexicon.Feed.ThreadgateRecord.MentionRule) + + /// A rule that indicates whether users that the post author is following can reply to the post. + case followingRule(AppBskyLexicon.Feed.ThreadgateRecord.FollowingRule) + + /// A rule that indicates whether users that are on a specific list made by the post author can + /// reply to the post. + case listRule(AppBskyLexicon.Feed.ThreadgateRecord.ListRule) + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + + if let value = try? container.decode(AppBskyLexicon.Feed.ThreadgateRecord.MentionRule.self) { + self = .mentionRule(value) + } else if let value = try? container.decode(AppBskyLexicon.Feed.ThreadgateRecord.FollowingRule.self) { + self = .followingRule(value) + } else if let value = try? container.decode(AppBskyLexicon.Feed.ThreadgateRecord.ListRule.self) { + self = .listRule(value) + } else { + throw DecodingError.typeMismatch( + ThreadgateUnion.self, DecodingError.Context( + codingPath: decoder.codingPath, debugDescription: "Unknown ThreadgateUnion type")) + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + + switch self { + case .mentionRule(let embedView): + try container.encode(embedView) + case .followingRule(let embedView): + try container.encode(embedView) + case .listRule(let embedView): + try container.encode(embedView) + } + } + } + + /// A reference containing the list of relationships of multiple user accounts. + public enum GetRelationshipsOutputRelationshipUnion: Codable { + + /// The relationship between two user accounts. + case relationship(AppBskyLexicon.Graph.RelationshipDefinition) + + /// Indicates the user account is not found. + case notFoundActor(AppBskyLexicon.Graph.NotFoundActorDefinition) + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + + if let value = try? container.decode(AppBskyLexicon.Graph.RelationshipDefinition.self) { + self = .relationship(value) + } else if let value = try? container.decode(AppBskyLexicon.Graph.NotFoundActorDefinition.self) { + self = .notFoundActor(value) + } else { + throw DecodingError.typeMismatch( + GetRelationshipsOutputRelationshipUnion.self, DecodingError.Context( + codingPath: decoder.codingPath, debugDescription: "Unknown GetRelationshipsOutputRelationshipUnion type")) + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + + switch self { + case .relationship(let relationship): + try container.encode(relationship) + case .notFoundActor(let notFoundActor): + try container.encode(notFoundActor) + } + } + } + + /// A reference containing the list of labeler views. + public enum GetServicesOutputViewsUnion: Codable { + + /// A labeler view. + case labelerView(AppBskyLexicon.Labeler.LabelerViewDefinition) + + /// A detailed view of a labeler. + case labelerViewDetailed(AppBskyLexicon.Labeler.LabelerViewDetailedDefinition) + + public init(from decoder: any Decoder) throws { + let container = try decoder.singleValueContainer() + + if let value = try? container.decode(AppBskyLexicon.Labeler.LabelerViewDefinition.self) { + self = .labelerView(value) + } else if let value = try? container.decode(AppBskyLexicon.Labeler.LabelerViewDetailedDefinition.self) { + self = .labelerViewDetailed(value) + } else { + throw DecodingError.typeMismatch( + GetServicesOutputViewsUnion.self, DecodingError.Context( + codingPath: decoder.codingPath, debugDescription: "Unknown GetServicesOutputViewsUnion type")) + } + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.singleValueContainer() + + switch self { + case .labelerView(let labelerView): + try container.encode(labelerView) + case .labelerViewDetailed(let labelerViewDetailed): + try container.encode(labelerViewDetailed) + } + } + } + + /// A reference containing the list of feature types. + public enum FacetFeatureUnion: Codable { + + /// The Mention feature. + case mention(AppBskyLexicon.RichText.Facet.Mention) + + /// The Link feature. + case link(AppBskyLexicon.RichText.Facet.Link) + + /// The Tag feature. + case tag(AppBskyLexicon.RichText.Facet.Tag) + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + + if let value = try? container.decode(AppBskyLexicon.RichText.Facet.Mention.self) { + self = .mention(value) + } else if let value = try? container.decode(AppBskyLexicon.RichText.Facet.Link.self) { + self = .link(value) + } else if let value = try? container.decode(AppBskyLexicon.RichText.Facet.Tag.self) { + self = .tag(value) + } else { + throw DecodingError.typeMismatch( + FacetFeatureUnion.self, DecodingError.Context( + codingPath: decoder.codingPath, debugDescription: "Unknown FacetFeatureUnion type")) + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + + switch self { + case .mention(let mention): + try container.encode(mention) + case .link(let link): + try container.encode(link) + case .tag(let tag): + try container.encode(tag) + } + } + } + + /// A reference containing the list of user-defined labels for feed generators. + public enum ListLabelsUnion: Codable { + + /// An array of user-defined labels. + case selfLabels(ComAtprotoLexicon.Label.SelfLabelsDefinition) + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + + if let value = try? container.decode(ComAtprotoLexicon.Label.SelfLabelsDefinition.self) { + self = .selfLabels(value) + } else { + throw DecodingError.typeMismatch( + ListLabelsUnion.self, DecodingError.Context( + codingPath: decoder.codingPath, debugDescription: "Unknown ListLabelsUnion type")) + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + + switch self { + case .selfLabels(let selfLabelsValue): + try container.encode(selfLabelsValue) + } + } + } + + /// A reference containing the list of message embeds. + public enum MessageInputEmbedUnion: Codable { + + /// A record within the embed. + case record(AppBskyLexicon.Embed.RecordDefinition) + + public init(from decoder: any Decoder) throws { + let container = try decoder.singleValueContainer() + + if let value = try? container.decode(AppBskyLexicon.Embed.RecordDefinition.self) { + self = .record(value) + } else { + throw DecodingError.typeMismatch( + MessageInputEmbedUnion.self, DecodingError.Context( + codingPath: decoder.codingPath, debugDescription: "Unknown MessageInputEmbedUnion type")) + } + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.singleValueContainer() + + switch self { + case .record(let record): + try container.encode(record) + } + } + } + + /// A reference containing the list of message embeds. + public enum MessageViewEmbedUnion: Codable { + + /// A record within the embed. + case record(AppBskyLexicon.Embed.RecordDefinition.View) + + public init(from decoder: any Decoder) throws { + let container = try decoder.singleValueContainer() + + if let value = try? container.decode(AppBskyLexicon.Embed.RecordDefinition.View.self) { + self = .record(value) + } else { + throw DecodingError.typeMismatch( + MessageViewEmbedUnion.self, DecodingError.Context( + codingPath: decoder.codingPath, debugDescription: "Unknown MessageViewEmbedUnion type")) + } + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.singleValueContainer() + + switch self { + case .record(let record): + try container.encode(record) + } + } + } + + /// A reference containing the list of messages. + public enum ConversationViewLastMessageUnion: Codable { + + /// A message view. + case messageView(ChatBskyLexicon.Conversation.MessageViewDefinition) + + /// A deleted message view. + case deletedMessageView(ChatBskyLexicon.Conversation.DeletedMessageViewDefinition) + + public init(from decoder: any Decoder) throws { + let container = try decoder.singleValueContainer() + + if let value = try? container.decode(ChatBskyLexicon.Conversation.MessageViewDefinition.self) { + self = .messageView(value) + } else if let value = try? container.decode(ChatBskyLexicon.Conversation.DeletedMessageViewDefinition.self) { + self = .deletedMessageView(value) + } else { + throw DecodingError.typeMismatch( + ConversationViewLastMessageUnion.self, DecodingError.Context( + codingPath: decoder.codingPath, debugDescription: "Unknown ConversationViewLastMessageUnion type")) + } + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.singleValueContainer() + + switch self { + case .messageView(let messageView): + try container.encode(messageView) + case .deletedMessageView(let deletedMessageView): + try container.encode(deletedMessageView) + } + } + } + + /// A reference containing the list of messages. + public enum LogCreateMessageUnion: Codable { + + /// A message view. + case messageView(ChatBskyLexicon.Conversation.MessageViewDefinition) + + /// A deleted message view. + case deletedMessageView(ChatBskyLexicon.Conversation.DeletedMessageViewDefinition) + + public init(from decoder: any Decoder) throws { + let container = try decoder.singleValueContainer() + + if let value = try? container.decode(ChatBskyLexicon.Conversation.MessageViewDefinition.self) { + self = .messageView(value) + } else if let value = try? container.decode(ChatBskyLexicon.Conversation.DeletedMessageViewDefinition.self) { + self = .deletedMessageView(value) + } else { + throw DecodingError.typeMismatch( + LogCreateMessageUnion.self, DecodingError.Context( + codingPath: decoder.codingPath, debugDescription: "Unknown LogCreateMessageUnion type")) + } + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.singleValueContainer() + + switch self { + case .messageView(let messageView): + try container.encode(messageView) + case .deletedMessageView(let deletedMessageView): + try container.encode(deletedMessageView) + } + } + } + + /// A reference containing the list of messages. + public enum LogDeleteMessageUnion: Codable { + + /// A message view. + case messageView(ChatBskyLexicon.Conversation.MessageViewDefinition) + + /// A deleted message view. + case deletedMessageView(ChatBskyLexicon.Conversation.DeletedMessageViewDefinition) + + public init(from decoder: any Decoder) throws { + let container = try decoder.singleValueContainer() + + if let value = try? container.decode(ChatBskyLexicon.Conversation.MessageViewDefinition.self) { + self = .messageView(value) + } else if let value = try? container.decode(ChatBskyLexicon.Conversation.DeletedMessageViewDefinition.self) { + self = .deletedMessageView(value) + } else { + throw DecodingError.typeMismatch( + LogDeleteMessageUnion.self, DecodingError.Context( + codingPath: decoder.codingPath, debugDescription: "Unknown LogDeleteMessageUnion type")) + } + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.singleValueContainer() + + switch self { + case .messageView(let messageView): + try container.encode(messageView) + case .deletedMessageView(let deletedMessageView): + try container.encode(deletedMessageView) + } + } + } + + /// A reference containing the list of message logs. + public enum MessageLogsUnion: Codable { + + /// A log entry for beginning the coversation. + case logBeginConversation(ChatBskyLexicon.Conversation.LogBeginConversationDefinition) + + /// A log entry for leaving the conversation. + case logLeaveConversation(ChatBskyLexicon.Conversation.LogLeaveConversationDefinition) + + /// A log entry for creating a message. + case logCreateMessage(ChatBskyLexicon.Conversation.LogCreateMessageDefinition) + + /// A log entry for deleting a message. + case logDeleteMessage(ChatBskyLexicon.Conversation.LogDeleteMessageDefinition) + + public init(from decoder: any Decoder) throws { + let container = try decoder.singleValueContainer() + + if let value = try? container.decode(ChatBskyLexicon.Conversation.LogBeginConversationDefinition.self) { + self = .logBeginConversation(value) + } else if let value = try? container.decode(ChatBskyLexicon.Conversation.LogLeaveConversationDefinition.self) { + self = .logLeaveConversation(value) + } else if let value = try? container.decode(ChatBskyLexicon.Conversation.LogCreateMessageDefinition.self) { + self = .logCreateMessage(value) + } else if let value = try? container.decode(ChatBskyLexicon.Conversation.LogDeleteMessageDefinition.self) { + self = .logDeleteMessage(value) + } else { + throw DecodingError.typeMismatch( + MessageLogsUnion.self, DecodingError.Context( + codingPath: decoder.codingPath, debugDescription: "Unknown MessageLogsUnion type")) + } + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.singleValueContainer() + + switch self { + case .logBeginConversation(let logBeginConversation): + try container.encode(logBeginConversation) + case .logLeaveConversation(let logLeaveConversation): + try container.encode(logLeaveConversation) + case .logCreateMessage(let logCreateMessage): + try container.encode(logCreateMessage) + case .logDeleteMessage(let logDeleteMessage): + try container.encode(logDeleteMessage) + } + } + } + + /// A reference containing the list of messages. + public enum GetMessagesOutputMessagesUnion: Codable { + + /// A message view. + case messageView(ChatBskyLexicon.Conversation.MessageViewDefinition) + + /// A deleted message view. + case deletedMessageView(ChatBskyLexicon.Conversation.DeletedMessageViewDefinition) + + public init(from decoder: any Decoder) throws { + let container = try decoder.singleValueContainer() + + if let value = try? container.decode(ChatBskyLexicon.Conversation.MessageViewDefinition.self) { + self = .messageView(value) + } else if let value = try? container.decode(ChatBskyLexicon.Conversation.DeletedMessageViewDefinition.self) { + self = .deletedMessageView(value) + } else { + throw DecodingError.typeMismatch( + GetMessagesOutputMessagesUnion.self, DecodingError.Context( + codingPath: decoder.codingPath, debugDescription: "Unknown GetMessagesOutputMessagesUnion type")) + } + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.singleValueContainer() + + switch self { + case .messageView(let messageView): + try container.encode(messageView) + case .deletedMessageView(let deletedMessageView): + try container.encode(deletedMessageView) + } + } + } + + /// A reference containing the list of messages. + public enum GetMessageContextOutputMessagesUnion: Codable { + + /// A message view. + case messageView(ChatBskyLexicon.Conversation.MessageViewDefinition) + + /// A deleted message view. + case deletedMessageView(ChatBskyLexicon.Conversation.DeletedMessageViewDefinition) + + public init(from decoder: any Decoder) throws { + let container = try decoder.singleValueContainer() + + if let value = try? container.decode(ChatBskyLexicon.Conversation.MessageViewDefinition.self) { + self = .messageView(value) + } else if let value = try? container.decode(ChatBskyLexicon.Conversation.DeletedMessageViewDefinition.self) { + self = .deletedMessageView(value) + } else { + throw DecodingError.typeMismatch( + ConversationViewLastMessageUnion.self, DecodingError.Context( + codingPath: decoder.codingPath, debugDescription: "Unknown ConversationViewLastMessageUnion type")) + } + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.singleValueContainer() + + switch self { + case .messageView(let messageView): + try container.encode(messageView) + case .deletedMessageView(let deletedMessageView): + try container.encode(deletedMessageView) + } + } + } + + /// A reference containing the list of repository references. + public enum AdminGetSubjectStatusUnion: Codable { + + /// A repository reference. + case repositoryReference(ComAtprotoLexicon.Admin.RepositoryReferenceDefinition) + + /// A strong reference. + case strongReference(ComAtprotoLexicon.Repository.StrongReference) + + /// A repository blob reference. + case repositoryBlobReference(ComAtprotoLexicon.Admin.RepositoryBlobReferenceDefinition) + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + + if let value = try? container.decode(ComAtprotoLexicon.Admin.RepositoryReferenceDefinition.self) { + self = .repositoryReference(value) + } else if let value = try? container.decode(ComAtprotoLexicon.Repository.StrongReference.self) { + self = .strongReference(value) + } else if let value = try? container.decode(ComAtprotoLexicon.Admin.RepositoryBlobReferenceDefinition.self) { + self = .repositoryBlobReference(value) + } else { + throw DecodingError.typeMismatch( + AdminGetSubjectStatusUnion.self, DecodingError.Context( + codingPath: decoder.codingPath, debugDescription: "Unknown AdminGetSubjectStatusUnion type")) + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + + switch self { + case .repositoryReference(let repositoryReference): + try container.encode(repositoryReference) + case .strongReference(let strongReference): + try container.encode(strongReference) + case .repositoryBlobReference(let repoBlobReference): + try container.encode(repoBlobReference) + } + } + } + + /// A reference containing the list of repository references. + public enum AdminUpdateSubjectStatusUnion: Codable { + + /// A repository reference. + case repositoryReference(ComAtprotoLexicon.Admin.RepositoryReferenceDefinition) + + /// A strong reference. + case strongReference(ComAtprotoLexicon.Repository.StrongReference) + + /// A repository blob reference. + case repositoryBlobReference(ComAtprotoLexicon.Admin.RepositoryBlobReferenceDefinition) + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + + if let value = try? container.decode(ComAtprotoLexicon.Admin.RepositoryReferenceDefinition.self) { + self = .repositoryReference(value) + } else if let value = try? container.decode(ComAtprotoLexicon.Repository.StrongReference.self) { + self = .strongReference(value) + } else if let value = try? container.decode(ComAtprotoLexicon.Admin.RepositoryBlobReferenceDefinition.self) { + self = .repositoryBlobReference(value) + } else { + throw DecodingError.typeMismatch( + AdminUpdateSubjectStatusUnion.self, DecodingError.Context( + codingPath: decoder.codingPath, debugDescription: "Uknown AdminUpdateSubjectStatusUnion type")) + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + + switch self { + case .repositoryReference(let repositoryReference): + try container.encode(repositoryReference) + case .strongReference(let strongReference): + try container.encode(strongReference) + case .repositoryBlobReference(let repoBlobReference): + try container.encode(repoBlobReference) + } + } + } + + /// A reference containing the list of repository references. + public enum CreateReportSubjectUnion: Codable { + + /// A repository reference. + case repositoryReference(ComAtprotoLexicon.Admin.RepositoryReferenceDefinition) + + /// A strong reference. + case strongReference(ComAtprotoLexicon.Repository.StrongReference) + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + + if let value = try? container.decode(ComAtprotoLexicon.Admin.RepositoryReferenceDefinition.self) { + self = .repositoryReference(value) + } else if let value = try? container.decode(ComAtprotoLexicon.Repository.StrongReference.self) { + self = .strongReference(value) + } else { + throw DecodingError.typeMismatch( + CreateReportSubjectUnion.self, DecodingError.Context( + codingPath: decoder.codingPath, debugDescription: "Unknown CreateReportSubjectUnion type")) + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + + switch self { + case .repositoryReference(let repositoryReference): + try container.encode(repositoryReference) + case .strongReference(let strongReference): + try container.encode(strongReference) + } + } + } + + /// A reference containing the list of write operations. + public enum ApplyWritesUnion: Codable { + + /// A "Create" write operation. + case create(ComAtprotoLexicon.Repository.ApplyWrites.Create) + + /// An "Update" write operation. + case update(ComAtprotoLexicon.Repository.ApplyWrites.Update) + + /// A "Delete" write operation. + case delete(ComAtprotoLexicon.Repository.ApplyWrites.Delete) + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + + if let value = try? container.decode(ComAtprotoLexicon.Repository.ApplyWrites.Create.self) { + self = .create(value) + } else if let value = try? container.decode(ComAtprotoLexicon.Repository.ApplyWrites.Update.self) { + self = .update(value) + } else if let value = try? container.decode(ComAtprotoLexicon.Repository.ApplyWrites.Delete.self) { + self = .delete(value) + } else { + throw DecodingError.typeMismatch( + ApplyWritesUnion.self, DecodingError.Context( + codingPath: decoder.codingPath, debugDescription: "Unknown ApplyWritesUnion type")) + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + + switch self { + case .create(let embedView): + try container.encode(embedView) + case .update(let embedView): + try container.encode(embedView) + case .delete(let embedView): + try container.encode(embedView) + } + } + } + + /// A reference containing the list of event views. + public enum ModerationEventViewUnion: Codable { + + /// A takedown event. + case moderationEventTakedown(ToolsOzoneLexicon.Moderation.EventTakedownDefinition) + + /// A reverse takedown event. + case moderationEventReverseTakedown(ToolsOzoneLexicon.Moderation.EventReverseTakedownDefinition) + + /// A comment event. + case moderationEventComment(ToolsOzoneLexicon.Moderation.EventCommentDefinition) + + /// A report event. + case moderationEventReport(ToolsOzoneLexicon.Moderation.EventReportDefinition) + + /// A label event. + case moderationEventLabel(ToolsOzoneLexicon.Moderation.EventLabelDefinition) + + /// An acknowledgement event. + case moderationEventAcknowledge(ToolsOzoneLexicon.Moderation.EventAcknowledgeDefinition) + + /// An escalation event. + case moderationEventEscalate(ToolsOzoneLexicon.Moderation.EventEscalateDefinition) + + /// A mute event. + case moderationEventMute(ToolsOzoneLexicon.Moderation.EventMuteDefinition) + + /// An unmute event. + case moderationEventUnmute(ToolsOzoneLexicon.Moderation.EventUnmuteDefinition) + + /// A mute reporter event. + case moderationEventMuteReporter(ToolsOzoneLexicon.Moderation.EventMuteReporterDefinition) + + /// An unmute reporter event. + case moderationEventUnmuteReporter(ToolsOzoneLexicon.Moderation.EventUnmuteReporterDefinition) + + /// An email event. + case moderationEventEmail(ToolsOzoneLexicon.Moderation.EventEmailDefinition) + + /// A resolve appeal event. + case moderationEventResolveAppeal(ToolsOzoneLexicon.Moderation.EventResolveAppealDefinition) + + /// A diversion event. + case moderationEventDivert(ToolsOzoneLexicon.Moderation.EventDivertDefinition) + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + + if let value = try? container.decode(ToolsOzoneLexicon.Moderation.EventTakedownDefinition.self) { + self = .moderationEventTakedown(value) + } else if let value = try? container.decode(ToolsOzoneLexicon.Moderation.EventReverseTakedownDefinition.self) { + self = .moderationEventReverseTakedown(value) + } else if let value = try? container.decode(ToolsOzoneLexicon.Moderation.EventCommentDefinition.self) { + self = .moderationEventComment(value) + } else if let value = try? container.decode(ToolsOzoneLexicon.Moderation.EventReportDefinition.self) { + self = .moderationEventReport(value) + } else if let value = try? container.decode(ToolsOzoneLexicon.Moderation.EventLabelDefinition.self) { + self = .moderationEventLabel(value) + } else if let value = try? container.decode(ToolsOzoneLexicon.Moderation.EventAcknowledgeDefinition.self) { + self = .moderationEventAcknowledge(value) + } else if let value = try? container.decode(ToolsOzoneLexicon.Moderation.EventEscalateDefinition.self) { + self = .moderationEventEscalate(value) + } else if let value = try? container.decode(ToolsOzoneLexicon.Moderation.EventMuteDefinition.self) { + self = .moderationEventMute(value) + } else if let value = try? container.decode(ToolsOzoneLexicon.Moderation.EventUnmuteDefinition.self) { + self = .moderationEventUnmute(value) + } else if let value = try? container.decode(ToolsOzoneLexicon.Moderation.EventMuteReporterDefinition.self) { + self = .moderationEventMuteReporter(value) + } else if let value = try? container.decode(ToolsOzoneLexicon.Moderation.EventUnmuteReporterDefinition.self) { + self = .moderationEventUnmuteReporter(value) + } else if let value = try? container.decode(ToolsOzoneLexicon.Moderation.EventEmailDefinition.self) { + self = .moderationEventEmail(value) + } else if let value = try? container.decode(ToolsOzoneLexicon.Moderation.EventResolveAppealDefinition.self) { + self = .moderationEventResolveAppeal(value) + } else if let value = try? container.decode(ToolsOzoneLexicon.Moderation.EventDivertDefinition.self) { + self = .moderationEventDivert(value) + } else { + throw DecodingError.typeMismatch( + ModerationEventViewUnion.self, DecodingError.Context( + codingPath: decoder.codingPath, debugDescription: "Unknown ModerationEventViewUnion type")) + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + + switch self { + case .moderationEventTakedown(let moderationEventTakedown): + try container.encode(moderationEventTakedown) + case .moderationEventReverseTakedown(let moderationEventReverseTakedown): + try container.encode(moderationEventReverseTakedown) + case .moderationEventComment(let moderationEventComment): + try container.encode(moderationEventComment) + case .moderationEventReport(let moderationEventReport): + try container.encode(moderationEventReport) + case .moderationEventLabel(let moderationEventLabel): + try container.encode(moderationEventLabel) + case .moderationEventAcknowledge(let moderationEventAcknowledge): + try container.encode(moderationEventAcknowledge) + case .moderationEventEscalate(let moderationEventEscalate): + try container.encode(moderationEventEscalate) + case .moderationEventMute(let moderationEventMute): + try container.encode(moderationEventMute) + case .moderationEventUnmute(let moderationEventUnmute): + try container.encode(moderationEventUnmute) + case .moderationEventMuteReporter(let moderationEventMuteReporter): + try container.encode(moderationEventMuteReporter) + case .moderationEventUnmuteReporter(let moderationEventUnmuteReporter): + try container.encode(moderationEventUnmuteReporter) + case .moderationEventEmail(let moderationEventEmail): + try container.encode(moderationEventEmail) + case .moderationEventResolveAppeal(let moderationEventResolveAppeal): + try container.encode(moderationEventResolveAppeal) + case .moderationEventDivert(let moderationEventDivert): + try container.encode(moderationEventDivert) + } + } + } + + /// A reference containing the list of repository references. + public enum ModerationEventViewSubjectUnion: Codable { + + /// A repository reference. + case repositoryReference(ComAtprotoLexicon.Admin.RepositoryReferenceDefinition) + + /// A strong reference. + case strongReference(ComAtprotoLexicon.Repository.StrongReference) + + /// A message reference for a conversation. + case messageReference(ChatBskyLexicon.Conversation.MessageReferenceDefinition) + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + + if let value = try? container.decode(ComAtprotoLexicon.Admin.RepositoryReferenceDefinition.self) { + self = .repositoryReference(value) + } else if let value = try? container.decode(ComAtprotoLexicon.Repository.StrongReference.self) { + self = .strongReference(value) + } else if let value = try? container.decode(ChatBskyLexicon.Conversation.MessageReferenceDefinition.self) { + self = .messageReference(value) + } else { + throw DecodingError.typeMismatch( + ModerationEventViewSubjectUnion.self, DecodingError.Context( + codingPath: decoder.codingPath, debugDescription: "Unknown ModerationEventViewSubjectUnion type")) + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + + switch self { + case .repositoryReference(let repositoryReference): + try container.encode(repositoryReference) + case .strongReference(let strongReference): + try container.encode(strongReference) + case .messageReference(let messageReference): + try container.encode(messageReference) + } + } + } + + /// A reference containing the list of moderator events. + public enum ModerationEventViewDetailUnion: Codable { + + /// A takedown event. + case moderationEventTakedown(ToolsOzoneLexicon.Moderation.EventTakedownDefinition) + + /// A reverse takedown event. + case moderationEventReverseTakedown(ToolsOzoneLexicon.Moderation.EventReverseTakedownDefinition) + + /// A comment event. + case moderationEventComment(ToolsOzoneLexicon.Moderation.EventCommentDefinition) + + /// A report event. + case moderationEventReport(ToolsOzoneLexicon.Moderation.EventReportDefinition) + + /// A label event. + case moderationEventLabel(ToolsOzoneLexicon.Moderation.EventLabelDefinition) + + /// An acknowledgment event. + case moderationEventAcknowledge(ToolsOzoneLexicon.Moderation.EventAcknowledgeDefinition) + + /// An escalation event. + case moderationEventEscalate(ToolsOzoneLexicon.Moderation.EventEscalateDefinition) + + /// A mute event. + case moderationEventMute(ToolsOzoneLexicon.Moderation.EventMuteDefinition) + + /// A resolve appeal event. + case moderationEventResolveAppeal(ToolsOzoneLexicon.Moderation.EventResolveAppealDefinition) + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + + if let value = try? container.decode(ToolsOzoneLexicon.Moderation.EventTakedownDefinition.self) { + self = .moderationEventTakedown(value) + } else if let value = try? container.decode(ToolsOzoneLexicon.Moderation.EventReverseTakedownDefinition.self) { + self = .moderationEventReverseTakedown(value) + } else if let value = try? container.decode(ToolsOzoneLexicon.Moderation.EventCommentDefinition.self) { + self = .moderationEventComment(value) + } else if let value = try? container.decode(ToolsOzoneLexicon.Moderation.EventReportDefinition.self) { + self = .moderationEventReport(value) + } else if let value = try? container.decode(ToolsOzoneLexicon.Moderation.EventLabelDefinition.self) { + self = .moderationEventLabel(value) + } else if let value = try? container.decode(ToolsOzoneLexicon.Moderation.EventAcknowledgeDefinition.self) { + self = .moderationEventAcknowledge(value) + } else if let value = try? container.decode(ToolsOzoneLexicon.Moderation.EventEscalateDefinition.self) { + self = .moderationEventEscalate(value) + } else if let value = try? container.decode(ToolsOzoneLexicon.Moderation.EventMuteDefinition.self) { + self = .moderationEventMute(value) + } else if let value = try? container.decode(ToolsOzoneLexicon.Moderation.EventResolveAppealDefinition.self) { + self = .moderationEventResolveAppeal(value) + } else { + throw DecodingError.typeMismatch( + ModerationEventViewDetailUnion.self, DecodingError.Context( + codingPath: decoder.codingPath, debugDescription: "Unknown ModerationEventViewDetailUnion type")) + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + + switch self { + case .moderationEventTakedown(let moderationEventTakedown): + try container.encode(moderationEventTakedown) + case .moderationEventReverseTakedown(let moderationEventDetail): + try container.encode(moderationEventDetail) + case .moderationEventComment(let moderationEventComment): + try container.encode(moderationEventComment) + case .moderationEventReport(let moderationEventReport): + try container.encode(moderationEventReport) + case .moderationEventLabel(let moderationEventLabel): + try container.encode(moderationEventLabel) + case .moderationEventAcknowledge(let moderationEventAcknowledge): + try container.encode(moderationEventAcknowledge) + case .moderationEventEscalate(let moderationEventEscalate): + try container.encode(moderationEventEscalate) + case .moderationEventMute(let moderationEventMute): + try container.encode(moderationEventMute) + case .moderationEventResolveAppeal(let moderationEventResolveAppeal): + try container.encode(moderationEventResolveAppeal) + } + } + } + + /// A reference containing the list of repository references. + public enum ModerationEventViewDetailSubjectUnion: Codable { + + /// A repository reference. + case repositoryReference(ComAtprotoLexicon.Admin.RepositoryReferenceDefinition) + + /// A strong reference. + case strongReference(ComAtprotoLexicon.Repository.StrongReference) + + /// A message reference for a conversation. + case messageReference(ChatBskyLexicon.Conversation.MessageReferenceDefinition) + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + + if let value = try? container.decode(ComAtprotoLexicon.Admin.RepositoryReferenceDefinition.self) { + self = .repositoryReference(value) + } else if let value = try? container.decode(ComAtprotoLexicon.Repository.StrongReference.self) { + self = .strongReference(value) + } else if let value = try? container.decode(ChatBskyLexicon.Conversation.MessageReferenceDefinition.self) { + self = .messageReference(value) + } else { + throw DecodingError.typeMismatch( + ModerationEventViewDetailSubjectUnion.self, DecodingError.Context( + codingPath: decoder.codingPath, debugDescription: "Unknown ModerationEventViewDetailSubjectUnion type")) + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + + switch self { + case .repositoryReference(let repositoryReference): + try container.encode(repositoryReference) + case .strongReference(let strongReference): + try container.encode(strongReference) + case .messageReference(let messageReference): + try container.encode(messageReference) + } + } + } + + /// A reference containing the list of repository references. + public enum SubjectStatusViewSubjectUnion: Codable { + + /// A repository reference. + case repositoryReference(ComAtprotoLexicon.Admin.RepositoryReferenceDefinition) + + /// A strong reference. + case strongReference(ComAtprotoLexicon.Repository.StrongReference) + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + + if let value = try? container.decode(ComAtprotoLexicon.Admin.RepositoryReferenceDefinition.self) { + self = .repositoryReference(value) + } else if let value = try? container.decode(ComAtprotoLexicon.Repository.StrongReference.self) { + self = .strongReference(value) + } else { + throw DecodingError.typeMismatch( + SubjectStatusViewSubjectUnion.self, DecodingError.Context( + codingPath: decoder.codingPath, debugDescription: "Unknown SubjectStatusViewSubjectUnion type")) + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + + switch self { + case .repositoryReference(let repositoryReference): + try container.encode(repositoryReference) + case .strongReference(let strongReference): + try container.encode(strongReference) + } + } + } + + /// A reference containing the list of the types of media details. + public enum BlobViewDetailUnion: Codable { + + /// The details for an image. + case mediaImageDetails(ToolsOzoneLexicon.Moderation.ImageDetailsDefinition) + + /// The details for a video. + case mediaVideoDetails(ToolsOzoneLexicon.Moderation.VideoDetailsDefinition) + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + + if let value = try? container.decode(ToolsOzoneLexicon.Moderation.ImageDetailsDefinition.self) { + self = .mediaImageDetails(value) + } else if let value = try? container.decode(ToolsOzoneLexicon.Moderation.VideoDetailsDefinition.self) { + self = .mediaVideoDetails(value) + } else { + throw DecodingError.typeMismatch( + BlobViewDetailUnion.self, DecodingError.Context( + codingPath: decoder.codingPath, debugDescription: "Unknown BlobViewDetailUnion type")) + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + + switch self { + case .mediaImageDetails(let mediaImageDetails): + try container.encode(mediaImageDetails) + case .mediaVideoDetails(let mediaVideoDetails): + try container.encode(mediaVideoDetails) + } + } + } + + /// A reference containing the list of event views. + public enum EmitEventUnion: Codable { + + /// A takedown event. + case moderationEventTakedown(ToolsOzoneLexicon.Moderation.EventTakedownDefinition) + + /// A reverse takedown event. + case moderationEventReverseTakedown(ToolsOzoneLexicon.Moderation.EventReverseTakedownDefinition) + + /// A comment event. + case moderationEventComment(ToolsOzoneLexicon.Moderation.EventCommentDefinition) + + /// A report event. + case moderationEventReport(ToolsOzoneLexicon.Moderation.EventReportDefinition) + + /// A label event. + case moderationEventLabel(ToolsOzoneLexicon.Moderation.EventLabelDefinition) + + /// An acknowledgement event. + case moderationEventAcknowledge(ToolsOzoneLexicon.Moderation.EventAcknowledgeDefinition) + + /// An escalation event. + case moderationEventEscalate(ToolsOzoneLexicon.Moderation.EventEscalateDefinition) + + /// A mute event. + case moderationEventMute(ToolsOzoneLexicon.Moderation.EventMuteDefinition) + + /// An unmute event. + case moderationEventUnmute(ToolsOzoneLexicon.Moderation.EventUnmuteDefinition) + + /// A mute reporter event. + case moderationEventMuteReporter(ToolsOzoneLexicon.Moderation.EventMuteReporterDefinition) + + /// An unmute reporter event. + case moderationEventUnmuteReporter(ToolsOzoneLexicon.Moderation.EventUnmuteReporterDefinition) + + /// An email event. + case moderationEventEmail(ToolsOzoneLexicon.Moderation.EventEmailDefinition) + + /// A resolve appeal event. + case moderationEventResolveAppeal(ToolsOzoneLexicon.Moderation.EventResolveAppealDefinition) + + /// A diversion event. + case moderationEventDivert(ToolsOzoneLexicon.Moderation.EventDivertDefinition) + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + + if let value = try? container.decode(ToolsOzoneLexicon.Moderation.EventTakedownDefinition.self) { + self = .moderationEventTakedown(value) + } else if let value = try? container.decode(ToolsOzoneLexicon.Moderation.EventReverseTakedownDefinition.self) { + self = .moderationEventReverseTakedown(value) + } else if let value = try? container.decode(ToolsOzoneLexicon.Moderation.EventCommentDefinition.self) { + self = .moderationEventComment(value) + } else if let value = try? container.decode(ToolsOzoneLexicon.Moderation.EventReportDefinition.self) { + self = .moderationEventReport(value) + } else if let value = try? container.decode(ToolsOzoneLexicon.Moderation.EventLabelDefinition.self) { + self = .moderationEventLabel(value) + } else if let value = try? container.decode(ToolsOzoneLexicon.Moderation.EventAcknowledgeDefinition.self) { + self = .moderationEventAcknowledge(value) + } else if let value = try? container.decode(ToolsOzoneLexicon.Moderation.EventEscalateDefinition.self) { + self = .moderationEventEscalate(value) + } else if let value = try? container.decode(ToolsOzoneLexicon.Moderation.EventMuteDefinition.self) { + self = .moderationEventMute(value) + } else if let value = try? container.decode(ToolsOzoneLexicon.Moderation.EventUnmuteDefinition.self) { + self = .moderationEventUnmute(value) + } else if let value = try? container.decode(ToolsOzoneLexicon.Moderation.EventMuteReporterDefinition.self) { + self = .moderationEventMuteReporter(value) + } else if let value = try? container.decode(ToolsOzoneLexicon.Moderation.EventUnmuteReporterDefinition.self) { + self = .moderationEventUnmuteReporter(value) + } else if let value = try? container.decode(ToolsOzoneLexicon.Moderation.EventEmailDefinition.self) { + self = .moderationEventEmail(value) + } else if let value = try? container.decode(ToolsOzoneLexicon.Moderation.EventResolveAppealDefinition.self) { + self = .moderationEventResolveAppeal(value) + } else if let value = try? container.decode(ToolsOzoneLexicon.Moderation.EventDivertDefinition.self) { + self = .moderationEventDivert(value) + } else { + throw DecodingError.typeMismatch( + EmitEventUnion.self, DecodingError.Context( + codingPath: decoder.codingPath, debugDescription: "Unknown EmitEventUnion type")) + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + + switch self { + case .moderationEventTakedown(let moderationEventTakedown): + try container.encode(moderationEventTakedown) + case .moderationEventReverseTakedown(let moderationEventReverseTakedown): + try container.encode(moderationEventReverseTakedown) + case .moderationEventComment(let moderationEventComment): + try container.encode(moderationEventComment) + case .moderationEventReport(let moderationEventReport): + try container.encode(moderationEventReport) + case .moderationEventLabel(let moderationEventLabel): + try container.encode(moderationEventLabel) + case .moderationEventAcknowledge(let moderationEventAcknowledge): + try container.encode(moderationEventAcknowledge) + case .moderationEventEscalate(let moderationEventEscalate): + try container.encode(moderationEventEscalate) + case .moderationEventMute(let moderationEventMute): + try container.encode(moderationEventMute) + case .moderationEventUnmute(let moderationEventUnmute): + try container.encode(moderationEventUnmute) + case .moderationEventMuteReporter(let moderationEventMuteReporter): + try container.encode(moderationEventMuteReporter) + case .moderationEventUnmuteReporter(let moderationEventUnmuteReporter): + try container.encode(moderationEventUnmuteReporter) + case .moderationEventEmail(let moderationEventEmail): + try container.encode(moderationEventEmail) + case .moderationEventResolveAppeal(let moderationEventResolveAppeal): + try container.encode(moderationEventResolveAppeal) + case .moderationEventDivert(let moderationEventDivert): + try container.encode(moderationEventDivert) + } + } + } + + /// A reference containing the list of repository references. + public enum EmitEventSubjectUnion: Codable { + + /// A repository reference. + case repositoryReference(ComAtprotoLexicon.Admin.RepositoryReferenceDefinition) + + /// A strong reference. + case strongReference(ComAtprotoLexicon.Repository.StrongReference) + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + + if let value = try? container.decode(ComAtprotoLexicon.Admin.RepositoryReferenceDefinition.self) { + self = .repositoryReference(value) + } else if let value = try? container.decode(ComAtprotoLexicon.Repository.StrongReference.self) { + self = .strongReference(value) + } else { + throw DecodingError.typeMismatch( + EmitEventSubjectUnion.self, DecodingError.Context( + codingPath: decoder.codingPath, debugDescription: "Unknown EmitEventSubjectUnion type")) + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + + switch self { + case .repositoryReference(let repositoryReference): + try container.encode(repositoryReference) + case .strongReference(let strongReference): + try container.encode(strongReference) + } + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/Lexicons.swift b/Sources/ATProtoKit/Models/Lexicons/Lexicons.swift new file mode 100644 index 0000000000..edb3467f9c --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/Lexicons.swift @@ -0,0 +1,20 @@ +// +// Lexicons.swift +// +// +// Created by Christopher Jr Riley on 2024-05-16. +// + +import Foundation + +/// A group of lexicons within the `app.bsky` namespace. +public struct AppBskyLexicon {} + +/// A group of lexicons within the `com.atproto` namespace. +public struct ComAtprotoLexicon {} + +/// A group of lexicons within the `chat.bsky` namespace. +public struct ChatBskyLexicon {} + +/// A group of lexicons within the `tools.ozone` namespace. +public struct ToolsOzoneLexicon {} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/AppBskyActorDefs.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/AppBskyActorDefs.swift new file mode 100644 index 0000000000..09fc0f24ff --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/AppBskyActorDefs.swift @@ -0,0 +1,935 @@ +// +// AppBskyActorDefs.swift +// +// +// Created by Christopher Jr Riley on 2024-05-16. +// + +import Foundation + +extension AppBskyLexicon.Actor { + + /// A definition model for a basic profile view. + /// + /// - SeeAlso: This is based on the [`app.bsky.actor.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/actor/defs.json + public struct ProfileViewBasicDefinition: Codable { + + /// The decentralized identifier (DID) of the user. + public let actorDID: String + + /// The unique handle of the user. + public let actorHandle: String + + /// The display name of the user. Optional. + /// + /// - Important: Current maximum length is 64 characters. + public let displayName: String? + + /// The avatar image URL of the user's profile. Optional. + public let avatarImageURL: URL? + + /// The associated profile view. Optional. + public let associated: ProfileAssociatedDefinition? + + /// The list of metadata relating to the requesting account's relationship with the subject + /// account. Optional. + public let viewer: ViewerStateDefinition? + + /// An array of labels created by the user. Optional. + public let labels: [ComAtprotoLexicon.Label.LabelDefinition]? + + public init(actorDID: String, actorHandle: String, displayName: String?, avatarImageURL: URL?, associated: ProfileAssociatedDefinition?, + viewer: ViewerStateDefinition?, labels: [ComAtprotoLexicon.Label.LabelDefinition]?) { + self.actorDID = actorDID + self.actorHandle = actorHandle + self.displayName = displayName + self.avatarImageURL = avatarImageURL + self.associated = associated + self.viewer = viewer + self.labels = labels + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.actorDID = try container.decode(String.self, forKey: .actorDID) + self.actorHandle = try container.decode(String.self, forKey: .actorHandle) + self.displayName = try container.decodeIfPresent(String.self, forKey: .displayName) + self.avatarImageURL = try container.decodeIfPresent(URL.self, forKey: .avatarImageURL) + self.associated = try container.decodeIfPresent(ProfileAssociatedDefinition.self, forKey: .associated) + self.viewer = try container.decodeIfPresent(ViewerStateDefinition.self, forKey: .viewer) + self.labels = try container.decodeIfPresent([ComAtprotoLexicon.Label.LabelDefinition].self, forKey: .labels) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.actorDID, forKey: .actorDID) + try container.encode(self.actorHandle, forKey: .actorHandle) + + // Truncate `displayName` to 640 characters before encoding + // `maxGraphemes`'s limit is 64, but `String.count` should respect that limit implictly + try truncatedEncodeIfPresent(self.displayName, withContainer: &container, forKey: .displayName, upToLength: 640) + try container.encodeIfPresent(self.avatarImageURL, forKey: .avatarImageURL) + try container.encodeIfPresent(self.associated, forKey: .associated) + try container.encodeIfPresent(self.viewer, forKey: .viewer) + try container.encodeIfPresent(self.labels, forKey: .labels) + } + + enum CodingKeys: String, CodingKey { + case actorDID = "did" + case actorHandle = "handle" + case displayName + case avatarImageURL = "avatar" + case associated + case viewer + case labels + } + } + + /// A definition model for a profile view. + /// + /// - SeeAlso: This is based on the [`app.bsky.actor.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/actor/defs.json + public struct ProfileViewDefinition: Codable { + + /// The decentralized identifier (DID) of the user. + public let actorDID: String + + /// The unique handle of the user. + public let actorHandle: String + + /// The display name of the user's profile. Optional. + /// + /// - Important: Current maximum length is 64 characters. + public var displayName: String? + + /// The description of the user's profile. Optional. + /// + /// - Important: Current maximum length is 256 characters. + public var description: String? + + /// The avatar image URL of a user's profile. Optional. + public let avatarImageURL: URL? + + /// The associated profile view. Optional. + public var associated: ProfileAssociatedDefinition? + + /// The date the profile was last indexed. Optional. + @DateFormattingOptional public var indexedAt: Date? + + /// The list of metadata relating to the requesting account's relationship with the subject + /// account. Optional. + public var viewer: ViewerStateDefinition? + + /// An array of labels created by the user. Optional. + public var labels: [ComAtprotoLexicon.Label.LabelDefinition]? + + public init(actorDID: String, actorHandle: String, displayName: String?, description: String?, avatarImageURL: URL?, + associated: ProfileAssociatedDefinition?, indexedAt: Date?, viewer: ViewerStateDefinition?, + labels: [ComAtprotoLexicon.Label.LabelDefinition]?) { + self.actorDID = actorDID + self.actorHandle = actorHandle + self.displayName = displayName + self.description = description + self.avatarImageURL = avatarImageURL + self.associated = associated + self._indexedAt = DateFormattingOptional(wrappedValue: indexedAt) + self.viewer = viewer + self.labels = labels + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.actorDID = try container.decode(String.self, forKey: .actorDID) + self.actorHandle = try container.decode(String.self, forKey: .actorHandle) + self.displayName = try container.decodeIfPresent(String.self, forKey: .displayName) + self.description = try container.decodeIfPresent(String.self, forKey: .description) + self.avatarImageURL = try container.decodeIfPresent(URL.self, forKey: .avatarImageURL) + self.associated = try container.decodeIfPresent(ProfileAssociatedDefinition.self, forKey: .associated) + self.indexedAt = try container.decodeIfPresent(DateFormattingOptional.self, forKey: .indexedAt)?.wrappedValue + self.viewer = try container.decodeIfPresent(ViewerStateDefinition.self, forKey: .viewer) + self.labels = try container.decodeIfPresent([ComAtprotoLexicon.Label.LabelDefinition].self, forKey: .labels) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.actorDID, forKey: .actorDID) + try container.encode(self.actorHandle, forKey: .actorHandle) + + // Truncate `displayName` to 640 characters before encoding + // `maxGraphemes`'s limit is 64, but `String.count` should respect that limit implictly + try truncatedEncodeIfPresent(self.displayName, withContainer: &container, forKey: .displayName, upToLength: 640) + + // Truncate `description` to 2560 characters before encoding + // `maxGraphemes`'s limit is 256, but `String.count` should respect that limit + try truncatedEncodeIfPresent(self.description, withContainer: &container, forKey: .description, upToLength: 2560) + try container.encodeIfPresent(self.avatarImageURL, forKey: .avatarImageURL) + try container.encodeIfPresent(self.associated, forKey: .associated) + try container.encodeIfPresent(self._indexedAt, forKey: .indexedAt) + try container.encodeIfPresent(self.viewer, forKey: .viewer) + try container.encodeIfPresent(self.labels, forKey: .labels) + } + + enum CodingKeys: String, CodingKey { + case actorDID = "did" + case actorHandle = "handle" + case displayName + case description + case avatarImageURL = "avatar" + case associated + case indexedAt + case viewer + case labels + } + } + + /// A definition model for a detailed profile view. + /// + /// - SeeAlso: This is based on the [`app.bsky.actor.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/actor/defs.json + public struct ProfileViewDetailedDefinition: Codable { + + /// The decentralized identifier (DID) of the user. + public let actorDID: String + + /// The unique handle of the user. + public let actorHandle: String + + /// The display name of the user's profile. Optional. + /// + /// - Important: Current maximum length is 64 characters. + public var displayName: String? + + /// The description of the user's profile. Optional. + /// + /// - Important: Current maximum length is 256 characters. + public var description: String? + + /// The avatar image URL of a user's profile. Optional. + public var avatarImageURL: URL? + + /// The banner image URL of a user's profile. Optional. + public var bannerImageURL: URL? + + /// The number of followers a user has. Optional. + public var followerCount: Int? + + /// The number of accounts the user follows. Optional. + public var followCount: Int? + + /// The number of posts the user has. Optional. + public var postCount: Int? + + /// The associated profile view. Optional. + public let associated: ProfileAssociatedDefinition? + + /// The date the profile was last indexed. Optional. + @DateFormattingOptional public var indexedAt: Date? + + /// The list of metadata relating to the requesting account's relationship with the subject + /// account. Optional. + public var viewer: ViewerStateDefinition? + + /// An array of labels created by the user. Optional. + public var labels: [ComAtprotoLexicon.Label.LabelDefinition]? + + public init(actorDID: String, actorHandle: String, displayName: String?, description: String?, avatarImageURL: URL?, bannerImageURL: URL?, + followerCount: Int?, followCount: Int?, postCount: Int?, associated: ProfileAssociatedDefinition?, indexedAt: Date?, + viewer: ViewerStateDefinition?, labels: [ComAtprotoLexicon.Label.LabelDefinition]?) { + self.actorDID = actorDID + self.actorHandle = actorHandle + self.displayName = displayName + self.description = description + self.avatarImageURL = avatarImageURL + self.bannerImageURL = bannerImageURL + self.followerCount = followerCount + self.followCount = followCount + self.postCount = postCount + self.associated = associated + self._indexedAt = DateFormattingOptional(wrappedValue: indexedAt) + self.viewer = viewer + self.labels = labels + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.actorDID = try container.decode(String.self, forKey: .actorDID) + self.actorHandle = try container.decode(String.self, forKey: .actorHandle) + self.displayName = try container.decodeIfPresent(String.self, forKey: .displayName) + self.description = try container.decodeIfPresent(String.self, forKey: .description) + self.avatarImageURL = try container.decodeIfPresent(URL.self, forKey: .avatarImageURL) + self.bannerImageURL = try container.decodeIfPresent(URL.self, forKey: .bannerImageURL) + self.followerCount = try container.decodeIfPresent(Int.self, forKey: .followerCount) + self.followCount = try container.decodeIfPresent(Int.self, forKey: .followCount) + self.postCount = try container.decodeIfPresent(Int.self, forKey: .postCount) + self.associated = try container.decodeIfPresent(ProfileAssociatedDefinition.self, forKey: .associated) + self.indexedAt = try container.decodeIfPresent(DateFormattingOptional.self, forKey: .indexedAt)?.wrappedValue + self.viewer = try container.decodeIfPresent(ViewerStateDefinition.self, forKey: .viewer) + self.labels = try container.decodeIfPresent([ComAtprotoLexicon.Label.LabelDefinition].self, forKey: .labels) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.actorDID, forKey: .actorDID) + try container.encode(self.actorHandle, forKey: .actorHandle) + + // Truncate `displayName` to 640 characters before encoding + // `maxGraphemes`'s limit is 64, but `String.count` should respect that limit implictly + try truncatedEncodeIfPresent(self.displayName, withContainer: &container, forKey: .displayName, upToLength: 640) + + // Truncate `description` to 2560 characters before decoding + // `maxGraphemes`'s limit is 256, but `String.count` should respect that limit + try truncatedEncodeIfPresent(self.description, withContainer: &container, forKey: .description, upToLength: 2560) + try container.encodeIfPresent(self.avatarImageURL, forKey: .avatarImageURL) + try container.encodeIfPresent(self.bannerImageURL, forKey: .bannerImageURL) + try container.encodeIfPresent(self.followerCount, forKey: .followerCount) + try container.encodeIfPresent(self.followCount, forKey: .followCount) + try container.encodeIfPresent(self.postCount, forKey: .postCount) + try container.encodeIfPresent(self.associated, forKey: .associated) + try container.encodeIfPresent(self._indexedAt, forKey: .indexedAt) + try container.encodeIfPresent(self.viewer, forKey: .viewer) + try container.encodeIfPresent(self.labels, forKey: .labels) + } + + enum CodingKeys: String, CodingKey { + case actorDID = "did" + case actorHandle = "handle" + case displayName + case description + case avatarImageURL = "avatar" + case bannerImageURL = "banner" + case followerCount = "followersCount" + case followCount = "followsCount" + case postCount = "postsCount" + case associated + case indexedAt + case viewer + case labels + } + } + + /// A definition model for an actor's associated profile. + /// + /// - SeeAlso: This is based on the [`app.bsky.actor.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/actor/defs.json + public struct ProfileAssociatedDefinition: Codable { + + /// The number of lists associated with the user. Optional. + public let lists: Int? + + /// The number of feed generators associated with the user. Optional. + public let feedGenerators: Int? + + /// Indicates whether the user account is a labeler. Optional. + public let isActorLabeler: Bool? + + enum CodingKeys: String, CodingKey { + case lists + case feedGenerators = "feedgens" + case isActorLabeler = "labeler" + } + } + + /// A definition model for an actor viewer state. + /// + /// - Note: From the AT Protocol specification: "Metadata about the requesting account's + /// relationship with the subject account. Only has meaningful content for authed requests." + /// + /// - SeeAlso: This is based on the [`app.bsky.actor.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/actor/defs.json + public struct ViewerStateDefinition: Codable { + + /// Indicates whether the requesting account has been muted by the subject + /// account. Optional. + public let isMuted: Bool? + + /// An array of lists that the subject account is muted by. + public let mutedByArray: AppBskyLexicon.Graph.ListViewBasicDefinition? + + /// Indicates whether the requesting account has been blocked by the subject + /// account. Optional. + public let isBlocked: Bool? + + /// A URI which indicates the user has blocked the requesting account. + public let blockingURI: String? + + /// An array of the subject account's lists. + public let blockingByArray: AppBskyLexicon.Graph.ListViewBasicDefinition? + + /// A URI which indicates the user is following the requesting account. + public let followingURI: String? + + /// A URI which indicates the user is being followed by the requesting account. + public let followedByURI: String? + + enum CodingKeys: String, CodingKey { + case isMuted = "muted" + case mutedByArray = "mutedByList" + case isBlocked = "blockedBy" + case blockingURI = "blocking" + case blockingByArray = "blockingByList" + case followingURI = "following" + case followedByURI = "followedBy" + } + } + + /// A definition model for preferences. + /// + /// - SeeAlso: This is based on the [`app.bsky.actor.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/actor/defs.json + public struct PreferencesDefinition: Codable { + + /// An array of different preferences the user can set. + public let preferences: [ATUnion.ActorPreferenceUnion] + + public init(preferences: [ATUnion.ActorPreferenceUnion]) { + self.preferences = preferences + } + } + + /// A definition model for an "Adult Content" preference. + /// + /// - SeeAlso: This is based on the [`app.bsky.actor.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/actor/defs.json + public struct AdultContentPreferencesDefinition: Codable { + + /// The identifier of the lexicon. + /// + /// - Warning: The value must not change. + public let type: String = "app.bsky.actor.defs#adultContentPref" + + /// Indicates whether the user will be able to see adult content in their feed. Set to + /// `false` by default. + public var isAdultContentEnabled: Bool = false + + public init(isAdultContentEnabled: Bool) { + self.isAdultContentEnabled = isAdultContentEnabled + } + + enum CodingKeys: String, CodingKey { + case type = "$type" + case isAdultContentEnabled = "enabled" + } + } + + /// A definition model for a "Content Label" preference. + /// + /// - SeeAlso: This is based on the [`app.bsky.actor.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/actor/defs.json + public struct ContentLabelPreferencesDefinition: Codable { + + /// The identifier of the lexicon. + /// + /// - Warning: The value must not change. + public let type: String = "app.bsky.actor.defs#contentLabelPref" + + /// The decentralized identifier of the labeler that this preference applies to. + /// + /// - Note: If this field is empty, then the preferences apply to all labels. + /// + /// - Note: According to the AT Protocol specifications: "Which labeler does this + /// preference apply to? If undefined, applies globally." + public let labelerDID: String? + + /// The name of the content label. + public let label: String + + /// Indicates the visibility of the label's content. + public let visibility: Visibility + + public init(labelerDID: String?, label: String, visibility: Visibility) { + self.labelerDID = labelerDID + self.label = label + self.visibility = visibility + } + + /// Determines how visible a label's content is. + public enum Visibility: String, Codable { + + /// Indicates the content can be ignored. + case ignore = "ignore" + + /// Indicates the content can be seen without restriction. + case show = "show" + + /// Indicates the content can be seen, but will ask if the user wants to view it. + case warn = "warn" + + /// Indicates the content is fully invisible by the user. + case hide = "hide" + } + + enum CodingKeys: String, CodingKey { + case type = "$type" + case labelerDID = "labelerDid" + case label + case visibility + } + } + + /// A definition model for a saved feed. + /// + /// - SeeAlso: This is based on the [`app.bsky.actor.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/actor/defs.json + public struct SavedFeed: Codable { + + /// The ID for the saved feed. + public let feedID: String + + /// The type of feed generator is. + /// + /// This is usually referring to the location of the feed in context to the + /// user account's choice of placement within Bluesky. + public let type: FeedType + + /// The value of the saved feed generator. + public let value: String + + /// Indicated whether the saved feed generator is pinned. + public let isPinned: Bool + + /// The type of feed generator. + /// + /// This is usually referring to the location of the feed in context to the + /// user account's choice of placement within Bluesky. + public enum FeedType: String, Codable { + + /// Indicates the feed generator resides only in the "Feeds" section of Bluesky. + case feed + + /// Indicates the feed generator additionally resides in a list. + case list + + /// Indicates the feed generator additionally resides within the + /// user account's timeline. + case timeline + } + + enum CodingKeys: String, CodingKey { + case feedID = "id" + case type + case value + case isPinned = "pinned" + } + } + + /// A definition model for version 2 of a "Saved Feeds" preference. + /// + /// - SeeAlso: This is based on the [`app.bsky.actor.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/actor/defs.json + public struct SavedFeedPreferencesVersion2Definition: Codable { + + /// An array of saved feed generators. + public let items: SavedFeed + } + + /// A definition model for a "Saved Feeds" preference. + /// + /// - SeeAlso: This is based on the [`app.bsky.actor.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/actor/defs.json + public struct SavedFeedsPreferencesDefinition: Codable { + + /// The identifier of the lexicon. + /// + /// - Warning: The value must not change. + public let type: String = "app.bsky.actor.defs#savedFeedsPref" + + /// An array of feed URIs that have been saved and pinned. + public let pinned: [String] + + /// An array of feed URIs that have been saved. + public let saved: [String] + + // TODO: Find out more about what this does. + /// The index number of the timeline for the list of feeds. Optional. + public var timelineIndex: Int? + + public init(pinned: [String], saved: [String], timelineIndex: Int?) { + self.pinned = pinned + self.saved = saved + self.timelineIndex = timelineIndex + } + + enum CodingKeys: String, CodingKey { + case type = "$type" + case pinned + case saved + case timelineIndex + } + } + + /// A definition model for a "Personal Details" preference. + /// + /// - SeeAlso: This is based on the [`app.bsky.actor.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/actor/defs.json + public struct PersonalDetailsPreferencesDefinition: Codable { + + /// The identifier of the lexicon. + /// + /// - Warning: The value must not change. + public let type: String = "app.bsky.actor.defs#personalDetailsPref" + + /// The birth date of the user. Optional. + /// + /// - Note: From the AT Protocol specification: "The birth date of account owner." + @DateFormattingOptional public var birthDate: Date? + + public init(birthDate: Date) { + self._birthDate = DateFormattingOptional(wrappedValue: birthDate) + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.birthDate = try container.decodeIfPresent(DateFormattingOptional.self, forKey: .birthDate)?.wrappedValue + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encodeIfPresent(self._birthDate, forKey: .birthDate) + } + + enum CodingKeys: String, CodingKey { + case type = "$type" + case birthDate + } + } + + /// A definition model for a "Feed View" preference. + /// + /// - SeeAlso: This is based on the [`app.bsky.actor.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/actor/defs.json + public struct FeedViewPreferencesDefinition: Codable { + + /// The identifier of the lexicon. + /// + /// - Warning: The value must not change. + public let type: String = "app.bsky.actor.defs#feedViewPref" + + /// The feed's identifier (typically the URI). + /// + /// - Note:From the AT Protocol specification: "The URI of the feed, or an identifier + /// which describes the feed." + public let feedURI: String + + /// Indicates whether the replies are hidden from the user. Optional. + /// + /// - Note: From the AT Protocol specification: "Hide replies in the feed." + public let areRepliesHidden: Bool? + + /// Indicates whether replies from users you don't follow are hidden from the user. Optional. + /// + /// - Note: From the AT Protocol specification: "Hide replies in the feed if they are not + /// by followed users." + public let areUnfollowedRepliesHidden: Bool? + + /// Indicates how many likes a post needs in order for the user to see the + /// reply. Optional. + /// + /// - Note: From the AT Protocol specification: "Hide replies in the feed if they do not + /// have this number of likes." + public let hideRepliesByLikeCount: Int? + + /// Indicates whether reposts are hidden from the user. Optional. + /// + /// - Note: From the AT Protocol specification: "Hide reposts in the feed." + public let areRepostsHidden: Bool? + + /// Indicates whether quote posts are hidden from the user. Optional. + /// + /// - Note: From the AT Protocol specification: "Hide quote posts in the feed." + public let areQuotePostsHidden: Bool? + + enum CodingKeys: String, CodingKey { + case type = "$type" + case feedURI = "feed" + case areRepliesHidden = "hideReplies" + case areUnfollowedRepliesHidden = "hideRepliesByUnfollowed" + case hideRepliesByLikeCount + case areRepostsHidden = "hideReposts" + case areQuotePostsHidden = "hideQuotePosts" + } + } + + /// A definition model for a "Thread View" preference. + /// + /// - SeeAlso: This is based on the [`app.bsky.actor.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/actor/defs.json + public struct ThreadViewPreferencesDefinition: Codable { + + /// The identifier of the lexicon. + /// + /// - Warning: The value must not change. + public let type: String = "app.bsky.actor.defs#threadViewPref" + + /// The sorting mode of a thread. Optional. + /// + /// - Note: From the AT Protocol specification: "Sorting mode for threads." + public let sortingMode: SortingMode? + + /// Indicates whether users you follow are prioritized over other users. Optional. + /// + /// - Note: From the AT Protocol specification: "Show followed users at the top of + /// all replies." + public let areFollowedUsersPrioritized: Bool? + + /// The sorting mode for a thread. + public enum SortingMode: String, Codable { + + /// Indicates the thread will be sorted from the oldest post. + case oldest = "oldest" + + /// Indicates the thread will be sorted from the newest post. + case newest = "newest" + + /// Indicates the thread will be sorted from the posts with the most number + /// of likes. + case mostLikes = "most-likes" + + /// Indicates the thread will be completely random. + case random = "random" + } + + enum CodingKeys: String, CodingKey { + case type = "$type" + case sortingMode = "sort" + case areFollowedUsersPrioritized = "prioritizeFollowedUsers" + } + } + + /// A definition model for an "Interest View" preference. + /// + /// - SeeAlso: This is based on the [`app.bsky.actor.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/actor/defs.json + public struct InterestViewPreferencesDefinition: Codable { + + /// The identifier of the lexicon. + /// + /// - Warning: The value must not change. + public let type: String = "app.bsky.actor.defs#interestsPref" + + /// An array of interest tags. + /// + /// - Note: According to AT Protocol's specifications: "A list of tags which describe the + /// account owner's interests gathered during onboarding." + /// + /// - Important: Current maximum limit is 100 tags. Current maximum length for each tag + /// name is 64 characters. + public let tags: [String] + + public init(tags: [String]) { + self.tags = tags + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.tags = try container.decode([String].self, forKey: .tags) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + // Truncate `tags` to 640 characters before encoding. + // `maxGraphemes`'s limit is 64, but `String.count` should respect that limit implictly. + // Then, truncate `tags` to 100 items before encoding. + try truncatedEncode( + self.tags.map { $0.truncated(toLength: 640) }, + withContainer: &container, forKey: .tags, upToLength: 100) + } + + enum CodingKeys: String, CodingKey { + case type = "$type" + case tags + } + } + + /// A definition model for the muted word's target. + /// + /// - SeeAlso: This is based on the [`app.bsky.actor.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/actor/defs.json + public enum MutedWordTarget: Codable { + + /// Indicates the muted word is within the content itself. + case content + + /// Indicates the muted word is a tag. + case tag + + /// Indicates the muted word is located at an unknown area. + /// + /// This case shouldn't be used. If it does appear, then Bluesky may have updated + /// something that ATProtoKit doesn't yet recognize. + case other(String) + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + + let value = try container.decode(String.self) + + switch value { + case "content": + self = .content + case "tag": + self = .tag + default: + self = .other(value) + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .content: + try container.encode("content") + case .tag: + try container.encode("tag") + case .other(let other): + // Truncate `other` to 640 characters before decoding + // `maxGraphemes`'s limit is 64, but `String.count` should respect that limit + let truncatedOther = other.truncated(toLength: 640) + try container.encode(truncatedOther) + } + } + } + + /// A definition model for a muted word. + /// + /// - Note: According to the AT Protocol specifications: "A word that the account owner + /// has muted." + /// + /// - SeeAlso: This is based on the [`app.bsky.actor.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/actor/defs.json + public struct MutedWord: Codable { + + /// The word to mute. + public let value: String + + /// An array of intended targets for the muted word. + public let targets: [MutedWordTarget] + + public init(value: String, targets: [MutedWordTarget]) { + self.value = value + self.targets = targets + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.value = try container.decode(String.self, forKey: .value) + self.targets = try container.decode([MutedWordTarget].self, forKey: .targets) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + // Truncate `value` to 1000 characters before decoding + // `maxGraphemes`'s limit is 100, but `String.count` should respect that limit + try truncatedEncode(self.value, withContainer: &container, forKey: .value, upToLength: 1000) + try container.encode(self.targets, forKey: .targets) + } + + enum CodingKeys: CodingKey { + case value + case targets + } + } + + /// A definition model for a "Muted Words" preference. + /// + /// - SeeAlso: This is based on the [`app.bsky.actor.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/actor/defs.json + public struct MutedWordsPreferencesDefinition: Codable { + + /// The identifier of the lexicon. + /// + /// - Warning: The value must not change. + public let type: String = "app.bsky.actor.defs#mutedWordsPref" + + /// An array of items the user has muted. + /// + /// - Note: According to the AT Protocol specifications: "A list of words the account + /// owner has muted." + public let mutedItems: [MutedWord] + + enum CodingKeys: String, CodingKey { + case type = "$type" + case mutedItems = "items" + } + } + + /// A definition model for a "Hidden Posts" preference. + /// + /// - SeeAlso: This is based on the [`app.bsky.actor.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/actor/defs.json + public struct HiddenPostsPreferencesDefinition: Codable { + + /// The identifier of the lexicon. + /// + /// - Warning: The value must not change. + public let type: String = "app.bsky.actor.defs#hiddenPostsPref" + + /// An array of URIs related to posts that the user wants to hide. + /// + /// - Note: According to the AT Protocol specifications: "A list of URIs of posts the + /// account owner has hidden." + public let items: [String] + + enum CodingKeys: String, CodingKey { + case type = "$type" + case items + } + } + + /// A definition model for a "Labelers" preference. + /// + /// - SeeAlso: This is based on the [`app.bsky.actor.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/actor/defs.json + public struct LabelersPreferencesDefinition: Codable { + + /// An array of labeler items. + public let labelers: [String] + } + + /// A definition model for a labeler item. + /// + /// - SeeAlso: This is based on the [`app.bsky.actor.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/actor/defs.json + public struct LabelersPreferenceItem: Codable { + + /// The decentralized identifier (DID) of the labeler. + public let labelerDID: String + + enum CodingKeys: String, CodingKey { + case labelerDID = "did" + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/AppBskyActorGetPreferences.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/AppBskyActorGetPreferences.swift new file mode 100644 index 0000000000..53765efd14 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/AppBskyActorGetPreferences.swift @@ -0,0 +1,26 @@ +// +// AppBskyActorGetPreferences.swift +// +// +// Created by Christopher Jr Riley on 2024-05-17. +// + +import Foundation + +extension AppBskyLexicon.Actor { + + /// An output data model definition for the output of getting preferences. + /// + /// - Note: According to the AT Protocol specifications: "Get private preferences attached to + /// the current account. Expected use is synchronization between multiple devices, and + /// import/export during account migration. Requires auth." + /// + /// - SeeAlso: This is based on the [`app.bsky.actor.getPreferences`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/actor/getPreferences.json + public struct GetPreferencesOutput: Codable { + + /// The list of preferences in the user's account. + public let preference: PreferencesDefinition + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/AppBskyActorGetProfile.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/AppBskyActorGetProfile.swift new file mode 100644 index 0000000000..0897d1fe5e --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/AppBskyActorGetProfile.swift @@ -0,0 +1,25 @@ +// +// AppBskyActorGetProfile.swift +// +// +// Created by Christopher Jr Riley on 2024-05-17. +// + +import Foundation + +extension AppBskyLexicon.Actor { + + /// A data model definition for the output for a detailed profile view for the user. + /// + /// - Note: According to the AT Protocol specifications: "Get detailed profile view of + /// an actor. Does not require auth, but contains relevant metadata with auth." + /// + /// - SeeAlso: This is based on the [`app.bsky.actor.getProfile`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/actor/getProfile.json + public struct GetProfileOutput: Codable { + + /// A detailed profile view of the user. + public let actorProfileView: ProfileViewDetailedDefinition + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/AppBskyActorGetProfiles.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/AppBskyActorGetProfiles.swift new file mode 100644 index 0000000000..ffcbd522fa --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/AppBskyActorGetProfiles.swift @@ -0,0 +1,25 @@ +// +// AppBskyActorGetProfiles.swift +// +// +// Created by Christopher Jr Riley on 2024-05-17. +// + +import Foundation + +extension AppBskyLexicon.Actor { + + /// A data model definition for the output of detailed profile views for multiple users. + /// + /// - Note: According to the AT Protocol specifications: "Get detailed profile views of + /// multiple actors." + /// + /// - SeeAlso: This is based on the [`app.bsky.actor.getProfiles`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/actor/getProfiles.json + public struct GetProfilesOutput: Codable { + + /// An array of detailed profile views for several users. + public let profiles: [ProfileViewDetailedDefinition] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/AppBskyActorGetSuggestions.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/AppBskyActorGetSuggestions.swift new file mode 100644 index 0000000000..30ba735bca --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/AppBskyActorGetSuggestions.swift @@ -0,0 +1,28 @@ +// +// AppBskyActorGetSuggestions.swift +// +// +// Created by Christopher Jr Riley on 2024-05-17. +// + +import Foundation + +extension AppBskyLexicon.Actor { + + /// A data model for the output of the list of suggested users to follow. + /// + /// - Note: According to the AT Protocol specifications: "Get a list of suggested actors. + /// Expected use is discovery of accounts to follow during new account onboarding." + /// + /// - SeeAlso: This is based on the [`app.bsky.actor.getSuggestions`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/actor/getSuggestions.json + public struct GetSuggestionsOutput: Codable { + + /// The mark used to indicate the starting point for the next set of results. Optional. + public let cursor: String? + + /// An array of actors. + public let actors: [ProfileViewDefinition] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/AppBskyActorProfile.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/AppBskyActorProfile.swift new file mode 100644 index 0000000000..75f671e982 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/AppBskyActorProfile.swift @@ -0,0 +1,58 @@ +// +// AppBskyActorProfile.swift +// +// +// Created by Christopher Jr Riley on 2024-05-17. +// + +import Foundation + +extension AppBskyLexicon.Actor { + + /// The main data model definition for an actor. + /// + /// - Note: According to the AT Protocol specifications: "A declaration of a Bluesky + /// account profile." + /// + /// - SeeAlso: This is based on the [`app.bsky.actor.profile`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/actor/profile.json + public struct ProfileRecord: ATRecordProtocol { + + /// The identifier of the lexicon. + /// + /// - Warning: The value must not change. + public static private(set) var type: String = "app.bsky.actor.profile" + + /// The display name of the profile. Optional. + public let displayName: String? + + /// The description of the profile. Optional. + /// + /// - Note: According to the AT Protocol specifications: "Free-form profile + /// description text." + public let description: String? + + /// The avatar image URL of the profile. Optional. + /// + /// - Note: According to the AT Protocol specifications: "Small image to be displayed next + /// to posts from account. AKA, 'profile picture'" + /// + /// - Note: Only JPEGs and PNGs are accepted. + public let avatarBlob: ComAtprotoLexicon.Repository.BlobContainer? + + /// The banner image URL of the profile. Optional. + /// + /// - Note: According to the AT Protocol specifications: "Larger horizontal image to + /// display behind profile view." + /// + /// - Note: Only JPEGs and PNGs are accepted. + public let bannerBlob: ComAtprotoLexicon.Repository.BlobContainer? + + /// An array of user-defined labels. Optional. + /// + /// - Note: According to the AT Protocol specifications: "Self-label values, specific to + /// the Bluesky application, on the overall account." + public let labels: [ComAtprotoLexicon.Label.SelfLabelsDefinition] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/AppBskyActorPutPreferences.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/AppBskyActorPutPreferences.swift new file mode 100644 index 0000000000..63af157e8d --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/AppBskyActorPutPreferences.swift @@ -0,0 +1,27 @@ +// +// AppBskyActorPutPreferences.swift +// +// +// Created by Christopher Jr Riley on 2024-05-17. +// + +import Foundation + +extension AppBskyLexicon.Actor { + + public struct PutPreferencesRequestBody: Codable { + + /// The identifier of the lexicon. + /// + /// - Warning: The value must not change. + public let type: String = "app.bsky.actor.putPreferences" + + /// A list of preferences by the user. + public let preferences: [ATUnion.ActorPreferenceUnion] + + enum CodingKeys: String, CodingKey { + case type = "$type" + case preferences + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/AppBskyActorSearchActors.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/AppBskyActorSearchActors.swift new file mode 100644 index 0000000000..5e9aeacccc --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/AppBskyActorSearchActors.swift @@ -0,0 +1,26 @@ +// +// AppBskyActorSearchActors.swift +// +// +// Created by Christopher Jr Riley on 2024-05-17. +// + +import Foundation + +extension AppBskyLexicon.Actor { + + /// A data model definition for the output of searching for actors matching the + /// search criteria. + /// + /// - SeeAlso: This is based on the [`app.bsky.actor.searchActors`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/actor/searchActors.json + public struct SearchActorsOutput: Codable { + + /// The mark used to indicate the starting point for the next set of results. Optional. + public let cursor: String + + /// An array of actors. + public let actors: [ProfileViewDefinition] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/AppBskyActorSearchActorsTypeahead.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/AppBskyActorSearchActorsTypeahead.swift new file mode 100644 index 0000000000..d733fd7f2b --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/AppBskyActorSearchActorsTypeahead.swift @@ -0,0 +1,23 @@ +// +// AppBskyActorSearchActorsTypeahead.swift +// +// +// Created by Christopher Jr Riley on 2024-05-17. +// + +import Foundation + +extension AppBskyLexicon.Actor { + + /// A data model definition for the output of searching for actors matching the prefixed + /// search criteria. + /// + /// - SeeAlso: This is based on the [`app.bsky.actor.searchActorsTypeahead`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/actor/searchActorsTypeahead.json + public struct SearchActorsTypeaheadOutput: Codable { + + /// An array of actors. + public let actors: [ProfileViewBasicDefinition] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/BskyActorDefs.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/BskyActorDefs.swift deleted file mode 100644 index 5760cf9843..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/BskyActorDefs.swift +++ /dev/null @@ -1,855 +0,0 @@ -// -// BskyActorDefs.swift -// -// -// Created by Christopher Jr Riley on 2024-01-25. -// -import Foundation - -/// A data model for a basic profile view definition. -/// -/// - SeeAlso: This is based on the [`app.bsky.actor.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/9579bec720d30e40c995d09772040212c261d6fb/lexicons/app/bsky/actor/defs.json -public struct ActorProfileViewBasic: Codable { - /// The decentralized identifier (DID) of the user. - public let actorDID: String - /// The unique handle of the user. - public let actorHandle: String - /// The display name of the user. Optional. - /// - /// - Important: Current maximum length is 64 characters. - public var displayName: String? = nil - /// The avatar image URL of the user's profile. Optional. - public var avatarImageURL: URL? = nil - /// The associated profile view. Optional. - public var associated: ActorProfileAssociated? - /// The list of metadata relating to the requesting account's relationship with the subject - /// account. Optional. - public var viewer: ActorViewerState? = nil - /// An array of labels created by the user. Optional. - public var labels: [Label]? = nil - - public init(actorDID: String, actorHandle: String, displayName: String?, avatarImageURL: URL?, associated: ActorProfileAssociated?, - viewer: ActorViewerState?, labels: [Label]?) { - self.actorDID = actorDID - self.actorHandle = actorHandle - self.displayName = displayName - self.avatarImageURL = avatarImageURL - self.associated = associated - self.viewer = viewer - self.labels = labels - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.actorDID = try container.decode(String.self, forKey: .actorDID) - self.actorHandle = try container.decode(String.self, forKey: .actorHandle) - self.displayName = try container.decodeIfPresent(String.self, forKey: .displayName) - self.avatarImageURL = try container.decodeIfPresent(URL.self, forKey: .avatarImageURL) - self.associated = try container.decodeIfPresent(ActorProfileAssociated.self, forKey: .associated) - self.viewer = try container.decodeIfPresent(ActorViewerState.self, forKey: .viewer) - self.labels = try container.decodeIfPresent([Label].self, forKey: .labels) - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - try container.encode(self.actorDID, forKey: .actorDID) - try container.encode(self.actorHandle, forKey: .actorHandle) - - // Truncate `displayName` to 640 characters before encoding - // `maxGraphemes`'s limit is 64, but `String.count` should respect that limit implictly - try truncatedEncodeIfPresent(self.displayName, withContainer: &container, forKey: .displayName, upToLength: 640) - try container.encodeIfPresent(self.avatarImageURL, forKey: .avatarImageURL) - try container.encodeIfPresent(self.associated, forKey: .associated) - try container.encodeIfPresent(self.viewer, forKey: .viewer) - try container.encodeIfPresent(self.labels, forKey: .labels) - } - - enum CodingKeys: String, CodingKey { - case actorDID = "did" - case actorHandle = "handle" - case displayName - case avatarImageURL = "avatar" - case associated - case viewer - case labels - } -} - -/// A data model for a profile view definition. -/// -/// - SeeAlso: This is based on the [`app.bsky.actor.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/9579bec720d30e40c995d09772040212c261d6fb/lexicons/app/bsky/actor/defs.json -public struct ActorProfileView: Codable { - /// The decentralized identifier (DID) of the user. - public let actorDID: String - /// The unique handle of the user. - public let actorHandle: String - /// The display name of the user's profile. Optional. - /// - /// - Important: Current maximum length is 64 characters. - public var displayName: String? = nil - /// The description of the user's profile. Optional. - /// - /// - Important: Current maximum length is 256 characters. - public var description: String? = nil - /// The avatar image URL of a user's profile. Optional. - public let avatarImageURL: URL? - /// The associated profile view. Optional. - public var associated: ActorProfileAssociated? - /// The date the profile was last indexed. Optional. - @DateFormattingOptional public var indexedAt: Date? = nil - /// The list of metadata relating to the requesting account's relationship with the subject - /// account. Optional. - public var viewer: ActorViewerState? = nil - /// An array of labels created by the user. Optional. - public var labels: [Label]? = nil - - public init(actorDID: String, actorHandle: String, displayName: String?, description: String?, avatarImageURL: URL?, associated: ActorProfileAssociated?, - indexedAt: Date?, viewer: ActorViewerState?, labels: [Label]?) { - self.actorDID = actorDID - self.actorHandle = actorHandle - self.displayName = displayName - self.description = description - self.avatarImageURL = avatarImageURL - self.associated = associated - self._indexedAt = DateFormattingOptional(wrappedValue: indexedAt) - self.viewer = viewer - self.labels = labels - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.actorDID = try container.decode(String.self, forKey: .actorDID) - self.actorHandle = try container.decode(String.self, forKey: .actorHandle) - self.displayName = try container.decodeIfPresent(String.self, forKey: .displayName) - self.description = try container.decodeIfPresent(String.self, forKey: .description) - self.avatarImageURL = try container.decodeIfPresent(URL.self, forKey: .avatarImageURL) - self.associated = try container.decodeIfPresent(ActorProfileAssociated.self, forKey: .associated) - self.indexedAt = try container.decodeIfPresent(DateFormattingOptional.self, forKey: .indexedAt)?.wrappedValue - self.viewer = try container.decodeIfPresent(ActorViewerState.self, forKey: .viewer) - self.labels = try container.decodeIfPresent([Label].self, forKey: .labels) - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - try container.encode(self.actorDID, forKey: .actorDID) - try container.encode(self.actorHandle, forKey: .actorHandle) - - // Truncate `displayName` to 640 characters before encoding - // `maxGraphemes`'s limit is 64, but `String.count` should respect that limit implictly - try truncatedEncodeIfPresent(self.displayName, withContainer: &container, forKey: .displayName, upToLength: 640) - - // Truncate `description` to 2560 characters before encoding - // `maxGraphemes`'s limit is 256, but `String.count` should respect that limit - try truncatedEncodeIfPresent(self.description, withContainer: &container, forKey: .description, upToLength: 2560) - try container.encodeIfPresent(self.avatarImageURL, forKey: .avatarImageURL) - try container.encodeIfPresent(self.associated, forKey: .associated) - try container.encodeIfPresent(self._indexedAt, forKey: .indexedAt) - try container.encodeIfPresent(self.viewer, forKey: .viewer) - try container.encodeIfPresent(self.labels, forKey: .labels) - } - - enum CodingKeys: String, CodingKey { - case actorDID = "did" - case actorHandle = "handle" - case displayName - case description - case avatarImageURL = "avatar" - case associated - case indexedAt - case viewer - case labels - } -} - -/// A data model for a detailed profile view definition. -/// -/// - SeeAlso: This is based on the [`app.bsky.actor.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/9579bec720d30e40c995d09772040212c261d6fb/lexicons/app/bsky/actor/defs.json -public struct ActorProfileViewDetailed: Codable { - /// The decentralized identifier (DID) of the user. - public let actorDID: String - /// The unique handle of the user. - public let actorHandle: String - /// The display name of the user's profile. Optional. - /// - /// - Important: Current maximum length is 64 characters. - public var displayName: String? = nil - /// The description of the user's profile. Optional. - /// - /// - Important: Current maximum length is 256 characters. - public var description: String? = nil - /// The avatar image URL of a user's profile. Optional. - public var avatarImageURL: URL? = nil - /// The banner image URL of a user's profile. Optional. - public var bannerImageURL: URL? = nil - /// The number of followers a user has. Optional. - public var followerCount: Int? = nil - /// The number of accounts the user follows. Optional. - public var followCount: Int? = nil - /// The number of posts the user has. Optional. - public var postCount: Int? = nil - /// The associated profile view. Optional. - public let associated: ActorProfileAssociated? - /// The date the profile was last indexed. Optional. - @DateFormattingOptional public var indexedAt: Date? = nil - /// The list of metadata relating to the requesting account's relationship with the subject - /// account. Optional. - public var viewer: ActorViewerState? = nil - /// An array of labels created by the user. Optional. - public var labels: [Label]? = nil - - public init(actorDID: String, actorHandle: String, displayName: String?, description: String?, avatarImageURL: URL?, bannerImageURL: URL?, - followerCount: Int?, followCount: Int?, postCount: Int?, associated: ActorProfileAssociated?, indexedAt: Date?, viewer: ActorViewerState?, labels: [Label]?) { - self.actorDID = actorDID - self.actorHandle = actorHandle - self.displayName = displayName - self.description = description - self.avatarImageURL = avatarImageURL - self.bannerImageURL = bannerImageURL - self.followerCount = followerCount - self.followCount = followCount - self.postCount = postCount - self.associated = associated - self._indexedAt = DateFormattingOptional(wrappedValue: indexedAt) - self.viewer = viewer - self.labels = labels - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.actorDID = try container.decode(String.self, forKey: .actorDID) - self.actorHandle = try container.decode(String.self, forKey: .actorHandle) - self.displayName = try container.decodeIfPresent(String.self, forKey: .displayName) - self.description = try container.decodeIfPresent(String.self, forKey: .description) - self.avatarImageURL = try container.decodeIfPresent(URL.self, forKey: .avatarImageURL) - self.bannerImageURL = try container.decodeIfPresent(URL.self, forKey: .bannerImageURL) - self.followerCount = try container.decodeIfPresent(Int.self, forKey: .followerCount) - self.followCount = try container.decodeIfPresent(Int.self, forKey: .followCount) - self.postCount = try container.decodeIfPresent(Int.self, forKey: .postCount) - self.associated = try container.decodeIfPresent(ActorProfileAssociated.self, forKey: .associated) - self.indexedAt = try container.decodeIfPresent(DateFormattingOptional.self, forKey: .indexedAt)?.wrappedValue - self.viewer = try container.decodeIfPresent(ActorViewerState.self, forKey: .viewer) - self.labels = try container.decodeIfPresent([Label].self, forKey: .labels) - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - try container.encode(self.actorDID, forKey: .actorDID) - try container.encode(self.actorHandle, forKey: .actorHandle) - - // Truncate `displayName` to 640 characters before encoding - // `maxGraphemes`'s limit is 64, but `String.count` should respect that limit implictly - try truncatedEncodeIfPresent(self.displayName, withContainer: &container, forKey: .displayName, upToLength: 640) - - // Truncate `description` to 2560 characters before decoding - // `maxGraphemes`'s limit is 256, but `String.count` should respect that limit - try truncatedEncodeIfPresent(self.description, withContainer: &container, forKey: .description, upToLength: 2560) - try container.encodeIfPresent(self.avatarImageURL, forKey: .avatarImageURL) - try container.encodeIfPresent(self.bannerImageURL, forKey: .bannerImageURL) - try container.encodeIfPresent(self.followerCount, forKey: .followerCount) - try container.encodeIfPresent(self.followCount, forKey: .followCount) - try container.encodeIfPresent(self.postCount, forKey: .postCount) - try container.encodeIfPresent(self.associated, forKey: .associated) - try container.encodeIfPresent(self._indexedAt, forKey: .indexedAt) - try container.encodeIfPresent(self.viewer, forKey: .viewer) - try container.encodeIfPresent(self.labels, forKey: .labels) - } - - enum CodingKeys: String, CodingKey { - case actorDID = "did" - case actorHandle = "handle" - case displayName - case description - case avatarImageURL = "avatar" - case bannerImageURL = "banner" - case followerCount = "followersCount" - case followCount = "followsCount" - case postCount = "postsCount" - case associated - case indexedAt - case viewer - case labels - } -} - -/// A data model definition for an actor's associated profile. -/// -/// - SeeAlso: This is based on the [`app.bsky.actor.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/9579bec720d30e40c995d09772040212c261d6fb/lexicons/app/bsky/actor/defs.json -public struct ActorProfileAssociated: Codable { - /// The number of lists associated with the user. Optional. - public let lists: Int? - /// The number of feed generators associated with the user. Optional. - public let feedGenerators: Int? - /// Indicates whether the user account is a labeler. Optional. - public let isActorLabeler: Bool? - - enum CodingKeys: String, CodingKey { - case lists - case feedGenerators = "feedgens" - case isActorLabeler = "labeler" - } -} - -/// A data model for an actor viewer state definition. -/// -/// - Note: From the AT Protocol specification: "Metadata about the requesting account's -/// relationship with the subject account. Only has meaningful content for authed requests." -/// -/// - SeeAlso: This is based on the [`app.bsky.actor.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/9579bec720d30e40c995d09772040212c261d6fb/lexicons/app/bsky/actor/defs.json -public struct ActorViewerState: Codable { - /// Indicates whether the requesting account has been muted by the subject account. Optional. - public let isMuted: Bool? = nil - // TODO: Figure out what this is about. - /// An array of lists that the subject account is muted by. - public let mutedByArray: GraphListViewBasic? = nil - /// Indicates whether the requesting account has been blocked by the subject account. Optional. - public let isBlocked: Bool? = nil - // TODO: Figure out what this is about. - /// A URI. - public let blockingURI: String? = nil - /// An array of the subject account's lists. - public let blockingByArray: GraphListViewBasic? = nil - // TODO: Figure out what this is about. - /// A URI. - public let followingURI: String? = nil - // TODO: Figure out what this is about. - /// A URI. - public let followedByURI: String? = nil - - enum CodingKeys: String, CodingKey { - case isMuted = "muted" - case mutedByArray = "mutedByList" - case isBlocked = "blockedBy" - case blockingURI = "blocking" - case blockingByArray = "blockingByList" - case followingURI = "following" - case followedByURI = "followedBy" - } -} - -/// A data model for a preferences definition. -/// -/// - SeeAlso: This is based on the [`app.bsky.actor.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/9579bec720d30e40c995d09772040212c261d6fb/lexicons/app/bsky/actor/defs.json -public struct ActorPreferences: Codable { - /// An array of different preferences the user can set. - public let preferences: [ActorPreferenceUnion] - - public init(preferences: [ActorPreferenceUnion]) { - self.preferences = preferences - } -} - -/// A data model for an "Adult Content" preference definition. -/// -/// - SeeAlso: This is based on the [`app.bsky.actor.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/9579bec720d30e40c995d09772040212c261d6fb/lexicons/app/bsky/actor/defs.json -public struct AdultContentPreferences: Codable { - /// The identifier of the lexicon. - /// - /// - Warning: The value must not change. - public let type: String = "app.bsky.actor.defs#adultContentPref" - /// Indicates whether the user will be able to see adult content in their feed. Set to `false` - /// by default. - public var isAdultContentEnabled: Bool = false - - public init(isAdultContentEnabled: Bool) { - self.isAdultContentEnabled = isAdultContentEnabled - } - - enum CodingKeys: String, CodingKey { - case type = "$type" - case isAdultContentEnabled = "enabled" - } -} - -/// A data model for a "Content Label" preference definition. -/// -/// - SeeAlso: This is based on the [`app.bsky.actor.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/9579bec720d30e40c995d09772040212c261d6fb/lexicons/app/bsky/actor/defs.json -public struct ContentLabelPreferences: Codable { - /// The identifier of the lexicon. - /// - /// - Warning: The value must not change. - public let type: String = "app.bsky.actor.defs#contentLabelPref" - /// The decentralized identifier of the labeler that this preference applies to. - /// - /// - Note: If this field is empty, then the preferences apply to all labels. - /// - /// - Note: According to the AT Protocol specifications: "Which labeler does this preference - /// apply to? If undefined, applies globally." - public let labelerDID: String? - /// The name of the content label. - public let label: String - /// Indicates the visibility of the label's content. - public let visibility: Visibility - - public init(labelerDID: String?, label: String, visibility: Visibility) { - self.labelerDID = labelerDID - self.label = label - self.visibility = visibility - } - /// Determines how visible a label's content is. - public enum Visibility: String, Codable { - /// Indicates the content can be ignored. - case ignore = "ignore" - /// Indicates the content can be seen without restriction. - case show = "show" - /// Indicates the content can be seen, but will ask if the user wants to view it. - case warn = "warn" - /// Indicates the content is fully invisible by the user. - case hide = "hide" - } - - enum CodingKeys: String, CodingKey { - case type = "$type" - case labelerDID = "labelerDid" - case label - case visibility - } -} - -/// A data model for a "Saved Feeds" preference definition. -/// -/// - SeeAlso: This is based on the [`app.bsky.actor.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/9579bec720d30e40c995d09772040212c261d6fb/lexicons/app/bsky/actor/defs.json -public struct SavedFeedsPreferences: Codable { - /// The identifier of the lexicon. - /// - /// - Warning: The value must not change. - public let type: String = "app.bsky.actor.defs#savedFeedsPref" - /// An array of feed URIs that have been saved and pinned. - public let pinned: [String] - /// An array of feed URIs that have been saved. - public let saved: [String] - // TODO: Find out more about what this does. - /// The index number of the timeline for the list of feeds. Optional. - public var timelineIndex: Int? = nil - - public init(pinned: [String], saved: [String], timelineIndex: Int?) { - self.pinned = pinned - self.saved = saved - self.timelineIndex = timelineIndex - } - - enum CodingKeys: String, CodingKey { - case type = "$type" - case pinned - case saved - case timelineIndex - } -} - -/// A data model for a "Personal Details" preference definition. -/// -/// - SeeAlso: This is based on the [`app.bsky.actor.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/9579bec720d30e40c995d09772040212c261d6fb/lexicons/app/bsky/actor/defs.json -public struct PersonalDetailsPreferences: Codable { - /// The identifier of the lexicon. - /// - /// - Warning: The value must not change. - public let type: String = "app.bsky.actor.defs#personalDetailsPref" - /// The birth date of the user. Optional. - /// - /// - Note: From the AT Protocol specification: "The birth date of account owner." - @DateFormattingOptional public var birthDate: Date? = nil - - public init(birthDate: Date) { - self._birthDate = DateFormattingOptional(wrappedValue: birthDate) - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.birthDate = try container.decodeIfPresent(DateFormattingOptional.self, forKey: .birthDate)?.wrappedValue - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - try container.encodeIfPresent(self._birthDate, forKey: .birthDate) - } - - enum CodingKeys: String, CodingKey { - case type = "$type" - case birthDate - } -} - -/// A data model for a "Feed View" preference definition. -/// -/// - SeeAlso: This is based on the [`app.bsky.actor.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/9579bec720d30e40c995d09772040212c261d6fb/lexicons/app/bsky/actor/defs.json -public struct FeedViewPreferences: Codable { - /// The identifier of the lexicon. - /// - /// - Warning: The value must not change. - public let type: String = "app.bsky.actor.defs#feedViewPref" - /// The feed's identifier (typically the URI). - /// - /// - Note:From the AT Protocol specification: "The URI of the feed, or an identifier which - /// describes the feed." - public let feedURI: String - /// Indicates whether the replies are hidden from the user. Optional. - /// - /// - Note: From the AT Protocol specification: "Hide replies in the feed." - public let areRepliesHidden: Bool? = nil - /// Indicates whether replies from users you don't follow are hidden from the user. Optional. - /// - /// - Note: From the AT Protocol specification: "Hide replies in the feed if they are not by - /// followed users." - public let areUnfollowedRepliesHidden: Bool? = true - /// Indicates how many likes a post needs in order for the user to see the reply. Optional. - /// - /// - Note: From the AT Protocol specification: "Hide replies in the feed if they do not have - /// this number of likes." - public let hideRepliesByLikeCount: Int? = nil - /// Indicates whether reposts are hidden from the user. Optional. - /// - /// - Note: From the AT Protocol specification: "Hide reposts in the feed." - public let areRepostsHidden: Bool? = nil - /// Indicates whether quote posts are hidden from the user. Optional. - /// - /// - Note: From the AT Protocol specification: "Hide quote posts in the feed." - public let areQuotePostsHidden: Bool? = nil - - enum CodingKeys: String, CodingKey { - case type = "$type" - case feedURI = "feed" - case areRepliesHidden = "hideReplies" - case areUnfollowedRepliesHidden = "hideRepliesByUnfollowed" - case hideRepliesByLikeCount - case areRepostsHidden = "hideReposts" - case areQuotePostsHidden = "hideQuotePosts" - } -} - -/// A data model for a "Thread View" preference definition. -/// -/// - SeeAlso: This is based on the [`app.bsky.actor.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/9579bec720d30e40c995d09772040212c261d6fb/lexicons/app/bsky/actor/defs.json -public struct ThreadViewPreferences: Codable { - /// The identifier of the lexicon. - /// - /// - Warning: The value must not change. - public let type: String = "app.bsky.actor.defs#threadViewPref" - /// The sorting mode of a thread. Optional. - /// - /// - Note: From the AT Protocol specification: "Sorting mode for threads." - public let sortingMode: SortingMode? = nil - /// Indicates whether users you follow are prioritized over other users. Optional. - /// - /// - Note: From the AT Protocol specification: "Show followed users at the top of - /// all replies." - public let areFollowedUsersPrioritized: Bool? = nil - - /// The sorting mode for a thread. - public enum SortingMode: String, Codable { - /// Indicates the thread will be sorted from the oldest post. - case oldest = "oldest" - /// Indicates the thread will be sorted from the newest post. - case newest = "newest" - /// Indicates the thread will be sorted from the posts with the most number of likes. - case mostLikes = "most-likes" - /// Indicates the thread will be completely random. - case random = "random" - } - - enum CodingKeys: String, CodingKey { - case type = "$type" - case sortingMode = "sort" - case areFollowedUsersPrioritized = "prioritizeFollowedUsers" - } -} - -/// A data model for an "Interest View" preference definition. -/// -/// - SeeAlso: This is based on the [`app.bsky.actor.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/9579bec720d30e40c995d09772040212c261d6fb/lexicons/app/bsky/actor/defs.json -public struct InterestViewPreferences: Codable { - /// The identifier of the lexicon. - /// - /// - Warning: The value must not change. - public let type: String = "app.bsky.actor.defs#interestsPref" - /// An array of interest tags. - /// - /// - Note: According to AT Protocol's specifications: "A list of tags which describe the - /// account owner's interests gathered during onboarding." - /// - Important: Current maximum limit is 100 tags. Current maximum length for each tag name - /// is 64 characters. - public let tags: [String] - - public init(tags: [String]) { - self.tags = tags - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.tags = try container.decode([String].self, forKey: .tags) - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - // Truncate `tags` to 640 characters before encoding. - // `maxGraphemes`'s limit is 64, but `String.count` should respect that limit implictly. - // Then, truncate `tags` to 100 items before encoding. - try truncatedEncode( - self.tags.map { $0.truncated(toLength: 640) }, - withContainer: &container, forKey: .tags, upToLength: 100) - } - - enum CodingKeys: String, CodingKey { - case type = "$type" - case tags - } -} - -/// A data model for a definition of the muted word's target. -/// -/// - SeeAlso: This is based on the [`app.bsky.actor.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/9579bec720d30e40c995d09772040212c261d6fb/lexicons/app/bsky/actor/defs.json -public enum MutedWordTarget: Codable { - case content - case tag - case other(String) - - public init(from decoder: Decoder) throws { - let container = try decoder.singleValueContainer() - let value = try container.decode(String.self) - - switch value { - case "content": - self = .content - case "tag": - self = .tag - // Handle other known cases - default: - self = .other(value) - } - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.singleValueContainer() - switch self { - case .content: - try container.encode("content") - case .tag: - try container.encode("tag") - case .other(let other): - // Truncate `other` to 640 characters before decoding - // `maxGraphemes`'s limit is 64, but `String.count` should respect that limit - let truncatedOther = other.truncated(toLength: 640) - try container.encode(truncatedOther) - } - } -} - -/// A data model for a muted word definition. -/// -/// - Note: According to the AT Protocol specifications: "A word that the account owner has muted." -/// -/// - SeeAlso: This is based on the [`app.bsky.actor.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/9579bec720d30e40c995d09772040212c261d6fb/lexicons/app/bsky/actor/defs.json -public struct MutedWord: Codable { - public let value: String - public let targets: [MutedWordTarget] - - public init(value: String, targets: [MutedWordTarget]) { - self.value = value - self.targets = targets - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.value = try container.decode(String.self, forKey: .value) - self.targets = try container.decode([MutedWordTarget].self, forKey: .targets) - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - // Truncate `value` to 1000 characters before decoding - // `maxGraphemes`'s limit is 100, but `String.count` should respect that limit - try truncatedEncode(self.value, withContainer: &container, forKey: .value, upToLength: 1000) - try container.encode(self.targets, forKey: .targets) - } - - enum CodingKeys: CodingKey { - case value - case targets - } -} - -/// A data model for a "Muted Words" preference definition. -/// -/// - SeeAlso: This is based on the [`app.bsky.actor.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/9579bec720d30e40c995d09772040212c261d6fb/lexicons/app/bsky/actor/defs.json -public struct MutedWordsPreferences: Codable { - /// The identifier of the lexicon. - /// - /// - Warning: The value must not change. - public let type: String = "app.bsky.actor.defs#mutedWordsPref" - /// An array of items the user has muted. - /// - /// - Note: According to the AT Protocol specifications: "A list of words the account owner - /// has muted." - public let mutedItems: [MutedWord] - - enum CodingKeys: String, CodingKey { - case type = "$type" - case mutedItems = "items" - } -} - -/// A data model for a "Hidden Posts" preference definition. -/// -/// - SeeAlso: This is based on the [`app.bsky.actor.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/9579bec720d30e40c995d09772040212c261d6fb/lexicons/app/bsky/actor/defs.json -public struct HiddenPostsPreferences: Codable { - /// The identifier of the lexicon. - /// - /// - Warning: The value must not change. - public let type: String = "app.bsky.actor.defs#hiddenPostsPref" - /// An array of URIs related to posts that the user wants to hide. - /// - /// - Note: According to the AT Protocol specifications: "A list of URIs of posts the account - /// owner has hidden." - public let items: [String] - - enum CodingKeys: String, CodingKey { - case type = "$type" - case items - } -} - -/// A data model for a "Labelers" preference definition. -/// -/// - SeeAlso: This is based on the [`app.bsky.actor.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/9579bec720d30e40c995d09772040212c261d6fb/lexicons/app/bsky/actor/defs.json -public struct LabelersPreferences: Codable { - /// An array of labeler items. - public let labelers: [String] -} - -/// A data model definition for a labeler item. -/// -/// - SeeAlso: This is based on the [`app.bsky.actor.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/9579bec720d30e40c995d09772040212c261d6fb/lexicons/app/bsky/actor/defs.json -public struct LabelersPreferenceItem: Codable { - /// The decentralized identifier (DID) of the labeler. - public let atDID: String -} - -// MARK: - Union types -/// A reference containing the list of preferences. -/// -/// - SeeAlso: This is based on the [`app.bsky.actor.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/9579bec720d30e40c995d09772040212c261d6fb/lexicons/app/bsky/actor/defs.json -public enum ActorPreferenceUnion: Codable { - /// The "Adult Content" preference. - case adultContent(AdultContentPreferences) - /// The "Content Label" preference. - case contentLabel(ContentLabelPreferences) - /// The "Saved Feeds" preference. - case savedFeeds(SavedFeedsPreferences) - /// The "Personal Details" preference. - case personalDetails(PersonalDetailsPreferences) - /// The "Feed View" preference. - case feedView(FeedViewPreferences) - /// The "Thread View" preference. - case threadView(ThreadViewPreferences) - /// The "Interest View" preference. - case interestViewPreferences(InterestViewPreferences) - /// The "Muted Words" preference. - case mutedWordsPreferences(MutedWordsPreferences) - /// The Hidden Posts" preference. - case hiddenPostsPreferences(HiddenPostsPreferences) - - // Implement custom decoding - public init(from decoder: Decoder) throws { - let container = try decoder.singleValueContainer() - - if let value = try? container.decode(AdultContentPreferences.self) { - self = .adultContent(value) - } else if let value = try? container.decode(ContentLabelPreferences.self) { - self = .contentLabel(value) - } else if let value = try? container.decode(SavedFeedsPreferences.self) { - self = .savedFeeds(value) - } else if let value = try? container.decode(PersonalDetailsPreferences.self) { - self = .personalDetails(value) - } else if let value = try? container.decode(FeedViewPreferences.self) { - self = .feedView(value) - } else if let value = try? container.decode(ThreadViewPreferences.self) { - self = .threadView(value) - } else if let value = try? container.decode(InterestViewPreferences.self) { - self = .interestViewPreferences(value) - } else if let value = try? container.decode(MutedWordsPreferences.self) { - self = .mutedWordsPreferences(value) - } else if let value = try? container.decode(HiddenPostsPreferences.self) { - self = .hiddenPostsPreferences(value) - } else { - throw DecodingError.typeMismatch( - ActorPreferenceUnion.self, DecodingError.Context( - codingPath: decoder.codingPath, debugDescription: "Unknown ActorPreference type")) - } - } - - // Implement custom encoding - public func encode(to encoder: Encoder) throws { - var container = encoder.singleValueContainer() - - switch self { - case .adultContent(let preference): - try container.encode(preference) - case .contentLabel(let preference): - try container.encode(preference) - case .savedFeeds(let preference): - try container.encode(preference) - case .personalDetails(let preference): - try container.encode(preference) - case .feedView(let preference): - try container.encode(preference) - case .threadView(let preference): - try container.encode(preference) - case .interestViewPreferences(let preference): - try container.encode(preference) - case .mutedWordsPreferences(let preference): - try container.encode(preference) - case .hiddenPostsPreferences(let preference): - try container.encode(preference) - } - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/BskyActorGetPreferences.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/BskyActorGetPreferences.swift deleted file mode 100644 index 87516eb1dc..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/BskyActorGetPreferences.swift +++ /dev/null @@ -1,23 +0,0 @@ -// -// BskyActorGetPreferences.swift -// -// -// Created by Christopher Jr Riley on 2024-02-18. -// - -import Foundation - -// MARK: - -/// A data model definition for the output of getting preferences. -/// -/// - Note: According to the AT Protocol specifications: "Get private preferences attached to the -/// current account. Expected use is synchronization between multiple devices, and -/// import/export during account migration. Requires auth." -/// -/// - SeeAlso: This is based on the [`app.bsky.actor.getPreferences`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/actor/getPreferences.json -public struct ActorGetPreferencesOutput: Codable { - /// The list of preferences in the user's account. - public let preference: ActorPreferences -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/BskyActorGetProfile.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/BskyActorGetProfile.swift deleted file mode 100644 index b68d67f8e9..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/BskyActorGetProfile.swift +++ /dev/null @@ -1,21 +0,0 @@ -// -// BskyActorGetProfile.swift.swift -// -// -// Created by Christopher Jr Riley on 2024-02-18. -// - -import Foundation - -/// A data model definition for the output for a detailed profile view for the user. -/// -/// - Note: According to the AT Protocol specifications: "Get detailed profile view of an actor. -/// Does not require auth, but contains relevant metadata with auth." -/// -/// - SeeAlso: This is based on the [`app.bsky.actor.getProfile`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/actor/getProfile.json -public struct ActorGetProfileOutput: Codable { - /// A detailed profile view of the user. - public let actorProfileView: ActorProfileViewDetailed -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/BskyActorGetProfiles.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/BskyActorGetProfiles.swift deleted file mode 100644 index af0461000f..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/BskyActorGetProfiles.swift +++ /dev/null @@ -1,21 +0,0 @@ -// -// BskyActorGetProfiles.swift -// -// -// Created by Christopher Jr Riley on 2024-02-19. -// - -import Foundation - -/// A data model definition for the output of detailed profile views for multiple users. -/// -/// - Note: According to the AT Protocol specifications: "Get detailed profile views of -/// multiple actors." -/// -/// - SeeAlso: This is based on the [`app.bsky.actor.getProfiles`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/actor/getProfiles.json -public struct ActorGetProfilesOutput: Codable { - /// An array of detailed profile views for several users. - public let profiles: [ActorProfileViewDetailed] -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/BskyActorGetSuggestions.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/BskyActorGetSuggestions.swift deleted file mode 100644 index 282b26c8d7..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/BskyActorGetSuggestions.swift +++ /dev/null @@ -1,23 +0,0 @@ -// -// BskyActorGetSuggestions.swift -// -// -// Created by Christopher Jr Riley on 2024-02-20. -// - -import Foundation - -/// A data model for the output of the list of suggested users to follow. -/// -/// - Note: According to the AT Protocol specifications: "Get a list of suggested actors. -/// Expected use is discovery of accounts to follow during new account onboarding." -/// -/// - SeeAlso: This is based on the [`app.bsky.actor.getSuggestions`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/actor/getSuggestions.json -public struct ActorGetSuggestionsOutput: Codable { - /// The mark used to indicate the starting point for the next set of results. Optional. - public let cursor: String? - /// An array of actors. - public let actors: [ActorProfileView] -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/BskyActorProfile.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/BskyActorProfile.swift deleted file mode 100644 index 593ef54420..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/BskyActorProfile.swift +++ /dev/null @@ -1,45 +0,0 @@ -// -// BskyActorProfile.swift -// -// -// Created by Christopher Jr Riley on 2024-02-22. -// - -import Foundation - -/// The main data model definition for an actor. -/// -/// - Note: According to the AT Protocol specifications: "A declaration of a Bluesky -/// account profile." -/// -/// - SeeAlso: This is based on the [`app.bsky.actor.profile`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/actor/profile.json -public struct ActorProfile: Codable { - /// The display name of the profile. Optional. - public let displayName: String? - /// The description of the profile. Optional. - /// - /// - Note: According to the AT Protocol specifications: "Free-form profile - /// description text." - public let description: String? - /// The avatar image URL of the profile. Optional. - /// - /// - Note: According to the AT Protocol specifications: "Small image to be displayed next - /// to posts from account. AKA, 'profile picture'" - /// - /// - Note: Only JPEGs and PNGs are accepted. - public let avatarBlob: BlobContainer? - /// The banner image URL of the profile. Optional. - /// - /// - Note: According to the AT Protocol specifications: "Larger horizontal image to display - /// behind profile view." - /// - /// - Note: Only JPEGs and PNGs are accepted. - public let bannerBlob: BlobContainer? - /// An array of user-defined labels. Optional. - /// - /// - Note: According to the AT Protocol specifications: "Self-label values, specific to the - /// Bluesky application, on the overall account." - public let labels: [SelfLabels] -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/BskyActorPutPreferences.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/BskyActorPutPreferences.swift deleted file mode 100644 index dd515e0ab3..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/BskyActorPutPreferences.swift +++ /dev/null @@ -1,34 +0,0 @@ -// -// BskyActorPutPreferences.swift -// -// -// Created by Christopher Jr Riley on 2024-02-22. -// - -import Foundation - -/// The main data model definition for editing user preferences. -/// -/// - Note: According to the AT Protocol specifications: "Set the private preferences attached to -/// the account." -/// -/// - SeeAlso: This is based on the [`app.bsky.actor.putPreferences`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/actor/putPreferences.json -public struct ActorPutPreferences: Codable { - /// The identifier of the lexicon. - /// - /// - Warning: The value must not change. - public let type: String = "app.bsky.actor.putPreferences" - /// A list of preferences by the user. - public let preferences: [ActorPreferenceUnion] - - public init(preferences: [ActorPreferenceUnion]) { - self.preferences = preferences - } - - enum CodingKeys: String, CodingKey { - case type = "$type" - case preferences - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/BskyActorSearchActors.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/BskyActorSearchActors.swift deleted file mode 100644 index cea8f6804f..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/BskyActorSearchActors.swift +++ /dev/null @@ -1,20 +0,0 @@ -// -// BskyActorSearchActors.swift -// -// -// Created by Christopher Jr Riley on 2024-02-23. -// - -import Foundation - -/// A data model definition for the output of searching for actors matching the search criteria. -/// -/// - SeeAlso: This is based on the [`app.bsky.actor.searchActors`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/actor/searchActors.json -public struct ActorSearchActorsOutput: Codable { - /// The mark used to indicate the starting point for the next set of results. Optional. - public let cursor: String - /// An array of actors. - public let actors: [ActorProfileView] -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/BskyActorSearchActorsTypeahead.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/BskyActorSearchActorsTypeahead.swift deleted file mode 100644 index 11c2f9d7bb..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Actor/BskyActorSearchActorsTypeahead.swift +++ /dev/null @@ -1,19 +0,0 @@ -// -// BskyActorSearchActorsTypeahead.swift -// -// -// Created by Christopher Jr Riley on 2024-02-23. -// - -import Foundation - -/// A data model definition for the output of searching for actors matching the prefixed -/// search criteria. -/// -/// - SeeAlso: This is based on the [`app.bsky.actor.searchActorsTypeahead`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/actor/searchActorsTypeahead.json -public struct ActorSearchActorsTypeaheadOutput: Codable { - /// An array of actors. - public let actors: [ActorProfileViewBasic] -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/AppBskyLexicon.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/AppBskyLexicon.swift new file mode 100644 index 0000000000..0379aaf7b2 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/AppBskyLexicon.swift @@ -0,0 +1,36 @@ +// +// AppBskyLexicon.swift +// +// +// Created by Christopher Jr Riley on 2024-05-16. +// + +import Foundation + + +extension AppBskyLexicon { + + /// A group of lexicons within the `app.bsky.actor` namespace. + public struct Actor {} + + /// A group of lexicons within the `app.bsky.embed` namespace. + public struct Embed {} + + /// A group of lexicons within the `app.bsky.feed` namespace. + public struct Feed {} + + /// A group of lexicons within the `app.bsky.graph` namespace. + public struct Graph {} + + /// A group of lexicons within the `app.bsky.labeler` namespace. + public struct Labeler {} + + /// A group of lexicons within the `app.bsky.notification` namespace. + public struct Notification {} + + /// A group of lexicons within the `app.bsky.richtext` namespace. + public struct RichText {} + + /// A group of lexicons within the `app.bsky.unspecced` namespace. + public struct Unspecced {} +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Embed/AppBskyEmbedExternal.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Embed/AppBskyEmbedExternal.swift new file mode 100644 index 0000000000..115b9cfe32 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Embed/AppBskyEmbedExternal.swift @@ -0,0 +1,110 @@ +// +// AppBskyEmbedExternal.swift +// +// +// Created by Christopher Jr Riley on 2024-05-17. +// + +import Foundation + +extension AppBskyLexicon.Embed { + + /// A definition model for external embeds. + /// + /// - Note: According to the AT Protocol specifications: "A representation of some externally + /// linked content (eg, a URL and 'card'), embedded in a Bluesky record (eg, a post)." + /// + /// - SeeAlso: This is based on the [`app.bsky.embed.external`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/embed/external.json + public struct ExternalDefinition: Codable { + + /// The identifier of the lexicon. + /// + /// - Warning: The value must not change. + public let type: String = "app.bsky.embed.external" + + /// The external content needed to be embeeded. + public let external: External + + enum CodingKeys: String, CodingKey { + case type = "$type" + case external + } + + // Enums + /// An external embed object. + /// + /// - SeeAlso: This is based on the [`app.bsky.embed.external`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/embed/external.json + public struct External: Codable { + + /// The URI of the external content. + public let embedURI: String + + /// The title of the external content. + public let title: String + + /// The description of the external content. + public let description: String + + /// The thumbnail image of the external content. + /// + /// - Warning: The image size can't be higher than 1 MB. Failure to do so will result + /// in the image failing to upload. + public let thumbnailImage: ComAtprotoLexicon.Repository.UploadBlobOutput? + + enum CodingKeys: String, CodingKey { + case embedURI = "uri" + case title + case description + case thumbnailImage = "thumb" + } + } + + /// A data model for an external view definition. + /// + /// - SeeAlso: This is based on the [`app.bsky.embed.external`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/embed/external.json + public struct View: Codable { + + /// The identifier of the lexicon. + /// + /// - Warning: The value must not change. + public let type: String = "app.bsky.embed.external#view" + + /// The external content embedded in a post. + public let external: ViewExternal + + enum CodingKeys: String, CodingKey { + case type = "$type" + case external + } + } + + /// A data model for a definition for the external content. + public struct ViewExternal: Codable { + + /// The URI of the external content. + public let embedURI: String + + /// The title of the external content. + public let title: String + + /// The description of the external content. + public let description: String + + /// The thumbnail image URL of the external content. + public let thumbnailImageURL: URL? + + enum CodingKeys: String, CodingKey { + case embedURI = "uri" + case title + case description + case thumbnailImageURL = "thumb" + } + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Embed/AppBskyEmbedImages.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Embed/AppBskyEmbedImages.swift new file mode 100644 index 0000000000..48833014b5 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Embed/AppBskyEmbedImages.swift @@ -0,0 +1,157 @@ +// +// AppBskyEmbedImages.swift +// +// +// Created by Christopher Jr Riley on 2024-05-17. +// + +import Foundation + +extension AppBskyLexicon.Embed { + + /// A definition model for image embeds. + /// + /// - Note: According to the AT Protocol specifications: "A set of images embedded in a Bluesky + /// record (eg, a post)." + /// + /// - SeeAlso: This is based on the [`app.bsky.embed.images`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/embed/images.json + public struct ImagesDefinition: Codable { + + /// The identifier of the lexicon. + /// + /// - Warning: The value must not change. + public let type: String = "app.bsky.embed.images" + + /// An array of images to embed. + /// + ///- Note: Current maximum upload count is 4 images. + public let images: [Image] + + public init(images: [Image]) { + self.images = images + } + + enum CodingKeys: String, CodingKey { + case type = "$type" + case images + } + + // Enums + /// A data model for an external definition. + /// + /// - SeeAlso: This is based on the [`app.bsky.embed.images`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/embed/images.json + public struct Image: Codable { + + /// The image that needs to be uploaded. + /// + /// - Warning: The image size can't be higher than 1 MB. Failure to do so will result + /// in the image failing to upload. + public let image: ComAtprotoLexicon.Repository.UploadBlobOutput + + /// The alternative text for the image. + /// + /// - Note: From the AT Protocol specification: "Alt text description of the image, + /// for accessibility." + public let altText: String + + /// The aspect ratio of the image. Optional. + public let aspectRatio: AspectRatio? + + public init(image: ComAtprotoLexicon.Repository.UploadBlobOutput, altText: String, aspectRatio: AspectRatio?) { + self.image = image + self.altText = altText + self.aspectRatio = aspectRatio + } + + enum CodingKeys: String, CodingKey { + case image + case altText = "alt" + case aspectRatio + } + } + + /// A data model for the aspect ratio definition. + /// + /// - Note: From the AT Protocol specification: "width:height represents an aspect ratio. + /// It may be approximate, and may not correspond to absolute dimensions in any + /// given unit." + /// + /// - SeeAlso: This is based on the [`app.bsky.embed.images`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/embed/images.json + public struct AspectRatio: Codable { + + /// The width of the image. + public let width: Int + + /// The height of the image. + public let height: Int + + public init(width: Int, height: Int) { + self.width = width + self.height = height + } + } + + /// A data model for the embed images definition. + /// + /// - SeeAlso: This is based on the [`app.bsky.embed.images`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/embed/images.json + public struct View: Codable { + + /// The identifier of the lexicon. + /// + /// - Warning: The value must not change. An array of images to be viewed. + public let images: [ViewImage] + } + + /// A data model for a definition related to viewing an image. + /// + /// - SeeAlso: This is based on the [`app.bsky.embed.images`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/embed/images.json + public struct ViewImage: Codable { + + /// The URI of the image's thumbnail. + /// + /// - Note: From the AT Protocol specification: "Fully-qualified URL where a thumbnail + /// of the image can be fetched. For example, CDN location provided by the App View." + public let thumbnailImageURL: URL + + /// The URI of the fully-sized image. + /// + /// - Note: From the AT Protocol specification: "Fully-qualified URL where a large + /// version of the image can be fetched. May or may not be the exact original blob. + /// For example, CDN location provided by the App View." + public let fullSizeImageURL: URL + + /// /// The alternative text for the image. + /// + /// - Note: From the AT Protocol specification: "Alt text description of the image, + /// for accessibility." + public let altText: String + + /// The aspect ratio of the image. Optional. + public let aspectRatio: AspectRatio? + + public init(thumbnailImageURL: URL, fullSizeImageURL: URL, altText: String, aspectRatio: AspectRatio?) { + self.thumbnailImageURL = thumbnailImageURL + self.fullSizeImageURL = fullSizeImageURL + self.altText = altText + self.aspectRatio = aspectRatio + } + + enum CodingKeys: String, CodingKey { + case thumbnailImageURL = "thumb" + case fullSizeImageURL = "fullsize" + case altText = "alt" + case aspectRatio + } + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Embed/AppBskyEmbedRecord.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Embed/AppBskyEmbedRecord.swift new file mode 100644 index 0000000000..0a83050a07 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Embed/AppBskyEmbedRecord.swift @@ -0,0 +1,204 @@ +// +// AppBskyEmbedRecord.swift +// +// +// Created by Christopher Jr Riley on 2024-05-17. +// + +import Foundation + +extension AppBskyLexicon.Embed { + + /// A definition model for record embeds. + /// + /// - Note: According to the AT Protocol specifications: "A representation of a record embedded + /// in a Bluesky record (eg, a post). For example, a quote-post, or sharing a + /// feed generator record." + /// + /// - SeeAlso: This is based on the [`app.bsky.embed.record`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/embed/record.json + public struct RecordDefinition: Codable { + + /// The identifier of the lexicon. + /// + /// - Warning: The value must not change. + public let type: String = "app.bsky.embed.record" + + /// The strong reference of the record. + public let record: ComAtprotoLexicon.Repository.StrongReference + + enum CodingKeys: String, CodingKey { + case type = "$type" + case record + } + + // Enums + /// A data model for a view definition. + /// + /// - SeeAlso: This is based on the [`app.bsky.embed.record`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/embed/record.json + public struct View: Codable { + + /// The identifier of the lexicon. + /// + /// - Warning: The value must not change. + public let type: String = "app.bsky.embed.record#view" + + /// The record of a specific type. + public let record: ATUnion.RecordViewUnion + + enum CodingKeys: String, CodingKey { + case type = "$type" + case record + } + } + + /// A data model for a record definition in an embed. + /// + /// - SeeAlso: This is based on the [`app.bsky.embed.record`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/embed/record.json + public struct ViewRecord: Codable { + + /// The identifier of the lexicon. + /// + /// - Warning: The value must not change. + public let type: String = "app.bsky.embed.record#viewRecord" + + /// The URI of the record. + public let recordURI: String + + /// The CID of the record. + public let cidHash: String + + /// The creator of the record. + public let author: AppBskyLexicon.Actor.ProfileViewBasicDefinition + + /// The value of the record. + /// + /// - Note: According to the AT Protocol specifications: "The record data itself." + public let value: UnknownType + + /// An array of labels attached to the record. + public let labels: [ComAtprotoLexicon.Label.LabelDefinition]? + + /// The number of replies for the record. Optional. + public let replyCount: Int? + + /// The number of reposts for the record. Optional. + public let repostCount: Int? + + /// The number of likes for the record. Optional. + public let likeCount: Int? + + /// An array of embed views of various types. + public let embeds: [ATUnion.EmbedViewUnion]? + + /// The date the record was last indexed. + @DateFormatting public var indexedAt: Date + + public init(recordURI: String, cidHash: String, author: AppBskyLexicon.Actor.ProfileViewBasicDefinition, value: UnknownType, + labels: [ComAtprotoLexicon.Label.LabelDefinition]?, replyCount: Int?, repostCount: Int?, likeCount: Int?, + embeds: [ATUnion.EmbedViewUnion]?, indexedAt: Date) { + self.recordURI = recordURI + self.cidHash = cidHash + self.author = author + self.value = value + self.labels = labels + self.replyCount = replyCount + self.repostCount = repostCount + self.likeCount = likeCount + self.embeds = embeds + self._indexedAt = DateFormatting(wrappedValue: indexedAt) + } + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.recordURI = try container.decode(String.self, forKey: .recordURI) + self.cidHash = try container.decode(String.self, forKey: .cidHash) + self.author = try container.decode(AppBskyLexicon.Actor.ProfileViewBasicDefinition.self, forKey: .author) + self.value = try container.decode(UnknownType.self, forKey: .value) + self.labels = try container.decodeIfPresent([ComAtprotoLexicon.Label.LabelDefinition].self, forKey: .labels) + self.replyCount = try container.decodeIfPresent(Int.self, forKey: .replyCount) + self.repostCount = try container.decodeIfPresent(Int.self, forKey: .repostCount) + self.likeCount = try container.decodeIfPresent(Int.self, forKey: .likeCount) + self.embeds = try container.decodeIfPresent([ATUnion.EmbedViewUnion].self, forKey: .embeds) + self.indexedAt = try container.decode(DateFormatting.self, forKey: .indexedAt).wrappedValue + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.recordURI, forKey: .recordURI) + try container.encode(self.cidHash, forKey: .cidHash) + try container.encode(self.author, forKey: .author) + try container.encode(self.value, forKey: .value) + try container.encodeIfPresent(self.labels, forKey: .labels) + try container.encodeIfPresent(self.replyCount, forKey: .replyCount) + try container.encodeIfPresent(self.repostCount, forKey: .repostCount) + try container.encodeIfPresent(self.likeCount, forKey: .likeCount) + try container.encodeIfPresent(self.embeds, forKey: .embeds) + try container.encode(self._indexedAt, forKey: .indexedAt) + } + + enum CodingKeys: String, CodingKey { + case type = "$type" + case recordURI = "uri" + case cidHash = "cid" + case author + case value + case labels + case replyCount + case repostCount + case likeCount + case embeds = "embeds" + case indexedAt + } + } + + /// A data model for a definition of a record that was unable to be found. + /// + /// - SeeAlso: This is based on the [`app.bsky.embed.record`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/embed/record.json + public struct ViewNotFound: Codable { + + /// The URI of the record. + public let recordURI: String + + /// Indicates whether the record was found. + public let isRecordNotFound: Bool + + enum CodingKeys: String, CodingKey { + case recordURI = "uri" + case isRecordNotFound = "notFound" + } + } + + /// A data model for a definition of a record that has been blocked. + /// + /// - SeeAlso: This is based on the [`app.bsky.embed.record`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/embed/record.json + public struct ViewBlocked: Codable { + + /// The URI of the record. + public let recordURI: String + + /// Indicates whether the record has been blocked. + public let isRecordBlocked: Bool + + /// The author of the record. + public let recordAuthor: AppBskyLexicon.Feed.BlockedAuthorDefinition + + enum CodingKeys: String, CodingKey { + case recordURI = "uri" + case isRecordBlocked = "blocked" + case recordAuthor = "author" + } + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Embed/AppBskyEmbedRecordWithMedia.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Embed/AppBskyEmbedRecordWithMedia.swift new file mode 100644 index 0000000000..f2283345f8 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Embed/AppBskyEmbedRecordWithMedia.swift @@ -0,0 +1,66 @@ +// +// AppBskyEmbedRecordWithMedia.swift +// +// +// Created by Christopher Jr Riley on 2024-05-17. +// + +import Foundation + +extension AppBskyLexicon.Embed { + + /// A definition model for a record embedded with some form of compatible media. + /// + /// - Note: According to the AT Protocol specifications: "A representation of a record + /// embedded in a Bluesky record (eg, a post), alongside other compatible embeds. For example, + /// a quote post and image, or a quote post and external URL card." + /// + /// - SeeAlso: This is based on the [`app.bsky.embed.recordWithMedia][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/embed/recordWithMedia.json + public struct RecordWithMediaDefinition: Codable { + + /// The identifier of the lexicon. + /// + /// - Warning: The value must not change. + public let type: String = "app.bsky.embed.recordWithMedia" + + /// The record that will be embedded. + public let record: RecordDefinition + + /// The media of a specific type. + public let media: ATUnion.RecordWithMediaUnion + + enum CodingKeys: String, CodingKey { + case type = "$type" + case record + case media + } + + // Enums + /// A data model for a definition which contains an embedded record and embedded media. + /// + /// - SeeAlso: This is based on the [`app.bsky.embed.recordWithMedia`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/embed/recordWithMedia.json + public struct View: Codable { + + /// The identifier of the lexicon. + /// + /// - Warning: The value must not change. + public let type: String = "app.bsky.embed.recordWithMedia#view" + + /// The embeded record. + public let record: AppBskyLexicon.Embed.RecordDefinition.View + + /// The embedded media. + public let media: ATUnion.MediaViewUnion + + enum CodingKeys: String, CodingKey { + case type = "$type" + case record + case media + } + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Embed/BskyEmbedExternal.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Embed/BskyEmbedExternal.swift deleted file mode 100644 index 51140d5189..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Embed/BskyEmbedExternal.swift +++ /dev/null @@ -1,96 +0,0 @@ -// -// BskyEmbedExternal.swift -// -// -// Created by Christopher Jr Riley on 2024-01-26. -// - -import Foundation - -// MARK: - Main definition -/// The main data model definition for external embeds. -/// -/// - Note: According to the AT Protocol specifications: "A representation of some externally -/// linked content (eg, a URL and 'card'), embedded in a Bluesky record (eg, a post)." -/// -/// - SeeAlso: This is based on the [`app.bsky.embed.external`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/embed/external.json -public struct EmbedExternal: Codable { - /// The identifier of the lexicon. - /// - /// - Warning: The value must not change. - public let type: String = "app.bsky.embed.external" - /// The external content needed to be embeeded. - public let external: External - - enum CodingKeys: String, CodingKey { - case type = "$type" - case external - } -} -// MARK: - -/// A data model for an external definition. -/// -/// - SeeAlso: This is based on the [`app.bsky.embed.external`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/embed/external.json -public struct External: Codable { - /// The URI of the external content. - public let embedURI: String - /// The title of the external content. - public let title: String - /// The description of the external content. - public let description: String - /// The thumbnail image of the external content. - /// - /// - Warning: The image size can't be higher than 1 MB. Failure to do so will result in the - /// image failing to upload. - public let thumbnailImage: UploadBlobOutput? - - enum CodingKeys: String, CodingKey { - case embedURI = "uri" - case title - case description - case thumbnailImage = "thumb" - } -} - -/// A data model for an external view definition. -/// -/// - SeeAlso: This is based on the [`app.bsky.embed.external`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/embed/external.json -public struct EmbedExternalView: Codable { - /// The identifier of the lexicon. - /// - /// - Warning: The value must not change. - public let type: String = "app.bsky.embed.external#view" - - /// The external content embedded in a post. - public let external: ViewExternal - - enum CodingKeys: String, CodingKey { - case type = "$type" - case external - } -} - -/// A data model for a definition for the external content. -public struct ViewExternal: Codable { - /// The URI of the external content. - public let embedURI: String - /// The title of the external content. - public let title: String - /// The description of the external content. - public let description: String - /// The thumbnail image URL of the external content. - public let thumbnailImageURL: URL? - - enum CodingKeys: String, CodingKey { - case embedURI = "uri" - case title - case description - case thumbnailImageURL = "thumb" - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Embed/BskyEmbedImages.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Embed/BskyEmbedImages.swift deleted file mode 100644 index 07e25845fc..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Embed/BskyEmbedImages.swift +++ /dev/null @@ -1,144 +0,0 @@ -// -// BskyEmbedImages.swift -// -// -// Created by Christopher Jr Riley on 2024-01-26. -// - -import Foundation - -// MARK: - Main definition -/// The main data model definition for image embeds. -/// -/// - Note: According to the AT Protocol specifications: "A set of images embedded in a Bluesky -/// record (eg, a post)." -/// -/// - SeeAlso: This is based on the [`app.bsky.embed.images`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/embed/images.json -public struct EmbedImages: Codable { - /// The identifier of the lexicon. - /// - /// - Warning: The value must not change. - public let type: String = "app.bsky.embed.images" - /// An array of images to embed. - /// - ///- Note: Current maximum upload count is 4 images. - public let images: [EmbedImage] - - public init(images: [EmbedImage]) { - self.images = images - } - - enum CodingKeys: String, CodingKey { - case type = "$type" - case images - } -} - -// MARK: - -/// A data model for an external definition. -/// -/// - SeeAlso: This is based on the [`app.bsky.embed.images`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/embed/images.json -public struct EmbedImage: Codable { - /// The image that needs to be uploaded. - /// - /// - Warning: The image size can't be higher than 1 MB. Failure to do so will result in the - /// image failing to upload. - public let image: UploadBlobOutput - /// The alternative text for the image. - /// - /// - Note: From the AT Protocol specification: "Alt text description of the image, - /// for accessibility." - public let altText: String - /// The aspect ratio of the image. Optional. - public let aspectRatio: AspectRatio? - - public init(image: UploadBlobOutput, altText: String, aspectRatio: AspectRatio?) { - self.image = image - self.altText = altText - self.aspectRatio = aspectRatio - } - - enum CodingKeys: String, CodingKey { - case image - case altText = "alt" - case aspectRatio - } -} - -/// A data model for the aspect ratio definition. -/// -/// - Note: From the AT Protocol specification: "width:height represents an aspect ratio. -/// It may be approximate, and may not correspond to absolute dimensions in any given unit." -/// -/// - SeeAlso: This is based on the [`app.bsky.embed.images`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/embed/images.json -public struct AspectRatio: Codable { - /// The width of the image. - public let width: Int - /// The height of the image. - public let height: Int - - public init(width: Int, height: Int) { - self.width = width - self.height = height - } -} - -/// A data model for the embed images definition. -/// -/// - SeeAlso: This is based on the [`app.bsky.embed.images`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/embed/images.json -public struct EmbedImagesView: Codable { - /// The identifier of the lexicon. - /// - /// - Warning: The value must not change. -// public let type: String = "app.bsky.embed.images#view" - /// An array of images to be viewed. - public let images: [ViewImage] -} - -/// A data model for a definition related to viewing an image. -/// -/// - SeeAlso: This is based on the [`app.bsky.embed.images`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/embed/images.json -public struct ViewImage: Codable { - /// The URI of the image's thumbnail. - /// - /// - Note: From the AT Protocol specification: "Fully-qualified URL where a thumbnail of the - /// image can be fetched. For example, CDN location provided by the App View." - public let thumbnailImageURL: URL - /// The URI of the fully-sized image. - /// - /// - Note: From the AT Protocol specification: "Fully-qualified URL where a large version of - /// the image can be fetched. May or may not be the exact original blob. For example, - /// CDN location provided by the App View." - public let fullSizeImageURL: URL - /// /// The alternative text for the image. - /// - /// - Note: From the AT Protocol specification: "Alt text description of the image, - /// for accessibility." - public let altText: String - /// The aspect ratio of the image. Optional. - public let aspectRatio: AspectRatio? - - public init(thumbnailImageURL: URL, fullSizeImageURL: URL, altText: String, aspectRatio: AspectRatio?) { - self.thumbnailImageURL = thumbnailImageURL - self.fullSizeImageURL = fullSizeImageURL - self.altText = altText - self.aspectRatio = aspectRatio - } - - enum CodingKeys: String, CodingKey { - case thumbnailImageURL = "thumb" - case fullSizeImageURL = "fullsize" - case altText = "alt" - case aspectRatio - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Embed/BskyEmbedRecord.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Embed/BskyEmbedRecord.swift deleted file mode 100644 index 651d4900cd..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Embed/BskyEmbedRecord.swift +++ /dev/null @@ -1,243 +0,0 @@ -// -// BskyEmbedRecord.swift -// -// -// Created by Christopher Jr Riley on 2024-01-26. -// - -import Foundation - -// MARK: - Main definition -/// The main data model definition for record embeds. -/// -/// - Note: According to the AT Protocol specifications: "A representation of a record embedded in -/// a Bluesky record (eg, a post). For example, a quote-post, or sharing a feed generator record." -/// -/// - SeeAlso: This is based on the [`app.bsky.embed.record`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/embed/record.json -public struct EmbedRecord: Codable { - /// The identifier of the lexicon. - /// - /// - Warning: The value must not change. - public let type: String = "app.bsky.embed.record" - /// The strong reference of the record. - public let record: StrongReference - - enum CodingKeys: String, CodingKey { - case type = "$type" - case record - } -} - -// MARK: - -/// A data model for a view definition. -/// -/// - SeeAlso: This is based on the [`app.bsky.embed.record`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/embed/record.json -public struct EmbedRecordView: Codable { - /// The identifier of the lexicon. - /// - /// - Warning: The value must not change. - public let type: String = "app.bsky.embed.record#view" - /// The record of a specific type. - public let record: RecordViewUnion - - enum CodingKeys: String, CodingKey { - case type = "$type" - case record - } -} - -/// A data model for a record definition in an embed. -/// -/// - SeeAlso: This is based on the [`app.bsky.embed.record`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/embed/record.json -public struct ViewRecord: Codable { - /// The identifier of the lexicon. - /// - /// - Warning: The value must not change. - public let type: String = "app.bsky.embed.record#viewRecord" - /// The URI of the record. - public let recordURI: String - /// The CID of the record. - public let cidHash: String - /// The creator of the record. - public let author: ActorProfileViewBasic - // TODO: Find out what specific type falls under this variable. - /// The value of the record. - /// - /// - Note: According to the AT Protocol specifications: "The record data itself." - public let value: UnknownType - /// An array of labels attached to the record. - public let labels: [Label]? - /// The number of replies for the record. Optional. - public let replyCount: Int? - /// The number of reposts for the record. Optional. - public let repostCount: Int? - /// The number of likes for the record. Optional. - public let likeCount: Int? - /// An array of embed views of various types. - public let embeds: [EmbedViewUnion]? - /// The date the record was last indexed. - @DateFormatting public var indexedAt: Date - - public init(recordURI: String, cidHash: String, author: ActorProfileViewBasic, value: UnknownType, labels: [Label]?, replyCount: Int?, - repostCount: Int?, likeCount: Int?, embeds: [EmbedViewUnion]?, indexedAt: Date) { - self.recordURI = recordURI - self.cidHash = cidHash - self.author = author - self.value = value - self.labels = labels - self.replyCount = replyCount - self.repostCount = repostCount - self.likeCount = likeCount - self.embeds = embeds - self._indexedAt = DateFormatting(wrappedValue: indexedAt) - } - - public init(from decoder: any Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.recordURI = try container.decode(String.self, forKey: .recordURI) - self.cidHash = try container.decode(String.self, forKey: .cidHash) - self.author = try container.decode(ActorProfileViewBasic.self, forKey: .author) - self.value = try container.decode(UnknownType.self, forKey: .value) - self.labels = try container.decodeIfPresent([Label].self, forKey: .labels) - self.replyCount = try container.decodeIfPresent(Int.self, forKey: .replyCount) - self.repostCount = try container.decodeIfPresent(Int.self, forKey: .repostCount) - self.likeCount = try container.decodeIfPresent(Int.self, forKey: .likeCount) - self.embeds = try container.decodeIfPresent([EmbedViewUnion].self, forKey: .embeds) - self.indexedAt = try container.decode(DateFormatting.self, forKey: .indexedAt).wrappedValue - } - - public func encode(to encoder: any Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - try container.encode(self.recordURI, forKey: .recordURI) - try container.encode(self.cidHash, forKey: .cidHash) - try container.encode(self.author, forKey: .author) - try container.encode(self.value, forKey: .value) - try container.encodeIfPresent(self.labels, forKey: .labels) - try container.encodeIfPresent(self.replyCount, forKey: .replyCount) - try container.encodeIfPresent(self.repostCount, forKey: .repostCount) - try container.encodeIfPresent(self.likeCount, forKey: .likeCount) - try container.encodeIfPresent(self.embeds, forKey: .embeds) - try container.encode(self._indexedAt, forKey: .indexedAt) - } - - enum CodingKeys: String, CodingKey { - case type = "$type" - case recordURI = "uri" - case cidHash = "cid" - case author - case value - case labels - case replyCount - case repostCount - case likeCount - case embeds = "embeds" - case indexedAt - } -} - -/// A data model for a definition of a record that was unable to be found. -/// -/// - SeeAlso: This is based on the [`app.bsky.embed.record`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/embed/record.json -public struct ViewNotFound: Codable { - /// The URI of the record. - public let recordURI: String - /// Indicates whether the record was found. - public let isRecordNotFound: Bool - - enum CodingKeys: String, CodingKey { - case recordURI = "uri" - case isRecordNotFound = "notFound" - } -} - -/// A data model for a definition of a record that has been blocked. -/// -/// - SeeAlso: This is based on the [`app.bsky.embed.record`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/embed/record.json -public struct ViewBlocked: Codable { - /// The URI of the record. - public let recordURI: String - /// Indicates whether the record has been blocked. - public let isRecordBlocked: Bool - /// The author of the record. - public let recordAuthor: FeedBlockedAuthor - - enum CodingKeys: String, CodingKey { - case recordURI = "uri" - case isRecordBlocked = "blocked" - case recordAuthor = "author" - } -} - -// MARK: - Union types -/// A reference containing the list of the status of a record. -/// -/// - SeeAlso: This is based on the [`app.bsky.embed.record`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/embed/record.json -public enum RecordViewUnion: Codable { - /// A normal record type. - case viewRecord(ViewRecord) - /// A record that may not have been found. - case viewNotFound(ViewNotFound) - /// A record that may have been blocked. - case viewBlocked(ViewBlocked) - /// A generator view. - case generatorView(FeedGeneratorView) - /// A list view. - case listView(GraphListView) - /// A labeler view. - case labelerView(LabelerView) - - public init(from decoder: Decoder) throws { - let container = try decoder.singleValueContainer() - - if let value = try? container.decode(ViewRecord.self) { - self = .viewRecord(value) - } else if let value = try? container.decode(ViewNotFound.self) { - self = .viewNotFound(value) - } else if let value = try? container.decode(ViewBlocked.self) { - self = .viewBlocked(value) - } else if let value = try? container.decode(FeedGeneratorView.self) { - self = .generatorView(value) - } else if let value = try? container.decode(GraphListView.self) { - self = .listView(value) - } else if let value = try? container.decode(LabelerView.self) { - self = .labelerView(value) - } else { - throw DecodingError.typeMismatch( - RecordViewUnion.self, DecodingError.Context( - codingPath: decoder.codingPath, debugDescription: "Unknown RecordViewUnion type")) - } - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.singleValueContainer() - - switch self { - case .viewRecord(let viewRecord): - try container.encode(viewRecord) - case .viewNotFound(let viewRecord): - try container.encode(viewRecord) - case .viewBlocked(let viewRecord): - try container.encode(viewRecord) - case .generatorView(let viewRecord): - try container.encode(viewRecord) - case .listView(let viewRecord): - try container.encode(viewRecord) - case .labelerView(let labelerView): - try container.encode(labelerView) - } - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Embed/BskyEmbedRecordWithMedia.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Embed/BskyEmbedRecordWithMedia.swift deleted file mode 100644 index 6f66f4b060..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Embed/BskyEmbedRecordWithMedia.swift +++ /dev/null @@ -1,133 +0,0 @@ -// -// BskyEmbedRecordWithMedia.swift -// -// -// Created by Christopher Jr Riley on 2024-01-27. -// - -import Foundation - -// MARK: - Main definition -/// The main data model definition for a record embedded with some form of compatible media. -/// -/// - Note: According to the AT Protocol specifications: "A representation of a record embedded in -/// a Bluesky record (eg, a post), alongside other compatible embeds. For example, a quote post -/// and image, or a quote post and external URL card." -/// -/// - SeeAlso: This is based on the [`app.bsky.embed.recordWithMedia][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/embed/recordWithMedia.json -public struct EmbedRecordWithMedia: Codable { - /// The identifier of the lexicon. - /// - /// - Warning: The value must not change. - public let type: String = "app.bsky.embed.recordWithMedia" - /// The record that will be embedded. - public let record: EmbedRecord - /// The media of a specific type. - public let media: MediaUnion - - enum CodingKeys: String, CodingKey { - case type = "$type" - case record - case media - } -} - -// MARK: - -/// A data model for a definition which contains an embedded record and embedded media. -/// -/// - SeeAlso: This is based on the [`app.bsky.embed.recordWithMedia`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/embed/recordWithMedia.json -public struct EmbedRecordWithMediaView: Codable { - /// The identifier of the lexicon. - /// - /// - Warning: The value must not change. - public let type: String = "app.bsky.embed.recordWithMedia#view" - /// The embeded record. - public let record: EmbedRecordView - /// The embedded media. - public let media: MediaViewUnion - - enum CodingKeys: String, CodingKey { - case type = "$type" - case record - case media - } -} - -// MARK: - Union Types -/// A reference containing the list of the types of compatible media. -/// -/// - SeeAlso: This is based on the [`app.bsky.embed.recordWithMedia`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/embed/recordWithMedia.json -public enum MediaUnion: Codable { - /// An image that will be embedded. - case embedImages(EmbedImages) - /// An external link that will be embedded. - case embedExternal(EmbedExternal) - - public init(from decoder: Decoder) throws { - let container = try decoder.singleValueContainer() - - if let value = try? container.decode(EmbedImages.self) { - self = .embedImages(value) - } else if let value = try? container.decode(EmbedExternal.self) { - self = .embedExternal(value) - } else { - throw DecodingError.typeMismatch( - PostUnion.self, DecodingError.Context( - codingPath: decoder.codingPath, debugDescription: "Unknown MediaUnion type")) - } - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.singleValueContainer() - - switch self { - case .embedImages(let media): - try container.encode(media) - case .embedExternal(let media): - try container.encode(media) - } - } -} - -/// A reference containing the list of the types of compatible media that can be viewed. -/// -/// - SeeAlso: This is based on the [`app.bsky.embed.recordWithMedia`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/embed/recordWithMedia.json -public enum MediaViewUnion: Codable { - /// An image that's been embedded. - case embedImagesView(EmbedImagesView) - /// An external link that's been embedded. - case embedExternalView(EmbedExternalView) - - public init(from decoder: Decoder) throws { - let container = try decoder.singleValueContainer() - - if let value = try? container.decode(EmbedImagesView.self) { - self = .embedImagesView(value) - } else if let value = try? container.decode(EmbedExternalView.self) { - self = .embedExternalView(value) - } else { - throw DecodingError.typeMismatch( - PostUnion.self, DecodingError.Context( - codingPath: decoder.codingPath, debugDescription: "Unknown MediaViewUnion type")) - } - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.singleValueContainer() - - switch self { - case .embedImagesView(let mediaView): - try container.encode(mediaView) - case .embedExternalView(let mediaView): - try container.encode(mediaView) - } - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedDefs.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedDefs.swift new file mode 100644 index 0000000000..76d60689bc --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedDefs.swift @@ -0,0 +1,708 @@ +// +// AppBskyFeedDefs.swift +// +// +// Created by Christopher Jr Riley on 2024-05-18. +// + +import Foundation + +extension AppBskyLexicon.Feed { + + /// A definition model for a post view. + /// + /// - SeeAlso: This is based on the [`app.bsky.feed.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/defs.json + public struct PostViewDefinition: Codable { + + /// The URI of the post. + public let postURI: String + + /// The CID of the post. + public let cidHash: String + + /// The author of the post. This will give the basic details of the post author. + public let author: AppBskyLexicon.Actor.ProfileViewBasicDefinition + + /// The record data itself. + public let record: UnknownType + + /// An embed view of a specific type. Optional. + public var embed: ATUnion.EmbedViewUnion? + + /// The number of replies in the post. Optional. + public var replyCount: Int? + + /// The number of reposts in the post. Optional. + public var repostCount: Int? + + /// The number of likes in the post. Optional. + public var likeCount: Int? + + /// The last time the post has been indexed. + @DateFormatting public var indexedAt: Date + + /// The viewer's interaction with the post. Optional. + public var viewer: ViewerStateDefinition? + + /// An array of labels attached to the post. Optional. + public var labels: [ComAtprotoLexicon.Label.LabelDefinition]? + + /// The ruleset of who can reply to the post. Optional. + public var threadgate: ThreadgateViewDefinition? + + public init(postURI: String, cidHash: String, author: AppBskyLexicon.Actor.ProfileViewBasicDefinition, record: UnknownType, + embed: ATUnion.EmbedViewUnion?, replyCount: Int?, repostCount: Int?, likeCount: Int?, indexedAt: Date, viewer: ViewerStateDefinition?, + labels: [ComAtprotoLexicon.Label.LabelDefinition]?, threadgate: ThreadgateViewDefinition?) { + self.postURI = postURI + self.cidHash = cidHash + self.author = author + self.record = record + self.embed = embed + self.replyCount = replyCount + self.repostCount = repostCount + self.likeCount = likeCount + self._indexedAt = DateFormatting(wrappedValue: indexedAt) + self.viewer = viewer + self.labels = labels + self.threadgate = threadgate + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.postURI = try container.decode(String.self, forKey: .postURI) + self.cidHash = try container.decode(String.self, forKey: .cidHash) + self.author = try container.decode(AppBskyLexicon.Actor.ProfileViewBasicDefinition.self, forKey: .author) + self.record = try container.decode(UnknownType.self, forKey: .record) + self.embed = try container.decodeIfPresent(ATUnion.EmbedViewUnion.self, forKey: .embed) + self.replyCount = try container.decodeIfPresent(Int.self, forKey: .replyCount) + self.repostCount = try container.decodeIfPresent(Int.self, forKey: .repostCount) + self.likeCount = try container.decodeIfPresent(Int.self, forKey: .likeCount) + self.indexedAt = try container.decode(DateFormatting.self, forKey: .indexedAt).wrappedValue + self.viewer = try container.decodeIfPresent(ViewerStateDefinition.self, forKey: .viewer) + self.labels = try container.decodeIfPresent([ComAtprotoLexicon.Label.LabelDefinition].self, forKey: .labels) + self.threadgate = try container.decodeIfPresent(ThreadgateViewDefinition.self, forKey: .threadgate) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.postURI, forKey: .postURI) + try container.encode(self.cidHash, forKey: .cidHash) + try container.encode(self.author, forKey: .author) + try container.encode(self.record, forKey: .record) + try container.encodeIfPresent(self.embed, forKey: .embed) + try container.encodeIfPresent(self.replyCount, forKey: .replyCount) + try container.encodeIfPresent(self.repostCount, forKey: .repostCount) + try container.encodeIfPresent(self.likeCount, forKey: .likeCount) + try container.encode(self._indexedAt, forKey: .indexedAt) + try container.encodeIfPresent(self.viewer, forKey: .viewer) + try container.encodeIfPresent(self.labels, forKey: .labels) + try container.encodeIfPresent(self.threadgate, forKey: .threadgate) + } + + enum CodingKeys: String, CodingKey { + case postURI = "uri" + case cidHash = "cid" + case author + case record + case embed + case replyCount + case repostCount + case likeCount + case indexedAt + case viewer + case labels + case threadgate + } + } + + /// A definition model for a viewer state. + /// + /// - Note: According to the AT Protocol specifications: "Metadata about the requesting + /// account's relationship with the subject content. Only has meaningful content for + /// authed requests." + /// + /// - SeeAlso: This is based on the [`app.bsky.feed.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/defs.json + public struct ViewerStateDefinition: Codable { + + /// The URI of the requesting account's repost of the subject account's post. Optional. + public let repostURI: String? + + /// The URI of the requesting account's like of the subject account's post. Optional. + public let likeURI: String? + + /// Indicates whether the requesting account can reply to the account's post. Optional. + public let areRepliesDisabled: Bool? + + enum CodingKeys: String, CodingKey { + case repostURI = "repost" + case likeURI = "like" + case areRepliesDisabled = "replyDisabled" + } + } + + /// A definition model for a feed's view. + /// + /// - SeeAlso: This is based on the [`app.bsky.feed.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/defs.json + public struct FeedViewPostDefinition: Codable { + + /// The post contained in a feed. + public let post: PostViewDefinition + + /// The reply reference for the post, if it's a reply. Optional. + public var reply: ReplyReferenceDefinition? + + // TODO: Check to see if this is correct. + /// The user who reposted the post. Optional. + public var reason: ATUnion.ReasonRepostUnion? + + /// The feed generator's context. Optional + /// + /// - Note: According to the AT Protocol specifications: "Context provided by + /// feed generator that may be passed back alongside interactions." + public let feedContext: String? + + public init(post: PostViewDefinition, reply: ReplyReferenceDefinition?, reason: ATUnion.ReasonRepostUnion?, feedContext: String?) { + self.post = post + self.reply = reply + self.reason = reason + self.feedContext = feedContext + } + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.post = try container.decode(PostViewDefinition.self, forKey: .post) + self.reply = try container.decodeIfPresent(ReplyReferenceDefinition.self, forKey: .reply) + self.reason = try container.decodeIfPresent(ATUnion.ReasonRepostUnion.self, forKey: .reason) + self.feedContext = try container.decodeIfPresent(String.self, forKey: .feedContext) + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.post, forKey: .post) + try container.encodeIfPresent(self.reply, forKey: .reply) + try container.encodeIfPresent(self.reason, forKey: .reason) + // Truncate `description` to 2000 characters before encoding + // `maxGraphemes`'s limit is 300, but `String.count` should respect that limit + try truncatedEncodeIfPresent(self.feedContext, withContainer: &container, forKey: .feedContext, upToLength: 2000) + } + + public enum CodingKeys: CodingKey { + case post + case reply + case reason + case feedContext + } + } + + /// A definition model for a reply reference. + /// + /// - SeeAlso: This is based on the [`app.bsky.feed.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/defs.json + public struct ReplyReferenceDefinition: Codable { + + /// The original post of the thread. + public let root: ATUnion.ReplyReferenceRootUnion + + // TODO: Fix up the note's message. + /// The direct post that the user's post is replying to. + /// + /// - Note: If `parent` and `root` are identical, the post is a direct reply to the + /// original post of the thread. + public let parent: ATUnion.ReplyReferenceParentUnion + + /// The author of the parent's post. + /// + /// - Note: According to the AT Protocol specifications: "When parent is a reply to another + /// post, this is the author of that post." + public let grandparentAuthor: AppBskyLexicon.Actor.ProfileViewBasicDefinition + } + + /// A definition model for a very stripped down version of a repost. + /// + /// - SeeAlso: This is based on the [`app.bsky.feed.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/defs.json + public struct ReasonRepostDefinition: Codable { + + /// The basic details of the user who reposted the post. + public let by: AppBskyLexicon.Actor.ProfileViewBasicDefinition + + /// The last time the repost was indexed. + @DateFormatting public var indexedAt: Date + + public init(by: AppBskyLexicon.Actor.ProfileViewBasicDefinition, indexedAt: Date) { + self.by = by + self._indexedAt = DateFormatting(wrappedValue: indexedAt) + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.by = try container.decode(AppBskyLexicon.Actor.ProfileViewBasicDefinition.self, forKey: .by) + self.indexedAt = try container.decode(DateFormatting.self, forKey: .indexedAt).wrappedValue + } + + enum CodingKeys: CodingKey { + case by + case indexedAt + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.by, forKey: .by) + try container.encode(self._indexedAt, forKey: .indexedAt) + } + } + + /// A definition model for a hydrated version of a repost. + /// + /// - SeeAlso: This is based on the [`app.bsky.feed.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/defs.json + public struct ThreadViewPostDefinition: Codable { + + /// The post contained in a thread. + public let post: PostViewDefinition + + /// The direct post that the user's post is replying to. Optional. + public let parent: ATUnion.ThreadViewPostParentUnion? + + /// An array of posts of various types. Optional. + public var replies: [ATUnion.ThreadViewPostRepliesUnion]? + } + + /// A definition model for a post that may not have been found. + /// + /// - SeeAlso: This is based on the [`app.bsky.feed.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/defs.json + public struct NotFoundPostDefinition: Codable { + + /// The URI of the post. + public let feedURI: String + + /// Indicates whether the post wasn't found. Defaults to `true`. + public private(set) var isNotFound: Bool + + public init(feedURI: String, isNotFound: Bool = true) { + self.feedURI = feedURI + self.isNotFound = isNotFound + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + feedURI = try container.decode(String.self, forKey: .feedURI) + isNotFound = (try? container.decodeIfPresent(Bool.self, forKey: .isNotFound)) ?? true + } + + enum CodingKeys: String, CodingKey { + case feedURI = "uri" + case isNotFound = "notFound" + } + } + + /// A definition model for a post that may have been blocked. + /// + /// - SeeAlso: This is based on the [`app.bsky.feed.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/defs.json + public struct BlockedPostDefinition: Codable { + + /// The URI of the post. + public let feedURI: String + + /// Indicates whether this post has been blocked from the user. Defaults to `true`. + public private(set) var isBlocked: Bool = true + + /// The author of the post. + public let author: BlockedAuthorDefinition + + public init(feedURI: String, isBlocked: Bool = true, author: BlockedAuthorDefinition) { + self.feedURI = feedURI + self.isBlocked = isBlocked + self.author = author + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.feedURI = try container.decode(String.self, forKey: .feedURI) + self.isBlocked = (try? container.decode(Bool.self, forKey: .isBlocked)) ?? true + self.author = try container.decode(BlockedAuthorDefinition.self, forKey: .author) + } + + enum CodingKeys: String, CodingKey { + case feedURI = "uri" + case isBlocked = "blocked" + case author + } + } + + /// A definition model for a blocked author. + /// + /// - SeeAlso: This is based on the [`app.bsky.feed.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/defs.json + public struct BlockedAuthorDefinition: Codable { + + /// The URI of the author. + public let authorDID: String + + /// The viewer state of the user. Optional. + public var viewer: AppBskyLexicon.Actor.ViewerStateDefinition? + + enum CodingKeys: String, CodingKey { + case authorDID = "did" + case viewer + } + } + + /// A definition model for a feed geneator. + /// + /// - SeeAlso: This is based on the [`app.bsky.feed.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/defs.json + public struct GeneratorViewDefinition: Codable { + + /// The URI of the feed generator. + public let feedURI: String + + /// The CID of the feed generator. + public let cidHash: String + + /// The decentralized identifier (DID) of the feed generator. + public let feedDID: String + + /// The author of the feed generator. + public let creator: AppBskyLexicon.Actor.ProfileViewDefinition + + /// The display name of the feed generator. + public let displayName: String + + /// The description of the feed generator. Optional. + public var description: String? + + /// An array of the facets within the feed generator's description. + public let descriptionFacets: [AppBskyLexicon.RichText.Facet]? + + /// The avatar image URL of the feed generator. + public var avatarImageURL: URL? + + /// The number of likes for the feed generator. + public var likeCount: Int? + + /// Indicates whether the feed generator can accept interactions. + /// + /// - Note: According to the AT Protocol specifications: "Context that will be passed + /// through to client and may be passed to feed generator back alongside interactions." + public let canAcceptInteractions: Bool? + + /// An array of labels. Optional. + public let labels: [ComAtprotoLexicon.Label.LabelDefinition]? + + /// The viewer's state for the feed generator. + public var viewer: GeneratorViewerStateDefinition? + + /// The last time the feed generator was indexed. + @DateFormatting public var indexedAt: Date + + public init(feedURI: String, cidHash: String, feedDID: String, creator: AppBskyLexicon.Actor.ProfileViewDefinition, displayName: String, + description: String?, descriptionFacets: [AppBskyLexicon.RichText.Facet]?, avatarImageURL: URL?, likeCount: Int?, + canAcceptInteractions: Bool?, labels: [ComAtprotoLexicon.Label.LabelDefinition]?, + viewer: GeneratorViewerStateDefinition?, indexedAt: Date) { + self.feedURI = feedURI + self.cidHash = cidHash + self.feedDID = feedDID + self.creator = creator + self.displayName = displayName + self.description = description + self.descriptionFacets = descriptionFacets + self.avatarImageURL = avatarImageURL + self.likeCount = likeCount + self.canAcceptInteractions = canAcceptInteractions + self.labels = labels + self.viewer = viewer + self._indexedAt = DateFormatting(wrappedValue: indexedAt) + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.feedURI = try container.decode(String.self, forKey: .feedURI) + self.cidHash = try container.decode(String.self, forKey: .cidHash) + self.feedDID = try container.decode(String.self, forKey: .feedDID) + self.creator = try container.decode(AppBskyLexicon.Actor.ProfileViewDefinition.self, forKey: .creator) + self.displayName = try container.decode(String.self, forKey: .displayName) + self.description = try container.decodeIfPresent(String.self, forKey: .description) + self.descriptionFacets = try container.decodeIfPresent([AppBskyLexicon.RichText.Facet].self, forKey: .descriptionFacets) + self.avatarImageURL = try container.decodeIfPresent(URL.self, forKey: .avatarImageURL) + self.likeCount = try container.decodeIfPresent(Int.self, forKey: .likeCount) + self.canAcceptInteractions = try container.decodeIfPresent(Bool.self, forKey: .canAcceptInteractions) + self.labels = try container.decodeIfPresent([ComAtprotoLexicon.Label.LabelDefinition].self, forKey: .labels) + self.viewer = try container.decodeIfPresent(GeneratorViewerStateDefinition.self, forKey: .viewer) + self.indexedAt = try container.decode(DateFormatting.self, forKey: .indexedAt).wrappedValue + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.feedURI, forKey: .feedURI) + try container.encode(self.cidHash, forKey: .cidHash) + try container.encode(self.feedDID, forKey: .feedDID) + try container.encode(self.creator, forKey: .creator) + try container.encode(self.displayName, forKey: .displayName) + + // Truncate `description` to 3000 characters before encoding + // `maxGraphemes`'s limit is 300, but `String.count` should respect that limit + try truncatedEncodeIfPresent(self.description, withContainer: &container, forKey: .description, upToLength: 3000) + + try container.encodeIfPresent(self.descriptionFacets, forKey: .descriptionFacets) + try container.encodeIfPresent(self.avatarImageURL, forKey: .avatarImageURL) + + // Assuming `likeCount` is not nil, only encode it if it's 0 or higher + if let likeCount = self.likeCount, likeCount >= 0 { + try container.encode(likeCount, forKey: .likeCount) + } + try container.encodeIfPresent(self.canAcceptInteractions, forKey: .canAcceptInteractions) + try container.encodeIfPresent(self.labels, forKey: .labels) + try container.encodeIfPresent(self.viewer, forKey: .viewer) + try container.encode(self._indexedAt, forKey: .indexedAt) + } + + enum CodingKeys: String, CodingKey { + case feedURI = "uri" + case cidHash = "cid" + case feedDID = "did" + case creator + case displayName + case description + case descriptionFacets = "descriptionFacets" + case avatarImageURL = "avatar" + case likeCount + case canAcceptInteractions = "acceptsInteractions" + case labels + case viewer + case indexedAt + } + } + + /// A definition model for the viewer's state of the feed generator. + /// + /// - SeeAlso: This is based on the [`app.bsky.feed.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/defs.json + public struct GeneratorViewerStateDefinition: Codable { + + /// The URI of the viewer's like, if they liked the feed generator. Optional. + public var likeURI: String? + + enum CodingKeys: String, CodingKey { + case likeURI = "like" + } + } + + /// A definition model for a feed's skeleton. + /// + /// - SeeAlso: This is based on the [`app.bsky.feed.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/defs.json + public struct SkeletonFeedPostDefinition: Codable { + + /// The URI of the post in the feed generator. + /// + /// - Note: This refers to the original post's URI. If the post is a repost, then `reason` + /// will contain a value. + public let postURI: String + + /// The indication that the post was a repost. Optional. + public var reason: ATUnion.SkeletonReasonRepostUnion? + + enum CodingKeys: String, CodingKey { + case postURI = "post" + case reason + } + } + + /// A definition model for a repost in a feed generator. + /// + /// - SeeAlso: This is based on the [`app.bsky.feed.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/defs.json + public struct SkeletonReasonRepostDefinition: Codable { + + /// The URI of the repost. + /// + /// This property uniquely identifies the repost itself, separate from the original post's URI. + public let repostURI: String + + enum CodingKeys: String, CodingKey { + case repostURI = "repost" + } + } + + /// A definition model for a feed threadgate view. + /// + /// - SeeAlso: This is based on the [`app.bsky.feed.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/defs.json + public struct ThreadgateViewDefinition: Codable { + + /// The URI of the feed's threadgate. + public let threadgateURI: String + + /// The CID of the feed's threadgate. + public let cidHash: String + + /// The record of the feed's threadgate + public let record: UnknownType + + // TODO: Make sure this is correct. + /// An array of user lists. + public let lists: [AppBskyLexicon.Graph.ListViewBasicDefinition] + + enum CodingKeys: String, CodingKey { + case threadgateURI = "uri" + case cidHash = "cid" + case record = "record" + case lists = "lists" + } + } + + /// A definition model for an interaction for an item in a feed generator. + /// + /// - SeeAlso: This is based on the [`app.bsky.feed.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/defs.json + public struct InteractionDefinition: Codable { + + /// The item itself. Optional. + public let item: String? + + /// The interaction event of the feed generator. Optional. + public let event: Event? + + /// The feed generator's context. Optional. + /// + /// - Note: According to the AT Protocol specifications: "Context on a feed item that was + /// orginally supplied by the feed generator on getFeedSkeleton." + public let feedContext: String? + + public init(item: String, event: Event, feedContext: String) { + self.item = item + self.event = event + self.feedContext = feedContext + } + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.item = try container.decode(String.self, forKey: .item) + self.event = try container.decode(Event.self, forKey: .event) + self.feedContext = try container.decode(String.self, forKey: .feedContext) + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.item, forKey: .item) + try container.encode(self.event, forKey: .event) + // Truncate `description` to 2000 characters before encoding + // `maxGraphemes`'s limit is 300, but `String.count` should respect that limit + try truncatedEncodeIfPresent(self.feedContext, withContainer: &container, forKey: .feedContext, upToLength: 2000) + } + + enum CodingKeys: CodingKey { + case item + case event + case feedContext + } + + // Enums + /// A definition model for an interaction event. + /// + /// - SeeAlso: This is based on the [`app.bsky.feed.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/defs.json + public enum Event: Codable { + + /// Indicates the feed generator should request less content similar to the feed's item. + /// + /// - Note: According to the AT Protocol specifications: "Request that less content like the + /// given feed item be shown in the feed." + case requestLess + + /// Indicates the feed generator should request more content similar to the feed's item. + /// + /// - Note: According to the AT Protocol specifications: "Request that more content like the + /// given feed item be shown in the feed." + case requestMore + + /// Indicates the feed generator clicked on the feed's item. + /// + /// - Note: According to the AT Protocol specifications: "User clicked through to the + /// feed item." + case clickthroughItem + + /// Indicates the user clicked on the author of the feed's item. + /// + /// - Note: According to the AT Protocol specifications: "User clicked through to the author + /// of the feed item." + case clickthroughAuthor + + /// Indicates the user clicked on the reposter of the feed's item. + /// + /// - Note: According to the AT Protocol specifications: "User clicked through to the reposter + /// of the feed item." + case clickthroughReposter + + /// Indicates the user clicked on the embedded content of the feed's item. + /// + /// - Note: According to the AT Protocol specifications: "User clicked through to the embedded + /// content of the feed item." + case clickthroughEmbed + + /// Indicates the user has viewed the item in the feed. + /// + /// - Note: According to the AT Protocol specifications: "Feed item was seen by user." + case interactionSeen + + /// Indicates the user has liked the item of the feed. + /// + /// - Note: According to the AT Protocol specifications: "User liked the feed item." + case interactionLike + + /// Indicates the user has reposted the item of the feed. + /// + /// - Note: According to the AT Protocol specifications: "User reposted the feed item." + case interactionRepost + + /// Indicates the user has replied to the item of the feed. + /// + /// - Note: According to the AT Protocol specifications: "User replied to the feed item." + case interactionReply + + /// Indicates the user has quote posted the feed's item. + /// + /// - Note: According to the AT Protocol specifications: "User quoted the feed item." + case interactionQuote + + /// Indicates the user has shared the feed's item. + /// + /// - Note: According to the AT Protocol specifications: "User shared the feed item." + case interactionShare + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedDescribeFeedGenerator.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedDescribeFeedGenerator.swift new file mode 100644 index 0000000000..36df009bf2 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedDescribeFeedGenerator.swift @@ -0,0 +1,60 @@ +// +// AppBskyFeedDescribeFeedGenerator.swift +// +// +// Created by Christopher Jr Riley on 2024-05-18. +// + +import Foundation + +extension AppBskyLexicon.Feed { + + /// A definition model for the output ofretrieving information about a feed generator. + /// + /// - Note: According to the AT Protocol specifications: "Get information about a + /// feed generator, including policies and offered feed URIs. Does not require auth; + /// implemented by Feed Generator services (not App View)." + /// + /// - SeeAlso: This is based on the [`app.bsky.feed.describeFeedGenerator`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/describeFeedGenerator.json + public struct DescribeFeedGeneratorOutput: Codable { + + /// The decentralized identifier (DID) of the feed generator. + public let atDID: String + + /// An array of feed generators. + public let feeds: [Feed] + + /// The URL of the Privacy Policy and Terms of Service. Optional. + public let links: Links? + + enum CodingKeys: String, CodingKey { + case atDID = "did" + case feeds + case links + } + + // Enums + /// A data model definiion for the feed generator. + public struct Feed: Codable { + + /// The URI of the feed. + public let feedURI: String + + enum CodingKeys: String, CodingKey { + case feedURI = "uri" + } + } + + /// A data model definition for the Privacy Policy and Terms of Service URLs. + public struct Links: Codable { + + /// The URL to the Privacy Policy. + public let privacyPolicy: URL + + /// The URL to the Terms of Service. + public let termsOfService: URL + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGenerator.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGenerator.swift new file mode 100644 index 0000000000..16c32a814e --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGenerator.swift @@ -0,0 +1,115 @@ +// +// AppBskyFeedGenerator.swift +// +// +// Created by Christopher Jr Riley on 2024-05-18. +// + +import Foundation + +extension AppBskyLexicon.Feed { + + /// A record model for a feed generator record. + /// + /// - Note: According to the AT Protocol specifications: "Record declaring of the existence of + /// a feed generator, and containing metadata about it. The record can exist in + /// any repository." + /// + /// - SeeAlso: This is based on the [`app.bsky.feed.generator`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/generator.json + public struct GeneratorRecord: ATRecordProtocol { + + /// The identifier of the lexicon. + /// + /// - Warning: The value must not change. + public static private(set) var type: String = "app.bsky.feed.generator" + + /// The decentralized identifier (DID) of the feed. + public let feedDID: String + + /// The display name of the feed. + /// + /// - Important: Current maximum lenth is 24 characters. This library will automatically + /// truncate the `String` to the maximum length if it does go over the limit. + public let displayName: String + + /// The description of the feed. Optional. + /// + /// - Important: Current maximum lenth is 300 characters. This library will automatically + /// truncate the `String` to the maximum length if it does go over the limit. + public let description: String? + + /// An array of the facets within the feed generator's description. Optional. + public let descriptionFacets: [AppBskyLexicon.RichText.Facet]? + + /// The URL of the avatar image. Optional. + public let avatarImageURL: URL? + + /// Indicates whether the feed generator can accept interactions. + /// + /// - Note: According to the AT Protocol specifications: "Declaration that a feed accepts + /// feedback interactions from a client through `app.bsky.feed.sendInteractions`" + public let canAcceptInteractions: Bool? + + /// An array of labels created by the user. Optional. + public let labels: ATUnion.GeneratorLabelsUnion? + + /// The date and time the feed was created. + @DateFormatting public var createdAt: Date + + public init(feedDID: String, displayName: String, description: String?, descriptionFacets: [AppBskyLexicon.RichText.Facet]?, avatarImageURL: URL?, + canAcceptInteractions: Bool?, labels: ATUnion.GeneratorLabelsUnion?, createdAt: Date) { + self.feedDID = feedDID + self.displayName = displayName + self.description = description + self.descriptionFacets = descriptionFacets + self.avatarImageURL = avatarImageURL + self.canAcceptInteractions = canAcceptInteractions + self.labels = labels + self._createdAt = DateFormatting(wrappedValue: createdAt) + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.feedDID = try container.decode(String.self, forKey: .feedDID) + self.displayName = try container.decode(String.self, forKey: .displayName) + self.description = try container.decodeIfPresent(String.self, forKey: .description) + self.descriptionFacets = try container.decodeIfPresent([AppBskyLexicon.RichText.Facet].self, forKey: .descriptionFacets) + self.avatarImageURL = try container.decodeIfPresent(URL.self, forKey: .avatarImageURL) + self.canAcceptInteractions = try container.decodeIfPresent(Bool.self, forKey: .canAcceptInteractions) + self.labels = try container.decodeIfPresent(ATUnion.GeneratorLabelsUnion.self, forKey: .labels) + self.createdAt = try container.decode(DateFormatting.self, forKey: .createdAt).wrappedValue + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.feedDID, forKey: .feedDID) + // Truncate `displayName` to 240 characters before encoding + // `maxGraphemes`'s limit is 24, but `String.count` should respect that limit implictly + try truncatedEncode(self.displayName, withContainer: &container, forKey: .description, upToLength: 240) + // Truncate `displayName` to 3,000 characters before encoding + // `maxGraphemes`'s limit is 300, but `String.count` should respect that limit implictly + try truncatedEncodeIfPresent(self.description, withContainer: &container, forKey: .description, upToLength: 3_000) + try container.encodeIfPresent(self.descriptionFacets, forKey: .descriptionFacets) + try container.encodeIfPresent(self.avatarImageURL, forKey: .avatarImageURL) + try container.encodeIfPresent(self.canAcceptInteractions, forKey: .canAcceptInteractions) + try container.encodeIfPresent(self.labels, forKey: .labels) + try container.encode(self._createdAt, forKey: .createdAt) + } + + enum CodingKeys: String, CodingKey { + case type = "$type" + case feedDID = "did" + case displayName + case description + case descriptionFacets + case avatarImageURL = "avatar" + case canAcceptInteractions = "acceptsInteractions" + case labels + case createdAt + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGetActorFeeds.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGetActorFeeds.swift new file mode 100644 index 0000000000..1b6a4bae40 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGetActorFeeds.swift @@ -0,0 +1,28 @@ +// +// AppBskyFeedGetActorFeeds.swift +// +// +// Created by Christopher Jr Riley on 2024-05-18. +// + +import Foundation + +extension AppBskyLexicon.Feed { + + /// An output model for the output of retrieving a feed list by a user. + /// + /// - Note: According to the AT Protocol specifications: "Get a list of feeds (feed generator + /// records) created by the actor (in the actor's repo)." + /// + /// - SeeAlso: This is based on the [`app.bsky.feed.getActorFeeds`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/getActorFeeds.json + public struct GetActorFeedsOutput: Codable { + + /// The mark used to indicate the starting point for the next set of results. Optional. + public let cursor: String? + + /// An array of feeds. + public let feeds: [GeneratorViewDefinition] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGetActorLikes.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGetActorLikes.swift new file mode 100644 index 0000000000..168f9af593 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGetActorLikes.swift @@ -0,0 +1,28 @@ +// +// AppBskyFeedGetActorLikes.swift +// +// +// Created by Christopher Jr Riley on 2024-05-18. +// + +import Foundation + +extension AppBskyLexicon.Feed { + + /// An output model for seeing all of a user account's likes. + /// + /// - Note: According to the AT Protocol specifications: "Get a list of posts liked by an actor. + /// Does not require auth." + /// + /// - SeeAlso: This is based on the [`app.bsky.feed.getActorLikes`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/getActorLikes.json + public struct GetActorLikesOutput: Codable { + + /// The mark used to indicate the starting point for the next set of result. Optional. + public let cursor: String? + + /// An array of like records. + public let feed: [AppBskyLexicon.Feed.FeedViewPostDefinition] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGetAuthorFeed.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGetAuthorFeed.swift new file mode 100644 index 0000000000..d766325229 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGetAuthorFeed.swift @@ -0,0 +1,51 @@ +// +// AppBskyFeedGetAuthorFeed.swift +// +// +// Created by Christopher Jr Riley on 2024-05-18. +// + +import Foundation + +extension AppBskyLexicon.Feed { + + /// The main data model seeing the user account's posts and reposts. + public struct GetAuthorFeed: Codable { + + /// Indicates the kind of combinations of posts and reposts for the feed's array. + /// + /// - Note: According to the AT Protocol specifications: "Combinations of post/repost types to + /// include in response." + public enum Filter: String { + + /// Indicates the array of feeds will contain posts with replies. + case postsWithReplies = "posts_with_replies" + + /// Indicates the array of feeds will contain posts with no replies. + case postsWithNoReplies = "posts_no_replies" + + /// Indicates the array of feeds will contain posts with media. + case postsWithMedia = "posts_with_media" + + /// Indicates the array of feeds will contain posts that are threads. + case postAndAuthorThreads = "posts_and_author_threads" + } + } + + /// An output model for seeing the user account's posts and reposts. + /// + /// - Note: According to the AT Protocol specifications: "Get a view of an actor's + /// 'author feed' (post and reposts by the author). Does not require auth." + /// + /// - SeeAlso: This is based on the [`app.bsky.feed.getAuthorFeed`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/getAuthorFeed.json + public struct GetAuthorFeedOutput: Codable { + + /// The mark used to indicate the starting point for the next set of result. Optional. + public let cursor: String? + + /// An array of like records. + public let feed: [FeedViewPostDefinition] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGetFeed.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGetFeed.swift new file mode 100644 index 0000000000..6d83f1c326 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGetFeed.swift @@ -0,0 +1,28 @@ +// +// AppBskyFeedGetFeed.swift +// +// +// Created by Christopher Jr Riley on 2024-05-18. +// + +import Foundation + +extension AppBskyLexicon.Feed { + + /// An output model for viewing the selected feed generator. + /// + /// - Note: According to the AT Protocol specifications: "Get a hydrated feed from an actor's + /// selected feed generator. Implemented by App View." + /// + /// - SeeAlso: This is based on the [`app.bsky.feed.getFeed`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/getFeed.json + public struct GetFeedOutput: Codable { + + /// The mark used to indicate the starting point for the next set of result. Optional. + public let cursor: String? + + /// An array of posts in the feed. + public let feed: [ViewerStateDefinition] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGetFeedGenerator.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGetFeedGenerator.swift new file mode 100644 index 0000000000..751fe2bbb9 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGetFeedGenerator.swift @@ -0,0 +1,37 @@ +// +// AppBskyFeedGetFeedGenerator.swift +// +// +// Created by Christopher Jr Riley on 2024-05-18. +// + +import Foundation + +extension AppBskyLexicon.Feed { + + /// An output model for getting information about a given feed generator. + /// + /// - Note: According to the AT Protocol specifications: "Get information about a feed + /// generator. Implemented by AppView." + /// + /// - SeeAlso: This is based on the [`app.bsky.feed.getFeedGenerator`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/getFeedGenerator.json + public struct GetFeedGeneratorOutput: Codable { + + /// The general information about the feed generator. + public let view: GeneratorViewDefinition + + /// Indicates whether the feed generator is currently online. + /// + /// - Note: According to the AT Protocol specifications: "Indicates whether the + /// feed generator service has been online recently, or else seems to be inactive." + public let isOnline: Bool + + /// Indicates whether the feed generator is compatible with the record declaration. + /// + /// - Note: According to the AT Protocol specifications: "Indicates whether the + /// feed generator service is compatible with the record declaration." + public let isValid: Bool + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGetFeedGenerators.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGetFeedGenerators.swift new file mode 100644 index 0000000000..0c97c502a3 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGetFeedGenerators.swift @@ -0,0 +1,25 @@ +// +// AppBskyFeedGetFeedGenerators.swift +// +// +// Created by Christopher Jr Riley on 2024-05-18. +// + +import Foundation + +extension AppBskyLexicon.Feed { + + /// An output model for getting information about several feed generators. + /// + /// - Note: According to the AT Protocol specifications: "Get information about a list of + /// feed generators." + /// + /// - SeeAlso: This is based on the [`app.bsky.feed.getFeedGenerators`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/getFeedGenerator.json + public struct GetFeedGeneratorsOutput: Codable { + + /// An array of feed generators. + public let feeds: [GeneratorViewDefinition] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGetFeedSkeleton.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGetFeedSkeleton.swift new file mode 100644 index 0000000000..a914ca1988 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGetFeedSkeleton.swift @@ -0,0 +1,29 @@ +// +// AppBskyFeedGetFeedSkeleton.swift +// +// +// Created by Christopher Jr Riley on 2024-05-18. +// + +import Foundation + +extension AppBskyLexicon.Feed { + + /// An output model for getting a skeleton for a feed generator. + /// + /// - Note: According to the AT Protocol specifications: "Get a skeleton of a feed provided + /// by a feed generator. Auth is optional, depending on provider requirements, and provides the + /// DID of the requester. Implemented by Feed Generator Service." + /// + /// - SeeAlso: This is based on the [`app.bsky.feed.getFeedSkeleton`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/getFeedSkeleton.json + public struct GetFeedSkeletonOutput: Codable { + + /// The mark used to indicate the starting point for the next set of result. Optional. + public let cursor: String? + + /// An array of skeleton feeds. + public let feed: [SkeletonFeedPostDefinition] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGetLikes.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGetLikes.swift new file mode 100644 index 0000000000..6800a239c5 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGetLikes.swift @@ -0,0 +1,85 @@ +// +// AppBskyFeedGetLikes.swift +// +// +// Created by Christopher Jr Riley on 2024-05-18. +// + +import Foundation + +extension AppBskyLexicon.Feed { + + /// An output model for etrieving like records of a specific subject. + /// + /// - Note: According to the AT Protocol specifications: "Get like records which reference a + /// subject (by AT-URI and CID)." + /// + /// - SeeAlso: This is based on the [`app.bsky.feed.getLikes`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/getLikes.json + public struct GetLikesOutput: Codable { + + /// The URI of the record. + public let recordURI: String + + /// The CID hash of the record. + public let recordCID: String? + + /// The mark used to indicate the starting point for the next set of results. + public let cursor: String? + + /// An array of like records. + public let likes: [Like] + + enum CodingKeys: String, CodingKey { + case recordURI = "uri" + case recordCID = "cid" + case cursor + case likes + } + + // Enums + /// A data model definition of the like record itself. + /// + /// - SeeAlso: This is based on the [`app.bsky.feed.getLikes`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/getLikes.json + public struct Like: Codable { + + /// The date and time the like record was indexed. + @DateFormatting public var indexedAt: Date + + /// The date and time the like record was created. + @DateFormatting public var createdAt: Date + + /// The user that created the like record. + public let actor: AppBskyLexicon.Actor.ProfileViewDefinition + + public init(indexedAt: Date, createdAt: Date, actor: AppBskyLexicon.Actor.ProfileViewDefinition) { + self._indexedAt = DateFormatting(wrappedValue: indexedAt) + self._createdAt = DateFormatting(wrappedValue: createdAt) + self.actor = actor + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + self.indexedAt = try container.decode(DateFormatting.self, forKey: .indexedAt).wrappedValue + self.createdAt = try container.decode(DateFormatting.self, forKey: .createdAt).wrappedValue + self.actor = try container.decode(AppBskyLexicon.Actor.ProfileViewDefinition.self, forKey: .actor) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(self._indexedAt, forKey: .indexedAt) + try container.encode(self._createdAt, forKey: .createdAt) + try container.encode(self.actor, forKey: .actor) + } + + public enum CodingKeys: CodingKey { + case indexedAt + case createdAt + case actor + } + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGetListFeed.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGetListFeed.swift new file mode 100644 index 0000000000..20c09d86c8 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGetListFeed.swift @@ -0,0 +1,28 @@ +// +// AppBskyFeedGetListFeed.swift +// +// +// Created by Christopher Jr Riley on 2024-05-18. +// + +import Foundation + +extension AppBskyLexicon.Feed { + + /// An output model for retireving recent posts and reposts from a given feed. + /// + /// - Note: According to the AT Protocol specifications: "Get a feed of recent posts from a + /// list (posts and reposts from any actors on the list). Does not require auth." + /// + /// - SeeAlso: This is based on the [`app.bsky.feed.getListFeed`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/getListFeed.json + public struct GetListFeedOutput: Codable { + + /// The mark used to indicate the starting point for the next set of results. Optional. + public let cursor: String? + + /// An array of posts in a feed. + public let feed: [FeedViewPostDefinition] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGetPostThread.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGetPostThread.swift new file mode 100644 index 0000000000..ab659aa927 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGetPostThread.swift @@ -0,0 +1,25 @@ +// +// AppBskyFeedGetPostThread.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Feed { + + /// An output model for retrieving a post thread. + /// + /// - Note: According to the AT Protocol specifications: "Get posts in a thread. Does not require + /// auth, but additional metadata and filtering will be applied for authed requests." + /// + /// - SeeAlso: This is based on the [`app.bsky.feed.getPostThread`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/getPostThread.json + public struct GetPostThreadOutput: Codable { + + /// The post thread itself. + public let thread: ATUnion.GetPostThreadOutputThreadUnion + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGetPosts.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGetPosts.swift new file mode 100644 index 0000000000..2df466ef6e --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGetPosts.swift @@ -0,0 +1,26 @@ +// +// AppBskyFeedGetPosts.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Feed { + + /// An output model for getting a hydrated array of posts. + /// + /// - Note: According to the AT Protocol specifications: "Gets post views for a specified list + /// of posts (by AT-URI). This is sometimes referred to as 'hydrating' + /// a 'feed skeleton'." + /// + /// - SeeAlso: This is based on the [`app.bsky.feed.getPosts`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/getPosts.json + public struct GetPostsOutput: Codable { + + /// An array of hydrated posts. + public let posts: [PostViewDefinition] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGetRepostedBy.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGetRepostedBy.swift new file mode 100644 index 0000000000..dfec95b13b --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGetRepostedBy.swift @@ -0,0 +1,41 @@ +// +// AppBskyFeedGetRepostedBy.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Feed { + + /// An output model for retrieving an array of users who have reposted the given post. + /// + /// - Note: According to the AT Protocol specifications: "Get a list of reposts for a + /// given post." + /// + /// - SeeAlso: This is based on the [`app.bsky.feed.getRepostedBy`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/getRepostedBy.json + public struct GetRepostedByOutput: Codable { + + /// The URI of the post record. + public let postURI: String + + /// The CID hash of the post record. + public let postCID: String? + + /// The mark used to indicate the starting point for the next set of results. Optional. + public let cursor: String? + + /// An array of user accounts who reported the post record. + public let repostedBy: [AppBskyLexicon.Actor.ProfileViewDefinition] + + enum CodingKeys:String, CodingKey { + case postURI = "uri" + case postCID = "cid" + case cursor + case repostedBy + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGetSuggestedFeeds.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGetSuggestedFeeds.swift new file mode 100644 index 0000000000..2869496481 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGetSuggestedFeeds.swift @@ -0,0 +1,28 @@ +// +// AppBskyFeedGetSuggestedFeeds.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Feed { + + /// An output model for getting a list of feed generators suggested for the user account. + /// + /// - Note: According to the AT Protocol specifications: "Get a list of suggested feeds + /// (feed generators) for the requesting account." + /// + /// - SeeAlso: This is based on the [`app.bsky.feed.getSuggestedFeeds`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/getSuggestedFeeds.json + public struct GetSuggestedFeedsOutput: Codable { + + /// The mark used to indicate the starting point for the next set of result. Optional. + public let cursor: String? + + /// An array of feed generators. + public let feeds: [GeneratorViewDefinition] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGetTimeline.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGetTimeline.swift new file mode 100644 index 0000000000..a0b7cdfdae --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedGetTimeline.swift @@ -0,0 +1,28 @@ +// +// AppBskyFeedGetTimeline.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Feed { + + /// An output model for getting the user account's timeline. + /// + /// - Note: According to the AT Protocol specifications: "Get a view of the requesting account's + /// home timeline. This is expected to be some form of reverse-chronological feed." + /// + /// - SeeAlso: This is based on the [`app.bsky.feed.getTimeline`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/getTimeline.json + public struct GetTimelineOutput: Codable { + + /// The mark used to indicate the starting point for the next set of results. Optional. + public let cursor: String? + + /// An array of post records. + public let feed: [FeedViewPostDefinition] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedLike.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedLike.swift new file mode 100644 index 0000000000..3f0a13f7bc --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedLike.swift @@ -0,0 +1,63 @@ +// +// AppBskyFeedLike.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Feed { + + /// The record model definition for a like record. + /// + /// - Note: According to the AT Protocol specifications: "Record declaring a 'like' of a piece + /// of subject content." + /// + /// - SeeAlso: This is based on the [`app.bsky.feed.like`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/like.json + public struct LikeRecord: ATRecordProtocol { + + /// The identifier of the lexicon. + /// + /// - Warning: The value must not change. + public static private(set) var type: String = "app.bsky.feed.like" + + /// The strong reference of the like. + /// + /// - Note: According to the AT Protocol specifications: "Record declaring a 'like' of a + /// piece of subject content." + public let subject: ComAtprotoLexicon.Repository.StrongReference + + /// The date the like record was created. + /// + /// This is the date where the user "liked" a post. + @DateFormatting public var createdAt: Date + + public init(subject: ComAtprotoLexicon.Repository.StrongReference, createdAt: Date) { + self.subject = subject + self._createdAt = DateFormatting(wrappedValue: createdAt) + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.subject = try container.decode(ComAtprotoLexicon.Repository.StrongReference.self, forKey: .subject) + self.createdAt = try container.decode(DateFormatting.self, forKey: .createdAt).wrappedValue + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.subject, forKey: .subject) + try container.encode(self._createdAt, forKey: .createdAt) + } + + enum CodingKeys: String, CodingKey { + case type = "$type" + case subject + case createdAt + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedPost.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedPost.swift new file mode 100644 index 0000000000..fbeb5cdff0 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedPost.swift @@ -0,0 +1,158 @@ +// +// AppBskyFeedPost.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Feed { + + /// The record model definition for a post record. + /// + /// - Note: According to the AT Protocol specifications: "Record containing a Bluesky post." + /// + /// - SeeAlso: This is based on the [`app.bsky.feed.post`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/post.json + public struct PostRecord: ATRecordProtocol { + + /// The identifier of the lexicon. + /// + /// - Warning: The value must not change. + public static private(set) var type: String = "app.bsky.feed.post" + + /// The text contained in the post. + /// + /// - Note: According to the AT Protocol specifications: "The primary post content. May be + /// an empty string, if there are embeds." + /// + /// - Important: Current maximum length is 300 characters. This library will automatically + /// truncate the `String` to the maximum length if it does go over the limit. + public let text: String + + /// An array of facets contained in the post's text. Optional. + /// + /// - Note: According to the AT Protocol specifications: "Annotations of text (mentions, URLs, + /// hashtags, etc)" + public var facets: [AppBskyLexicon.RichText.Facet]? + + /// The references to posts when replying. Optional. + public var reply: ReplyReference? + + /// The embed of the post. Optional. + public var embed: ATUnion.PostEmbedUnion? + + /// An array of languages the post text contains. Optional. + /// + /// - Note: According to the AT Protocol specifications: "Indicates human language of post + /// primary text content." + /// + /// - Important: Current maximum length is 3 languages. This library will automatically + /// truncate the `Array` to the maximum number of items if it does go over the limit. + public var languages: [String]? + + /// An array of user-defined labels. Optional. + /// + /// - Note: According to the AT Protocol specifications: "Self-label values for this post. + /// Effectively content warnings." + public var labels: ATUnion.PostSelfLabelsUnion? + + /// An array of user-defined tags. Optional. + /// + /// - Note: According to the AT Protocol specifications: "Additional hashtags, in addition to + /// any included in post text and facets." + /// + /// - Important: Current maximum length is 8 tags. Current maximum length of the tag name + /// is 64 characters. This library will automatically truncate the `Array`and `String` + /// respectively to the maximum length if it does go over the limit. + public var tags: [String]? + + /// The date the post was created. + /// + /// - Note: According to the AT Protocol specifications: "Client-declared timestamp when this + /// post was originally created." + @DateFormatting public var createdAt: Date + + public init(text: String, facets: [AppBskyLexicon.RichText.Facet]?, reply: ReplyReference?, embed: ATUnion.PostEmbedUnion?, languages: [String]?, + labels: ATUnion.PostSelfLabelsUnion?, tags: [String]?, createdAt: Date) { + self.text = text + self.facets = facets + self.reply = reply + self.embed = embed + self.languages = languages + self.labels = labels + self.tags = tags + self._createdAt = DateFormatting(wrappedValue: createdAt) + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.text = try container.decode(String.self, forKey: .text) + self.facets = try container.decodeIfPresent([AppBskyLexicon.RichText.Facet].self, forKey: .facets) + self.reply = try container.decodeIfPresent(ReplyReference.self, forKey: .reply) + self.embed = try container.decodeIfPresent(ATUnion.PostEmbedUnion.self, forKey: .embed) + self.languages = try container.decodeIfPresent([String].self, forKey: .languages) + self.labels = try container.decodeIfPresent(ATUnion.PostSelfLabelsUnion.self, forKey: .labels) + self.tags = try container.decodeIfPresent([String].self, forKey: .tags) + self.createdAt = try container.decode(DateFormatting.self, forKey: .createdAt).wrappedValue + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.text, forKey: .text) + // Truncate `tags` to 3000 characters before encoding + // `maxGraphemes`'s limit is 300, but `String.count` should respect that limit implictly + try truncatedEncode(self.text, withContainer: &container, forKey: .text, upToLength: 300) + try container.encodeIfPresent(self.facets, forKey: .facets) + try container.encodeIfPresent(self.reply, forKey: .reply) + try container.encodeIfPresent(self.embed, forKey: .embed) + // Truncate `langs` to 3 items before encoding. + try truncatedEncodeIfPresent(self.languages, withContainer: &container, forKey: .languages, upToLength: 3) + try container.encodeIfPresent(self.labels, forKey: .labels) + + // Truncate `tags` to 640 characters before encoding + // `maxGraphemes`'s limit is 64, but `String.count` should respect that limit implictly + // Then, truncate `tags` to 8 items before encoding + try truncatedEncodeIfPresent( + self.tags.map { $0.truncated(toLength: 640) }, + withContainer: &container, forKey: .tags, upToLength: 8) + + try container.encode(self._createdAt, forKey: .createdAt) + } + + enum CodingKeys: String, CodingKey { + case type = "$type" + case text + case entities + case facets + case reply + case embed + case languages = "langs" + case labels + case tags + case createdAt + } + + // Enums + /// A data model for a reply reference definition. + /// + /// - SeeAlso: This is based on the [`app.bsky.feed.post`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/post.json + public struct ReplyReference: Codable { + + /// The original post of the thread. + public let root: ComAtprotoLexicon.Repository.StrongReference + + /// The direct post that the user's post is replying to. + /// + /// - Note: If `parent` and `root` are identical, the post is a direct reply to the original + /// post of the thread. + public let parent: ComAtprotoLexicon.Repository.StrongReference + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedRepost.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedRepost.swift new file mode 100644 index 0000000000..7738d55758 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedRepost.swift @@ -0,0 +1,60 @@ +// +// AppBskyFeedRepost.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Feed { + + /// The record model definition for a repost record on Bluesky. + /// + /// - Note: According to the AT Protocol specifications: "Record representing a 'repost' of an + /// existing Bluesky post." + /// + /// - SeeAlso: This is based on the [`app.bsky.feed.repost`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/repost.json + public struct RepostRecord: ATRecordProtocol { + + /// The identifier of the lexicon. + /// + /// - Warning: The value must not change. + public static private(set) var type: String = "app.bsky.feed.repost" + + /// The strong reference of the repost record. + public let subject: ComAtprotoLexicon.Repository.StrongReference + + /// The date the like record was created. + /// + /// This is the date where the user "liked" a post. + @DateFormatting public var createdAt: Date + + public init(subject: ComAtprotoLexicon.Repository.StrongReference, createdAt: Date) { + self.subject = subject + self._createdAt = DateFormatting(wrappedValue: createdAt) + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.subject = try container.decode(ComAtprotoLexicon.Repository.StrongReference.self, forKey: .subject) + self.createdAt = try container.decode(DateFormatting.self, forKey: .createdAt).wrappedValue + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.subject, forKey: .subject) + try container.encode(self._createdAt, forKey: .createdAt) + } + + enum CodingKeys: String, CodingKey { + case type = "$type" + case subject + case createdAt + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedSearchPosts.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedSearchPosts.swift new file mode 100644 index 0000000000..58e8dfe9b4 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedSearchPosts.swift @@ -0,0 +1,58 @@ +// +// AppBskyFeedSearchPosts.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Feed { + + /// The main data model definition for the results of the post search query. + public struct SearchPosts: Codable { + + /// Determines the ranking order for the search results. + /// + /// - Note: According to the AT Protocol specifications: "Specifies the ranking order + /// of results." + /// + /// - SeeAlso: This is based on the [`app.bsky.feed.searchPosts`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/searchPosts.json + public enum SortRanking: String { + + /// Indicates the results will be sorted by the top posts. + case top + + /// Indicates the results will be sorted by the latest posts. + case latest + } + } + + /// An output model for the results of the post search query. + /// + /// - Note: According to the AT Protocol specifications: "Find posts matching search criteria, + /// returning views of those posts." + /// + /// - SeeAlso: This is based on the [`app.bsky.feed.searchPosts`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/searchPosts.json + public struct SearchPostsOutput: Codable { + + /// The mark used to indicate the starting point for the next set of results. Optional. + /// + /// - Note: According to the AT Protocol specifications: "Optional pagination mechanism; + /// may not necessarily allow scrolling through entire result set." + public let cursor: String? + + /// The number of times the query appears. Optional. + /// + /// - Note: According to the AT Protocol specifications: "Count of search hits. Optional, + /// may be rounded/truncated, and may not be possible to paginate through all hits." + public let hitsTotal: Int? + + /// An array of post records in the results. + public let posts: [PostViewDefinition] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedSendInteractions.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedSendInteractions.swift new file mode 100644 index 0000000000..d8b98d4b54 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedSendInteractions.swift @@ -0,0 +1,32 @@ +// +// AppBskyFeedSendInteractions.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Feed { + + /// The request body model definition for sending interactions to a feed generator. + /// + /// - Note: According to the AT Protocol specifications: "end information about interactions with + /// feed items back to the feed generator that served them." + /// + /// - SeeAlso: This is based on the [`app.bsky.feed.sendInteractions`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/sendInteractions.json + public struct SendInteractionsRequestBody: Codable { + + /// An array of interactions. + public let interactions: [InteractionDefinition] + } + + /// An output model for sending interactions to a feed generator. + /// + /// - SeeAlso: This is based on the [`app.bsky.feed.sendInteractions`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/sendInteractions.json + public struct SendInteractionsOutput: Codable {} +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedThreadgate.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedThreadgate.swift new file mode 100644 index 0000000000..a2042fd95a --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/AppBskyFeedThreadgate.swift @@ -0,0 +1,90 @@ +// +// AppBskyFeedThreadgate.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Feed { + + /// A record model for a threadgate. + /// + /// - Note: According to the AT Protocol specifications: "Record defining interaction gating rules + /// for a thread (aka, reply controls). The record key (rkey) of the threadgate record must match + /// the record key of the thread's root post, and that record must be in the same repository." + /// + /// - SeeAlso: This is based on the [`app.bsky.feed.threadgate`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/threadgate.json + public struct ThreadgateRecord: ATRecordProtocol { + + /// The identifier of the lexicon. + /// + /// - Warning: The value must not change. + public static private(set) var type: String = "app.bsky.feed.threadgate" + + /// The URI of a post record. + /// + /// - Note: According to the AT Protocol specifications: "Reference (AT-URI) to the + /// post record." + public let post: String + + /// An array of rules used as an allowlist. + public let allow: [ATUnion.ThreadgateUnion] + + /// The date and time of the creation of the threadgate. + @DateFormatting public var createdAt: Date + + public init(post: String, allow: [ATUnion.ThreadgateUnion], createdAt: Date) { + self.post = post + self.allow = allow + self._createdAt = DateFormatting(wrappedValue: createdAt) + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.post = try container.decode(String.self, forKey: .post) + self.allow = try container.decode([ATUnion.ThreadgateUnion].self, forKey: .allow) + self.createdAt = try container.decode(DateFormatting.self, forKey: .createdAt).wrappedValue + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.post, forKey: .post) + try container.encode(self.allow, forKey: .allow) + try container.encode(self._createdAt, forKey: .createdAt) + } + + enum CodingKeys: String, CodingKey { + case type = "$type" + case post + case allow + case createdAt + } + + /// A rule that indicates whether users that the post author mentions can reply to the post. + /// + /// - Note: According to the AT Protocol specifications: "Allow replies from actors mentioned + /// in your post." + public struct MentionRule: Codable {} + + /// A rule that indicates whether users that the post author is following can reply to the post. + /// + /// - Note: According to the AT Protocol specifications: "Allow replies from actors you follow." + public struct FollowingRule: Codable {} + + /// A rule that indicates whether users that are on a specific list made by the post author can + /// reply to the post. + /// + /// - Note: According to the AT Protocol specifications: "Allow replies from actors on a list." + public struct ListRule: Codable { + + /// The list itself. + public let list: String + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedDefs.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedDefs.swift deleted file mode 100644 index 2cc524dff3..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedDefs.swift +++ /dev/null @@ -1,770 +0,0 @@ -// -// BskyFeedDefs.swift -// -// -// Created by Christopher Jr Riley on 2024-01-25. -// - -import Foundation - -/// A data model for a post view definition. -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/defs.json -public struct FeedPostView: Codable { - /// The URI of the post. - public let postURI: String - /// The CID of the post. - public let cidHash: String - /// The author of the post. This will give the basic details of the post author. - public let author: ActorProfileViewBasic - /// The record data itself. - public let record: FeedPost - /// An embed view of a specific type. Optional. - public var embed: EmbedViewUnion? = nil - /// The number of replies in the post. Optional. - public var replyCount: Int? = nil - /// The number of reposts in the post. Optional. - public var repostCount: Int? = nil - /// The number of likes in the post. Optional. - public var likeCount: Int? = nil - /// The last time the post has been indexed. - @DateFormatting public var indexedAt: Date - /// The viewer's interaction with the post. Optional. - public var viewer: FeedViewerState? = nil - /// An array of labels attached to the post. Optional. - public var labels: [Label]? = nil - /// The ruleset of who can reply to the post. Optional. - public var threadgate: FeedThreadgateView? = nil - - public init(postURI: String, cidHash: String, author: ActorProfileViewBasic, record: FeedPost, embed: EmbedViewUnion?, replyCount: Int?, - repostCount: Int?, likeCount: Int?, indexedAt: Date, viewer: FeedViewerState?, labels: [Label]?, threadgate: FeedThreadgateView?) { - self.postURI = postURI - self.cidHash = cidHash - self.author = author - self.record = record - self.embed = embed - self.replyCount = replyCount - self.repostCount = repostCount - self.likeCount = likeCount - self._indexedAt = DateFormatting(wrappedValue: indexedAt) - self.viewer = viewer - self.labels = labels - self.threadgate = threadgate - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.postURI = try container.decode(String.self, forKey: .postURI) - self.cidHash = try container.decode(String.self, forKey: .cidHash) - self.author = try container.decode(ActorProfileViewBasic.self, forKey: .author) - self.record = try container.decode(FeedPost.self, forKey: .record) - self.embed = try container.decodeIfPresent(EmbedViewUnion.self, forKey: .embed) - self.replyCount = try container.decodeIfPresent(Int.self, forKey: .replyCount) - self.repostCount = try container.decodeIfPresent(Int.self, forKey: .repostCount) - self.likeCount = try container.decodeIfPresent(Int.self, forKey: .likeCount) - self.indexedAt = try container.decode(DateFormatting.self, forKey: .indexedAt).wrappedValue - self.viewer = try container.decodeIfPresent(FeedViewerState.self, forKey: .viewer) - self.labels = try container.decodeIfPresent([Label].self, forKey: .labels) - self.threadgate = try container.decodeIfPresent(FeedThreadgateView.self, forKey: .threadgate) - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - try container.encode(self.postURI, forKey: .postURI) - try container.encode(self.cidHash, forKey: .cidHash) - try container.encode(self.author, forKey: .author) - try container.encode(self.record, forKey: .record) - try container.encodeIfPresent(self.embed, forKey: .embed) - try container.encodeIfPresent(self.replyCount, forKey: .replyCount) - try container.encodeIfPresent(self.repostCount, forKey: .repostCount) - try container.encodeIfPresent(self.likeCount, forKey: .likeCount) - try container.encode(self._indexedAt, forKey: .indexedAt) - try container.encodeIfPresent(self.viewer, forKey: .viewer) - try container.encodeIfPresent(self.labels, forKey: .labels) - try container.encodeIfPresent(self.threadgate, forKey: .threadgate) - } - - enum CodingKeys: String, CodingKey { - case postURI = "uri" - case cidHash = "cid" - case author - case record - case embed - case replyCount - case repostCount - case likeCount - case indexedAt - case viewer - case labels - case threadgate - } -} - -/// A data model for a viewer state definition. -/// -/// - Note: According to the AT Protocol specifications: "Metadata about the requesting account's -/// relationship with the subject content. Only has meaningful content for authed requests." -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/defs.json -public struct FeedViewerState: Codable { - /// The URI of the requesting account's repost of the subject account's post. Optional. - public let repostURI: String? = nil - /// The URI of the requesting account's like of the subject account's post. Optional. - public let likeURI: String? = nil - /// Indicates whether the requesting account can reply to the account's post. Optional. - public let areRepliesDisabled: Bool? = nil - - enum CodingKeys: String, CodingKey { - case repostURI = "repost" - case likeURI = "like" - case areRepliesDisabled = "replyDisabled" - } -} - -/// A data model for a definition of a feed's view. -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/defs.json -public struct FeedViewPost: Codable { - /// The post contained in a feed. - public let post: FeedPostView - /// The reply reference for the post, if it's a reply. Optional. - public var reply: FeedReplyReference? = nil - // TODO: Check to see if this is correct. - /// The user who reposted the post. Optional. - public var reason: FeedReasonRepost? = nil - /// The feed generator's context. Optional - /// - /// - Note: According to the AT Protocol specifications: "Context provided by feed generator - /// that may be passed back alongside interactions." - public let feedContext: String? - - public init(post: FeedPostView, reply: FeedReplyReference? = nil, reason: FeedReasonRepost? = nil, feedContext: String?) { - self.post = post - self.reply = reply - self.reason = reason - self.feedContext = feedContext - } - - public init(from decoder: any Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.post = try container.decode(FeedPostView.self, forKey: .post) - self.reply = try container.decodeIfPresent(FeedReplyReference.self, forKey: .reply) - self.reason = try container.decodeIfPresent(FeedReasonRepost.self, forKey: .reason) - self.feedContext = try container.decodeIfPresent(String.self, forKey: .feedContext) - } - - public func encode(to encoder: any Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - try container.encode(self.post, forKey: .post) - try container.encodeIfPresent(self.reply, forKey: .reply) - try container.encodeIfPresent(self.reason, forKey: .reason) - // Truncate `description` to 2000 characters before encoding - // `maxGraphemes`'s limit is 300, but `String.count` should respect that limit - try truncatedEncodeIfPresent(self.feedContext, withContainer: &container, forKey: .feedContext, upToLength: 2000) - } - - public enum CodingKeys: CodingKey { - case post - case reply - case reason - case feedContext - } -} - -/// A data model for a reply reference definition. -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/defs.json -public struct FeedReplyReference: Codable { - /// The original post of the thread. - public let root: PostUnion - // TODO: Fix up the note's message. - /// The direct post that the user's post is replying to. - /// - /// - Note: If `parent` and `root` are identical, the post is a direct reply to the original - /// post of the thread. - public let parent: PostUnion - /// The author of the parent's post. - /// - /// - Note: According to the AT Protocol specifications: "When parent is a reply to another - /// post, this is the author of that post." - public let grandparentAuthor: ActorProfileViewBasic -} - -/// A data model for a definition for a very stripped down version of a repost. -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/defs.json -public struct FeedReasonRepost: Codable { - /// The basic details of the user who reposted the post. - public let by: ActorProfileViewBasic - /// The last time the repost was indexed. - @DateFormatting public var indexedAt: Date - - public init(by: ActorProfileViewBasic, indexedAt: Date) { - self.by = by - self._indexedAt = DateFormatting(wrappedValue: indexedAt) - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.by = try container.decode(ActorProfileViewBasic.self, forKey: .by) - self.indexedAt = try container.decode(DateFormatting.self, forKey: .indexedAt).wrappedValue - } - - enum CodingKeys: CodingKey { - case by - case indexedAt - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - try container.encode(self.by, forKey: .by) - try container.encode(self._indexedAt, forKey: .indexedAt) - } -} - -/// A data model for a definition of a hydrated version of a repost. -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/defs.json -public struct FeedThreadViewPost: Codable { - /// The post contained in a thread. - public let post: FeedPostView - /// The direct post that the user's post is replying to. Optional. - public var parent: ThreadPostUnion? = nil - /// An array of posts of various types. Optional. - public var replies: [ThreadPostUnion]? = nil -} - -/// A data model for a definition of a post that may not have been found. -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/defs.json -public struct FeedNotFoundPost: Codable { - /// The URI of the post. - public let feedURI: String - /// Indicates whether the post wasn't found. Defaults to `true`. - public private(set) var isNotFound: Bool = true - - public init(feedURI: String, isNotFound: Bool = true) { - self.feedURI = feedURI - self.isNotFound = isNotFound - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - feedURI = try container.decode(String.self, forKey: .feedURI) - isNotFound = (try? container.decodeIfPresent(Bool.self, forKey: .isNotFound)) ?? true - } - - enum CodingKeys: String, CodingKey { - case feedURI = "uri" - case isNotFound = "notFound" - } -} - -/// A data model for a definition of a post that may have been blocked. -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/defs.json -public struct FeedBlockedPost: Codable { - /// The URI of the post. - public let feedURI: String - /// Indicates whether this post has been blocked from the user. Defaults to `true`. - public private(set) var isBlocked: Bool = true - /// The author of the post. - public let author: FeedBlockedAuthor - - public init(feedURI: String, isBlocked: Bool = true, author: FeedBlockedAuthor) { - self.feedURI = feedURI - self.isBlocked = isBlocked - self.author = author - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.feedURI = try container.decode(String.self, forKey: .feedURI) - self.isBlocked = (try? container.decode(Bool.self, forKey: .isBlocked)) ?? true - self.author = try container.decode(FeedBlockedAuthor.self, forKey: .author) - } - - enum CodingKeys: String, CodingKey { - case feedURI = "uri" - case isBlocked = "blocked" - case author - } -} - -/// The data model of a blocked author definition. -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/defs.json -public struct FeedBlockedAuthor: Codable { - /// The URI of the author. - public let authorDID: String - /// The viewer state of the user. Optional. - public var viewer: ActorViewerState? = nil - - enum CodingKeys: String, CodingKey { - case authorDID = "did" - case viewer - } -} - -/// The data model of a feed generator definition. -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/defs.json -public struct FeedGeneratorView: Codable { - /// The URI of the feed generator. - public let feedURI: String - /// The CID of the feed generator. - public let cidHash: String - /// The decentralized identifier (DID) of the feed generator. - public let feedDID: String - /// The author of the feed generator. - public let creator: ActorProfileView - /// The display name of the feed generator. - public let displayName: String - /// The description of the feed generator. Optional. - public var description: String? = nil - /// An array of the facets within the feed generator's description. - public let descriptionFacets: [Facet]? - /// The avatar image URL of the feed generator. - public var avatarImageURL: URL? = nil - /// The number of likes for the feed generator. - public var likeCount: Int? = nil - /// Indicates whether the feed generator can accept interactions. - /// - /// - Note: According to the AT Protocol specifications: "Context that will be passed through - /// to client and may be passed to feed generator back alongside interactions." - public let canAcceptInteractions: Bool? - /// An array of labels. Optional. - public let labels: [Label]? - /// The viewer's state for the feed generator. - public var viewer: FeedGeneratorViewerState? = nil - /// The last time the feed generator was indexed. - @DateFormatting public var indexedAt: Date - - public init(feedURI: String, cidHash: String, feedDID: String, creator: ActorProfileView, displayName: String, description: String?, - descriptionFacets: [Facet]?, avatarImageURL: URL?, likeCount: Int?, canAcceptInteractions: Bool?, labels: [Label]?, - viewer: FeedGeneratorViewerState?, indexedAt: Date) { - self.feedURI = feedURI - self.cidHash = cidHash - self.feedDID = feedDID - self.creator = creator - self.displayName = displayName - self.description = description - self.descriptionFacets = descriptionFacets - self.avatarImageURL = avatarImageURL - self.likeCount = likeCount - self.canAcceptInteractions = canAcceptInteractions - self.labels = labels - self.viewer = viewer - self._indexedAt = DateFormatting(wrappedValue: indexedAt) - } - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.feedURI = try container.decode(String.self, forKey: .feedURI) - self.cidHash = try container.decode(String.self, forKey: .cidHash) - self.feedDID = try container.decode(String.self, forKey: .feedDID) - self.creator = try container.decode(ActorProfileView.self, forKey: .creator) - self.displayName = try container.decode(String.self, forKey: .displayName) - self.description = try container.decodeIfPresent(String.self, forKey: .description) - self.descriptionFacets = try container.decodeIfPresent([Facet].self, forKey: .descriptionFacets) - self.avatarImageURL = try container.decodeIfPresent(URL.self, forKey: .avatarImageURL) - self.likeCount = try container.decodeIfPresent(Int.self, forKey: .likeCount) - self.canAcceptInteractions = try container.decodeIfPresent(Bool.self, forKey: .canAcceptInteractions) - self.labels = try container.decodeIfPresent([Label].self, forKey: .labels) - self.viewer = try container.decodeIfPresent(FeedGeneratorViewerState.self, forKey: .viewer) - self.indexedAt = try container.decode(DateFormatting.self, forKey: .indexedAt).wrappedValue - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - try container.encode(self.feedURI, forKey: .feedURI) - try container.encode(self.cidHash, forKey: .cidHash) - try container.encode(self.feedDID, forKey: .feedDID) - try container.encode(self.creator, forKey: .creator) - try container.encode(self.displayName, forKey: .displayName) - - // Truncate `description` to 3000 characters before encoding - // `maxGraphemes`'s limit is 300, but `String.count` should respect that limit - try truncatedEncodeIfPresent(self.description, withContainer: &container, forKey: .description, upToLength: 3000) - - try container.encodeIfPresent(self.descriptionFacets, forKey: .descriptionFacets) - try container.encodeIfPresent(self.avatarImageURL, forKey: .avatarImageURL) - - // Assuming `likeCount` is not nil, only encode it if it's 0 or higher - if let likeCount = self.likeCount, likeCount >= 0 { - try container.encode(likeCount, forKey: .likeCount) - } - try container.encodeIfPresent(self.canAcceptInteractions, forKey: .canAcceptInteractions) - try container.encodeIfPresent(self.labels, forKey: .labels) - try container.encodeIfPresent(self.viewer, forKey: .viewer) - try container.encode(self._indexedAt, forKey: .indexedAt) - } - - enum CodingKeys: String, CodingKey { - case feedURI = "uri" - case cidHash = "cid" - case feedDID = "did" - case creator - case displayName - case description - case descriptionFacets = "descriptionFacets" - case avatarImageURL = "avatar" - case likeCount - case canAcceptInteractions = "acceptsInteractions" - case labels - case viewer - case indexedAt - } -} - -/// The data model of a definition for the viewer's state of the feed generator. -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/defs.json -public struct FeedGeneratorViewerState: Codable { - /// The URI of the viewer's like, if they liked the feed generator. Optional. - public var likeURI: String? = nil - - enum CodingKeys: String, CodingKey { - case likeURI = "like" - } -} - -/// The data model of a feed's skeleton -public struct FeedSkeletonFeedPost: Codable { - /// The URI of the post in the feed generator. - /// - /// - Note: This refers to the original post's URI. If the post is a repost, then `reason` - /// will contain a value. - public let postURI: String - /// The indication that the post was a repost. Optional. - public var reason: FeedSkeletonReasonRepost? = nil - - enum CodingKeys: String, CodingKey { - case postURI = "post" - case reason - } -} - -/// The data model of a definition for a respost in a feed generator. -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/defs.json -public struct FeedSkeletonReasonRepost: Codable { - /// The URI of the repost. - /// - /// This property uniquely identifies the repost itself, separate from the original post's URI. - public let repostURI: String - - enum CodingKeys: String, CodingKey { - case repostURI = "repost" - } -} - -/// The data model of a feed threadgate view definition. -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/defs.json -public struct FeedThreadgateView: Codable { - /// The URI of the feed's threadgate. - public let threadgateURI: String - /// The CID of the feed's threadgate. - public let cidHash: String - /// The record of the feed's threadgate - public let record: UnknownType - // TODO: Make sure this is correct. - /// An array of user lists. - public let lists: [GraphListViewBasic] - - enum CodingKeys: String, CodingKey { - case threadgateURI = "uri" - case cidHash = "cid" - case record = "record" - case lists = "lists" - } -} - -/// The main data model definition for an interaction for an item in a feed generator. -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/defs.json -public struct FeedInteraction: Codable { - /// The item itself. Optional. - public let item: String? - /// The interaction event of the feed generator. Optional. - public let event: FeedInteractionEvent? - /// The feed generator's context. Optional. - /// - /// - Note: According to the AT Protocol specifications: "Context on a feed item that was orginally - /// supplied by the feed generator on getFeedSkeleton." - public let feedContext: String? - - public init(item: String, event: FeedInteractionEvent, feedContext: String) { - self.item = item - self.event = event - self.feedContext = feedContext - } - - public init(from decoder: any Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.item = try container.decode(String.self, forKey: .item) - self.event = try container.decode(FeedInteractionEvent.self, forKey: .event) - self.feedContext = try container.decode(String.self, forKey: .feedContext) - } - - public func encode(to encoder: any Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - try container.encode(self.item, forKey: .item) - try container.encode(self.event, forKey: .event) - // Truncate `description` to 2000 characters before encoding - // `maxGraphemes`'s limit is 300, but `String.count` should respect that limit - try truncatedEncodeIfPresent(self.feedContext, withContainer: &container, forKey: .feedContext, upToLength: 2000) - } - - enum CodingKeys: CodingKey { - case item - case event - case feedContext - } -} - -/// A data model definition for an interaction event. -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/defs.json -public enum FeedInteractionEvent: Codable { - /// Indicates the feed generator should request less content similar to the feed's item. - /// - /// - Note: According to the AT Protocol specifications: "Request that less content like the - /// given feed item be shown in the feed." - case requestLess - /// Indicates the feed generator should request more content similar to the feed's item. - /// - /// - Note: According to the AT Protocol specifications: "Request that more content like the - /// given feed item be shown in the feed." - case requestMore - /// Indicates the feed generator clicked on the feed's item. - /// - /// - Note: According to the AT Protocol specifications: "User clicked through to the - /// feed item." - case clickthroughItem - /// Indicates the user clicked on the author of the feed's item. - /// - /// - Note: According to the AT Protocol specifications: "User clicked through to the author - /// of the feed item." - case clickthroughAuthor - /// Indicates the user clicked on the reposter of the feed's item. - /// - /// - Note: According to the AT Protocol specifications: "User clicked through to the reposter - /// of the feed item." - case clickthroughReposter - /// Indicates the user clicked on the embedded content of the feed's item. - /// - /// - Note: According to the AT Protocol specifications: "User clicked through to the embedded - /// content of the feed item." - case clickthroughEmbed - /// Indicates the user has viewed the item in the feed. - /// - /// - Note: According to the AT Protocol specifications: "Feed item was seen by user." - case interactionSeen - /// Indicates the user has liked the item of the feed. - /// - /// - Note: According to the AT Protocol specifications: "User liked the feed item." - case interactionLike - /// Indicates the user has reposted the item of the feed. - /// - /// - Note: According to the AT Protocol specifications: "User reposted the feed item." - case interactionRepost - /// Indicates the user has replied to the item of the feed. - /// - /// - Note: According to the AT Protocol specifications: "User replied to the feed item." - case interactionReply - /// Indicates the user has quote posted the feed's item. - /// - /// - Note: According to the AT Protocol specifications: "User quoted the feed item." - case interactionQuote - /// Indicates the user has shared the feed's item. - /// - /// - Note: According to the AT Protocol specifications: "User shared the feed item." - case interactionShare -} - -// MARK: - Union Types -/// A reference containing the list of the types of embeds. -/// -/// - Note: This is based on the following lexicons:\ -///\- `app.bsky.embed.record`\ -///\- `app.bsky.feed.defs` -/// -/// - SeeAlso: The lexicons can be viewed in their GitHub repo pages:\ -/// \- [`app.bsky.embed.record`][embed_record]\ -/// \- [`app.bsky.feed.defs`][feed_def] -/// -/// [embed_record]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/embed/record.json -/// [feed_def]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/defs.json -public enum EmbedViewUnion: Codable { - /// The view of an external embed. - case embedExternalView(EmbedExternalView) - /// The view of an image embed. - case embedImagesView(EmbedImagesView) - /// The view of a record embed. - case embedRecordView(EmbedRecordView) - /// The view of a record embed alongside an embed of some compatible media. - case embedRecordWithMediaView(EmbedRecordWithMediaView) - - public init(from decoder: Decoder) throws { - let container = try decoder.singleValueContainer() - - if let value = try? container.decode(EmbedExternalView.self) { - self = .embedExternalView(value) - } else if let value = try? container.decode(EmbedImagesView.self) { - self = .embedImagesView(value) - } else if let value = try? container.decode(EmbedRecordView.self) { - print("EmbedView.embedRecordView is about to be read.") - self = .embedRecordView(value) - } else if let value = try? container.decode(EmbedRecordWithMediaView.self) { - self = .embedRecordWithMediaView(value) - } else { - throw DecodingError.typeMismatch( - EmbedViewUnion.self, DecodingError.Context( - codingPath: decoder.codingPath, debugDescription: "Unknown EmbedView type")) - } - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.singleValueContainer() - - switch self { - case .embedExternalView(let embedView): - try container.encode(embedView) - case .embedImagesView(let embedView): - try container.encode(embedView) - case .embedRecordView(let embedView): - try container.encode(embedView) - case .embedRecordWithMediaView(let embedView): - try container.encode(embedView) - } - } -} - -/// A reference containing the list of the states of a post. -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/defs.json -public enum PostUnion: Codable { - /// The view of a post. - case postView(FeedPostView) - /// The view of a post that may not have been found. - case notFoundPost(FeedNotFoundPost) - /// The view of a post that's been blocked by the post author. - case blockedPost(FeedBlockedPost) - - public init(from decoder: Decoder) throws { - let container = try decoder.singleValueContainer() - - if let value = try? container.decode(FeedPostView.self) { - self = .postView(value) - } else if let value = try? container.decode(FeedNotFoundPost.self) { - self = .notFoundPost(value) - } else if let value = try? container.decode(FeedBlockedPost.self) { - self = .blockedPost(value) - } else { - throw DecodingError.typeMismatch( - PostUnion.self, DecodingError.Context( - codingPath: decoder.codingPath, debugDescription: "Unknown PostUnion type")) - } - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.singleValueContainer() - - switch self { - case .postView(let union): - try container.encode(union) - case .notFoundPost(let union): - try container.encode(union) - case .blockedPost(let union): - try container.encode(union) - } - } -} - -/// A reference containing the list of the states of a post. -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/defs.json -public indirect enum ThreadPostUnion: Codable { - /// The view of a post thread. - case threadViewPost(FeedThreadViewPost) - /// The view of a post that may not have been found. - case notFoundPost(FeedNotFoundPost) - /// The view of a post that's been blocked by the post author. - case blockedPost(FeedBlockedPost) - - public init(from decoder: Decoder) throws { - let container = try decoder.singleValueContainer() - - if let value = try? container.decode(FeedThreadViewPost.self) { - self = .threadViewPost(value) - } else if let value = try? container.decode(FeedNotFoundPost.self) { - self = .notFoundPost(value) - } else if let value = try? container.decode(FeedBlockedPost.self) { - self = .blockedPost(value) - } else { - throw DecodingError.typeMismatch( - ThreadPostUnion.self, DecodingError.Context( - codingPath: decoder.codingPath, debugDescription: "Unknown ThreadPostUnion type")) - } - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.singleValueContainer() - - switch self { - case .threadViewPost(let union): - try container.encode(union) - case .notFoundPost(let union): - try container.encode(union) - case .blockedPost(let union): - try container.encode(union) - } - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedDescribeFeedGenerator.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedDescribeFeedGenerator.swift deleted file mode 100644 index 19e6ae8197..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedDescribeFeedGenerator.swift +++ /dev/null @@ -1,51 +0,0 @@ -// -// BskyFeedDescribeFeedGenerator.swift -// -// -// Created by Christopher Jr Riley on 2024-03-03. -// - -import Foundation - -// TODO: Figure out a proper way of doing this. -/// A data model definition for the output ofretrieving information about a feed generator. -/// -/// - Note: According to the AT Protocol specifications: "Get information about a feed generator, -/// including policies and offered feed URIs. Does not require auth; implemented by -/// Feed Generator services (not App View)." -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.describeFeedGenerator`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/describeFeedGenerator.json -public struct FeedDescribeFeedGeneratorOutput: Codable { - /// The decentralized identifier (DID) of the feed generator. - public let atDID: String - /// An array of feed generators. - public let feeds: [FeedDescribeFeedGeneratorFeed] - /// The URL of the Privacy Policy and Terms of Service. Optional. - public let links: FeedDescribeFeedGeneratorLinks? - - enum CodingKeys: String, CodingKey { - case atDID = "did" - case feeds - case links - } -} - -/// A data model definiion for the feed generator. -public struct FeedDescribeFeedGeneratorFeed: Codable { - /// The URI of the feed. - public let feedURI: String - - enum CodingKeys: String, CodingKey { - case feedURI = "uri" - } -} - -/// A data model definition for the Privacy Policy and Terms of Service URLs. -public struct FeedDescribeFeedGeneratorLinks: Codable { - /// The URL to the Privacy Policy. - public let privacyPolicy: URL - /// The URL to the Terms of Service. - public let termsOfService: URL -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGenerator.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGenerator.swift deleted file mode 100644 index c918c4d5e7..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGenerator.swift +++ /dev/null @@ -1,103 +0,0 @@ -// -// BskyFeedGenerator.swift -// -// -// Created by Christopher Jr Riley on 2024-03-04. -// - -import Foundation - -/// The main data model definition for a feed generator record. -/// -/// - Note: According to the AT Protocol specifications: "Record declaring of the existence of a -/// feed generator, and containing metadata about it. The record can exist in any repository." -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.generator`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/generator.json -public struct FeedGenerator: ATRecordProtocol { - /// The identifier of the lexicon. - /// - /// - Warning: The value must not change. - public static private(set) var type: String = "app.bsky.feed.generator" - /// The decentralized identifier (DID) of the feed. - public let feedDID: String - /// The display name of the feed. - /// - /// - Important: Current maximum lenth is 24 characters. This library will automatically - /// truncate the `String` to the maximum length if it does go over the limit. - public let displayName: String - /// The description of the feed. Optional. - /// - /// - Important: Current maximum lenth is 300 characters. This library will automatically - /// truncate the `String` to the maximum length if it does go over the limit. - public let description: String? - /// An array of the facets within the feed generator's description. Optional. - public let descriptionFacets: [Facet]? - /// The URL of the avatar image. Optional. - public let avatarImageURL: URL? - /// Indicates whether the feed generator can accept interactions. - /// - /// - Note: According to the AT Protocol specifications: "Declaration that a feed accepts - /// feedback interactions from a client through `app.bsky.feed.sendInteractions`" - public let canAcceptInteractions: Bool? - /// An array of labels created by the user. Optional. - public let labels: [SelfLabels]? - /// The date and time the feed was created. - @DateFormatting public var createdAt: Date - - public init(feedDID: String, displayName: String, description: String?, descriptionFacets: [Facet]?, avatarImageURL: URL?, - canAcceptInteractions: Bool?, labels: [SelfLabels]?, createdAt: Date) { - self.feedDID = feedDID - self.displayName = displayName - self.description = description - self.descriptionFacets = descriptionFacets - self.avatarImageURL = avatarImageURL - self.canAcceptInteractions = canAcceptInteractions - self.labels = labels - self._createdAt = DateFormatting(wrappedValue: createdAt) - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.feedDID = try container.decode(String.self, forKey: .feedDID) - self.displayName = try container.decode(String.self, forKey: .displayName) - self.description = try container.decodeIfPresent(String.self, forKey: .description) - self.descriptionFacets = try container.decodeIfPresent([Facet].self, forKey: .descriptionFacets) - self.avatarImageURL = try container.decodeIfPresent(URL.self, forKey: .avatarImageURL) - self.canAcceptInteractions = try container.decodeIfPresent(Bool.self, forKey: .canAcceptInteractions) - self.labels = try container.decodeIfPresent([SelfLabels].self, forKey: .labels) - self.createdAt = try container.decode(DateFormatting.self, forKey: .createdAt).wrappedValue - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - -// try container.encode(self.type, forKey: .type) - try container.encode(self.feedDID, forKey: .feedDID) - // Truncate `displayName` to 240 characters before encoding - // `maxGraphemes`'s limit is 24, but `String.count` should respect that limit implictly - try truncatedEncode(self.displayName, withContainer: &container, forKey: .description, upToLength: 240) - // Truncate `displayName` to 3,000 characters before encoding - // `maxGraphemes`'s limit is 300, but `String.count` should respect that limit implictly - try truncatedEncodeIfPresent(self.description, withContainer: &container, forKey: .description, upToLength: 3_000) - try container.encodeIfPresent(self.descriptionFacets, forKey: .descriptionFacets) - try container.encodeIfPresent(self.avatarImageURL, forKey: .avatarImageURL) - try container.encodeIfPresent(self.canAcceptInteractions, forKey: .canAcceptInteractions) - try container.encodeIfPresent(self.labels, forKey: .labels) - try container.encode(self._createdAt, forKey: .createdAt) - } - - enum CodingKeys: String, CodingKey { - case type = "$type" - case feedDID = "did" - case displayName - case description - case descriptionFacets - case avatarImageURL = "avatar" - case canAcceptInteractions = "acceptsInteractions" - case labels - case createdAt - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGetActorFeeds.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGetActorFeeds.swift deleted file mode 100644 index fcb460efaf..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGetActorFeeds.swift +++ /dev/null @@ -1,23 +0,0 @@ -// -// BskyFeedGetActorFeeds.swift -// -// -// Created by Christopher Jr Riley on 2024-03-04. -// - -import Foundation - -/// The main data model definition for the output of retrieving a feed list by a user. -/// -/// - Note: According to the AT Protocol specifications: "Get a list of feeds (feed generator -/// records) created by the actor (in the actor's repo)." -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.getActorFeeds`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/getActorFeeds.json -public struct FeedGetActorFeedsOutput: Codable { - /// The mark used to indicate the starting point for the next set of results. Optional. - public let cursor: String? - /// An array of feeds. - public let feeds: [FeedGeneratorView] -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGetActorLikes.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGetActorLikes.swift deleted file mode 100644 index 20a972964e..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGetActorLikes.swift +++ /dev/null @@ -1,23 +0,0 @@ -// -// BskyFeedGetActorLikes.swift -// -// -// Created by Christopher Jr Riley on 2024-03-04. -// - -import Foundation - -/// The main data model definition for the output of seeing all of a user account's likes. -/// -/// - Note: According to the AT Protocol specifications: "Get a list of posts liked by an actor. -/// Does not require auth." -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.getActorLikes`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/getActorLikes.json -public struct FeedGetActorLikesOutput: Codable { - /// The mark used to indicate the starting point for the next set of result. Optional. - public let cursor: String? - /// An array of like records. - public let feed: [FeedViewPost] -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGetAuthorFeed.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGetAuthorFeed.swift deleted file mode 100644 index 97b7bf01c5..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGetAuthorFeed.swift +++ /dev/null @@ -1,38 +0,0 @@ -// -// BskyFeedGetAuthorFeed.swift -// -// -// Created by Christopher Jr Riley on 2024-03-04. -// - -import Foundation - -/// The main data model definition for the output of seeing the user account's posts and reposts. -/// -/// - Note: According to the AT Protocol specifications: "Get a view of an actor's 'author feed' -/// (post and reposts by the author). Does not require auth." -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.getAuthorFeed`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/getAuthorFeed.json -public struct FeedGetAuthorFeedOutput: Codable { - /// The mark used to indicate the starting point for the next set of result. Optional. - public let cursor: String? - /// An array of like records. - public let feed: [FeedViewPost] -} - -/// Indicates the kind of combinations of posts and reposts for the feed's array. -/// -/// - Note: According to the AT Protocol specifications: "Combinations of post/repost types to -/// include in response." -public enum FeedGetAuthorFeedFilter: String { - /// Indicates the array of feeds will contain posts with replies. - case postsWithReplies = "posts_with_replies" - /// Indicates the array of feeds will contain posts with no replies. - case postsWithNoReplies = "posts_no_replies" - /// Indicates the array of feeds will contain posts with media. - case postsWithMedia = "posts_with_media" - /// Indicates the array of feeds will contain posts that are threads. - case postAndAuthorThreads = "posts_and_author_threads" -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGetFeed.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGetFeed.swift deleted file mode 100644 index 1ab2e9af9d..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGetFeed.swift +++ /dev/null @@ -1,23 +0,0 @@ -// -// BskyFeedGetFeed.swift -// -// -// Created by Christopher Jr Riley on 2024-03-04. -// - -import Foundation - -/// The main data model definition for the output of viewing the selected feed generator. -/// -/// - Note: According to the AT Protocol specifications: "Get a hydrated feed from an actor's -/// selected feed generator. Implemented by App View." -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.getFeed`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/getFeed.json -public struct FeedGetFeedOutput: Codable { - /// The mark used to indicate the starting point for the next set of result. Optional. - public let cursor: String? - /// An array of posts in the feed. - public let feed: [FeedViewPost] -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGetFeedGenerator.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGetFeedGenerator.swift deleted file mode 100644 index b187d1dfef..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGetFeedGenerator.swift +++ /dev/null @@ -1,33 +0,0 @@ -// -// BskyFeedGetFeedGenerator.swift -// -// -// Created by Christopher Jr Riley on 2024-03-04. -// - -import Foundation - -/// The main data model definition for the output of getting information about a given -/// feed generator. -/// -/// - Note: According to the AT Protocol specifications: "Get information about a feed -/// generator. Implemented by AppView." -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.getFeedGenerator`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/getFeedGenerator.json -public struct FeedGetFeedGeneratorOutput: Codable { - /// The general information about the feed generator.. - public let view: FeedGeneratorView - /// Indicates whether the feed generator is currently online. - /// - /// - Note: According to the AT Protocol specifications: "Indicates whether the feed generator - /// service has been online recently, or else seems to be inactive." - public let isOnline: Bool - /// Indicates whether the feed generator is compatible with the record declaration. - /// - /// - Note: According to the AT Protocol specifications: "Indicates whether the feed generator - /// service is compatible with the record declaration." - public let isValid: Bool - -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGetFeedGenerators.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGetFeedGenerators.swift deleted file mode 100644 index 753d9fc137..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGetFeedGenerators.swift +++ /dev/null @@ -1,22 +0,0 @@ -// -// BskyFeedGetFeedGenerators.swift -// -// -// Created by Christopher Jr Riley on 2024-03-04. -// - -import Foundation - -/// The main data model definition for the output of getting information about several -/// feed generators. -/// -/// - Note: According to the AT Protocol specifications: "Get information about a list of -/// feed generators." -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.getFeedGenerators`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/getFeedGenerator.json -public struct FeedGetFeedGeneratorsOutput: Codable { - /// An array of feed generators. - public let feeds: [FeedGeneratorView] -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGetFeedSkeleton.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGetFeedSkeleton.swift deleted file mode 100644 index 2fd9f2bea1..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGetFeedSkeleton.swift +++ /dev/null @@ -1,24 +0,0 @@ -// -// BskyFeedGetFeedSkeleton.swift -// -// -// Created by Christopher Jr Riley on 2024-03-04. -// - -import Foundation - -/// The main data model definition for the output of getting a skeleton for a feed generator. -/// -/// - Note: According to the AT Protocol specifications: "Get a skeleton of a feed provided by a -/// feed generator. Auth is optional, depending on provider requirements, and provides the DID of -/// the requester. Implemented by Feed Generator Service." -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.getFeedSkeleton`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/getFeedSkeleton.json -public struct FeedGetFeedSkeletonOutput: Codable { - /// The mark used to indicate the starting point for the next set of result. Optional. - public let cursor: String? - /// An array of skeleton feeds. - public let feed: [FeedSkeletonFeedPost] -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGetLikes.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGetLikes.swift deleted file mode 100644 index ce7b0ed677..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGetLikes.swift +++ /dev/null @@ -1,70 +0,0 @@ -// -// BskyFeedGetLikes.swift -// -// -// Created by Christopher Jr Riley on 2024-03-04. -// - -import Foundation - -/// The main data model definition for the output of retrieving like records of a specific subject. -/// -/// - Note: According to the AT Protocol specifications: "Get like records which reference a -/// subject (by AT-URI and CID)." -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.getLikes`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/getLikes.json -public struct FeedGetLikesOutput: Codable { - /// The URI of the record. - public let recordURI: String - /// The CID hash of the record. - public let recordCID: String? - /// The mark used to indicate the starting point for the next set of results. - public let cursor: String? - /// An array of like records. - public let likes: [FeedGetLikesLike] - - enum CodingKeys: String, CodingKey { - case recordURI = "uri" - case recordCID = "cid" - case cursor - case likes - } -} - -/// A data model definition of the like record itself. -public struct FeedGetLikesLike: Codable { - /// The date and time the like record was indexed. - @DateFormatting public var indexedAt: Date - /// The date and time the like record was created. - @DateFormatting public var createdAt: Date - /// The user that created the like record. - public let actor: ActorProfileView - - public init(indexedAt: Date, createdAt: Date, actor: ActorProfileView) { - self._indexedAt = DateFormatting(wrappedValue: indexedAt) - self._createdAt = DateFormatting(wrappedValue: createdAt) - self.actor = actor - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - self.indexedAt = try container.decode(DateFormatting.self, forKey: .indexedAt).wrappedValue - self.createdAt = try container.decode(DateFormatting.self, forKey: .createdAt).wrappedValue - self.actor = try container.decode(ActorProfileView.self, forKey: .actor) - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(self._indexedAt, forKey: .indexedAt) - try container.encode(self._createdAt, forKey: .createdAt) - try container.encode(self.actor, forKey: .actor) - } - - public enum CodingKeys: CodingKey { - case indexedAt - case createdAt - case actor - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGetListFeed.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGetListFeed.swift deleted file mode 100644 index 9be4a42bf5..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGetListFeed.swift +++ /dev/null @@ -1,25 +0,0 @@ -// -// BskyFeedGetListFeed.swift -// -// -// Created by Christopher Jr Riley on 2024-03-06. -// - -import Foundation - -/// The main data model definition for the output of retireving recent posts and reposts from a -/// given feed. -/// -/// - Note: According to the AT Protocol specifications: "Get a feed of recent posts from a list -/// (posts and reposts from any actors on the list). -/// Does not require auth." -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.getListFeed`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/getListFeed.json -public struct FeedGetListFeedOutput: Codable { - /// The mark used to indicate the starting point for the next set of results. Optional. - public let cursor: String? - /// An array of posts in a feed. - public let feed: [FeedViewPost] -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGetPostThread.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGetPostThread.swift deleted file mode 100644 index 746489f8be..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGetPostThread.swift +++ /dev/null @@ -1,60 +0,0 @@ -// -// BskyFeedGetPostThread.swift -// -// -// Created by Christopher Jr Riley on 2024-03-05. -// - -import Foundation - -/// The main data model definition for the output of retrieving a post thread. -/// -/// - Note: According to the AT Protocol specifications: "Get posts in a thread. Does not require -/// auth, but additional metadata and filtering will be applied for authed requests." -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.getPostThread`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/getPostThread.json -public struct FeedGetPostThreadOutput: Codable { - /// The post thread itself. - public let thread: FeedGetPostThreadUnion -} - -/// A reference containing the list of the state of a post thread. -public enum FeedGetPostThreadUnion: Codable { - /// A post thread. - case threadViewPost(FeedThreadViewPost) - /// The post thread wasn't found. - case notFoundPost(FeedNotFoundPost) - /// The post thread was made by someone who blocked the user account. - case blockedPost(FeedBlockedPost) - - public init(from decoder: Decoder) throws { - let container = try decoder.singleValueContainer() - - if let value = try? container.decode(FeedThreadViewPost.self) { - self = .threadViewPost(value) - } else if let value = try? container.decode(FeedNotFoundPost.self) { - self = .notFoundPost(value) - } else if let value = try? container.decode(FeedBlockedPost.self) { - self = .blockedPost(value) - } else { - throw DecodingError.typeMismatch( - FeedGetPostThreadUnion.self, DecodingError.Context( - codingPath: decoder.codingPath, debugDescription: "Unknown FeedGetPostThread type")) - } - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.singleValueContainer() - - switch self { - case .threadViewPost(let threadViewPost): - try container.encode(threadViewPost) - case .notFoundPost(let notFoundPost): - try container.encode(notFoundPost) - case .blockedPost(let blockedPost): - try container.encode(blockedPost) - } - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGetPosts.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGetPosts.swift deleted file mode 100644 index c7bea1ae24..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGetPosts.swift +++ /dev/null @@ -1,22 +0,0 @@ -// -// BskyFeedGetPosts.swift -// -// -// Created by Christopher Jr Riley on 2024-03-06. -// - -import Foundation - -/// The main data model definition for the output of getting a hydrated array of posts. -/// -/// - Note: According to the AT Protocol specifications: "Gets post views for a specified list -/// of posts (by AT-URI). This is sometimes referred to as 'hydrating' -/// a 'feed skeleton'." -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.getPosts`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/getPosts.json -public struct FeedGetPostsOutput: Codable { - /// An array of hydrated posts. - public let posts: [FeedPostView] -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGetRepostedBy.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGetRepostedBy.swift deleted file mode 100644 index de80d2a2a4..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGetRepostedBy.swift +++ /dev/null @@ -1,34 +0,0 @@ -// -// BskyFeedGetRepostedBy.swift -// -// -// Created by Christopher Jr Riley on 2024-03-06. -// - -import Foundation - -/// The main data model definition for the output of retrieving an array of users who have -/// reposted the given post. -/// -/// - Note: According to the AT Protocol specifications: "Get a list of reposts for a given post." -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.getRepostedBy`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/getRepostedBy.json -public struct FeedGetRepostedBy: Codable { - /// The URI of the post record. - public let postURI: String - /// The CID hash of the post record. - public let postCID: String? - /// The mark used to indicate the starting point for the next set of results. Optional. - public let cursor: String? - /// An array of user accounts who reported the post record. - public let repostedBy: [ActorProfileView] - - enum CodingKeys:String, CodingKey { - case postURI = "uri" - case postCID = "cid" - case cursor - case repostedBy - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGetSuggestedFeeds.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGetSuggestedFeeds.swift deleted file mode 100644 index 9d1db7b0ce..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGetSuggestedFeeds.swift +++ /dev/null @@ -1,24 +0,0 @@ -// -// BskyFeedGetSuggestedFeeds.swift -// -// -// Created by Christopher Jr Riley on 2024-03-06. -// - -import Foundation - -/// The main data model definition for the output of getting a list of feed generators suggested -/// for the user account. -/// -/// - Note: According to the AT Protocol specifications: "Get a list of suggested feeds -/// (feed generators) for the requesting account." -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.getSuggestedFeeds`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/getSuggestedFeeds.json -public struct FeedGetSuggestedFeedsOutput: Codable { - /// The mark used to indicate the starting point for the next set of result. Optional. - public let cursor: String? - /// An array of feed generators. - public let feeds: [FeedGeneratorView] -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGetTimeline.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGetTimeline.swift deleted file mode 100644 index 22b4a6effc..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedGetTimeline.swift +++ /dev/null @@ -1,23 +0,0 @@ -// -// BskyFeedGetTimeline.swift -// -// -// Created by Christopher Jr Riley on 2024-03-06. -// - -import Foundation - -/// The main data model definition for the output of getting the user account's timeline. -/// -/// - Note: According to the AT Protocol specifications: "Get a view of the requesting account's -/// home timeline. This is expected to be some form of reverse-chronological feed." -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.getTimeline`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/getTimeline.json -public struct FeedGetTimelineOutput: Codable { - /// The mark used to indicate the starting point for the next set of results. Optional. - public let cursor: String? - /// An array of post records. - public let feed: [FeedViewPost] -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedLike.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedLike.swift deleted file mode 100644 index 130847abfa..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedLike.swift +++ /dev/null @@ -1,59 +0,0 @@ -// -// BskyFeedLike.swift -// -// -// Created by Christopher Jr Riley on 2024-02-08. -// - -import Foundation - -// MARK: - Main definition -/// The record model definition for a like record. -/// -/// - Note: According to the AT Protocol specifications: "Record declaring a 'like' of a piece -/// of subject content." -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.like`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/like.json -public struct FeedLike: ATRecordProtocol { - /// The identifier of the lexicon. - /// - /// - Warning: The value must not change. - public static private(set) var type: String = "app.bsky.feed.like" - /// The strong reference of the like. - /// - /// - Note: According to the AT Protocol specifications: "Record declaring a 'like' of a piece - /// of subject content." - public let subject: StrongReference - /// The date the like record was created. - /// - /// This is the date where the user "liked" a post. - @DateFormatting public var createdAt: Date - - public init(subject: StrongReference, createdAt: Date) { - self.subject = subject - self._createdAt = DateFormatting(wrappedValue: createdAt) - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.subject = try container.decode(StrongReference.self, forKey: .subject) - self.createdAt = try container.decode(DateFormatting.self, forKey: .createdAt).wrappedValue - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - -// try container.encode(self.type, forKey: .type) - try container.encode(self.subject, forKey: .subject) - try container.encode(self._createdAt, forKey: .createdAt) - } - - enum CodingKeys: String, CodingKey { - case type = "$type" - case subject - case createdAt - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedPost.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedPost.swift deleted file mode 100644 index 5209a53266..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedPost.swift +++ /dev/null @@ -1,250 +0,0 @@ -// -// BskyFeedPost.swift -// -// -// Created by Christopher Jr Riley on 2024-01-27. -// - -import Foundation - -// MARK: - Main definition -/// The record model definition for a post record. -/// -/// - Note: According to the AT Protocol specifications: "Record containing a Bluesky post." -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.post`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/post.json -public struct FeedPost: ATRecordProtocol { - /// The identifier of the lexicon. - /// - /// - Warning: The value must not change. - public static private(set) var type: String = "app.bsky.feed.post" - /// The text contained in the post. - /// - /// - Note: According to the AT Protocol specifications: "The primary post content. May be - /// an empty string, if there are embeds." - /// - /// - Important: Current maximum length is 300 characters. This library will automatically - /// truncate the `String` to the maximum length if it does go over the limit. - public let text: String - /// An array of facets contained in the post's text. Optional. - /// - /// - Note: According to the AT Protocol specifications: "Annotations of text (mentions, URLs, - /// hashtags, etc)" - public var facets: [Facet]? = nil - /// The references to posts when replying. Optional. - public var reply: ReplyReference? = nil - /// The embed of the post. Optional. - public var embed: EmbedUnion? = nil - /// An array of languages the post text contains. Optional. - /// - /// - Note: According to the AT Protocol specifications: "Indicates human language of post - /// primary text content." - /// - /// - Important: Current maximum length is 3 languages. This library will automatically - /// truncate the `Array` to the maximum number of items if it does go over the limit. - public var languages: [String]? = nil - /// An array of user-defined labels. Optional. - /// - /// - Note: According to the AT Protocol specifications: "Self-label values for this post. - /// Effectively content warnings." - public var labels: FeedLabelUnion? = nil - /// An array of user-defined tags. Optional. - /// - /// - Note: According to the AT Protocol specifications: "Additional hashtags, in addition to - /// any included in post text and facets." - /// - /// - Important: Current maximum length is 8 tags. Current maximum length of the tag name is - /// 64 characters. This library will automatically truncate the `Array`and `String` - /// respectively to the maximum length if it does go over the limit. - public var tags: [String]? = nil - /// The date the post was created. - /// - /// - Note: According to the AT Protocol specifications: "Client-declared timestamp when this - /// post was originally created." - @DateFormatting public var createdAt: Date - - public init(text: String, facets: [Facet]? = nil, reply: ReplyReference? = nil, embed: EmbedUnion? = nil, languages: [String]? = nil, - labels: FeedLabelUnion? = nil, tags: [String]? = nil, createdAt: Date) { - self.text = text - self.facets = facets - self.reply = reply - self.embed = embed - self.languages = languages - self.labels = labels - self.tags = tags - self._createdAt = DateFormatting(wrappedValue: createdAt) - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.text = try container.decode(String.self, forKey: .text) - self.facets = try container.decodeIfPresent([Facet].self, forKey: .facets) - self.reply = try container.decodeIfPresent(ReplyReference.self, forKey: .reply) - self.embed = try container.decodeIfPresent(EmbedUnion.self, forKey: .embed) - self.languages = try container.decodeIfPresent([String].self, forKey: .languages) - self.labels = try container.decodeIfPresent(FeedLabelUnion.self, forKey: .labels) - self.tags = try container.decodeIfPresent([String].self, forKey: .tags) - self.createdAt = try container.decode(DateFormatting.self, forKey: .createdAt).wrappedValue - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - -// try container.encode(self.type, forKey: .type) - try container.encode(self.text, forKey: .text) - // Truncate `tags` to 3000 characters before encoding - // `maxGraphemes`'s limit is 300, but `String.count` should respect that limit implictly - try truncatedEncode(self.text, withContainer: &container, forKey: .text, upToLength: 300) - try container.encodeIfPresent(self.facets, forKey: .facets) - try container.encodeIfPresent(self.reply, forKey: .reply) - try container.encodeIfPresent(self.embed, forKey: .embed) - // Truncate `langs` to 3 items before encoding. - try truncatedEncodeIfPresent(self.languages, withContainer: &container, forKey: .languages, upToLength: 3) - try container.encodeIfPresent(self.labels, forKey: .labels) - - // Truncate `tags` to 640 characters before encoding - // `maxGraphemes`'s limit is 64, but `String.count` should respect that limit implictly - // Then, truncate `tags` to 8 items before encoding - try truncatedEncodeIfPresent( - self.tags.map { $0.truncated(toLength: 640) }, - withContainer: &container, forKey: .tags, upToLength: 8) - - try container.encode(self._createdAt, forKey: .createdAt) - } - - enum CodingKeys: String, CodingKey { - case type = "$type" - case text - case entities - case facets - case reply - case embed - case languages = "langs" - case labels - case tags - case createdAt - } -} - -// MARK: - -/// A data model for a reply reference definition. -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.post`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/post.json -public struct ReplyReference: Codable { - /// The original post of the thread. - public let root: StrongReference - /// The direct post that the user's post is replying to. - /// - /// - Note: If `parent` and `root` are identical, the post is a direct reply to the original - /// post of the thread. - public let parent: StrongReference - - public init(root: StrongReference, parent: StrongReference) { - self.root = root - self.parent = parent - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.root = try container.decode(StrongReference.self, forKey: .root) - self.parent = try container.decode(StrongReference.self, forKey: .parent) - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - try container.encode(self.root, forKey: .root) - try container.encode(self.parent, forKey: .parent) - } - - enum CodingKeys: CodingKey { - case root - case parent - } -} - -// MARK: - Union type -/// A reference containing the list of types of embeds. -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.post`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/post.json -public enum EmbedUnion: Codable { - /// An image embed. - case images(EmbedImages) - /// An external embed. - case external(EmbedExternal) - /// A record embed. - case record(EmbedRecord) - /// A embed with both a record and some compatible media. - case recordWithMedia(EmbedRecordWithMedia) - - public init(from decoder: Decoder) throws { - let container = try decoder.singleValueContainer() - - if let imagesValue = try? container.decode(EmbedImages.self) { - self = .images(imagesValue) - } else if let externalValue = try? container.decode(EmbedExternal.self) { - self = .external(externalValue) - } else if let recordValue = try? container.decode(EmbedRecord.self) { - self = .record(recordValue) - } else if let recordWithMediaValue = try? container.decode(EmbedRecordWithMedia.self) { - self = .recordWithMedia(recordWithMediaValue) - } else { - throw DecodingError.typeMismatch( - EmbedUnion.self, DecodingError.Context( - codingPath: decoder.codingPath, debugDescription: "Unknown EmbedUnion type")) - } - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.singleValueContainer() - - switch self { - case .images(let imagesValue): - try container.encode(imagesValue) - case .external(let externalValue): - try container.encode(externalValue) - case .record(let recordValue): - try container.encode(recordValue) - case .recordWithMedia(let recordWithMediaValue): - try container.encode(recordWithMediaValue) - } - } -} - -/// A reference containing the list of user-defined labels. -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.post`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/post.json -public enum FeedLabelUnion: Codable { - /// An array of user-defined labels. - case selfLabels(SelfLabels) - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - let selfLabelsValue = try container.decode(SelfLabels.self, forKey: .selfLabels) - self = .selfLabels(selfLabelsValue) - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.singleValueContainer() - - switch self { - case .selfLabels(let selfLabelsValue): - try container.encode(selfLabelsValue) - } - } - - enum CodingKeys: String, CodingKey { - case selfLabels - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedRepost.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedRepost.swift deleted file mode 100644 index e0d5fde853..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedRepost.swift +++ /dev/null @@ -1,54 +0,0 @@ -// -// BskyFeedRepost.swift -// -// -// Created by Christopher Jr Riley on 2024-03-06. -// - -import Foundation - -/// The record model definition for a repost record on Bluesky. -/// -/// - Note: According to the AT Protocol specifications: "Record representing a 'repost' of an -/// existing Bluesky post." -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.repost`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/repost.json -public struct FeedRepost: ATRecordProtocol { - /// The identifier of the lexicon. - /// - /// - Warning: The value must not change. - public static private(set) var type: String = "app.bsky.feed.repost" - /// The strong reference of the repost record. - public let subject: StrongReference - /// The date the like record was created. - /// - /// This is the date where the user "liked" a post. - @DateFormatting public var createdAt: Date - - public init(subject: StrongReference, createdAt: Date) { - self.subject = subject - self._createdAt = DateFormatting(wrappedValue: createdAt) - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - self.subject = try container.decode(StrongReference.self, forKey: .subject) - self.createdAt = try container.decode(DateFormatting.self, forKey: .createdAt).wrappedValue - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - -// try container.encode(self.type, forKey: .type) - try container.encode(self.subject, forKey: .subject) - try container.encode(self._createdAt, forKey: .createdAt) - } - - enum CodingKeys: String, CodingKey { - case type = "$type" - case subject - case createdAt - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedSearchPosts.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedSearchPosts.swift deleted file mode 100644 index e8ea4a99a7..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedSearchPosts.swift +++ /dev/null @@ -1,43 +0,0 @@ -// -// BskyFeedSearchPosts.swift -// -// -// Created by Christopher Jr Riley on 2024-03-06. -// - -import Foundation - -/// The main data model definition for the output of the results of the post search query. -/// -/// - Note: According to the AT Protocol specifications: "Find posts matching search criteria, -/// returning views of those posts." -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.searchPosts`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/searchPosts.json -public struct FeedSearchPostsOutput: Codable { - /// The mark used to indicate the starting point for the next set of results. Optional. - /// - /// - Note: According to the AT Protocol specifications: "Optional pagination mechanism; - /// may not necessarily allow scrolling through entire result set." - public let cursor: String? - /// The number of times the query appears. Optional. - /// - /// - Note: According to the AT Protocol specifications: "Count of search hits. Optional, - /// may be rounded/truncated, and may not be possible to paginate through all hits." - public let hitsTotal: Int? - /// An array of post records in the results. - public let posts: [FeedPostView] -} - -/// Determines the ranking order for the search results. -/// -/// - Note: According to the AT Protocol specifications: "Specifies the ranking order of results." -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.searchPosts`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/searchPosts.json -public enum FeedSearchPostsSortRanking: String { - case top - case latest -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedSendInteractions.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedSendInteractions.swift deleted file mode 100644 index 6f3bb6343b..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedSendInteractions.swift +++ /dev/null @@ -1,28 +0,0 @@ -// -// BskyFeedSendInteractions.swift -// -// -// Created by Christopher Jr Riley on 2024-04-15. -// - -import Foundation - -/// The request body model definition for sending interactions to a feed generator. -/// -/// - Note: According to the AT Protocol specifications: "end information about interactions with -/// feed items back to the feed generator that served them." -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.sendInteractions`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/sendInteractions.json -public struct FeedSendInteractions: Codable { - /// An array of interactions. - public let interactions: [FeedInteraction] -} - -/// The output model definition for sending interactions to a feed generator. -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.sendInteractions`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/sendInteractions.json -public struct FeedSendInteractionsOutput: Codable {} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedThreadgate.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedThreadgate.swift deleted file mode 100644 index 4d186e4bed..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Feed/BskyFeedThreadgate.swift +++ /dev/null @@ -1,114 +0,0 @@ -// -// BskyFeedThreadgate.swift -// -// -// Created by Christopher Jr Riley on 2024-03-06. -// - -import Foundation - -/// The main data model definition for a threadgate record. -/// -/// - Note: According to the AT Protocol specifications: "Record defining interaction gating rules -/// for a thread (aka, reply controls). The record key (rkey) of the threadgate record must match -/// the record key of the thread's root post, and that record must be in the same repository." -/// -/// - SeeAlso: This is based on the [`app.bsky.feed.threadgate`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/threadgate.json -public struct FeedThreadgate: ATRecordProtocol { - /// The identifier of the lexicon. - /// - /// - Warning: The value must not change. - public static private(set) var type: String = "app.bsky.feed.threadgate" - /// The URI of a post record. - public let post: String - public let allow: [ThreadgateUnion] - @DateFormatting public var createdAt: Date - - public init(post: String, allow: [ThreadgateUnion], createdAt: Date) { - self.post = post - self.allow = allow - self._createdAt = DateFormatting(wrappedValue: createdAt) - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.post = try container.decode(String.self, forKey: .post) - self.allow = try container.decode([ThreadgateUnion].self, forKey: .allow) - self.createdAt = try container.decode(DateFormatting.self, forKey: .createdAt).wrappedValue - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - -// try container.encode(self.type, forKey: .type) - try container.encode(self.post, forKey: .post) - try container.encode(self.allow, forKey: .allow) - try container.encode(self._createdAt, forKey: .createdAt) - } - - enum CodingKeys: String, CodingKey { - case type = "$type" - case post - case allow - case createdAt - } -} - -/// A rule that indicates whether users that the post author mentions can reply to the post. -/// -/// - Note: According to the AT Protocol specifications: "Allow replies from actors mentioned -/// in your post." -public struct FeedThreadgateMentionRule: Codable {} - -/// A rule that indicates whether users that the post author is following can reply to the post. -/// -/// - Note: According to the AT Protocol specifications: "Allow replies from actors you follow." -public struct FeedThreadgateFollowingRule: Codable {} - -/// A rule that indicates whether users that are on a specific list made by the post author can -/// reply to the post. -/// -/// - Note: According to the AT Protocol specifications: "Allow replies from actors on a list." -public struct FeedThreadgateListRule: Codable { - public let list: String -} - - -/// A reference containing the list of thread rules for a post. -public enum ThreadgateUnion: Codable { - case mentionRule(FeedThreadgateMentionRule) - case followingRule(FeedThreadgateFollowingRule) - case listRule(FeedThreadgateListRule) - - public init(from decoder: Decoder) throws { - let container = try decoder.singleValueContainer() - - if let value = try? container.decode(FeedThreadgateMentionRule.self) { - self = .mentionRule(value) - } else if let value = try? container.decode(FeedThreadgateFollowingRule.self) { - self = .followingRule(value) - } else if let value = try? container.decode(FeedThreadgateListRule.self) { - self = .listRule(value) - } else { - throw DecodingError.typeMismatch( - EmbedViewUnion.self, DecodingError.Context( - codingPath: decoder.codingPath, debugDescription: "Unknown ThreadgateUnion type")) - } - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.singleValueContainer() - - switch self { - case .mentionRule(let embedView): - try container.encode(embedView) - case .followingRule(let embedView): - try container.encode(embedView) - case .listRule(let embedView): - try container.encode(embedView) - } - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphBlock.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphBlock.swift new file mode 100644 index 0000000000..7d1e3d57ba --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphBlock.swift @@ -0,0 +1,61 @@ +// +// AppBskyGraphBlock.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Graph { + + /// A record model for a block. + /// + /// - Note: According to the AT Protocol specifications: "Record declaring a 'block' + /// relationship against another account. NOTE: blocks are public in Bluesky; see + /// blog posts for details." + /// + /// - SeeAlso: This is based on the [`app.bsky.graph.block`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/block.json + public struct BlockRecord: ATRecordProtocol { + + /// The identifier of the lexicon. + /// + /// - Warning: The value must not change. + public static private(set) var type: String = "app.bsky.graph.block" + + /// The decentralized identifier(DID) of the subject that has been blocked. + /// + /// - Note: According to the AT Protocol specifications: "DID of the account to be blocked." + public let subjectDID: String + + /// The date and time the block record was created. + @DateFormatting public var createdAt: Date + + public init(subjectDID: String, createdAt: Date) { + self.subjectDID = subjectDID + self._createdAt = DateFormatting(wrappedValue: createdAt) + } + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.subjectDID = try container.decode(String.self, forKey: .subjectDID) + self.createdAt = try container.decode(DateFormatting.self, forKey: .createdAt).wrappedValue + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.subjectDID, forKey: .subjectDID) + try container.encode(self._createdAt, forKey: .createdAt) + } + + enum CodingKeys: String, CodingKey { + case type = "$type" + case subjectDID = "subject" + case createdAt + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphDefs.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphDefs.swift new file mode 100644 index 0000000000..937b718e60 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphDefs.swift @@ -0,0 +1,306 @@ +// +// AppBskyGraphDefs.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Graph { + + /// A definition model for a basic list view. + /// + /// - SeeAlso: This is based on the [`app.bsky.graph.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/defs.json + public struct ListViewBasicDefinition: Codable { + + /// The URI of a user list. + public let actorURI: String + + /// The CID of a user list. + public let cidHash: String + + /// The name of the list. + public let name: String + + /// The purpose of the user list. + /// + /// - Important: Current maximum length is 64 characters. This library will truncate the + /// `String` to the maximum number of characters if it does go over. + public let purpose: ListPurpose + + /// The avatar image URL of the user list. Optional. + public let avatarImageURL: URL? + + /// The viewer's state of the user list. Optional. + public var viewer: ListViewerStateDefinition? + + /// The late time the user list was indexed. + @DateFormattingOptional public var indexedAt: Date? + + public init(actorURI: String, cidHash: String, name: String, purpose: ListPurpose, avatarImageURL: URL?, viewer: ListViewerStateDefinition?, + indexedAt: Date?) { + self.actorURI = actorURI + self.cidHash = cidHash + self.name = name + self.purpose = purpose + self.avatarImageURL = avatarImageURL + self.viewer = viewer + self._indexedAt = DateFormattingOptional(wrappedValue: indexedAt) + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.actorURI = try container.decode(String.self, forKey: .actorURI) + self.cidHash = try container.decode(String.self, forKey: .cidHash) + self.name = try container.decode(String.self, forKey: .name) + self.purpose = try container.decode(ListPurpose.self, forKey: .purpose) + self.avatarImageURL = try container.decodeIfPresent(URL.self, forKey: .avatarImageURL) + self.viewer = try container.decodeIfPresent(ListViewerStateDefinition.self, forKey: .viewer) + self.indexedAt = try container.decodeIfPresent(DateFormattingOptional.self, forKey: .indexedAt)?.wrappedValue + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.actorURI, forKey: .actorURI) + try container.encode(self.cidHash, forKey: .cidHash) + try container.encode(self.name, forKey: .name) + try truncatedEncode(self.name, withContainer: &container, forKey: .name, upToLength: 64) + try container.encode(self.purpose, forKey: .purpose) + try container.encodeIfPresent(self.avatarImageURL, forKey: .avatarImageURL) + try container.encodeIfPresent(self.viewer, forKey: .viewer) + try container.encode(self._indexedAt, forKey: .indexedAt) + } + + enum CodingKeys: String, CodingKey { + case actorURI = "uri" + case cidHash = "cid" + case name = "name" + case purpose = "purpose" + case avatarImageURL = "avatar" + case viewer = "viewer" + case indexedAt + } + } + + /// A definition model for the view of a user list. + /// + /// - SeeAlso: This is based on the [`app.bsky.graph.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/defs.json + public struct ListViewDefinition: Codable { + + /// The URI of the user list. + public let listURI: String + + /// The CID of the user list. + public let cidHash: String + + /// The creator of the user list. + public let creator: AppBskyLexicon.Actor.ProfileViewDefinition + + /// The name of the user list. + /// + /// - Important: Current maximum length is 64 characters. This library will truncate the + /// `String` to the maximum number of characters if it does go over. + public let name: String + + /// The purpose of the user list. + public let purpose: ListPurpose + + /// The description of the user list. Optional. + /// + /// - Important: Current maximum length is 300 characters. This library will truncate the + /// `String` to the maximum number of characters if it does go over. + public var description: String? + + /// An array of facets contained in the post's text. Optional. + public var descriptionFacets: [AppBskyLexicon.RichText.Facet]? + + /// The avatar image URL of the user list. Optional. + public var avatarImageURL: URL? + + /// The viewer's state of the user list. Optional. + public var viewer: ListViewerStateDefinition? + + /// The late time the user list was indexed. + @DateFormatting public var indexedAt: Date + + public init(listURI: String, cidHash: String, creator: AppBskyLexicon.Actor.ProfileViewDefinition, name: String, purpose: ListPurpose, + description: String?, descriptionFacets: [AppBskyLexicon.RichText.Facet]?, avatarImageURL: URL?, + viewer: ListViewerStateDefinition?, indexedAt: Date) { + self.listURI = listURI + self.cidHash = cidHash + self.creator = creator + self.name = name + self.purpose = purpose + self.description = description + self.descriptionFacets = descriptionFacets + self.avatarImageURL = avatarImageURL + self.viewer = viewer + self._indexedAt = DateFormatting(wrappedValue: indexedAt) + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.listURI = try container.decode(String.self, forKey: .listURI) + self.cidHash = try container.decode(String.self, forKey: .cidHash) + self.creator = try container.decode(AppBskyLexicon.Actor.ProfileViewDefinition.self, forKey: .creator) + self.name = try container.decode(String.self, forKey: .name) + self.purpose = try container.decode(ListPurpose.self, forKey: .purpose) + self.description = try container.decodeIfPresent(String.self, forKey: .description) + self.descriptionFacets = try container.decodeIfPresent([AppBskyLexicon.RichText.Facet].self, forKey: .descriptionFacets) + self.avatarImageURL = try container.decodeIfPresent(URL.self, forKey: .avatarImageURL) + self.viewer = try container.decodeIfPresent(ListViewerStateDefinition.self, forKey: .viewer) + self.indexedAt = try container.decode(DateFormatting.self, forKey: .indexedAt).wrappedValue + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.listURI, forKey: .listURI) + try container.encode(self.cidHash, forKey: .cidHash) + try container.encode(self.creator, forKey: .creator) + // Truncate `name` to 64 characters before encoding. + try truncatedEncode(self.name, withContainer: &container, forKey: .name, upToLength: 64) + try container.encode(self.purpose, forKey: .purpose) + + // Truncate `description` to 3000 characters before encoding + // `maxGraphemes`'s limit is 300, but `String.count` should respect that limit + try truncatedEncodeIfPresent(self.description, withContainer: &container, forKey: .description, upToLength: 3000) + try container.encodeIfPresent(self.descriptionFacets, forKey: .descriptionFacets) + try container.encodeIfPresent(self.avatarImageURL, forKey: .avatarImageURL) + try container.encodeIfPresent(self.viewer, forKey: .viewer) + try container.encode(self._indexedAt, forKey: .indexedAt) + } + + enum CodingKeys: String, CodingKey { + case listURI = "uri" + case cidHash = "cid" + case creator = "creator" + case name = "name" + case purpose = "purpose" + case description = "description" + case descriptionFacets = "descriptionFacets" + case avatarImageURL = "avatar" + case viewer = "viewer" + case indexedAt = "indexedAt" + } + } + + /// A definition model for an item with in a user list. + /// + /// - SeeAlso: This is based on the [`app.bsky.graph.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/defs.json + public struct ListItemViewDefinition: Codable { + + /// The URI of the user list item. + public let listItemURI: String + + /// A user in the user list item. + public let subject: AppBskyLexicon.Actor.ProfileViewDefinition + + enum CodingKeys: String, CodingKey { + case listItemURI = "uri" + case subject + } + } + + /// A definition model for the user list's purpose. + /// + /// - SeeAlso: This is based on the [`app.bsky.graph.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/defs.json + public enum ListPurpose: String, Codable { + + /// An array of actors to apply an aggregate moderation action (mute/block) on. + /// + /// - Note: The documentation is taken directly from the lexicon itself. + case modlist = "app.bsky.graph.defs#modlist" + + /// An array of actors used for curation purposes such as list feeds or interaction gating. + /// + /// - Note: The documentation is taken directly from the lexicon itself. + case curatelist = "app.bsky.graph.defs#curatelist" + } + + /// A definition model for a viewer's state of a user list. + /// + /// - SeeAlso: This is based on the [`app.bsky.graph.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/defs.json + public struct ListViewerStateDefinition: Codable { + + /// Indicates whether the user is muted. Optional. + public var isMuted: Bool? + + /// The URI of the block record if the user has blocked the user list. Optional + public var blockedURI: String? + + enum CodingKeys: String, CodingKey { + case isMuted = "muted" + case blockedURI = "blocked" + } + } + + /// A definition model for a user that may not have been found in the user list. + /// + /// - SeeAlso: This is based on the [`app.bsky.graph.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/defs.json + public struct NotFoundActorDefinition: Codable { + + /// The URI of the user. + /// + /// - Note: According to the AT Protocol specifications: "indicates that a handle or DID + /// could not be resolved". + public let actorURI: String + + /// Indicates whether the user is not found. + public let isNotFound: Bool + + enum CodingKeys: String, CodingKey { + case actorURI = "actor" + case isNotFound = "notFound" + } + } + + /// A definition model for a graph relationship between two user accounts. + /// + /// - Note: According to the AT Protocol specifications: "lists the bi-directional graph + /// relationships between one actor (not indicated in the object), and the target actors (the DID + /// included in the object)" + /// + /// - SeeAlso: This is based on the [`app.bsky.graph.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/defs.json + public struct RelationshipDefinition: Codable { + + /// The decentralized identifier (DID) of the target user. + public let actorDID: String + + /// The URI of the follow record, if the first user is following the target user. Optional. + /// + /// - Note: According to the AT Protocol specifications: "if the actor follows this DID, this + /// is the AT-URI of the follow record" + public let followingURI: String? + + /// The URI of the follow record, if the target user is following the first user. Optional. + /// + /// - Note: According to the AT Protocol specifications: "if the actor is followed by this + /// DID, contains the AT-URI of the follow record" + public let followedByURI: String? + + enum CodingKeys: String, CodingKey { + case actorDID = "did" + case followingURI = "following" + case followedByURI = "followedBy" + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphFollow.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphFollow.swift new file mode 100644 index 0000000000..e09788c67a --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphFollow.swift @@ -0,0 +1,57 @@ +// +// AppBskyGraphFollow.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Graph { + + /// A record model for a follow. + /// + /// - Note: According to the AT Protocol specifications: "Record declaring a social 'follow' + /// relationship of another account. Duplicate follows will be ignored by the AppView." + /// + /// - SeeAlso: This is based on the [`app.bsky.graph.follow`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/follow.json + public struct FollowRecord: ATRecordProtocol { + + /// The identifier of the lexicon. + /// + /// - Warning: The value must not change. + public static private(set) var type: String = "app.bsky.graph.follow" + + /// The subject that the user account wants to "follow." + public let subjectDID: String + + /// The date and time the record was created. + @DateFormatting public var createdAt: Date + + public init(subjectDID: String, createdAt: Date) { + self.subjectDID = subjectDID + self._createdAt = DateFormatting(wrappedValue: createdAt) + } + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.subjectDID = try container.decode(String.self, forKey: .subjectDID) + self.createdAt = try container.decode(DateFormatting.self, forKey: .createdAt).wrappedValue + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.subjectDID, forKey: .subjectDID) + try container.encode(self._createdAt, forKey: .createdAt) + } + + enum CodingKeys: String, CodingKey { + case subjectDID = "subject" + case createdAt + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphGetBlocks.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphGetBlocks.swift new file mode 100644 index 0000000000..e6ce463f26 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphGetBlocks.swift @@ -0,0 +1,28 @@ +// +// AppBskyGraphGetBlocks.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Graph { + + /// An output model for getting all of the users that have been blocked by the user account. + /// + /// - Note: According to the AT Protocol specifications: "Enumerates which accounts the + /// requesting account is currently blocking. Requires auth." + /// + /// - SeeAlso: This is based on the [`app.bsky.graph.getBlocks`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/getBlocks.json + public struct GetBlocksOutput: Codable { + + /// The mark used to indicate the starting point for the next set of results. Optional. + public let cursor: String? + + /// An array of profiles that have been blocked by the user account. + public let blocks: [AppBskyLexicon.Actor.ProfileViewDefinition] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphGetFollowers.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphGetFollowers.swift new file mode 100644 index 0000000000..0f3700f682 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphGetFollowers.swift @@ -0,0 +1,31 @@ +// +// AppBskyGraphGetFollowers.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Graph { + + /// An output model for getting all of the user account's followers. + /// + /// - Note: According to the AT Protocol specifications: "Enumerates accounts which follow a + /// specified account (actor)." + /// + /// - SeeAlso: This is based on the [`app.bsky.graph.getFollowers`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/getFollowers.json + public struct GetFollowersOutput: Codable { + + /// The user account itself. + public let subject: AppBskyLexicon.Actor.ProfileViewDefinition + + /// The mark used to indicate the starting point for the next set of results. Optional. + public let cursor: String? + + /// An array of user accounts that follow the user account. + public let followers: [AppBskyLexicon.Actor.ProfileViewDefinition] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphGetFollows.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphGetFollows.swift new file mode 100644 index 0000000000..82f76c7f75 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphGetFollows.swift @@ -0,0 +1,31 @@ +// +// AppBskyGraphGetFollows.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Graph { + + /// An output model for for grabbing all of the accounts the user account follows. + /// + /// - Note: According to the AT Protocol specifications: "Enumerates accounts which a specified + /// account (actor) follows." + /// + /// - SeeAlso: This is based on the [`app.bsky.graph.getFollows`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/getFollows.json + public struct GetFollowsOutput: Codable { + + /// The user account itself. + public let subject: AppBskyLexicon.Actor.ProfileViewDefinition + + /// The mark used to indicate the starting point for the next set of results. Optional. + public let cursor: String? + + /// An array of user accounts that the user account follows. + public let follows: [AppBskyLexicon.Actor.ProfileViewDefinition] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphGetList.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphGetList.swift new file mode 100644 index 0000000000..76403e0f0d --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphGetList.swift @@ -0,0 +1,31 @@ +// +// AppBskyGraphGetList.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Graph { + + /// An output model for grabbing the list view. + /// + /// - Note: According to the AT Protocol specifications: "Gets a 'view' (with additional context) + /// of a specified list." + /// + /// - SeeAlso: This is based on the [`app.bsky.graph.getList`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/getList.json + public struct GetListOutput: Codable { + + /// The mark used to indicate the starting point for the next set of results. Optional. + public let cursor: String? + + /// The metadata of the list. + public let list: ListViewDefinition + + /// An array of list items. + public let items: [ListItemViewDefinition] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphGetListBlocks.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphGetListBlocks.swift new file mode 100644 index 0000000000..71a47f7678 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphGetListBlocks.swift @@ -0,0 +1,28 @@ +// +// AppBskyGraphGetListBlocks.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Graph { + + /// An output model for getting the moderator lists that the user account is blocking. + /// + /// - Note: According to the AT Protocol specifications: "Get mod lists that the requesting + /// account (actor) is blocking. Requires auth." + /// + /// - SeeAlso: This is based on the [`app.bsky.graph.getListBlocks`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/getListBlocks.json + public struct GetListBlocksOutput: Codable { + + /// The mark used to indicate the starting point for the next set of results. Optional. + public let cursor: String? + + /// An array of lists that the user account is blocking. + public let lists: [ListViewDefinition] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphGetListMutes.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphGetListMutes.swift new file mode 100644 index 0000000000..a8fe24cf9e --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphGetListMutes.swift @@ -0,0 +1,28 @@ +// +// AppBskyGraphGetListMutes.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Graph { + + /// An output model for grabbing the moderator list that the user account is currently muting. + /// + /// - Note: According to the AT Protocol specifications: "Enumerates mod lists that the requesting + /// account (actor) currently has muted. Requires auth." + /// + /// - SeeAlso: This is based on the [`app.bsky.graph.getListMutes`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/getListMutes.json + public struct GetListMutesOutput: Codable { + + /// The mark used to indicate the starting point for the next set of results. Optional. + public let cursor: String? + + /// An array of lists the user account is muting. + public let lists: [AppBskyLexicon.Graph.ListViewDefinition] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphGetLists.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphGetLists.swift new file mode 100644 index 0000000000..de9489d360 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphGetLists.swift @@ -0,0 +1,28 @@ +// +// AppBskyGraphGetLists.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Graph { + + /// An output model for retrieving the lists created by the user account. + /// + /// - Note: According to the AT Protocol specifications: "Enumerates the lists created by a + /// specified account (actor)." + /// + /// - SeeAlso: This is based on the [`app.bsky.graph.getLists`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/getLists.json + public struct GetListsOutput: Codable { + + /// The mark used to indicate the starting point for the next set of results. Optional. + public let cursor: String? + + /// An array of lists created by the user account. + public let lists: [ListViewDefinition] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphGetMutes.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphGetMutes.swift new file mode 100644 index 0000000000..6214553568 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphGetMutes.swift @@ -0,0 +1,28 @@ +// +// AppBskyGraphGetMutes.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Graph { + + /// An output model for retrieving all accounts the user account is currently muting. + /// + /// - Note: According to the AT Protocol specifications: "Enumerates accounts that the + /// requesting account (actor) currently has muted. Requires auth." + /// + /// - SeeAlso: This is based on the [`app.bsky.graph.getMutes`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/getMutes.json + public struct GetMutesOutput: Codable { + + /// The mark used to indicate the starting point for the next set of results. Optional. + public let cursor: String? + + /// An array of accounts the user account is muting. + public let mutes: [AppBskyLexicon.Actor.ProfileViewDefinition] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphGetRelationships.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphGetRelationships.swift new file mode 100644 index 0000000000..ce9bac96e0 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphGetRelationships.swift @@ -0,0 +1,28 @@ +// +// AppBskyGraphGetRelationships.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Graph { + + /// An output model for the public relationship between two user accounts. + /// + /// - Note: According to the AT Protocol specifications: "Enumerates public relationships between + /// one account, and a list of other accounts. Does not require auth." + /// + /// - SeeAlso: This is based on the [`app.bsky.graph.getRelationships`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/getRelationships.json + public struct GetRelationshipsOutput: Codable { + + /// The decentralized identifier (DID) of the user account. + public let actor: String? + + /// The metadata containing the relationship between mutliple user accounts. + public let relationships: [ATUnion.GetRelationshipsOutputRelationshipUnion] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphGetSuggestedFollowsByActor.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphGetSuggestedFollowsByActor.swift new file mode 100644 index 0000000000..1d6cd96be3 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphGetSuggestedFollowsByActor.swift @@ -0,0 +1,27 @@ +// +// AppBskyGraphGetSuggestedFollowsByActor.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Graph { + + /// A output model for getting the list of user accounts that requesting user account is + /// suggested to follow. + /// + /// - Note: According to the AT Protocol specifications: "Enumerates follows similar to a given + /// account (actor). Expected use is to recommend additional accounts immediately after + /// following one account." + /// + /// - SeeAlso: This is based on the [`app.bsky.graph.getSuggestedFollowsByActor`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/getSuggestedFollowsByActor.json + public struct GetSuggestedFollowsByActorOutput: Codable { + + /// An array of user accounts the requesting user account is suggested to follow. + public let suggestions: [AppBskyLexicon.Actor.ProfileViewDefinition] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphList.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphList.swift new file mode 100644 index 0000000000..3888e2f916 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphList.swift @@ -0,0 +1,101 @@ +// +// AppBskyGraphList.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Graph { + + /// A record model for a list. + /// + /// - Note: According to the AT Protocol specifications: "Record representing a list of + /// accounts (actors). Scope includes both moderation-oriented lists and + /// curration-oriented lists." + /// + /// - SeeAlso: This is based on the [`app.bsky.graph.list`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/list.json + public struct ListRecord: ATRecordProtocol { + + /// The identifier of the lexicon. + /// + /// - Warning: The value must not change. + public static private(set) var type: String = "app.bsky.graph.list" + + /// The name of the list. + /// + /// - Note: According to the AT Protocol specifications: "Display name for list; can not + /// be empty." + public let name: String + + /// The purpose of the list. + /// + /// - Note: According to the AT Protocol specifications: "Defines the purpose of the list + /// (aka, moderation-oriented or curration-oriented)." + public let purpose: ListPurpose + + /// The description of the list. Optional. + public let description: String? + + /// An array of facets contained within the description. Optional. + public let descriptionFacets: [AppBskyLexicon.RichText.Facet]? + + /// The avatar image of the list. Optional. + public let avatarImage: ComAtprotoLexicon.Repository.UploadBlobOutput? + + /// The user-defined labels for the list. Optional. + public let labels: ATUnion.ListLabelsUnion + + /// The date and time the list was created. + @DateFormatting public var createdAt: Date + + public init(name: String, purpose: ListPurpose, description: String?, descriptionFacets: [AppBskyLexicon.RichText.Facet]?, + avatarImage: ComAtprotoLexicon.Repository.UploadBlobOutput?, labels: ATUnion.ListLabelsUnion, createdAt: Date) { + self.name = name + self.purpose = purpose + self.description = description + self.descriptionFacets = descriptionFacets + self.avatarImage = avatarImage + self.labels = labels + self._createdAt = DateFormatting(wrappedValue: createdAt) + } + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.name = try container.decode(String.self, forKey: .name) + self.purpose = try container.decode(ListPurpose.self, forKey: .purpose) + self.description = try container.decodeIfPresent(String.self, forKey: .description) + self.descriptionFacets = try container.decodeIfPresent([AppBskyLexicon.RichText.Facet].self, forKey: .descriptionFacets) + self.avatarImage = try container.decodeIfPresent(ComAtprotoLexicon.Repository.UploadBlobOutput.self, forKey: .avatarImage) + self.labels = try container.decode(ATUnion.ListLabelsUnion.self, forKey: .labels) + self.createdAt = try container.decode(DateFormatting.self, forKey: .createdAt).wrappedValue + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.name, forKey: .name) + try container.encode(self.purpose, forKey: .purpose) + try container.encodeIfPresent(self.description, forKey: .description) + try container.encodeIfPresent(self.descriptionFacets, forKey: .descriptionFacets) + try container.encodeIfPresent(self.avatarImage, forKey: .avatarImage) + try container.encode(self.labels, forKey: .labels) + try container.encode(self._createdAt, forKey: .createdAt) + } + + enum CodingKeys: String, CodingKey { + case type = "$type" + case name + case purpose + case description + case descriptionFacets + case avatarImage = "avatar" + case labels + case createdAt + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphListblock.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphListblock.swift new file mode 100644 index 0000000000..a91e0d3079 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphListblock.swift @@ -0,0 +1,61 @@ +// +// AppBskyGraphListblock.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Graph { + + /// A record model for a blocking list. + /// + /// - Note: According to the AT Protocol specifications: "Record representing a block + /// relationship against an entire [...] list of accounts (actors)." + /// + /// - SeeAlso: This is based on the [`app.bsky.graph.listblock`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/listblock.json + public struct ListBlockRecord: ATRecordProtocol { + + /// The identifier of the lexicon. + /// + /// - Warning: The value must not change. + public static private(set) var type: String = "app.bsky.graph.listblock" + + /// The decentralized identifier (DID) of the moderator list record. + /// + /// - Note: According to the AT Protocol specifications: "Reference (AT-URI) to the mod + /// list record." + public let subjectDID: String + + /// The date and time the record was created. + @DateFormatting public var createdAt: Date + + public init(subjectDID: String, createdAt: Date) { + self.subjectDID = subjectDID + self._createdAt = DateFormatting(wrappedValue: createdAt) + } + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.subjectDID = try container.decode(String.self, forKey: .subjectDID) + self.createdAt = try container.decode(DateFormatting.self, forKey: .createdAt).wrappedValue + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.subjectDID, forKey: .subjectDID) + try container.encode(self._createdAt, forKey: .createdAt) + } + + enum CodingKeys: String, CodingKey { + case type = "$type" + case subjectDID = "subject" + case createdAt + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphListitem.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphListitem.swift new file mode 100644 index 0000000000..9a6e4109cc --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphListitem.swift @@ -0,0 +1,71 @@ +// +// AppBskyGraphListitem.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Graph { + + /// A record model for a list item. + /// + /// - Note: According to the AT Protocol specifications: "Record representing an account's + /// inclusion on a specific list. The AppView will ignore duplicate listitem records." + /// + /// - SeeAlso: This is based on the [`app.bsky.graph.listitem`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/listitem.json + public struct ListItemRecord: ATRecordProtocol { + + /// The identifier of the lexicon. + /// + /// - Warning: The value must not change. + public static private(set) var type: String = "app.bsky.graph.listitem" + + /// The decentralized identifier (DID) of the account that's in a list. + /// + /// - Note: According to the AT Protocol specifications: "The account which is included on + /// the list." + public let subjectDID: String + + /// The decentralized identifier (DID) of the list record. + /// + /// - Note: According to the AT Protocol specifications: "The account which is included on + /// the list." + public let list: String + + /// The date and time the record was created. + @DateFormatting public var createdAt: Date + + public init(subjectDID: String, list: String, createdAt: Date) { + self.subjectDID = subjectDID + self.list = list + self._createdAt = DateFormatting(wrappedValue: createdAt) + } + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.subjectDID = try container.decode(String.self, forKey: .subjectDID) + self.list = try container.decode(String.self, forKey: .list) + self.createdAt = try container.decode(DateFormatting.self, forKey: .createdAt).wrappedValue + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.subjectDID, forKey: .subjectDID) + try container.encode(self.list, forKey: .list) + try container.encode(self._createdAt, forKey: .createdAt) + } + + enum CodingKeys: String, CodingKey { + case type = "$type" + case subjectDID = "subject" + case list + case createdAt + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphMuteActor.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphMuteActor.swift new file mode 100644 index 0000000000..a13614bb74 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphMuteActor.swift @@ -0,0 +1,29 @@ +// +// AppBskyGraphMuteActor.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Graph { + + /// A request body model formuting a user account. + /// + /// - Note: According to the AT Protocol specifications: "Creates a mute relationship for the + /// specified account. Mutes are private in Bluesky. Requires auth." + /// + /// - SeeAlso: This is based on the [`app.bsky.graph.muteActor`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/muteActor.json + public struct MuteActorRequestBody: Codable { + + /// The decentralized identifier (DID) or handle of a user account. + public let actorDID: String + + enum CodingKeys: String, CodingKey { + case actorDID = "actor" + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphMuteActorList.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphMuteActorList.swift new file mode 100644 index 0000000000..83577c24b6 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphMuteActorList.swift @@ -0,0 +1,29 @@ +// +// AppBskyGraphMuteActorList.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Graph { + + /// A request body model formuting a list. + /// + /// - Note: According to the AT Protocol specifications: "Creates a mute relationship for the + /// specified list of accounts. Mutes are private in Bluesky. Requires auth." + /// + /// - SeeAlso: This is based on the [`app.bsky.graph.muteActorList`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/muteActor.json + public struct MuteActorListRequestBody: Codable { + + /// The URI of a list. + public let listURI: String + + enum CodingKeys: String, CodingKey { + case listURI = "list" + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphUnmuteActor.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphUnmuteActor.swift new file mode 100644 index 0000000000..ab2a70d151 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphUnmuteActor.swift @@ -0,0 +1,29 @@ +// +// AppBskyGraphUnmuteActor.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Graph { + + /// A request body model for unmuting a user account. + /// + /// - Note: According to the AT Protocol specifications: "Unmutes the specified account. + /// Requires auth." + /// + /// - SeeAlso: This is based on the [`app.bsky.graph.unmuteActor`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/unmuteActor.json + public struct UnmuteActorRequestBody: Codable { + + /// The decentralized identifier (DID) or handle of a user account. + public let actorDID: String + + enum CodingKeys: String, CodingKey { + case actorDID = "actor" + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphUnmuteActorList.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphUnmuteActorList.swift new file mode 100644 index 0000000000..589f93d12e --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/AppBskyGraphUnmuteActorList.swift @@ -0,0 +1,29 @@ +// +// AppBskyGraphUnmuteActorList.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Graph { + + /// A request body model for unmuting a list of user accounts. + /// + /// - Note: According to the AT Protocol specifications: "Unmutes the specified list of + /// accounts. Requires auth." + /// + /// - SeeAlso: This is based on the [`app.bsky.graph.unmuteActorList`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/unmuteActorList.json + public struct UnmuteActorListRequestBody: Codable { + + /// The URI of a list. + public let listURI: String + + enum CodingKeys: String, CodingKey { + case listURI = "list" + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphBlock.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphBlock.swift deleted file mode 100644 index 3b42ab03a0..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphBlock.swift +++ /dev/null @@ -1,55 +0,0 @@ -// -// BskyGraphBlock.swift -// -// -// Created by Christopher Jr Riley on 2024-03-08. -// - -import Foundation - -/// The main data model definition for a block record. -/// -/// - Note: According to the AT Protocol specifications: "Record declaring a 'block' relationship -/// against another account. NOTE: blocks are public in Bluesky; see blog posts for details." -/// -/// - SeeAlso: This is based on the [`app.bsky.graph.block`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/block.json -public struct GraphBlock: ATRecordProtocol { - /// The identifier of the lexicon. - /// - /// - Warning: The value must not change. - public static private(set) var type: String = "app.bsky.graph.block" - /// The decentralized identifier(DID) of the subject that has been blocked. - /// - /// - Note: According to the AT Protocol specifications: "DID of the account to be blocked." - public let subjectDID: String - /// The date and time the block record was created. - @DateFormatting public var createdAt: Date - - public init(subjectDID: String, createdAt: Date) { - self.subjectDID = subjectDID - self._createdAt = DateFormatting(wrappedValue: createdAt) - } - - public init(from decoder: any Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.subjectDID = try container.decode(String.self, forKey: .subjectDID) - self.createdAt = try container.decode(DateFormatting.self, forKey: .createdAt).wrappedValue - } - - public func encode(to encoder: any Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - -// try container.encode(self.type, forKey: .type) - try container.encode(self.subjectDID, forKey: .subjectDID) - try container.encode(self._createdAt, forKey: .createdAt) - } - - enum CodingKeys: String, CodingKey { - case type = "$type" - case subjectDID = "subject" - case createdAt - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphDefs.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphDefs.swift deleted file mode 100644 index 4babafaab3..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphDefs.swift +++ /dev/null @@ -1,273 +0,0 @@ -// -// BskyGraphDefs.swift -// -// -// Created by Christopher Jr Riley on 2024-01-25. -// - -import Foundation - -/// A data model for a basic list view definition. -/// -/// - SeeAlso: This is based on the [`app.bsky.graph.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/defs.json -public struct GraphListViewBasic: Codable { - /// The URI of a user list. - public let actorURI: String - /// The CID of a user list. - public let cidHash: String - /// The name of the list. - public let name: String - /// The purpose of the user list. - /// - /// - Important: Current maximum length is 64 characters. This library will truncate the - /// `String` to the maximum number of characters if it does go over. - public let purpose: GraphListPurpose - /// The avatar image URL of the user list. Optional. - public let avatarImageURL: URL? - /// The viewer's state of the user list. Optional. - public var viewer: GraphListViewerState? = nil - /// The late time the user list was indexed. - @DateFormattingOptional public var indexedAt: Date? = nil - - public init(actorURI: String, cidHash: String, name: String, purpose: GraphListPurpose, avatarImageURL: URL?, viewer: GraphListViewerState?, - indexedAt: Date?) { - self.actorURI = actorURI - self.cidHash = cidHash - self.name = name - self.purpose = purpose - self.avatarImageURL = avatarImageURL - self.viewer = viewer - self._indexedAt = DateFormattingOptional(wrappedValue: indexedAt) - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.actorURI = try container.decode(String.self, forKey: .actorURI) - self.cidHash = try container.decode(String.self, forKey: .cidHash) - self.name = try container.decode(String.self, forKey: .name) - self.purpose = try container.decode(GraphListPurpose.self, forKey: .purpose) - self.avatarImageURL = try container.decodeIfPresent(URL.self, forKey: .avatarImageURL) - self.viewer = try container.decodeIfPresent(GraphListViewerState.self, forKey: .viewer) - self.indexedAt = try container.decodeIfPresent(DateFormattingOptional.self, forKey: .indexedAt)?.wrappedValue - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - try container.encode(self.actorURI, forKey: .actorURI) - try container.encode(self.cidHash, forKey: .cidHash) - try container.encode(self.name, forKey: .name) - // - try truncatedEncode(self.name, withContainer: &container, forKey: .name, upToLength: 64) - try container.encode(self.purpose, forKey: .purpose) - try container.encodeIfPresent(self.avatarImageURL, forKey: .avatarImageURL) - try container.encodeIfPresent(self.viewer, forKey: .viewer) - try container.encode(self._indexedAt, forKey: .indexedAt) - } - - enum CodingKeys: String, CodingKey { - case actorURI = "uri" - case cidHash = "cid" - case name = "name" - case purpose = "purpose" - case avatarImageURL = "avatar" - case viewer = "viewer" - case indexedAt - } -} - -/// A data model for a definition of the view of a user list. -/// -/// - SeeAlso: This is based on the [`app.bsky.graph.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/defs.json -public struct GraphListView: Codable { - /// The URI of the user list. - public let listURI: String - /// The CID of the user list. - public let cidHash: String - /// The creator of the user list. - public let creator: ActorProfileView - /// The name of the user list. - /// - /// - Important: Current maximum length is 64 characters. This library will truncate the - /// `String` to the maximum number of characters if it does go over. - public let name: String - /// The purpose of the user list. - public let purpose: GraphListPurpose - /// The description of the user list. Optional. - /// - /// - Important: Current maximum length is 300 characters. This library will truncate the - /// `String` to the maximum number of characters if it does go over. - public var description: String? = nil - /// An array of facets contained in the post's text. Optional. - public var descriptionFacets: [Facet]? = nil - /// The avatar image URL of the user list. Optional. - public var avatarImageURL: URL? = nil - /// The viewer's state of the user list. Optional. - public var viewer: GraphListViewerState? = nil - /// The late time the user list was indexed. - @DateFormatting public var indexedAt: Date - - public init(listURI: String, cidHash: String, creator: ActorProfileView, name: String, purpose: GraphListPurpose, description: String?, - descriptionFacets: [Facet]?, avatarImageURL: URL?, viewer: GraphListViewerState?, indexedAt: Date) { - self.listURI = listURI - self.cidHash = cidHash - self.creator = creator - self.name = name - self.purpose = purpose - self.description = description - self.descriptionFacets = descriptionFacets - self.avatarImageURL = avatarImageURL - self.viewer = viewer - self._indexedAt = DateFormatting(wrappedValue: indexedAt) - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.listURI = try container.decode(String.self, forKey: .listURI) - self.cidHash = try container.decode(String.self, forKey: .cidHash) - self.creator = try container.decode(ActorProfileView.self, forKey: .creator) - self.name = try container.decode(String.self, forKey: .name) - self.purpose = try container.decode(GraphListPurpose.self, forKey: .purpose) - self.description = try container.decodeIfPresent(String.self, forKey: .description) - self.descriptionFacets = try container.decodeIfPresent([Facet].self, forKey: .descriptionFacets) - self.avatarImageURL = try container.decodeIfPresent(URL.self, forKey: .avatarImageURL) - self.viewer = try container.decodeIfPresent(GraphListViewerState.self, forKey: .viewer) - self.indexedAt = try container.decode(DateFormatting.self, forKey: .indexedAt).wrappedValue - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - try container.encode(self.listURI, forKey: .listURI) - try container.encode(self.cidHash, forKey: .cidHash) - try container.encode(self.creator, forKey: .creator) - // Truncate `name` to 64 characters before encoding. - try truncatedEncode(self.name, withContainer: &container, forKey: .name, upToLength: 64) - try container.encode(self.purpose, forKey: .purpose) - - // Truncate `description` to 3000 characters before encoding - // `maxGraphemes`'s limit is 300, but `String.count` should respect that limit - try truncatedEncodeIfPresent(self.description, withContainer: &container, forKey: .description, upToLength: 3000) - try container.encodeIfPresent(self.descriptionFacets, forKey: .descriptionFacets) - try container.encodeIfPresent(self.avatarImageURL, forKey: .avatarImageURL) - try container.encodeIfPresent(self.viewer, forKey: .viewer) - try container.encode(self._indexedAt, forKey: .indexedAt) - } - - enum CodingKeys: String, CodingKey { - case listURI = "uri" - case cidHash = "cid" - case creator = "creator" - case name = "name" - case purpose = "purpose" - case description = "description" - case descriptionFacets = "descriptionFacets" - case avatarImageURL = "avatar" - case viewer = "viewer" - case indexedAt = "indexedAt" - } -} - -/// A data model for the definition of an item with in a user list. -/// -/// - SeeAlso: This is based on the [`app.bsky.graph.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/defs.json -public struct GraphListItemView: Codable { - /// The URI of the user list item. - public let listItemURI: String - /// A user in the user list item. - public let subject: ActorProfileView - - enum CodingKeys: String, CodingKey { - case listItemURI = "uri" - case subject - } -} - -/// A data model of the definition of the user list's purpose. -/// -/// - SeeAlso: This is based on the [`app.bsky.graph.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/defs.json -public enum GraphListPurpose: String, Codable { - /// An array of actors to apply an aggregate moderation action (mute/block) on. - case modlist = "app.bsky.graph.defs#modlist" - - /// An array of actors used for curation purposes such as list feeds or interaction gating. - case curatelist = "app.bsky.graph.defs#curatelist" -} - - -/// A data model of a definition for a viewer's state of a user list. -/// -/// - SeeAlso: This is based on the [`app.bsky.graph.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/defs.json -public struct GraphListViewerState: Codable { - /// Indicates whether the user is muted. Optional. - public var isMuted: Bool? = nil - /// The URI of the block record if the user has blocked the user list. Optional - public var blockedURI: String? = nil - - enum CodingKeys: String, CodingKey { - case isMuted = "muted" - case blockedURI = "blocked" - } -} - -/// A data model for a definition of a user that may not have been found in the user list. -/// -/// - SeeAlso: This is based on the [`app.bsky.graph.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/defs.json -public struct GraphNotFoundActor: Codable { - /// The URI of the user. - /// - /// - Note: According to the AT Protocol specifications: "indicates that a handle or DID could - /// not be resolved", - public let actorURI: String - /// Indicates whether the user is not found. - public let isNotFound: Bool - - enum CodingKeys: String, CodingKey { - case actorURI = "actor" - case isNotFound = "notFound" - } -} - -/// A data model for the graph relationship definition. -/// -/// - Note: According to the AT Protocol specifications: "lists the bi-directional graph -/// relationships between one actor (not indicated in the object), and the target actors (the DID -/// included in the object)" -/// -/// - SeeAlso: This is based on the [`app.bsky.graph.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/defs.json -public struct GraphRelationship: Codable { - /// The decentralized identifier (DID) of the target user. - public let actorDID: String - /// The URI of the follow record, if the first user is following the target user. Optional. - /// - /// - Note: According to the AT Protocol specifications: "if the actor follows this DID, this - /// is the AT-URI of the follow record" - public let followingURI: String? - /// The URI of the follow record, if the target user is following the first user. Optional. - /// - /// - Note: According to the AT Protocol specifications: "if the actor is followed by this - /// DID, contains the AT-URI of the follow record" - public let followedByURI: String? - - enum CodingKeys: String, CodingKey { - case actorDID = "did" - case followingURI = "following" - case followedByURI = "followedBy" - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphFollow.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphFollow.swift deleted file mode 100644 index 40724e6852..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphFollow.swift +++ /dev/null @@ -1,52 +0,0 @@ -// -// BskyGraphFollow.swift -// -// -// Created by Christopher Jr Riley on 2024-03-08. -// - -import Foundation - -/// The main data model definition for a follow record. -/// -/// - Note: According to the AT Protocol specifications: "Record declaring a social 'follow' -/// relationship of another account. Duplicate follows will be ignored by the AppView." -/// -/// - SeeAlso: This is based on the [`app.bsky.graph.follow`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/follow.json -public struct GraphFollow: ATRecordProtocol { - /// The identifier of the lexicon. - /// - /// - Warning: The value must not change. - public static private(set) var type: String = "app.bsky.graph.follow" - - /// The subject that the user account wants to "follow." - public let subjectDID: String - /// The date and time the record was created. - @DateFormatting public var createdAt: Date - - public init(subjectDID: String, createdAt: Date) { - self.subjectDID = subjectDID - self._createdAt = DateFormatting(wrappedValue: createdAt) - } - - public init(from decoder: any Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.subjectDID = try container.decode(String.self, forKey: .subjectDID) - self.createdAt = try container.decode(DateFormatting.self, forKey: .createdAt).wrappedValue - } - - public func encode(to encoder: any Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - try container.encode(self.subjectDID, forKey: .subjectDID) - try container.encode(self._createdAt, forKey: .createdAt) - } - - enum CodingKeys: String, CodingKey { - case subjectDID = "subject" - case createdAt - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphGetBlocks.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphGetBlocks.swift deleted file mode 100644 index b394d69e45..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphGetBlocks.swift +++ /dev/null @@ -1,24 +0,0 @@ -// -// BskyGraphGetBlocks.swift -// -// -// Created by Christopher Jr Riley on 2024-03-08. -// - -import Foundation - -/// The main data model definition for the output of getting all of the users that have been -/// blocked by the user account. -/// -/// - Note: According to the AT Protocol specifications: "Enumerates which accounts the -/// requesting account is currently blocking. Requires auth." -/// -/// - SeeAlso: This is based on the [`app.bsky.graph.getBlocks`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/getBlocks.json -public struct GraphGetBlocksOutput: Codable { - /// The mark used to indicate the starting point for the next set of results. Optional. - public let cursor: String? - /// An array of profiles that have been blocked by the user account. - public let blocks: [ActorProfileView] -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphGetFollowers.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphGetFollowers.swift deleted file mode 100644 index 50c9907ae2..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphGetFollowers.swift +++ /dev/null @@ -1,25 +0,0 @@ -// -// BskyGraphGetFollowers.swift -// -// -// Created by Christopher Jr Riley on 2024-03-08. -// - -import Foundation - -/// The main data model definition for the output of getting all of the user account's followers. -/// -/// - Note: According to the AT Protocol specifications: "Enumerates accounts which follow a -/// specified account (actor)." -/// -/// - SeeAlso: This is based on the [`app.bsky.graph.getFollowers`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/getFollowers.json -public struct GraphGetFollowersOutput: Codable { - /// The user account itself. - public let subject: ActorProfileView - /// The mark used to indicate the starting point for the next set of results. Optional. - public let cursor: String? - /// An array of user accounts that follow the user account. - public let followers: [ActorProfileView] -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphGetFollows.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphGetFollows.swift deleted file mode 100644 index 14e8d2ddea..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphGetFollows.swift +++ /dev/null @@ -1,26 +0,0 @@ -// -// BskyGraphGetFollows.swift -// -// -// Created by Christopher Jr Riley on 2024-03-08. -// - -import Foundation - -/// The main data model definition for the output for grabbing all of the accounts the user -/// account follows. -/// -/// - Note: According to the AT Protocol specifications: "Enumerates accounts which a specified -/// account (actor) follows." -/// -/// - SeeAlso: This is based on the [`app.bsky.graph.getFollows`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/getFollows.json -public struct GraphFollowsOutput: Codable { - /// The user account itself. - public let subject: ActorProfileView - /// The mark used to indicate the starting point for the next set of results. Optional. - public let cursor: String? - /// An array of user accounts that the user account follows. - public let follows: [ActorProfileView] -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphGetList.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphGetList.swift deleted file mode 100644 index f5991c6697..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphGetList.swift +++ /dev/null @@ -1,25 +0,0 @@ -// -// BskyGraphGetList.swift -// -// -// Created by Christopher Jr Riley on 2024-03-09. -// - -import Foundation - -/// The main data model definition for the output of grabbing the list view. -/// -/// - Note: According to the AT Protocol specifications: "Gets a 'view' (with additional context) -/// of a specified list." -/// -/// - SeeAlso: This is based on the [`app.bsky.graph.getList`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/getList.json -public struct GraphGetListOutput: Codable { - /// The mark used to indicate the starting point for the next set of results. Optional. - public let cursor: String? - /// The metadata of the list. - public let list: GraphListView - /// An array of list items. - public let items: [GraphListItemView] -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphGetListBlocks.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphGetListBlocks.swift deleted file mode 100644 index fb92814ff7..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphGetListBlocks.swift +++ /dev/null @@ -1,24 +0,0 @@ -// -// BskyGraphGetListBlocks.swift -// -// -// Created by Christopher Jr Riley on 2024-03-10. -// - -import Foundation - -/// The main data model definition for the output of getting the moderator lists that the user -/// account is blocking. -/// -/// - Note: According to the AT Protocol specifications: "Get mod lists that the requesting -/// account (actor) is blocking. Requires auth." -/// -/// - SeeAlso: This is based on the [`app.bsky.graph.getListBlocks`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/getListBlocks.json -public struct GraphGetListBlocksOutput: Codable { - /// The mark used to indicate the starting point for the next set of results. Optional. - public let cursor: String? - /// An array of lists that the user account is blocking. - public let lists: [GraphListView] -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphGetListMutes.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphGetListMutes.swift deleted file mode 100644 index bf03bc39db..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphGetListMutes.swift +++ /dev/null @@ -1,24 +0,0 @@ -// -// BskyGraphGetListMutes.swift -// -// -// Created by Christopher Jr Riley on 2024-03-10. -// - -import Foundation - -/// The main data model definition for the output of grabbing the moderator list that the user -/// account is currently muting. -/// -/// - Note: According to the AT Protocol specifications: "Enumerates mod lists that the requesting -/// account (actor) currently has muted. Requires auth." -/// -/// - SeeAlso: This is based on the [`app.bsky.graph.getListMutes`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/getListMutes.json -public struct GraphGetListMutesOutput: Codable { - /// The mark used to indicate the starting point for the next set of results. Optional. - public let cursor: String? - /// An array of lists the user account is muting. - public let lists: [GraphListView] -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphGetLists.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphGetLists.swift deleted file mode 100644 index 75942d3b6c..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphGetLists.swift +++ /dev/null @@ -1,24 +0,0 @@ -// -// BskyGraphGetLists.swift -// -// -// Created by Christopher Jr Riley on 2024-03-10. -// - -import Foundation - -/// The main data model definition for the output of retrieving the lists created by the -/// user account. -/// -/// - Note: According to the AT Protocol specifications: "Enumerates the lists created by a -/// specified account (actor)." -/// -/// - SeeAlso: This is based on the [`app.bsky.graph.getLists`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/getLists.json -public struct GraphGetListsOutput: Codable { - /// The mark used to indicate the starting point for the next set of results. Optional. - public let cursor: String? - /// An array of lists created by the user account. - public let lists: [GraphListView] -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphGetMutes.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphGetMutes.swift deleted file mode 100644 index 1080c7ba79..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphGetMutes.swift +++ /dev/null @@ -1,24 +0,0 @@ -// -// BskyGraphGetMutes.swift -// -// -// Created by Christopher Jr Riley on 2024-03-10. -// - -import Foundation - -/// The main data model definition for the output of retrieving all accounts the user account is -/// currently muting. -/// -/// - Note: According to the AT Protocol specifications: "Enumerates accounts that the requesting -/// account (actor) currently has muted. Requires auth." -/// -/// - SeeAlso: This is based on the [`app.bsky.graph.getMutes`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/getMutes.json -public struct GraphGetMutesOutput: Codable { - /// The mark used to indicate the starting point for the next set of results. Optional. - public let cursor: String? - /// An array of accounts the user account is muting. - public let mutes: [ActorProfileView] -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphGetRelationships.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphGetRelationships.swift deleted file mode 100644 index 231d045e71..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphGetRelationships.swift +++ /dev/null @@ -1,56 +0,0 @@ -// -// BskyGraphGetRelationships.swift -// -// -// Created by Christopher Jr Riley on 2024-03-10. -// - -import Foundation - -/// The main data model definition for the output of the public relationship between two -/// user accounts. -/// -/// - Note: According to the AT Protocol specifications: "Enumerates public relationships between -/// one account, and a list of other accounts. Does not require auth." -/// -/// - SeeAlso: This is based on the [`app.bsky.graph.getRelationships`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/getRelationships.json -public struct GraphGetRelationships: Codable { - /// The decentralized identifier (DID) of the user account. - public let actor: String? - /// The metadata containing the relationship between mutliple user accounts. - public let relationships: [GraphRelationshipUnion] -} - - -/// A reference containing the list of relationships of multiple user accounts. -public enum GraphRelationshipUnion: Codable { - case relationship(GraphRelationship) - case notFoundActor(GraphNotFoundActor) - - public init(from decoder: Decoder) throws { - let container = try decoder.singleValueContainer() - - if let value = try? container.decode(GraphRelationship.self) { - self = .relationship(value) - } else if let value = try? container.decode(GraphNotFoundActor.self) { - self = .notFoundActor(value) - } else { - throw DecodingError.typeMismatch( - ActorPreferenceUnion.self, DecodingError.Context( - codingPath: decoder.codingPath, debugDescription: "Unknown GraphRelationshipUnion type")) - } - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.singleValueContainer() - - switch self { - case .relationship(let relationship): - try container.encode(relationship) - case .notFoundActor(let notFoundActor): - try container.encode(notFoundActor) - } - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphGetSuggestedFollowsByActor.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphGetSuggestedFollowsByActor.swift deleted file mode 100644 index 0b1ef1c56b..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphGetSuggestedFollowsByActor.swift +++ /dev/null @@ -1,23 +0,0 @@ -// -// BskyGraphGetSuggestedFollowsByActor.swift -// -// -// Created by Christopher Jr Riley on 2024-03-10. -// - -import Foundation - -/// The main data model definition for the output of getting the list of user accounts that -/// requesting user account is suggested to follow. -/// -/// - Note: According to the AT Protocol specifications: "Enumerates follows similar to a given -/// account (actor). Expected use is to recommend additional accounts immediately after following -/// one account." -/// -/// - SeeAlso: This is based on the [`app.bsky.graph.getSuggestedFollowsByActor`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/getSuggestedFollowsByActor.json -public struct GraphGetSuggestedFollowsByActorOutput: Codable { - /// An array of user accounts the requesting user account is suggested to follow. - public let suggestions: [ActorProfileView] -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphList.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphList.swift deleted file mode 100644 index 3c7af951f6..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphList.swift +++ /dev/null @@ -1,90 +0,0 @@ -// -// BskyGraphList.swift -// -// -// Created by Christopher Jr Riley on 2024-03-10. -// - -import Foundation - -/// The main data model definition for a list record. -/// -/// - Note: According to the AT Protocol specifications: "Record representing a list of accounts -/// (actors). Scope includes both moderation-oriented lists and curration-oriented lists." -/// -/// - SeeAlso: This is based on the [`app.bsky.graph.list`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/list.json -public struct GraphList: ATRecordProtocol { - /// The identifier of the lexicon. - /// - /// - Warning: The value must not change. - public static private(set) var type: String = "app.bsky.graph.list" - /// The name of the list. - /// - /// - Note: According to the AT Protocol specifications: "Display name for list; can not be empty." - public let name: String - /// The purpose of the list. - /// - /// - Note: According to the AT Protocol specifications: "Defines the purpose of the list - /// (aka, moderation-oriented or curration-oriented)." - public let purpose: GraphListPurpose - /// The description of the list. Optional. - public let description: String? - /// An array of facets contained within the description. Optional. - public let descriptionFacets: [Facet]? - /// The avatar image of the list. Optional. - public let avatarImage: UploadBlobOutput? - /// The user-defined labels for the list. Optional. - public let labels: SelfLabels - /// The date and time the list was created. - @DateFormatting public var createdAt: Date - - public init(name: String, purpose: GraphListPurpose, description: String?, descriptionFacets: [Facet]?, avatarImage: UploadBlobOutput?, - labels: SelfLabels, createdAt: Date) { - self.name = name - self.purpose = purpose - self.description = description - self.descriptionFacets = descriptionFacets - self.avatarImage = avatarImage - self.labels = labels - self._createdAt = DateFormatting(wrappedValue: createdAt) - } - - public init(from decoder: any Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.name = try container.decode(String.self, forKey: .name) - self.purpose = try container.decode(GraphListPurpose.self, forKey: .purpose) - self.description = try container.decodeIfPresent(String.self, forKey: .description) - self.descriptionFacets = try container.decodeIfPresent([Facet].self, forKey: .descriptionFacets) - self.avatarImage = try container.decodeIfPresent(UploadBlobOutput.self, forKey: .avatarImage) - self.labels = try container.decode(SelfLabels.self, forKey: .labels) - self.createdAt = try container.decode(DateFormatting.self, forKey: .createdAt).wrappedValue - } - - public func encode(to encoder: any Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - -// try container.encode(self.type, forKey: .type) - try container.encode(self.name, forKey: .name) - try container.encode(self.purpose, forKey: .purpose) - try container.encodeIfPresent(self.description, forKey: .description) - try container.encodeIfPresent(self.descriptionFacets, forKey: .descriptionFacets) - try container.encodeIfPresent(self.avatarImage, forKey: .avatarImage) - try container.encode(self.labels, forKey: .labels) - try container.encode(self._createdAt, forKey: .createdAt) - } - - enum CodingKeys: String, CodingKey { - case type = "$type" - case name - case purpose - case description - case descriptionFacets - case avatarImage = "avatar" - case labels - case createdAt - } - -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphListblock.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphListblock.swift deleted file mode 100644 index ac92d3cc7b..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphListblock.swift +++ /dev/null @@ -1,56 +0,0 @@ -// -// BskyGraphListblock.swift -// -// -// Created by Christopher Jr Riley on 2024-03-10. -// - -import Foundation - -/// The main data model definition for a blocking list record. -/// -/// - Note: According to the AT Protocol specifications: "Record representing a block relationship -/// against an entire [...] list of accounts (actors)." -/// -/// - SeeAlso: This is based on the [`app.bsky.graph.listblock`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/listblock.json -public struct GraphListBlock: ATRecordProtocol { - /// The identifier of the lexicon. - /// - /// - Warning: The value must not change. - public static private(set) var type: String = "app.bsky.graph.listblock" - /// The decentralized identifier (DID) of the moderator list record. - /// - /// - Note: According to the AT Protocol specifications: "Reference (AT-URI) to the mod - /// list record." - public let subjectDID: String - /// The date and time the record was created. - @DateFormatting public var createdAt: Date - - public init(subjectDID: String, createdAt: Date) { - self.subjectDID = subjectDID - self._createdAt = DateFormatting(wrappedValue: createdAt) - } - - public init(from decoder: any Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.subjectDID = try container.decode(String.self, forKey: .subjectDID) - self.createdAt = try container.decode(DateFormatting.self, forKey: .createdAt).wrappedValue - } - - public func encode(to encoder: any Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - -// try container.encode(self.type, forKey: .type) - try container.encode(self.subjectDID, forKey: .subjectDID) - try container.encode(self._createdAt, forKey: .createdAt) - } - - enum CodingKeys: String, CodingKey { - case type = "$type" - case subjectDID = "subject" - case createdAt - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphListitem.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphListitem.swift deleted file mode 100644 index 924ecf74c5..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphListitem.swift +++ /dev/null @@ -1,65 +0,0 @@ -// -// BskyGraphListitem.swift -// -// -// Created by Christopher Jr Riley on 2024-03-10. -// - -import Foundation - -/// The main data model definition for a list item record. -/// -/// - Note: According to the AT Protocol specifications: "Record representing an account's -/// inclusion on a specific list. The AppView will ignore duplicate listitem records." -/// -/// - SeeAlso: This is based on the [`app.bsky.graph.listitem`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/listitem.json -public struct GraphListItem: ATRecordProtocol { - /// The identifier of the lexicon. - /// - /// - Warning: The value must not change. - public static private(set) var type: String = "app.bsky.graph.listitem" - /// The decentralized identifier (DID) of the account that's in a list. - /// - /// - Note: According to the AT Protocol specifications: "The account which is included on - /// the list." - public let subjectDID: String - /// The decentralized identifier (DID) of the list record. - /// - /// - Note: According to the AT Protocol specifications: "The account which is included on - /// the list." - public let list: String - /// The date and time the record was created. - @DateFormatting public var createdAt: Date - - public init(subjectDID: String, list: String, createdAt: Date) { - self.subjectDID = subjectDID - self.list = list - self._createdAt = DateFormatting(wrappedValue: createdAt) - } - - public init(from decoder: any Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.subjectDID = try container.decode(String.self, forKey: .subjectDID) - self.list = try container.decode(String.self, forKey: .list) - self.createdAt = try container.decode(DateFormatting.self, forKey: .createdAt).wrappedValue - } - - public func encode(to encoder: any Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - -// try container.encode(self.type, forKey: .type) - try container.encode(self.subjectDID, forKey: .subjectDID) - try container.encode(self.list, forKey: .list) - try container.encode(self._createdAt, forKey: .createdAt) - } - - enum CodingKeys: String, CodingKey { - case type = "$type" - case subjectDID = "subject" - case list - case createdAt - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphMuteActor.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphMuteActor.swift deleted file mode 100644 index 30be3b6ed7..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphMuteActor.swift +++ /dev/null @@ -1,25 +0,0 @@ -// -// BskyGraphMuteActor.swift -// -// -// Created by Christopher Jr Riley on 2024-03-10. -// - -import Foundation - -/// The main data model definition for muting a user account. -/// -/// - Note: According to the AT Protocol specifications: "Creates a mute relationship for the -/// specified account. Mutes are private in Bluesky. Requires auth." -/// -/// - SeeAlso: This is based on the [`app.bsky.graph.muteActor`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/muteActor.json -public struct GraphMuteActor: Codable { - /// The decentralized identifier (DID) or handle of a user account. - public let actorDID: String - - enum CodingKeys: String, CodingKey { - case actorDID = "actor" - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphMuteActorList.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphMuteActorList.swift deleted file mode 100644 index 92204ac038..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphMuteActorList.swift +++ /dev/null @@ -1,25 +0,0 @@ -// -// BskyGraphMuteActorList.swift -// -// -// Created by Christopher Jr Riley on 2024-03-10. -// - -import Foundation - -/// The main data model definition for muting a list. -/// -/// - Note: According to the AT Protocol specifications: "Creates a mute relationship for the -/// specified list of accounts. Mutes are private in Bluesky. Requires auth." -/// -/// - SeeAlso: This is based on the [`app.bsky.graph.muteActorList`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/muteActor.json -public struct GraphMuteActorList: Codable { - /// The URI of a list. - public let listURI: String - - enum CodingKeys: String, CodingKey { - case listURI = "list" - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphUnmuteActor.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphUnmuteActor.swift deleted file mode 100644 index 018afcf718..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphUnmuteActor.swift +++ /dev/null @@ -1,25 +0,0 @@ -// -// BskyGraphUnmuteActor.swift -// -// -// Created by Christopher Jr Riley on 2024-03-10. -// - -import Foundation - -/// The main data model definition for unmuting a user account. -/// -/// - Note: According to the AT Protocol specifications: "Unmutes the specified account. -/// Requires auth." -/// -/// - SeeAlso: This is based on the [`app.bsky.graph.unmuteActor`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/unmuteActor.json -public struct GraphUnmuteActor: Codable { - /// The decentralized identifier (DID) or handle of a user account. - public let actorDID: String - - enum CodingKeys: String, CodingKey { - case actorDID = "actor" - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphUnmuteActorList.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphUnmuteActorList.swift deleted file mode 100644 index 43c1b0be25..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Graph/BskyGraphUnmuteActorList.swift +++ /dev/null @@ -1,26 +0,0 @@ -// -// BskyGraphUnmuteActorList.swift -// -// -// Created by Christopher Jr Riley on 2024-03-10. -// - -import Foundation - -/// The main data model definition for unmuting a list of user accounts. -/// -/// - Note: According to the AT Protocol specifications: "Unmutes the specified list of -/// accounts. Requires auth." -/// -/// - SeeAlso: This is based on the [`app.bsky.graph.unmuteActorList`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/graph/unmuteActorList.json -public struct GraphUnmuteActorList: Codable { - /// The URI of a list. - public let listURI: String - - enum CodingKeys: String, CodingKey { - case listURI = "list" - } -} - diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Labeler/AppBskyLabelerDefs.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Labeler/AppBskyLabelerDefs.swift new file mode 100644 index 0000000000..12e124d073 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Labeler/AppBskyLabelerDefs.swift @@ -0,0 +1,210 @@ +// +// AppBskyLabelerDefs.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Labeler { + + /// A definition model for a labeler view. + /// + /// - SeeAlso: This is based on the [`app.bsky.labeler.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/labeler/defs.json + public struct LabelerViewDefinition: Codable { + + /// The URI of the labeler. + public let labelerURI: String + + /// The CID hash of the labeler. + public let labelerCIDHash: String + + /// The creator of the labeler. + public let creator: AppBskyLexicon.Actor.ProfileViewDefinition + + /// The number of likes for the labeler. Optional. + public let likeCount: Int? + + /// The viewer state of the labeler. Optional. + public let viewer: LabelerViewerStateDefinition? + + /// The date and time the labeler was last indexed. + @DateFormatting public var indexedAt: Date + + /// An array of labels. Optional. + public let labels: [ComAtprotoLexicon.Label.LabelDefinition]? + + public init(labelerURI: String, labelerCIDHash: String, creator: AppBskyLexicon.Actor.ProfileViewDefinition, likeCount: Int?, + viewer: LabelerViewerStateDefinition?, indexedAt: Date, labels: [ComAtprotoLexicon.Label.LabelDefinition]?) { + self.labelerURI = labelerURI + self.labelerCIDHash = labelerCIDHash + self.creator = creator + self.likeCount = likeCount + self.viewer = viewer + self._indexedAt = DateFormatting(wrappedValue: indexedAt) + self.labels = labels + } + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.labelerURI = try container.decode(String.self, forKey: .labelerURI) + self.labelerCIDHash = try container.decode(String.self, forKey: .labelerCIDHash) + self.creator = try container.decode(AppBskyLexicon.Actor.ProfileViewDefinition.self, forKey: .creator) + self.likeCount = try container.decodeIfPresent(Int.self, forKey: .likeCount) + self.viewer = try container.decodeIfPresent(LabelerViewerStateDefinition.self, forKey: .viewer) + self.indexedAt = try container.decode(DateFormatting.self, forKey: .indexedAt).wrappedValue + self.labels = try container.decodeIfPresent([ComAtprotoLexicon.Label.LabelDefinition].self, forKey: .labels) + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.labelerURI, forKey: .labelerURI) + try container.encode(self.labelerCIDHash, forKey: .labelerCIDHash) + try container.encode(self.creator, forKey: .creator) + + // Assuming `likeCount` is not nil, only encode it if it's 0 or higher + if let likeCount = self.likeCount, likeCount >= 0 { + try container.encode(likeCount, forKey: .likeCount) + } + try container.encodeIfPresent(self.viewer, forKey: .viewer) + try container.encode(self._indexedAt, forKey: .indexedAt) + try container.encodeIfPresent(self.labels, forKey: .labels) + } + + enum CodingKeys: String, CodingKey { + case labelerURI = "uri" + case labelerCIDHash = "cid" + case creator + case likeCount + case viewer + case indexedAt + case labels + } + } + + /// A definition model for a detailed labeler view. + /// + /// - SeeAlso: This is based on the [`app.bsky.labeler.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/labeler/defs.json + public struct LabelerViewDetailedDefinition: Codable { + + /// The URI of the labeler. + public let labelerURI: String + + /// The CID hash of the labeler. + public let labelerCIDHash: String + + /// The creator of the labeler. + public let creator: AppBskyLexicon.Actor.ProfileViewDefinition + + /// A list of policies by the labeler. + public let policies: LabelerPolicies + + /// The number of likes for the labeler. Optional. + public let likeCount: Int? + + /// The viewer state of the labeler. Optional. + public let viewer: AppBskyLexicon.Labeler.LabelerViewerStateDefinition? + + /// The date and time the labeler was last indexed. + @DateFormatting public var indexedAt: Date + + /// An array of labels. Optional. + public let labels: [ComAtprotoLexicon.Label.LabelDefinition]? + + public init(labelerURI: String, labelerCIDHash: String, creator: AppBskyLexicon.Actor.ProfileViewDefinition, policies: LabelerPolicies, + likeCount: Int?, viewer: AppBskyLexicon.Labeler.LabelerViewerStateDefinition?, indexedAt: Date, + labels: [ComAtprotoLexicon.Label.LabelDefinition]?) { + self.labelerURI = labelerURI + self.labelerCIDHash = labelerCIDHash + self.creator = creator + self.policies = policies + self.likeCount = likeCount + self.viewer = viewer + self._indexedAt = DateFormatting(wrappedValue: indexedAt) + self.labels = labels + } + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.labelerURI = try container.decode(String.self, forKey: .labelerURI) + self.labelerCIDHash = try container.decode(String.self, forKey: .labelerCIDHash) + self.creator = try container.decode(AppBskyLexicon.Actor.ProfileViewDefinition.self, forKey: .creator) + self.policies = try container.decode(LabelerPolicies.self, forKey: .policies) + self.likeCount = try container.decodeIfPresent(Int.self, forKey: .likeCount) + self.viewer = try container.decodeIfPresent(AppBskyLexicon.Labeler.LabelerViewerStateDefinition.self, forKey: .viewer) + self.indexedAt = try container.decode(DateFormatting.self, forKey: .indexedAt).wrappedValue + self.labels = try container.decodeIfPresent([ComAtprotoLexicon.Label.LabelDefinition].self, forKey: .labels) + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.labelerURI, forKey: .labelerURI) + try container.encode(self.labelerCIDHash, forKey: .labelerCIDHash) + try container.encode(self.creator, forKey: .creator) + try container.encode(self.policies, forKey: .policies) + + // Assuming `likeCount` is not nil, only encode it if it's 0 or higher + if let likeCount = self.likeCount, likeCount >= 0 { + try container.encode(likeCount, forKey: .likeCount) + } + try container.encodeIfPresent(self.viewer, forKey: .viewer) + try container.encode(self._indexedAt, forKey: .indexedAt) + try container.encodeIfPresent(self.labels, forKey: .labels) + } + + enum CodingKeys: String, CodingKey { + case labelerURI = "uri" + case labelerCIDHash = "cid" + case creator + case policies + case likeCount + case viewer + case indexedAt + case labels + } + } + + /// A definition model for a user account's view state for the labeler. + /// + /// - SeeAlso: This is based on the [`app.bsky.labeler.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/labeler/defs.json + public struct LabelerViewerStateDefinition: Codable { + + /// The URI of the like record, if the user liked the labeler. + public let like: String + } + + /// A definition model for a labeler's policies. + /// + /// - SeeAlso: This is based on the [`app.bsky.labeler.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/labeler/defs.json + public struct LabelerPolicies: Codable { + + /// An array of the labeler-published values. + /// + /// - Note: According to the AT Protocol specifications: "The label values which this labeler + /// publishes. May include global + /// or custom labels." + public let labelValues: [ComAtprotoLexicon.Label.LabelValueDefinition] + + /// An array of labeler-created labels. + /// + /// Labels made in here will override global definitions. + /// + /// - Note: According to the AT Protocol specifications: "Label values created by this labeler + /// and scoped exclusively to it. Labels defined here will override global label definitions + /// for this labeler." + public let labelValueDefinitions: [ComAtprotoLexicon.Label.LabelValueDefinition] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Labeler/AppBskyLabelerGetServices.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Labeler/AppBskyLabelerGetServices.swift new file mode 100644 index 0000000000..46658e6973 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Labeler/AppBskyLabelerGetServices.swift @@ -0,0 +1,26 @@ +// +// AppBskyLabelerGetServices.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Labeler { + + /// An output model for the labeler service information. + /// + /// - Note: According to the AT Protocol specifications: "Get information about a list of + /// labeler services." + /// + /// - SeeAlso: This is based on the [`app.bsky.labeler.getServices`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/labeler/getServices.json + public struct GetServicesOutput: Codable { + + /// A labeler view. + public let views: ATUnion.GetServicesOutputViewsUnion + + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Labeler/AppBskyLabelerService.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Labeler/AppBskyLabelerService.swift new file mode 100644 index 0000000000..3214b1f28a --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Labeler/AppBskyLabelerService.swift @@ -0,0 +1,65 @@ +// +// AppBskyLabelerService.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Labeler { + + /// A record model for a labeler service. + /// + /// - Note: According to the AT Protocol specifications: "A declaration of the existence of + /// labeler service." + /// + /// - SeeAlso: This is based on the [`app.bsky.labeler.service`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/labeler/service.json + public struct ServiceRecord: ATRecordProtocol { + + /// The identifier of the lexicon. + /// + /// - Warning: The value must not change. + public static private(set) var type: String = "app.bsky.labeler.service" + + /// The policies the labeler service adheres to. + public let policies: LabelerPolicies + + /// An array of labels the labeler uses. Optional. + public let labels: [ComAtprotoLexicon.Label.SelfLabelDefinition]? + + /// The date and time the labeler service was created. + @DateFormatting public var createdAt: Date + + public init(policies: LabelerPolicies, labels: [ComAtprotoLexicon.Label.SelfLabelDefinition], createdAt: Date) { + self.policies = policies + self.labels = labels + self._createdAt = DateFormatting(wrappedValue: createdAt) + } + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.policies = try container.decode(LabelerPolicies.self, forKey: .policies) + self.labels = try container.decode([ComAtprotoLexicon.Label.SelfLabelDefinition].self, forKey: .labels) + self.createdAt = try container.decode(DateFormatting.self, forKey: .createdAt).wrappedValue + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.policies, forKey: .policies) + try container.encode(self.labels, forKey: .labels) + try container.encode(self._createdAt, forKey: .createdAt) + } + + enum CodingKeys: String, CodingKey { + case type = "$type" + case policies + case labels + case createdAt + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Labeler/BskyLabelerDefs.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Labeler/BskyLabelerDefs.swift deleted file mode 100644 index b109e031be..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Labeler/BskyLabelerDefs.swift +++ /dev/null @@ -1,186 +0,0 @@ -// -// BskyLabelerDefs.swift -// -// -// Created by Christopher Jr Riley on 2024-03-14. -// - -import Foundation - -/// A data model definition for a labeler view. -/// -/// - SeeAlso: This is based on the [`app.bsky.labeler.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/labeler/defs.json -public struct LabelerView: Codable { - /// The URI of the labeler. - public let labelerURI: String - /// The CID hash of the labeler. - public let labelerCIDHash: String - /// The creator of the labeler. - public let creator: ActorProfileView - /// The number of likes for the labeler. Optional. - public let likeCount: Int? - /// The viewer state of the labeler. Optional. - public let viewer: LabelerViewerState? - /// The date and time the labeler was last indexed. - @DateFormatting public var indexedAt: Date - /// An array of labels. Optional. - public let labels: [Label]? - - public init(labelerURI: String, labelerCIDHash: String, creator: ActorProfileView, likeCount: Int?, viewer: LabelerViewerState?, indexedAt: Date, labels: [Label]?) { - self.labelerURI = labelerURI - self.labelerCIDHash = labelerCIDHash - self.creator = creator - self.likeCount = likeCount - self.viewer = viewer - self._indexedAt = DateFormatting(wrappedValue: indexedAt) - self.labels = labels - } - - public init(from decoder: any Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.labelerURI = try container.decode(String.self, forKey: .labelerURI) - self.labelerCIDHash = try container.decode(String.self, forKey: .labelerCIDHash) - self.creator = try container.decode(ActorProfileView.self, forKey: .creator) - self.likeCount = try container.decodeIfPresent(Int.self, forKey: .likeCount) - self.viewer = try container.decodeIfPresent(LabelerViewerState.self, forKey: .viewer) - self.indexedAt = try container.decode(DateFormatting.self, forKey: .indexedAt).wrappedValue - self.labels = try container.decodeIfPresent([Label].self, forKey: .labels) - } - - public func encode(to encoder: any Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - try container.encode(self.labelerURI, forKey: .labelerURI) - try container.encode(self.labelerCIDHash, forKey: .labelerCIDHash) - try container.encode(self.creator, forKey: .creator) - - // Assuming `likeCount` is not nil, only encode it if it's 0 or higher - if let likeCount = self.likeCount, likeCount >= 0 { - try container.encode(likeCount, forKey: .likeCount) - } - try container.encodeIfPresent(self.viewer, forKey: .viewer) - try container.encode(self._indexedAt, forKey: .indexedAt) - try container.encodeIfPresent(self.labels, forKey: .labels) - } - - enum CodingKeys: String, CodingKey { - case labelerURI = "uri" - case labelerCIDHash = "cid" - case creator - case likeCount - case viewer - case indexedAt - case labels - } -} - -/// A data model definition for a detailed labeler view. -/// -/// - SeeAlso: This is based on the [`app.bsky.labeler.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/labeler/defs.json -public struct LabelerViewDetailed: Codable { - /// The URI of the labeler. - public let labelerURI: String - /// The CID hash of the labeler. - public let labelerCIDHash: String - /// The creator of the labeler. - public let creator: ActorProfileView - /// A list of policies by the labeler. - public let policies: LabelerPolicies - /// The number of likes for the labeler. Optional. - public let likeCount: Int? - /// The viewer state of the labeler. Optional. - public let viewer: LabelerViewerState? - /// The date and time the labeler was last indexed. - @DateFormatting public var indexedAt: Date - /// An array of labels. Optional. - public let labels: [Label]? - - public init(labelerURI: String, labelerCIDHash: String, creator: ActorProfileView, policies: LabelerPolicies, likeCount: Int?, viewer: LabelerViewerState?, indexedAt: Date, labels: [Label]?) { - self.labelerURI = labelerURI - self.labelerCIDHash = labelerCIDHash - self.creator = creator - self.policies = policies - self.likeCount = likeCount - self.viewer = viewer - self._indexedAt = DateFormatting(wrappedValue: indexedAt) - self.labels = labels - } - - public init(from decoder: any Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.labelerURI = try container.decode(String.self, forKey: .labelerURI) - self.labelerCIDHash = try container.decode(String.self, forKey: .labelerCIDHash) - self.creator = try container.decode(ActorProfileView.self, forKey: .creator) - self.policies = try container.decode(LabelerPolicies.self, forKey: .policies) - self.likeCount = try container.decodeIfPresent(Int.self, forKey: .likeCount) - self.viewer = try container.decodeIfPresent(LabelerViewerState.self, forKey: .viewer) - self.indexedAt = try container.decode(DateFormatting.self, forKey: .indexedAt).wrappedValue - self.labels = try container.decodeIfPresent([Label].self, forKey: .labels) - } - - public func encode(to encoder: any Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - try container.encode(self.labelerURI, forKey: .labelerURI) - try container.encode(self.labelerCIDHash, forKey: .labelerCIDHash) - try container.encode(self.creator, forKey: .creator) - try container.encode(self.policies, forKey: .policies) - - // Assuming `likeCount` is not nil, only encode it if it's 0 or higher - if let likeCount = self.likeCount, likeCount >= 0 { - try container.encode(likeCount, forKey: .likeCount) - } - try container.encodeIfPresent(self.viewer, forKey: .viewer) - try container.encode(self._indexedAt, forKey: .indexedAt) - try container.encodeIfPresent(self.labels, forKey: .labels) - } - - enum CodingKeys: String, CodingKey { - case labelerURI = "uri" - case labelerCIDHash = "cid" - case creator - case policies - case likeCount - case viewer - case indexedAt - case labels - } -} - -/// A data model definition for a user account's view state for the labeler. -/// -/// - SeeAlso: This is based on the [`app.bsky.labeler.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/labeler/defs.json -public struct LabelerViewerState: Codable { - /// The URI of the like record, if the user liked the labeler. - public let like: String -} - -/// A data model definition for a labeler's policies. -/// -/// - SeeAlso: This is based on the [`app.bsky.labeler.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/labeler/defs.json -public struct LabelerPolicies: Codable { - /// An array of the labeler-published values. - /// - /// - Note: According to the AT Protocol specifications: "The label values which this labeler - /// publishes. May include global - /// or custom labels." - public let labelValues: [LabelValue] - /// An array of labeler-created labels. - /// - /// Labels made in here will override global definitions. - /// - /// - Note: According to the AT Protocol specifications: "Label values created by this labeler - /// and scoped exclusively to it. Labels defined here will override global label definitions - /// for this labeler." - public let labelValueDefinitions: [LabelValueDefinition] -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Labeler/BskyLabelerGetServices.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Labeler/BskyLabelerGetServices.swift deleted file mode 100644 index 9b2ac0c86e..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Labeler/BskyLabelerGetServices.swift +++ /dev/null @@ -1,54 +0,0 @@ -// -// BskyLabelerGetServices.swift -// -// -// Created by Christopher Jr Riley on 2024-03-14. -// - -import Foundation - -/// The main data model definition for the output of the labeler service information. -/// -/// - Note: According to the AT Protocol specifications: "Get information about a list of -/// labeler services." -/// -/// - SeeAlso: This is based on the [`app.bsky.labeler.getServices`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/labeler/getServices.json -public struct LabelerGetServicesOutput: Codable { - /// A labeler view. - public let views: LabelerViewUnion -} - -/// A reference containing the list of labeler views. -public enum LabelerViewUnion: Codable { - /// A labeler view. - case labelerView(LabelerView) - /// A detailed view of a labeler. - case labelerViewDetailed(LabelerViewDetailed) - - public init(from decoder: any Decoder) throws { - let container = try decoder.singleValueContainer() - - if let value = try? container.decode(LabelerView.self) { - self = .labelerView(value) - } else if let value = try? container.decode(LabelerViewDetailed.self) { - self = .labelerViewDetailed(value) - } else { - throw DecodingError.typeMismatch( - ActorPreferenceUnion.self, DecodingError.Context( - codingPath: decoder.codingPath, debugDescription: "Unknown LabelerViewUnion type")) - } - } - - public func encode(to encoder: any Encoder) throws { - var container = encoder.singleValueContainer() - - switch self { - case .labelerView(let labelerView): - try container.encode(labelerView) - case .labelerViewDetailed(let labelerViewDetailed): - try container.encode(labelerViewDetailed) - } - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Labeler/BskyLabelerService.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Labeler/BskyLabelerService.swift deleted file mode 100644 index ee2fa1415e..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Labeler/BskyLabelerService.swift +++ /dev/null @@ -1,59 +0,0 @@ -// -// BskyLabelerService.swift -// -// -// Created by Christopher Jr Riley on 2024-03-14. -// - -import Foundation - -/// The main data model definition for a labeler service record. -/// -/// - Note: According to the AT Protocol specifications: "A declaration of the existence of -/// labeler service." -/// -/// - SeeAlso: This is based on the [`app.bsky.labeler.service`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/labeler/service.json -public struct LabelerService: ATRecordProtocol { - /// The identifier of the lexicon. - /// - /// - Warning: The value must not change. - public static private(set) var type: String = "app.bsky.labeler.service" - /// The policies the labeler service adheres to. - public let policies: LabelerPolicies - /// An array of labels the labeler uses. Optional. - public let labels: [SelfLabels]? - /// The date and time the labeler service was created. - @DateFormatting public var createdAt: Date - - public init(policies: LabelerPolicies, labels: [SelfLabels], createdAt: Date) { - self.policies = policies - self.labels = labels - self._createdAt = DateFormatting(wrappedValue: createdAt) - } - - public init(from decoder: any Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.policies = try container.decode(LabelerPolicies.self, forKey: .policies) - self.labels = try container.decode([SelfLabels].self, forKey: .labels) - self.createdAt = try container.decode(DateFormatting.self, forKey: .createdAt).wrappedValue - } - - public func encode(to encoder: any Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - -// try container.encode(self.type, forKey: .type) - try container.encode(self.policies, forKey: .policies) - try container.encode(self.labels, forKey: .labels) - try container.encode(self._createdAt, forKey: .createdAt) - } - - enum CodingKeys: String, CodingKey { - case type = "$type" - case policies - case labels - case createdAt - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Notification/AppBskyNotificationGetUnreadCount.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Notification/AppBskyNotificationGetUnreadCount.swift new file mode 100644 index 0000000000..302a99c5ea --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Notification/AppBskyNotificationGetUnreadCount.swift @@ -0,0 +1,25 @@ +// +// AppBskyNotificationGetUnreadCount.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Notification { + + /// An output model for counting the unread notifications. + /// + /// - Note: According to the AT Protocol specifications: "Count the number of unread + /// notifications for the requesting account. Requires auth." + /// + /// - SeeAlso: This is based on the [`app.bsky.notification.getUnreadCount`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/notification/getUnreadCount.json + public struct GetUnreadCountOutput: Codable { + + /// The number of unread notifications. + public let count: Int + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Notification/AppBskyNotificationListNotifications.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Notification/AppBskyNotificationListNotifications.swift new file mode 100644 index 0000000000..38b663bd40 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Notification/AppBskyNotificationListNotifications.swift @@ -0,0 +1,144 @@ +// +// AppBskyNotificationListNotifications.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Notification { + + /// An output model for listing notifications. + /// + /// - Note: According to the AT Protocol specifications: "Enumerate notifications for the + /// requesting account. Requires auth." + /// + /// - SeeAlso: This is based on the [`app.bsky.notification.listNotifications`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/notification/listNotifications.json + public struct ListNotificationsOutput: Codable { + + /// The mark used to indicate the starting point for the next set of results. Optional. + public let cursor: String? + + /// An array of notifications. + public let notifications: [Notification] + } + + /// A data model definition for a notification. + /// + /// - SeeAlso: This is based on the [`app.bsky.notification.listNotifications`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/notification/listNotifications.json + public struct Notification: Codable { + + /// The URI of the notification. + public let notificationURI: String + + /// The CID hash of the notification. + public let notificationCID: String + + /// The author of the record contained in the notification. + public let notificationAuthor: String + + /// The kind of notification received. + /// + /// - Note: According to the AT Protocol specifications: "Expected values are 'like', + /// 'repost', 'follow', 'mention', 'reply', and 'quote'." + public let notificationReason: Reason + + /// The URI of the subject in the notification. Optional. + public let reasonSubjectURI: String? + + /// The record itself that's attached to the notification. + public let record: UnknownType + + /// Indicates whether or not this notification was read. + public let isRead: Bool + + /// The date and time the notification was last indexed. + @DateFormatting public var indexedAt: Date + + /// An array of labels. Optional. + public let labels: [ComAtprotoLexicon.Label.LabelDefinition]? + + public init(notificationURI: String, notificationCID: String, notificationAuthor: String, notificationReason: Reason, reasonSubjectURI: String, + record: UnknownType, isRead: Bool, indexedAt: Date, labels: [ComAtprotoLexicon.Label.LabelDefinition]) { + self.notificationURI = notificationURI + self.notificationCID = notificationCID + self.notificationAuthor = notificationAuthor + self.notificationReason = notificationReason + self.reasonSubjectURI = reasonSubjectURI + self.record = record + self.isRead = isRead + self._indexedAt = DateFormatting(wrappedValue: indexedAt) + self.labels = labels + } + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.notificationURI = try container.decode(String.self, forKey: .notificationURI) + self.notificationCID = try container.decode(String.self, forKey: .notificationCID) + self.notificationAuthor = try container.decode(String.self, forKey: .notificationAuthor) + self.notificationReason = try container.decode(Notification.Reason.self, forKey: .notificationReason) + self.reasonSubjectURI = try container.decodeIfPresent(String.self, forKey: .reasonSubjectURI) + self.record = try container.decode(UnknownType.self, forKey: .record) + self.isRead = try container.decode(Bool.self, forKey: .isRead) + self.indexedAt = try container.decode(DateFormatting.self, forKey: .indexedAt).wrappedValue + self.labels = try container.decodeIfPresent([ComAtprotoLexicon.Label.LabelDefinition].self, forKey: .labels) + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.notificationURI, forKey: .notificationURI) + try container.encode(self.notificationCID, forKey: .notificationCID) + try container.encode(self.notificationAuthor, forKey: .notificationAuthor) + try container.encode(self.notificationReason, forKey: .notificationReason) + try container.encodeIfPresent(self.reasonSubjectURI, forKey: .reasonSubjectURI) + try container.encode(self.record, forKey: .record) + try container.encode(self.isRead, forKey: .isRead) + try container.encode(self._indexedAt, forKey: .indexedAt) + try container.encodeIfPresent(self.labels, forKey: .labels) + } + + enum CodingKeys: String, CodingKey { + case notificationURI = "uri" + case notificationCID = "cid" + case notificationAuthor = "author" + case notificationReason = "reason" + case reasonSubjectURI = "reasonSubject" + case record + case isRead + case indexedAt + case labels + } + + // Enums + /// The kind of notification received. + public enum Reason: String, Codable { + + /// Indicates the notification is about someone liking a post from the user account. + case like + + /// Indicates the notification is about someone reposting a post from the + /// user account. + case repost + + /// Indicates the notification is about someone following the user account. + case follow + + /// Indicates the notification is about someone @mentioning the user account. + case mention + + /// Indicates the notification is about someone replying to one of the + /// user account's posts. + case reply + + /// Indicates the notification is about someone quoting a post from the user account. + case quote + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Notification/AppBskyNotificationRegisterPush.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Notification/AppBskyNotificationRegisterPush.swift new file mode 100644 index 0000000000..61cc08baf1 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Notification/AppBskyNotificationRegisterPush.swift @@ -0,0 +1,60 @@ +// +// AppBskyNotificationRegisterPush.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Notification { + + + /// The main data model definition for registering push notifications. + public struct RegisterPush: Codable { + + /// Represents the platform for the push notifications. + public enum Platform: String, Codable { + + /// Indicates iOS as the platform. + case ios + + /// Indicates Android as the platform. + case android + + /// Indicates the web as the platform. + case web + } + } + + /// A request body model for registering push notifications. + /// + /// - Note: According to the AT Protocol specifications: "Register to receive + /// push notifications, via a specified service, for the requesting account. + /// Requires auth." + /// + /// - SeeAlso: This is based on the [`app.bsky.notification.registerPush`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/notification/registerPush.json + public struct RegisterPushRequestBody: Codable { + + /// The decentralized identifier (DID) for the push notification request. + public let serviceDID: String + + /// The push notification token. + public let token: String + + /// The platform for the push notifications. + public let platform: RegisterPush.Platform + + /// The app ID for the push notification. + public let appID: String + + enum CodingKeys: String, CodingKey { + case serviceDID = "serviceDid" + case token + case platform + case appID = "appId" + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Notification/AppBskyNotificationUpdateSeen.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Notification/AppBskyNotificationUpdateSeen.swift new file mode 100644 index 0000000000..7b309f2277 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Notification/AppBskyNotificationUpdateSeen.swift @@ -0,0 +1,45 @@ +// +// AppBskyNotificationUpdateSeen.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Notification { + + /// A request body model for updating the server of the user seeing the notification. + /// + /// - Note: According to the AT Protocol specifications: "Notify server that the requesting + /// account has seen notifications. Requires auth." + /// + /// - SeeAlso: This is based on the [`app.bsky.notification.updateSeen`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/notification/updateSeen.json + public struct UpdateSeenRequestBody: Codable { + + /// The date and time the notification was seen by the user account. + @DateFormatting public var seenAt: Date + + public init(seenAt: Date) { + self._seenAt = DateFormatting(wrappedValue: seenAt) + } + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.seenAt = try container.decode(DateFormatting.self, forKey: .seenAt).wrappedValue + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self._seenAt, forKey: .seenAt) + } + + enum CodingKeys: CodingKey { + case seenAt + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Notification/BaskyNotificationUpdateSeen.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Notification/BaskyNotificationUpdateSeen.swift deleted file mode 100644 index 3b22e10483..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Notification/BaskyNotificationUpdateSeen.swift +++ /dev/null @@ -1,40 +0,0 @@ -// -// BaskyNotificationUpdateSeen.swift -// -// -// Created by Christopher Jr Riley on 2024-03-15. -// - -import Foundation - -/// The main data model definition for updating the server of the user seeing the notification. -/// -/// - Note: According to the AT Protocol specifications: "Notify server that the requesting account -/// has seen notifications. Requires auth." -/// -/// - SeeAlso: This is based on the [`app.bsky.notification.updateSeen`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/notification/updateSeen.json -public struct NotificationUpdateSeen: Codable { - @DateFormatting public var seenAt: Date - - public init(seenAt: Date) { - self._seenAt = DateFormatting(wrappedValue: seenAt) - } - - public init(from decoder: any Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.seenAt = try container.decode(DateFormatting.self, forKey: .seenAt).wrappedValue - } - - public func encode(to encoder: any Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - try container.encode(self._seenAt, forKey: .seenAt) - } - - enum CodingKeys: CodingKey { - case seenAt - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Notification/BskyNotificationGetUnreadCount.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Notification/BskyNotificationGetUnreadCount.swift deleted file mode 100644 index 66cdcfb820..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Notification/BskyNotificationGetUnreadCount.swift +++ /dev/null @@ -1,20 +0,0 @@ -// -// BskyNotificationGetUnreadCount.swift -// -// -// Created by Christopher Jr Riley on 2024-03-15. -// - -import Foundation - -/// The main data model definition for the output of counting the unread notifications. -/// -/// - Note: According to the AT Protocol specifications: "Count the number of unread -/// notifications for the requesting account. Requires auth." -/// -/// - SeeAlso: This is based on the [`app.bsky.notification.getUnreadCount`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/notification/getUnreadCount.json -public struct NotificationGetUnreadCountOutput: Codable { - public let count: Int -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Notification/BskyNotificationListNotifications.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Notification/BskyNotificationListNotifications.swift deleted file mode 100644 index dd3bd83f71..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Notification/BskyNotificationListNotifications.swift +++ /dev/null @@ -1,115 +0,0 @@ -// -// BskyNotificationListNotifications.swift -// -// -// Created by Christopher Jr Riley on 2024-03-15. -// - -import Foundation - -/// The main data model definition for the output of listing notifications. -/// -/// - Note: According to the AT Protocol specifications: "Enumerate notifications for the -/// requesting account. Requires auth." -/// -/// - SeeAlso: This is based on the [`app.bsky.notification.listNotifications`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/notification/listNotifications.json -public struct NotificationListNotificationsOutput: Codable { - /// The mark used to indicate the starting point for the next set of results. Optional. - public let cursor: String? - /// An array of notifications. - public let notifications: [ATNotification] -} - -/// A data model definition for a notification. -/// -/// - SeeAlso: This is based on the [`app.bsky.notification.listNotifications`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/notification/listNotifications.json -public struct ATNotification: Codable { - /// The URI of the notification. - public let notificationURI: String - /// The CID hash of the notification. - public let notificationCID: String - /// The author of the record contained in the notification. - public let notificationAuthor: String - /// The type of notification received. - /// - /// - Note: According to the AT Protocol specifications: "Expected values are 'like', 'repost', - /// 'follow', 'mention', 'reply', and 'quote'." - public let notificationReason: Reason - /// The URI of the subject in the notification. Optional. - public let reasonSubjectURI: String? - /// The record itself that's attached to the notification. - public let record: UnknownType - /// Indicates whether or not this notification was read. - public let isRead: Bool - /// The date and time the notification was last indexed. - @DateFormatting public var indexedAt: Date - /// An array of labels. Optional. - public let labels: [Label]? - - public init(notificationURI: String, notificationCID: String, notificationAuthor: String, notificationReason: Reason, reasonSubjectURI: String, - record: UnknownType, isRead: Bool, indexedAt: Date, labels: [Label]) { - self.notificationURI = notificationURI - self.notificationCID = notificationCID - self.notificationAuthor = notificationAuthor - self.notificationReason = notificationReason - self.reasonSubjectURI = reasonSubjectURI - self.record = record - self.isRead = isRead - self._indexedAt = DateFormatting(wrappedValue: indexedAt) - self.labels = labels - } - - public init(from decoder: any Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.notificationURI = try container.decode(String.self, forKey: .notificationURI) - self.notificationCID = try container.decode(String.self, forKey: .notificationCID) - self.notificationAuthor = try container.decode(String.self, forKey: .notificationAuthor) - self.notificationReason = try container.decode(ATNotification.Reason.self, forKey: .notificationReason) - self.reasonSubjectURI = try container.decodeIfPresent(String.self, forKey: .reasonSubjectURI) - self.record = try container.decode(UnknownType.self, forKey: .record) - self.isRead = try container.decode(Bool.self, forKey: .isRead) - self.indexedAt = try container.decode(DateFormatting.self, forKey: .indexedAt).wrappedValue - self.labels = try container.decodeIfPresent([Label].self, forKey: .labels) - } - - public func encode(to encoder: any Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - try container.encode(self.notificationURI, forKey: .notificationURI) - try container.encode(self.notificationCID, forKey: .notificationCID) - try container.encode(self.notificationAuthor, forKey: .notificationAuthor) - try container.encode(self.notificationReason, forKey: .notificationReason) - try container.encodeIfPresent(self.reasonSubjectURI, forKey: .reasonSubjectURI) - try container.encode(self.record, forKey: .record) - try container.encode(self.isRead, forKey: .isRead) - try container.encode(self._indexedAt, forKey: .indexedAt) - try container.encodeIfPresent(self.labels, forKey: .labels) - } - - enum CodingKeys: String, CodingKey { - case notificationURI = "uri" - case notificationCID = "cid" - case notificationAuthor = "author" - case notificationReason = "reason" - case reasonSubjectURI = "reasonSubject" - case record - case isRead - case indexedAt - case labels - } - - // Enums - public enum Reason: String, Codable { - case like - case repost - case follow - case mention - case reply - case quote - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Notification/BskyNotificationRegisterPush.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Notification/BskyNotificationRegisterPush.swift deleted file mode 100644 index cc564ea41e..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Notification/BskyNotificationRegisterPush.swift +++ /dev/null @@ -1,45 +0,0 @@ -// -// BskyNotificationRegisterPush.swift -// -// -// Created by Christopher Jr Riley on 2024-01-27. -// - -import Foundation - -// MARK: - Main definition -/// The main data model definition for registering push notifications. -/// -/// - Note: According to the AT Protocol specifications: "Register to receive push notifications, -/// via a specified service, for the requesting account. Requires auth." -/// -/// - SeeAlso: This is based on the [`app.bsky.notification.registerPush`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/notification/registerPush.json -public struct RegisterPushRequest: Codable { - /// The decentralized identifier (DID) for the push notification request. - public let serviceDID: String - /// The push notification token. - public let token: String - /// The platform for the push notifications. - public let platform: Platform - /// The app ID for the push notification. - public let appID: String - - /// Represents the platform for the push notifications. - public enum Platform: String, Codable { - /// Indicates iOS as the platform. - case ios - /// Indicates Android as the platform. - case android - /// Indicates the web as the platform. - case web - } - - enum CodingKeys: String, CodingKey { - case serviceDID = "serviceDid" - case token - case platform - case appID = "appId" - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/RichText/AppBskyRichTextFacet.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/RichText/AppBskyRichTextFacet.swift new file mode 100644 index 0000000000..e84f1db356 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/RichText/AppBskyRichTextFacet.swift @@ -0,0 +1,239 @@ +// +// AppBskyRichTextFacet.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.RichText { + + /// The main data model definition for a facet. + /// + /// - Note: According to the AT Protocol specifications: "Annotation of a sub-string within + /// rich text." + /// + /// - SeeAlso: This is based on the [`app.bsky.richtext.facet`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/richtext/facet.json + public struct Facet: Codable { + + /// The range of characters related to the facet. + public let index: ByteSlice + + /// The facet's feature type. + public let features: [ATUnion.FacetFeatureUnion] + + public init(index: ByteSlice, features: [ATUnion.FacetFeatureUnion]) { + self.index = index + self.features = features + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.index = try container.decode(ByteSlice.self, forKey: .index) + self.features = try container.decode([ATUnion.FacetFeatureUnion].self, forKey: .features) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.index, forKey: .index) + try container.encode(self.features, forKey: .features) + } + + enum CodingKeys: String, CodingKey { + case index + case features + } + + // Enums + // Represents the ByteSlice + /// The data model definition for the byte slice. + /// + /// - Note: According to the AT Protocol specifications: "Specifies the sub-string range a + /// facet feature applies to. Start index is inclusive, end index is exclusive. Indices are + /// zero-indexed, counting bytes of the UTF-8 encoded text. NOTE: some languages, like + /// Javascript, use UTF-16 or Unicode codepoints for string slice indexing; in these + /// languages, convert to byte arrays before working with facets." + /// + /// - SeeAlso: This is based on the [`app.bsky.richtext.facet`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/richtext/facet.json + public struct ByteSlice: Codable { + + /// The start index of the byte slice. + public let byteStart: Int + + /// The end index of the byte slice. + public let byteEnd: Int + + public init(byteStart: Int, byteEnd: Int) { + self.byteStart = byteStart + self.byteEnd = byteEnd + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.byteStart = try container.decode(Int.self, forKey: .byteStart) + self.byteEnd = try container.decode(Int.self, forKey: .byteEnd) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.byteStart, forKey: .byteStart) + try container.encode(self.byteEnd, forKey: .byteEnd) + } + + enum CodingKeys: String, CodingKey { + case byteStart + case byteEnd + } + } + + /// A data model protocol for Features. + /// + /// - SeeAlso: This is based on the [`app.bsky.richtext.facet`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/richtext/facet.json + internal protocol FeatureCodable: Codable { + + /// The identifier of the lexicon. + /// + /// - Warning: The value must not change. + static var type: String { get } + } + + /// A data model for the Mention feature definition. + /// + /// - Note: According to the AT Protocol specifications: "Facet feature for mention of + /// another account. The text is usually a handle, including a '@' prefix, but the facet + /// reference is a DID." + /// + /// - SeeAlso: This is based on the [`app.bsky.richtext.facet`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/richtext/facet.json + public struct Mention: FeatureCodable { + + /// The identifier of the lexicon. + /// + /// - Warning: The value must not change. + public static var type: String = "app.bsky.richtext.facet#mention" + + /// The decentralized identifier (DID) of the feature. + public let did: String + + public init(did: String) { + self.did = did + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.did = try container.decode(String.self, forKey: .did) + Mention.type = try container.decode(String.self, forKey: .type) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.did, forKey: .did) + try container.encode(Mention.type, forKey: .type) + } + + enum CodingKeys: String, CodingKey { + case type = "$type" + case did + } + } + + /// A data model for the Link feature definition. + /// + /// - Note: According to the AT Protocol specifications: "Facet feature for a URL. The text URL + /// may have been simplified or truncated, but the facet reference should be a complete URL." + /// + /// - SeeAlso: This is based on the [`app.bsky.richtext.facet`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/richtext/facet.json + public struct Link: FeatureCodable { + + /// The identifier of the lexicon. + /// + /// - Warning: The value must not change. + public static var type: String = "app.bsky.richtext.facet#link" + + /// The URI of the feature. + public let uri: String + + public init(uri: String) { + self.uri = uri + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.uri = try container.decode(String.self, forKey: .uri) + Link.type = try container.decode(String.self, forKey: .type) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.uri, forKey: .uri) + try container.encode(Link.type, forKey: .type) + } + + enum CodingKeys: String, CodingKey { + case type = "$type" + case uri + } + } + + /// A data model for the Tag feature definition. + /// + /// - Note: According to the AT Protocol specifications: "Facet feature for a hashtag. The text + /// usually includes a '#' prefix, but the facet reference should not (except in the case of + /// 'double hash tags')." + /// + /// - SeeAlso: This is based on the [`app.bsky.richtext.facet`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/richtext/facet.json + public struct Tag: FeatureCodable { + + /// The identifier of the lexicon. + /// + /// - Warning: The value must not change. + public static var type: String = "app.bsky.richtext.facet#tag" + + /// The name of the tag. + public let tag: String + + public init(tag: String) { + self.tag = tag + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.tag = try container.decode(String.self, forKey: .tag) + Tag.type = try container.decode(String.self, forKey: .type) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.tag, forKey: .tag) + try container.encode(Tag.type, forKey: .type) + } + + enum CodingKeys: String, CodingKey { + case type = "$type" + case tag + } + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/RichText/BskyRichTextFacet.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/RichText/BskyRichTextFacet.swift deleted file mode 100644 index 7bcd169dc3..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/RichText/BskyRichTextFacet.swift +++ /dev/null @@ -1,270 +0,0 @@ -// -// BskyRichTextFacet.swift -// -// -// Created by Christopher Jr Riley on 2024-01-25. -// - -import Foundation - -// MARK: - Main definition -/// The main data model definition for a facet. -/// -/// - Note: According to the AT Protocol specifications: "Annotation of a sub-string within -/// rich text." -/// -/// - SeeAlso: This is based on the [`app.bsky.richtext.facet`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/richtext/facet.json -public struct Facet: Codable { - /// The range of characters related to the facet. - public let index: ByteSlice - /// The facet's feature type. - public let features: [FeatureUnion] - - public init(index: ByteSlice, features: [FeatureUnion]) { - self.index = index - self.features = features - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.index = try container.decode(ByteSlice.self, forKey: .index) - self.features = try container.decode([FeatureUnion].self, forKey: .features) - } - - public func encode(to encoder: Encoder) throws { - - var container = encoder.container(keyedBy: CodingKeys.self) - - try container.encode(self.index, forKey: .index) - try container.encode(self.features, forKey: .features) - } - - enum CodingKeys: String, CodingKey { - case index - case features - } -} - -// Represents the ByteSlice -/// The data model definition for the byte slice. -/// -/// - Note: According to the AT Protocol specifications: "Specifies the sub-string range a facet -/// feature applies to. Start index is inclusive, end index is exclusive. Indices are zero-indexed, -/// counting bytes of the UTF-8 encoded text. NOTE: some languages, like Javascript, use -/// UTF-16 or Unicode codepoints for string slice indexing; in these languages, convert to byte -/// arrays before working with facets." -/// -/// - SeeAlso: This is based on the [`app.bsky.richtext.facet`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/richtext/facet.json -public struct ByteSlice: Codable { - /// The start index of the byte slice. - public let byteStart: Int - /// The end index of the byte slice. - public let byteEnd: Int - - public init(byteStart: Int, byteEnd: Int) { - self.byteStart = byteStart - self.byteEnd = byteEnd - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - self.byteStart = try container.decode(Int.self, forKey: .byteStart) - self.byteEnd = try container.decode(Int.self, forKey: .byteEnd) - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(self.byteStart, forKey: .byteStart) - try container.encode(self.byteEnd, forKey: .byteEnd) - } - - enum CodingKeys: String, CodingKey { - case byteStart - case byteEnd - } -} - -/// A data model protocol for Features. -/// -/// - SeeAlso: This is based on the [`app.bsky.richtext.facet`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/richtext/facet.json -internal protocol FeatureCodable: Codable { - /// The identifier of the lexicon. - /// - /// - Warning: The value must not change. - static var type: String { get } -} - - -/// A data model for the Mention feature definition. -/// -/// - Note: According to the AT Protocol specifications: "Facet feature for mention of -/// another account. The text is usually a handle, including a '@' prefix, but the facet -/// reference is a DID." -/// -/// - SeeAlso: This is based on the [`app.bsky.richtext.facet`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/richtext/facet.json -public struct Mention: FeatureCodable { - /// The decentralized identifier (DID) of the feature. - public let did: String - /// The identifier of the lexicon. - /// - /// - Warning: The value must not change. - static public var type: String = "app.bsky.richtext.facet#mention" - - public init(did: String) { - self.did = did - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.did = try container.decode(String.self, forKey: .did) - Mention.type = try container.decode(String.self, forKey: .type) - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - try container.encode(self.did, forKey: .did) - try container.encode(Mention.type, forKey: .type) - } - - enum CodingKeys: String, CodingKey { - case type = "$type" - case did - } -} - - -/// A data model for the Link feature definition. -/// -/// - Note: According to the AT Protocol specifications: "Facet feature for a URL. The text URL -/// may have been simplified or truncated, but the facet reference should be a complete URL." -/// -/// - SeeAlso: This is based on the [`app.bsky.richtext.facet`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/richtext/facet.json -public struct Link: FeatureCodable { - /// The URI of the feature. - public let uri: String - /// The identifier of the lexicon. - /// - /// - Warning: The value must not change. - static public var type: String = "app.bsky.richtext.facet#link" - - public init(uri: String) { - self.uri = uri - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.uri = try container.decode(String.self, forKey: .uri) - Link.type = try container.decode(String.self, forKey: .type) - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - try container.encode(self.uri, forKey: .uri) - try container.encode(Link.type, forKey: .type) - } - - enum CodingKeys: String, CodingKey { - case type = "$type" - case uri - } -} - -/// A data model for the Tag feature definition. -/// -/// - Note: According to the AT Protocol specifications: "Facet feature for a hashtag. The text -/// usually includes a '#' prefix, but the facet reference should not (except in the case of -/// 'double hash tags')." -/// -/// - SeeAlso: This is based on the [`app.bsky.richtext.facet`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/richtext/facet.json -public struct Tag: FeatureCodable { - /// The - public let tag: String - /// The identifier of the lexicon. - /// - /// - Warning: The value must not change. - static public var type: String = "app.bsky.richtext.facet#tag" - - public init(tag: String) { - self.tag = tag - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.tag = try container.decode(String.self, forKey: .tag) - Tag.type = try container.decode(String.self, forKey: .type) - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - try container.encode(self.tag, forKey: .tag) - try container.encode(Tag.type, forKey: .type) - } - - enum CodingKeys: String, CodingKey { - case type = "$type" - case tag - } -} - -// MARK: - Union types -/// A reference containing the list of feature types. -/// -/// - SeeAlso: This is based on the [`app.bsky.richtext.facet`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/richtext/facet.json -public enum FeatureUnion: Codable { - /// The Mention feature. - case mention(Mention) - /// The Link feature. - case link(Link) - /// The Tag feature. - case tag(Tag) - - public init(from decoder: Decoder) throws { - let container = try decoder.singleValueContainer() - - if let value = try? container.decode(Mention.self) { - self = .mention(value) - } else if let value = try? container.decode(Link.self) { - self = .link(value) - } else if let value = try? container.decode(Tag.self) { - self = .tag(value) - } else { - throw DecodingError.typeMismatch( - FeatureUnion.self, DecodingError.Context( - codingPath: decoder.codingPath, debugDescription: "Unknown FeatureUnion type")) - } - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.singleValueContainer() - - switch self { - case .mention(let feature): - try container.encode(feature) - case .link(let feature): - try container.encode(feature) - case .tag(let feature): - try container.encode(feature) - } - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Unspecced/AppBskyUnspeccedDefs.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Unspecced/AppBskyUnspeccedDefs.swift new file mode 100644 index 0000000000..2681e808a5 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Unspecced/AppBskyUnspeccedDefs.swift @@ -0,0 +1,47 @@ +// +// AppBskyUnspeccedDefs.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Unspecced { + + /// A definition model for a skeleton search post. + /// + /// - Important: This is an unspecced model, and as such, this is highly volatile and may + /// change or be removed at any time. Use at your own risk. + /// + /// - SeeAlso: This is based on the [`app.bsky.unspecced.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/unspecced/defs.json + public struct SkeletonSearchPostDefinition: Codable { + + /// The URI of the skeleton search post. + public let postURI: String + + enum CodingKeys: String, CodingKey { + case postURI = "uri" + } + } + + /// A definition model for a skeleton search post. + /// + /// - Important: This is an unspecced model, and as such, this is highly volatile and may + /// change or be removed at any time. Use at your own risk. + /// + /// - SeeAlso: This is based on the [`app.bsky.unspecced.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/unspecced/defs.json + public struct SkeletonSearchActorDefinition: Codable { + + /// The URI of the skeleton search actor. + public let actorDID: String + + enum CodingKeys: String, CodingKey { + case actorDID = "did" + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Unspecced/AppBskyUnspeccedGetPopularFeedGenerators.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Unspecced/AppBskyUnspeccedGetPopularFeedGenerators.swift new file mode 100644 index 0000000000..1b76415034 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Unspecced/AppBskyUnspeccedGetPopularFeedGenerators.swift @@ -0,0 +1,31 @@ +// +// AppBskyUnspeccedGetPopularFeedGenerators.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Unspecced { + + /// An output model for globally popular feed generators. + /// + /// - Note: According to the AT Protocol specifications: "An unspecced view of globally + /// popular feed generators." + /// + /// - Important: This is an unspecced model, and as such, this is highly volatile and may + /// change or be removed at any time. Use at your own risk. + /// + /// - SeeAlso: This is based on the [`app.bsky.unspecced.getPopularFeedGenerators`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/unspecced/getPopularFeedGenerators.json + public struct GetPopularFeedGeneratorsOutput: Codable { + + /// The mark used to indicate the starting point for the next set of result. Optional. + public let cursor: String? + + /// An array of feed generators. + public let feeds: [AppBskyLexicon.Feed.GeneratorViewDefinition] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Unspecced/AppBskyUnspeccedGetSuggestionsSkeleton.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Unspecced/AppBskyUnspeccedGetSuggestionsSkeleton.swift new file mode 100644 index 0000000000..80bf3bc04c --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Unspecced/AppBskyUnspeccedGetSuggestionsSkeleton.swift @@ -0,0 +1,31 @@ +// +// AppBskyUnspeccedGetSuggestionsSkeleton.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Unspecced { + + /// An output model for getting a skeleton of suggestion of actors. + /// + /// - Note: According to the AT Protocol specifications: "Get a skeleton of suggested actors. + /// Intended to be called and then hydrated through app.bsky.actor.getSuggestions." + /// + /// - Important: This is an unspecced model, and as such, this is highly volatile and may change + /// or be removed at any time. Use at your own risk. + /// + /// - SeeAlso: This is based on the [`app.bsky.unspecced.getSuggestionsSkeleton`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/unspecced/getSuggestionsSkeleton.json + public struct GetSuggestionsSkeletonOutput: Codable { + + /// The mark used to indicate the starting point for the next set of results. Optional. + public let cursor: String? + + /// An array of actors. + public let actors: [SkeletonSearchActorDefinition] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Unspecced/AppBskyUnspeccedGetTaggedSuggestions.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Unspecced/AppBskyUnspeccedGetTaggedSuggestions.swift new file mode 100644 index 0000000000..601d3d563a --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Unspecced/AppBskyUnspeccedGetTaggedSuggestions.swift @@ -0,0 +1,87 @@ +// +// AppBskyUnspeccedGetTaggedSuggestions.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Unspecced { + + /// An output model for getting tagged suggestions. + /// + /// - Note: According to the AT Protocol specifications: "Get a list of suggestions (feeds + /// and users) tagged with categories." + /// + /// - Important: This is an unspecced model, and as such, this is highly volatile and may + /// change or be removed at any time. Use at your own risk. + /// + /// - SeeAlso: This is based on the [`app.bsky.unspecced.getTaggedSuggestions`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/unspecced/getTaggedSuggestions.json + public struct GetTaggedSuggestionsOutput: Codable { + + /// An array of suggestions. + public let suggestions: [Suggestion] + + /// A data model for a tagged suggestion. + /// + /// - Important: This is an unspecced model, and as such, this is highly volatile and may + /// change or be removed at any time. Use at your own risk. + /// + /// - SeeAlso: This is based on the [`app.bsky.unspecced.getTaggedSuggestions`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/unspecced/getTaggedSuggestions.json + public struct Suggestion: Codable { + + /// The tag attached to the suggestion. + public let tag: String + + /// Indicates whether the suggestion is a feed generator or actor (user). + public let subjectType: Subject + + /// The URI of the suggestion. + public let subjectURI: String + + public init(tag: String, subjectType: Subject, subjectURI: String) { + self.tag = tag + self.subjectType = subjectType + self.subjectURI = subjectURI + } + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.tag = try container.decode(String.self, forKey: .tag) + self.subjectType = try container.decode(Suggestion.Subject.self, forKey: .subjectType) + self.subjectURI = try container.decode(String.self, forKey: .subjectURI) + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.tag, forKey: .tag) + try container.encode(self.subjectType, forKey: .subjectType) + try container.encode(self.subjectURI, forKey: .subjectURI) + } + + enum CodingKeys: String, CodingKey { + case tag + case subjectType + case subjectURI = "subject" + } + + // Enums + /// Indicates whether the subject of the suggestion is a feed generator or an actor (user). + public enum Subject: String, Codable { + + /// Indicates the subject of the suggestion is an actor (user). + case actor + + /// Indicates the subject of the suggestion is a feed generator. + case feed + } + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Unspecced/AppBskyUnspeccedSearchActorsSkeleton.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Unspecced/AppBskyUnspeccedSearchActorsSkeleton.swift new file mode 100644 index 0000000000..197339f925 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Unspecced/AppBskyUnspeccedSearchActorsSkeleton.swift @@ -0,0 +1,40 @@ +// +// AppBskyUnspeccedSearchActorsSkeleton.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Unspecced { + + /// An output model for retrieving the skeleton results of actors (users). + /// + /// - Important: This is an unspecced model, and as such, this is highly volatile and may + /// change or be removed at any time. Use at your own risk. + /// + /// - Note: According to the AT Protocol specifications: "Backend Actors (profile) search, + /// returns only skeleton." + /// + /// - SeeAlso: This is based on the [`app.bsky.unspecced.searchActorsSkeleton`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/unspecced/searchActorsSkeleton.json + public struct SearchActorsSkeletonOutput: Codable { + + /// The mark used to indicate the starting point for the next set of result. Optional. + public let cursor: String? + + /// The number of search results. + /// + /// This number may not be completely reliable, as it can be rounded or truncated. This number + /// doesn't reflect all of the possible actors that can be seen. + /// + /// - Note: According to the AT Protocol specifications: "Count of search hits. Optional, may + /// be rounded/truncated, and may not be possible to paginate through all hits." + public let hitsTotal: Int? + + /// An array of actors. + public let actors: [SkeletonSearchActorDefinition] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Unspecced/AppBskyUnspeccedSearchPostsSkeleton.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Unspecced/AppBskyUnspeccedSearchPostsSkeleton.swift new file mode 100644 index 0000000000..856fb21284 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Unspecced/AppBskyUnspeccedSearchPostsSkeleton.swift @@ -0,0 +1,66 @@ +// +// AppBskyUnspeccedSearchPostsSkeleton.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension AppBskyLexicon.Unspecced { + + /// The main data model for retrieving the skeleton results of posts. + /// + /// - SeeAlso: This is based on the [`app.bsky.unspecced.searchPostsSkeleton`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/unspecced/searchPostsSkeleton.json + public struct SearchPostsSkeleton: Codable { + + /// Determines the ranking order for the search results. + /// + /// - Note: According to the AT Protocol specifications: "Specifies the ranking order + /// of results." + /// + /// - SeeAlso: This is based on the [`app.bsky.unspecced.searchPostsSkeleton`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/unspecced/searchPostsSkeleton.json + public enum Sort: String { + + /// Indicates the results will be sorted by the top posts. + case top + + /// Indicates the results will be sorted by the latest posts. + case latest + } + } + + /// An output model for retrieving the skeleton results of posts. + /// + /// - Important: This is an unspecced model, and as such, this is highly volatile and may + /// change or be removed at any time. Use at your own risk. + /// + /// - Note: According to the AT Protocol specifications: "Backend Posts search, returns + /// only skeleton." + /// + /// - SeeAlso: This is based on the [`app.bsky.unspecced.searchPostsSkeleton`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/unspecced/searchPostsSkeleton.json + public struct SearchPostsSkeletonOutput: Codable { + + /// The mark used to indicate the starting point for the next set of result. Optional. + public let cursor: String? + + /// The number of search results. + /// + /// This number may not be completely reliable, as it can be rounded or truncated. + /// This number doesn't reflect all of the possible posts that can be seen. + /// + /// - Note: According to the AT Protocol specifications: "Count of search hits. + /// Optional, may be rounded/truncated, and may not be possible to paginate through + /// all hits." + public let hitsTotal: Int? + + /// An array of posts. + public let posts: [SkeletonSearchPostDefinition] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Unspecced/BskyUnspeccedDefs.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Unspecced/BskyUnspeccedDefs.swift deleted file mode 100644 index 7993fea9d1..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Unspecced/BskyUnspeccedDefs.swift +++ /dev/null @@ -1,42 +0,0 @@ -// -// BskyUnspeccedDefs.swift -// -// -// Created by Christopher Jr Riley on 2024-03-17. -// - -import Foundation - -/// A data model definition for a skeleton search post. -/// -/// - Important: This is an unspecced model, and as such, this is highly volatile and may change -/// or be removed at any time. Use at your own risk. -/// -/// - SeeAlso: This is based on the [`app.bsky.unspecced.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/unspecced/defs.json -public struct UnspeccedSkeletonSearchPost: Codable { - /// The URI of the skeleton search post. - public let postURI: String - - enum CodingKeys: String, CodingKey { - case postURI = "uri" - } -} - -/// A data model definition for a skeleton search post. -/// -/// - Important: This is an unspecced model, and as such, this is highly volatile and may change -/// or be removed at any time. Use at your own risk. -/// -/// - SeeAlso: This is based on the [`app.bsky.unspecced.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/unspecced/defs.json -public struct UnspeccedSkeletonSearchActor: Codable { - /// The URI of the skeleton search actor. - public let actorDID: String - - enum CodingKeys: String, CodingKey { - case actorDID = "did" - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Unspecced/BskyUnspeccedGetPopularFeedGenerators.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Unspecced/BskyUnspeccedGetPopularFeedGenerators.swift deleted file mode 100644 index 8de29952af..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Unspecced/BskyUnspeccedGetPopularFeedGenerators.swift +++ /dev/null @@ -1,26 +0,0 @@ -// -// BskyUnspeccedGetPopularFeedGenerators.swift -// -// -// Created by Christopher Jr Riley on 2024-03-17. -// - -import Foundation - -/// The main data model definition for the output of globally popular feed generators. -/// -/// - Note: According to the AT Protocol specifications: "An unspecced view of globally -/// popular feed generators." -/// -/// - Important: This is an unspecced model, and as such, this is highly volatile and may change -/// or be removed at any time. Use at your own risk. -/// -/// - SeeAlso: This is based on the [`app.bsky.unspecced.getPopularFeedGenerators`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/unspecced/getPopularFeedGenerators.json -public struct UnspeccedGetPopularFeedGeneratorsOutput: Codable { - /// The mark used to indicate the starting point for the next set of result. Optional. - public let cursor: String? - /// An array of feed generators. - public let feeds: [FeedGeneratorView] -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Unspecced/BskyUnspeccedGetSuggestionsSkeleton.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Unspecced/BskyUnspeccedGetSuggestionsSkeleton.swift deleted file mode 100644 index a7a3428846..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Unspecced/BskyUnspeccedGetSuggestionsSkeleton.swift +++ /dev/null @@ -1,26 +0,0 @@ -// -// BskyUnspeccedGetSuggestionsSkeleton.swift -// -// -// Created by Christopher Jr Riley on 2024-04-16. -// - -import Foundation - -/// The main data model definition for getting a skeleton of suggestion of actors. -/// -/// - Note: According to the AT Protocol specifications: "Get a skeleton of suggested actors. -/// Intended to be called and then hydrated through app.bsky.actor.getSuggestions." -/// -/// - Important: This is an unspecced model, and as such, this is highly volatile and may change -/// or be removed at any time. Use at your own risk. -/// -/// - SeeAlso: This is based on the [`app.bsky.unspecced.getSuggestionsSkeleton`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/unspecced/getSuggestionsSkeleton.json -public struct UnspeccedGetSuggestionsSkeletonOutput: Codable { - /// The mark used to indicate the starting point for the next set of results. Optional. - public let cursor: String? - /// An array of actors. - public let actors: [UnspeccedSkeletonSearchActor] -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Unspecced/BskyUnspeccedGetTaggedSuggestions.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Unspecced/BskyUnspeccedGetTaggedSuggestions.swift deleted file mode 100644 index 71c607909e..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Unspecced/BskyUnspeccedGetTaggedSuggestions.swift +++ /dev/null @@ -1,78 +0,0 @@ -// -// BskyUnspeccedGetTaggedSuggestions.swift -// -// -// Created by Christopher Jr Riley on 2024-03-17. -// - -import Foundation - -/// The main data model definition for the output of getting tagged suggestions. -/// -/// - Note: According to the AT Protocol specifications: "Get a list of suggestions (feeds -/// and users) tagged with categories." -/// -/// - Important: This is an unspecced model, and as such, this is highly volatile and may change -/// or be removed at any time. Use at your own risk. -/// -/// - SeeAlso: This is based on the [`app.bsky.unspecced.getTaggedSuggestions`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/unspecced/getTaggedSuggestions.json -public struct UnspeccedGetTaggedSuggestionsOutput: Codable { - /// An array of suggestions. - public let suggestions: [TaggedSuggestion] -} - -/// A data model for a tagged suggestion. -/// -/// - Important: This is an unspecced model, and as such, this is highly volatile and may change -/// or be removed at any time. Use at your own risk. -/// -/// - SeeAlso: This is based on the [`app.bsky.unspecced.getTaggedSuggestions`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/unspecced/getTaggedSuggestions.json -public struct TaggedSuggestion: Codable { - /// The tag attached to the suggestion. - public let tag: String - /// Indicates whether the suggestion is a feed generator or actor (user). - public let subjectType: SubjectType - /// The URI of the suggestion. - public let subjectURI: String - - public init(tag: String, subjectType: SubjectType, subjectURI: String) { - self.tag = tag - self.subjectType = subjectType - self.subjectURI = subjectURI - } - - public init(from decoder: any Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.tag = try container.decode(String.self, forKey: .tag) - self.subjectType = try container.decode(TaggedSuggestion.SubjectType.self, forKey: .subjectType) - self.subjectURI = try container.decode(String.self, forKey: .subjectURI) - } - - public func encode(to encoder: any Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - try container.encode(self.tag, forKey: .tag) - try container.encode(self.subjectType, forKey: .subjectType) - try container.encode(self.subjectURI, forKey: .subjectURI) - } - - enum CodingKeys: String, CodingKey { - case tag - case subjectType - case subjectURI = "subject" - } - - // Enums - /// Indicates whether the subject of the suggestion is a feed generator or an actor (user). - public enum SubjectType: String, Codable { - /// Indicates the subject of the suggestion is an actor (user). - case actor - /// Indicates the subject of the suggestion is a feed generator. - case feed - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Unspecced/BskyUnspeccedSearchActorsSkeleton.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Unspecced/BskyUnspeccedSearchActorsSkeleton.swift deleted file mode 100644 index c90c520769..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Unspecced/BskyUnspeccedSearchActorsSkeleton.swift +++ /dev/null @@ -1,34 +0,0 @@ -// -// BskyUnspeccedSearchActorsSkeleton.swift -// -// -// Created by Christopher Jr Riley on 2024-03-17. -// - -import Foundation - -/// The main data model definition for the output of retrieving the skeleton results of actors (users). -/// -/// - Important: This is an unspecced model, and as such, this is highly volatile and may change -/// or be removed at any time. Use at your own risk. -/// -/// - Note: According to the AT Protocol specifications: "Backend Actors (profile) search, returns -/// only skeleton." -/// -/// - SeeAlso: This is based on the [`app.bsky.unspecced.searchActorsSkeleton`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/unspecced/searchActorsSkeleton.json -public struct UnspeccedSearchActorsSkeletonOutput: Codable { - /// The mark used to indicate the starting point for the next set of result. Optional. - public let cursor: String? - /// The number of search results. - /// - /// This number may not be completely reliable, as it can be rounded or truncated. This number - /// doesn't reflect all of the possible actors that can be seen. - /// - /// - Note: According to the AT Protocol specifications: "Count of search hits. Optional, may - /// be rounded/truncated, and may not be possible to paginate through all hits." - public let hitsTotal: Int? - /// An array of actors. - public let actors: [UnspeccedSkeletonSearchActor] -} diff --git a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Unspecced/BskyUnspeccedSearchPostsSkeleton.swift b/Sources/ATProtoKit/Models/Lexicons/app.bsky/Unspecced/BskyUnspeccedSearchPostsSkeleton.swift deleted file mode 100644 index 0b4bc5efeb..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/app.bsky/Unspecced/BskyUnspeccedSearchPostsSkeleton.swift +++ /dev/null @@ -1,46 +0,0 @@ -// -// BskyUnspeccedSearchPostsSkeleton.swift -// -// -// Created by Christopher Jr Riley on 2024-03-17. -// - -import Foundation - -/// The main data model definition for the output of retrieving the skeleton results of posts. -/// -/// - Important: This is an unspecced model, and as such, this is highly volatile and may change -/// or be removed at any time. Use at your own risk. -/// -/// - Note: According to the AT Protocol specifications: "Backend Posts search, returns -/// only skeleton." -/// -/// - SeeAlso: This is based on the [`app.bsky.unspecced.searchPostsSkeleton`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/unspecced/searchPostsSkeleton.json -public struct UnspeccedSearchPostsSkeletonOutput: Codable { - /// The mark used to indicate the starting point for the next set of result. Optional. - public let cursor: String? - /// The number of search results. - /// - /// This number may not be completely reliable, as it can be rounded or truncated. This number - /// doesn't reflect all of the possible posts that can be seen. - /// - /// - Note: According to the AT Protocol specifications: "Count of search hits. Optional, may - /// be rounded/truncated, and may not be possible to paginate through all hits." - public let hitsTotal: Int? - /// An array of posts. - public let posts: [UnspeccedSkeletonSearchPost] -} - -/// Determines the ranking order for the search results. -/// -/// - Note: According to the AT Protocol specifications: "Specifies the ranking order of results." -/// -/// - SeeAlso: This is based on the [`app.bsky.unspecced.searchPostsSkeleton`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/unspecced/searchPostsSkeleton.json -public enum UnspeccedSearchPostsSortRanking: String { - case top - case latest -} diff --git a/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Actor/ChatBskyActorDeclaration.swift b/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Actor/ChatBskyActorDeclaration.swift new file mode 100644 index 0000000000..a22c1f4493 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Actor/ChatBskyActorDeclaration.swift @@ -0,0 +1,49 @@ +// +// ChatBskyActorDeclaration.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension ChatBskyLexicon.Actor { + + /// A record model for a Bluesky chat account. + /// + /// - Note: According to the AT Protocol specifications: "A declaration of a Bluesky + /// chat account." + /// + /// - SeeAlso: This is based on the [`chat.bsky.actor.declaration`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/actor/declaration.json + public struct DeclarationRecord: ATRecordProtocol { + + /// The identifier of the lexicon. + /// + /// - Warning: The value must not change. + public private(set) static var type: String = "chat.bsky.actor.declaration" + + /// Establishes rule for who can message the user account. + public let allowIncoming: AllIncoming + + enum CodingKeys: String, CodingKey { + case allowIncoming + } + + // Enums + /// A rule that states who can message the user account. + public enum AllIncoming: Codable { + + /// Indicates that anyone can message the user account. + case all + + /// Indicates that no one can message the user account. + case none + + /// Indicates that only people who the user account follows can message + /// the user account. + case following + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Actor/ChatBskyActorDefs.swift b/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Actor/ChatBskyActorDefs.swift new file mode 100644 index 0000000000..cc7d7ccaf5 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Actor/ChatBskyActorDefs.swift @@ -0,0 +1,101 @@ +// +// ChatBskyActorDefs.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension ChatBskyLexicon.Actor { + + /// A definition model for a basic profile view. + /// + /// - SeeAlso: This is based on the [`chat.bsky.actor.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/actor/defs.json + public struct ProfileViewBasicDefinition: Codable { + + /// The decentralized identifier (DID) of the user. + public let actorDID: String + + /// The unique handle of the user. + public let actorHandle: String + + /// The display name of the user account. Optional. + /// + /// - Important: Current maximum length is 64 characters. + public let displayName: String? + + /// The avatar image URL of the user's profile. Optional. + public let avatarImageURL: URL? + + /// The associated profile view. Optional. + public let associated: AppBskyLexicon.Actor.ProfileAssociatedDefinition? + + /// The list of metadata relating to the requesting account's relationship with the + /// subject account. Optional. + public let viewer: [AppBskyLexicon.Actor.ViewerStateDefinition]? + + /// An array of labels created by the user. Optional. + public let labels: [ComAtprotoLexicon.Label.LabelDefinition]? + + /// Indicates whether the user account can no longer be a part of the conversations. Optional. + /// + /// - Note: According to the AT Protocol specifications: "Set to true when the actor + /// cannot actively participate in converations" + public let isChatDisabled: Bool? + + public init(actorDID: String, actorHandle: String, displayName: String?, avatarImageURL: URL?, + associated: AppBskyLexicon.Actor.ProfileAssociatedDefinition?, viewer: [AppBskyLexicon.Actor.ViewerStateDefinition]?, + labels: [ComAtprotoLexicon.Label.LabelDefinition]?, isChatDisabled: Bool?) { + self.actorDID = actorDID + self.actorHandle = actorHandle + self.displayName = displayName + self.avatarImageURL = avatarImageURL + self.associated = associated + self.viewer = viewer + self.labels = labels + self.isChatDisabled = isChatDisabled + } + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.actorDID = try container.decode(String.self, forKey: .actorDID) + self.actorHandle = try container.decode(String.self, forKey: .actorHandle) + self.displayName = try container.decodeIfPresent(String.self, forKey: .displayName) + self.avatarImageURL = try container.decodeIfPresent(URL.self, forKey: .avatarImageURL) + self.associated = try container.decodeIfPresent(AppBskyLexicon.Actor.ProfileAssociatedDefinition.self, forKey: .associated) + self.viewer = try container.decodeIfPresent([AppBskyLexicon.Actor.ViewerStateDefinition].self, forKey: .viewer) + self.labels = try container.decodeIfPresent([ComAtprotoLexicon.Label.LabelDefinition].self, forKey: .labels) + self.isChatDisabled = try container.decodeIfPresent(Bool.self, forKey: .isChatDisabled) + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.actorDID, forKey: .actorDID) + try container.encode(self.actorHandle, forKey: .actorHandle) + // Truncate `displayName` to 640 characters before encoding + // `maxGraphemes`'s limit is 64, but `String.count` should respect that limit implictly + try truncatedEncodeIfPresent(self.displayName, withContainer: &container, forKey: .displayName, upToLength: 640) + try container.encodeIfPresent(self.avatarImageURL, forKey: .avatarImageURL) + try container.encodeIfPresent(self.associated, forKey: .associated) + try container.encodeIfPresent(self.viewer, forKey: .viewer) + try container.encodeIfPresent(self.labels, forKey: .labels) + try container.encodeIfPresent(self.isChatDisabled, forKey: .isChatDisabled) + } + + enum CodingKeys: String, CodingKey { + case actorDID = "did" + case actorHandle = "handle" + case displayName + case avatarImageURL = "avatar" + case associated + case viewer + case labels + case isChatDisabled = "chatDisabled" + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Actor/ChatBskyActorDeleteAccount.swift b/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Actor/ChatBskyActorDeleteAccount.swift new file mode 100644 index 0000000000..722936223f --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Actor/ChatBskyActorDeleteAccount.swift @@ -0,0 +1,18 @@ +// +// ChatBskyActorDeleteAccount.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension ChatBskyLexicon.Actor { + + /// A request body model for deleting an account. + /// + /// - SeeAlso: This is based on the [`chat.bsky.actor.deleteAccount`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/actor/deleteAccount.json + public struct DeleteAccount: Codable {} +} diff --git a/Sources/ATProtoKit/Models/Lexicons/chat.bsky/ChatBskyLexicon.swift b/Sources/ATProtoKit/Models/Lexicons/chat.bsky/ChatBskyLexicon.swift new file mode 100644 index 0000000000..54d829c12a --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/chat.bsky/ChatBskyLexicon.swift @@ -0,0 +1,20 @@ +// +// ChatBskyLexicon.swift +// +// +// Created by Christopher Jr Riley on 2024-05-16. +// + +import Foundation + +extension ChatBskyLexicon { + + /// A group of lexicons within the `chat.bsky.actor` namespace. + public struct Actor {} + + /// A group of lexicons within the `chat.bsky.convo` namespace. + public struct Conversation {} + + /// A group of lexicons within the `chat.bsky.moderation` namespace. + public struct Moderation {} +} diff --git a/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Convo/ChatBskyConvoDefs.swift b/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Convo/ChatBskyConvoDefs.swift new file mode 100644 index 0000000000..41df669795 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Convo/ChatBskyConvoDefs.swift @@ -0,0 +1,339 @@ +// +// ChatBskyConvoDefs.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension ChatBskyLexicon.Conversation { + + /// A definition model for a message reference. + /// + /// - SeeAlso: This is based on the [`chat.bsky.convo.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/convo/defs.json + public struct MessageReferenceDefinition: Codable { + + /// The decentralized identifier (DID) of the message. + public let messageDID: String + + /// The ID of the message. + public let messageID: String + + /// The ID of the conversation. + public let conversationID: String + + enum CodingKeys: String, CodingKey { + case messageDID = "did" + case messageID = "messageId" + case conversationID = "convoId" + } + } + + /// A definition model for a message. + /// + /// - SeeAlso: This is based on the [`chat.bsky.convo.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/convo/defs.json + public struct MessageInputDefinition: Codable { + + /// The message text itself. + /// + /// - Important: Current maximum length is 1,000 characters. + public let text: String + + /// An array of facets contained in the message's text. Optional. + /// + /// - Note: According to the AT Protocol specifications: "Annotations of text (mentions, + /// URLs, hashtags, etc)" + public let facets: [AppBskyLexicon.RichText.Facet]? + + /// An array of embeds for the message. Optional. + public let embeds: [ATUnion.MessageInputEmbedUnion]? + + public func encode(to encoder: any Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + // Truncate `tags` to 10000 characters before encoding + // `maxGraphemes`'s limit is 1000, but `String.count` should respect that limit implictly + try truncatedEncode(self.text, withContainer: &container, forKey: .text, upToLength: 1_000) + try container.encodeIfPresent(self.facets, forKey: .facets) + try container.encodeIfPresent(self.embeds, forKey: .embeds) + } + + enum CodingKeys: String, CodingKey { + case text + case facets + case embeds = "embed" + } + } + + /// A definition model for a message view. + /// + /// - SeeAlso: This is based on the [`chat.bsky.convo.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/convo/defs.json + public struct MessageViewDefinition: Codable { + + /// The ID of the message. Optional. + public let messageID: String? + + /// The revision of the message. + public let revision: String + + /// The message text itself. + /// + /// - Important: Current maximum length is 1,000 characters. + public let text: String + + /// An array of facets contained in the message's text. Optional. + /// + /// - Note: According to the AT Protocol specifications: "Annotations of text (mentions, + /// URLs, hashtags, etc)" + public let facets: [AppBskyLexicon.RichText.Facet]? + + /// An array of embeds for the message. Optional. + public let embeds: [ATUnion.MessageViewEmbedUnion]? + + /// The sender of the message. + public let sender: String + + /// The date and time the message was seen. + @DateFormatting public var seenAt: Date + + public init(messageID: String?, revision: String, text: String, facets: [AppBskyLexicon.RichText.Facet]?, + embeds: [ATUnion.MessageViewEmbedUnion]?, sender: String, seenAt: Date) { + self.messageID = messageID + self.revision = revision + self.text = text + self.facets = facets + self.embeds = embeds + self.sender = sender + self._seenAt = DateFormatting(wrappedValue: seenAt) + } + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.messageID = try container.decodeIfPresent(String.self, forKey: .messageID) + self.revision = try container.decode(String.self, forKey: .revision) + self.text = try container.decode(String.self, forKey: .text) + self.facets = try container.decodeIfPresent([AppBskyLexicon.RichText.Facet].self, forKey: .facets) + self.embeds = try container.decodeIfPresent([ATUnion.MessageViewEmbedUnion].self, forKey: .embeds) + self.sender = try container.decode(String.self, forKey: .sender) + self.seenAt = try container.decode(DateFormatting.self, forKey: .seenAt).wrappedValue + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encodeIfPresent(self.messageID, forKey: .messageID) + try container.encode(self.revision, forKey: .revision) + // Truncate `tags` to 10000 characters before encoding + // `maxGraphemes`'s limit is 1000, but `String.count` should respect that limit implictly + try truncatedEncode(self.text, withContainer: &container, forKey: .text, upToLength: 1_000) + try container.encodeIfPresent(self.facets, forKey: .facets) + try container.encodeIfPresent(self.embeds, forKey: .embeds) + try container.encode(self.sender, forKey: .sender) + try container.encode(self._seenAt, forKey: .seenAt) + } + + public enum CodingKeys: String, CodingKey { + case messageID = "id" + case revision = "rev" + case text + case facets + case embeds = "embed" + case sender + case seenAt + } + } + + /// A definition model for a deleted message view. + /// + /// - SeeAlso: This is based on the [`chat.bsky.convo.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/convo/defs.json + public struct DeletedMessageViewDefinition: Codable { + + /// The ID of the message. Optional. + public let messageID: String? + + /// The revision of the message. + public let revision: String + + /// The sender of the message. + public let sender: String + + /// The date and time the message was seen. + @DateFormatting public var seenAt: Date + + public init(messageID: String?, revision: String, sender: String, seenAt: Date) { + self.messageID = messageID + self.revision = revision + self.sender = sender + self._seenAt = DateFormatting(wrappedValue: seenAt) + } + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.messageID = try container.decodeIfPresent(String.self, forKey: .messageID) + self.revision = try container.decode(String.self, forKey: .revision) + self.sender = try container.decode(String.self, forKey: .sender) + self.seenAt = try container.decode(DateFormatting.self, forKey: .seenAt).wrappedValue + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encodeIfPresent(self.messageID, forKey: .messageID) + try container.encode(self.revision, forKey: .revision) + try container.encode(self.sender, forKey: .sender) + try container.encode(self._seenAt, forKey: .seenAt) + } + + enum CodingKeys: String, CodingKey { + case messageID = "id" + case revision = "rev" + case sender + case seenAt + } + } + + /// A definition model for the message view's sender. + /// + /// - SeeAlso: This is based on the [`chat.bsky.convo.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/convo/defs.json + public struct MessageViewSenderDefinition: Codable { + + /// The decentralized identifier (DID) of the message. + public let messageDID: String + + enum CodingKeys: String, CodingKey { + case messageDID = "did" + } + } + + /// A definition model for a conversation view. + /// + /// - SeeAlso: This is based on the [`chat.bsky.convo.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/convo/defs.json + public struct ConversationViewDefinition: Codable { + + /// The ID of the conversation. + public let conversationID: String + + /// The revision of the conversation. + public let revision: String + + /// An array of basic profile views within the conversation. + public let members: [ChatBskyLexicon.Actor.ProfileViewBasicDefinition] + + /// The last message in the conversation. Optional. + public let lastMessage: ATUnion.ConversationViewLastMessageUnion? + + /// Indicates whether the conversation is muted. + public let isMuted: Bool + + /// The number of messages that haven't been read. + public let unreadCount: Int + + enum CodingKeys: String, CodingKey { + case conversationID = "id" + case revision = "rev" + case members + case lastMessage + case isMuted = "muted" + case unreadCount + } + } + + /// A definition model for a log for beginning the coversation. + /// + /// - SeeAlso: This is based on the [`chat.bsky.convo.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/convo/defs.json + public struct LogBeginConversationDefinition: Codable { + + /// The revision of the log. + public let revision: String + + /// The ID of the conversation. + public let conversationID: String + + enum CodingKeys: String, CodingKey { + case revision = "rev" + case conversationID = "convoID" + } + } + + /// A definition model for a log for leaving the conversation. + /// + /// - SeeAlso: This is based on the [`chat.bsky.convo.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/convo/defs.json + public struct LogLeaveConversationDefinition: Codable { + + /// The revision of the log. + public let revision: String + + /// The ID of the conversation. + public let conversationID: String + + enum CodingKeys: String, CodingKey { + case revision = "rev" + case conversationID = "convoID" + } + } + + /// A definition model for a log for creating a message. + /// + /// - SeeAlso: This is based on the [`chat.bsky.convo.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/convo/defs.json + public struct LogCreateMessageDefinition: Codable { + + /// The revision of the log. + public let revision: String + + /// The ID of the conversation. + public let conversationID: String + + /// The message itself. + public let message: ATUnion.LogCreateMessageUnion + + enum CodingKeys: String, CodingKey { + case revision = "rev" + case conversationID = "convoID" + case message + } + } + + /// A definition model for a log for deleting a message. + /// + /// - SeeAlso: This is based on the [`chat.bsky.convo.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/convo/defs.json + public struct LogDeleteMessageDefinition: Codable { + + /// The revision of the log. + public let revision: String + + /// The ID of the conversation. + public let conversationID: String + + /// The message itself. + public let message: ATUnion.LogDeleteMessageUnion + + enum CodingKeys: String, CodingKey { + case revision = "rev" + case conversationID = "convoID" + case message + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Convo/ChatBskyConvoDeleteMessageForSelf.swift b/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Convo/ChatBskyConvoDeleteMessageForSelf.swift new file mode 100644 index 0000000000..b4859bbcb3 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Convo/ChatBskyConvoDeleteMessageForSelf.swift @@ -0,0 +1,30 @@ +// +// ChatBskyConvoDeleteMessageForSelf.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension ChatBskyLexicon.Conversation { + + /// A request body model for deleting a message only from the user account's end. + /// + /// - SeeAlso: This is based on the [`chat.bsky.convo.deleteMessageForSelf`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/convo/deleteMessageForSelf.json + public struct DeleteMessageForSelfRequestBody: Codable { + + /// The ID of the conversation. + public let conversationID: String + + /// The ID of the message. + public let messageID: String + + enum CodingKeys: String, CodingKey { + case conversationID = "convoID" + case messageID = "messageId" + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Convo/ChatBskyConvoGetConvo.swift b/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Convo/ChatBskyConvoGetConvo.swift new file mode 100644 index 0000000000..5e4356bb73 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Convo/ChatBskyConvoGetConvo.swift @@ -0,0 +1,26 @@ +// +// ChatBskyConvoGetConvo.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension ChatBskyLexicon.Conversation { + + /// An output model for a message reference. + /// + /// - SeeAlso: This is based on the [`chat.bsky.convo.getConvo`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/convo/getConvo.json + public struct GetConversationOutput: Codable { + + /// The conversation itself. + public let conversation: ConversationViewDefinition + + enum CodingKeys: String, CodingKey { + case conversation = "convo" + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Convo/ChatBskyConvoGetConvoForMembers.swift b/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Convo/ChatBskyConvoGetConvoForMembers.swift new file mode 100644 index 0000000000..ac4526453d --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Convo/ChatBskyConvoGetConvoForMembers.swift @@ -0,0 +1,26 @@ +// +// ChatBskyConvoGetConvoForMembers.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension ChatBskyLexicon.Conversation { + + /// An output model for getting a conversation for members. + /// + /// - SeeAlso: This is based on the [`chat.bsky.convo.getConvoForMembers`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/convo/getConvoForMembers.json + public struct GetConversationForMembersOutput: Codable { + + /// The conversation view. + public let conversation: ConversationViewDefinition + + enum CodingKeys: String, CodingKey { + case conversation = "convo" + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Convo/ChatBskyConvoGetLog.swift b/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Convo/ChatBskyConvoGetLog.swift new file mode 100644 index 0000000000..88c0f180b7 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Convo/ChatBskyConvoGetLog.swift @@ -0,0 +1,25 @@ +// +// ChatBskyConvoGetLog.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension ChatBskyLexicon.Conversation { + + /// An output model for getting logs for messages. + /// + /// - SeeAlso: This is based on the [`chat.bsky.convo.getLog`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/convo/getLog.json + public struct GetLogOutput: Codable { + + /// The mark used to indicate the starting point for the next set of results. Optional. + public let cursor: String? + + /// An array of logs. + public let logs: [ATUnion.MessageLogsUnion] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Convo/ChatBskyConvoGetMessages.swift b/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Convo/ChatBskyConvoGetMessages.swift new file mode 100644 index 0000000000..a10951ac18 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Convo/ChatBskyConvoGetMessages.swift @@ -0,0 +1,25 @@ +// +// ChatBskyConvoGetMessages.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension ChatBskyLexicon.Conversation { + + /// An output model for getting messages. + /// + /// - SeeAlso: This is based on the [`chat.bsky.convo.getMessages`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/convo/getMessages.json + public struct GetMessagesOutput: Codable { + + /// The mark used to indicate the starting point for the next set of results. Optional. + public let cursor: String? + + /// An array of messages. + public let messages: [ATUnion.GetMessagesOutputMessagesUnion] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Convo/ChatBskyConvoLeaveConvo.swift b/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Convo/ChatBskyConvoLeaveConvo.swift new file mode 100644 index 0000000000..284bf228f3 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Convo/ChatBskyConvoLeaveConvo.swift @@ -0,0 +1,45 @@ +// +// ChatBskyConvoLeaveConvo.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension ChatBskyLexicon.Conversation { + + /// A request body model for leaving a conversation. + /// + /// - SeeAlso: This is based on the [`chat.bsky.convo.leaveConvo`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/convo/leaveConvo.json + public struct LeaveConversationRequestBody: Codable { + + /// The ID of the conversation. + public let conversationID: String + + enum CodingKeys: String, CodingKey { + case conversationID = "convoId" + } + } + + /// An output model for leaving a conversation. + /// + /// - SeeAlso: This is based on the [`chat.bsky.convo.leaveConvo`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/convo/leaveConvo.json + public struct LeaveConversationOutput: Codable { + + /// The ID of the conversation. + public let conversationID: String + + /// The revision of the conversation. + public let revision: String + + enum CodingKeys: String, CodingKey { + case conversationID = "convoId" + case revision = "rev" + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Convo/ChatBskyConvoListConvo.swift b/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Convo/ChatBskyConvoListConvo.swift new file mode 100644 index 0000000000..163b4ebd7e --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Convo/ChatBskyConvoListConvo.swift @@ -0,0 +1,30 @@ +// +// ChatBskyConvoListConvo.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension ChatBskyLexicon.Conversation { + + /// An output model for listing various conversations. + /// + /// - SeeAlso: This is based on the [`chat.bsky.convo.listConvos`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/convo/listConvos.json + public struct ListConversationsOutput: Codable { + + /// The mark used to indicate the starting point for the next set of results. Optional. + public let cursor: String + + /// An array of conversations. + public let conversations: [ConversationViewDefinition] + + enum CodingKeys: String, CodingKey { + case cursor + case conversations = "convos" + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Convo/ChatBskyConvoMuteConvo.swift b/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Convo/ChatBskyConvoMuteConvo.swift new file mode 100644 index 0000000000..453ae9ee7c --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Convo/ChatBskyConvoMuteConvo.swift @@ -0,0 +1,41 @@ +// +// ChatBskyConvoMuteConvo.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension ChatBskyLexicon.Conversation { + + /// A request body model for muting a conversation. + /// + /// - SeeAlso: This is based on the [`chat.bsky.convo.muteConvo`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/convo/muteConvo.json + public struct MuteConversationRequestBody: Codable { + + /// The ID of the conversation. + public let conversationID: String + + enum CodingKeys: String, CodingKey { + case conversationID = "convoId" + } + } + + /// An output model for muting a conversation. + /// + /// - SeeAlso: This is based on the [`chat.bsky.convo.muteConvo`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/convo/muteConvo.json + public struct MuteConversationOutput: Codable { + + /// The conversation itself. + public let conversation: [ConversationViewDefinition] + + enum CodingKeys: String, CodingKey { + case conversation = "convo" + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Convo/ChatBskyConvoSendMessage.swift b/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Convo/ChatBskyConvoSendMessage.swift new file mode 100644 index 0000000000..1abeef91e2 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Convo/ChatBskyConvoSendMessage.swift @@ -0,0 +1,30 @@ +// +// ChatBskyConvoSendMessage.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension ChatBskyLexicon.Conversation { + + /// A request body model for sending a message. + /// + /// - SeeAlso: This is based on the [`chat.bsky.convo.sendMessage`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/convo/sendMessage.json + public struct SendMessageRequestBody: Codable { + + /// The ID of the conversation. + public let conversationID: String + + /// The message text itself. + public let message: MessageInputDefinition + + enum CodingKeys: String, CodingKey { + case conversationID = "convoId" + case message + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Convo/ChatBskyConvoSendMessageBatch.swift b/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Convo/ChatBskyConvoSendMessageBatch.swift new file mode 100644 index 0000000000..458f5fe461 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Convo/ChatBskyConvoSendMessageBatch.swift @@ -0,0 +1,66 @@ +// +// ChatBskyConvoSendMessageBatch.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension ChatBskyLexicon.Conversation { + + /// The main data model for sending a message batch. + /// + /// - SeeAlso: This is based on the [`chat.bsky.convo.sendMessageBatch`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/convo/sendMessageBatch.json + public struct SendMessageBatch: Codable { + + /// A message batch object. + /// + /// - SeeAlso: This is based on the [`chat.bsky.convo.sendMessageBatch`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/convo/sendMessageBatch.json + public struct MessageBatchItem: Codable { + + /// The ID of the conversation. + public let conversationID: String + + /// The message text itself. + public let message: MessageInputDefinition + + enum CodingKeys: String, CodingKey { + case conversationID = "convoId" + case message + } + } + } + + /// A request body model for sending a message batch. + /// + /// - SeeAlso: This is based on the [`chat.bsky.convo.sendMessageBatch`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/convo/sendMessageBatch.json + public struct SendMessageBatchRequestBody: Codable { + + /// An array of messages. + public let items: [SendMessageBatch.MessageBatchItem] + + public func encode(to encoder: any Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try truncatedEncode(self.items, withContainer: &container, forKey: .items, upToLength: 100) + } + } + + /// An output model for sending a message batch. + /// + /// - SeeAlso: This is based on the [`chat.bsky.convo.sendMessageBatch`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/convo/sendMessageBatch.json + public struct SendMessageBatchOutput: Codable { + + /// An array of message views. + public let items: [MessageViewDefinition] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Convo/ChatBskyConvoUnmuteConvo.swift b/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Convo/ChatBskyConvoUnmuteConvo.swift new file mode 100644 index 0000000000..7d300aea10 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Convo/ChatBskyConvoUnmuteConvo.swift @@ -0,0 +1,41 @@ +// +// ChatBskyConvoUnmuteConvo.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension ChatBskyLexicon.Conversation { + + /// A request body model for unmuting a conversation. + /// + /// - SeeAlso: This is based on the [`chat.bsky.convo.unmuteConvo`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/convo/unmuteConvo.json + public struct UnMuteConversationRequestBody: Codable { + + /// The ID of the conversation. + public let conversationID: String + + enum CodingKeys: String, CodingKey { + case conversationID = "convoId" + } + } + + /// An output model for unmuting a conversation. + /// + /// - SeeAlso: This is based on the [`chat.bsky.convo.unmuteConvo`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/convo/unmuteConvo.json + public struct UnmuteConversationOutput: Codable { + + /// The conversation itself. + public let conversationView: ConversationViewDefinition + + enum CodingKeys: String, CodingKey { + case conversationView = "convo" + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Convo/ChatBskyConvoUpdateRead.swift b/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Convo/ChatBskyConvoUpdateRead.swift new file mode 100644 index 0000000000..2be33de111 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Convo/ChatBskyConvoUpdateRead.swift @@ -0,0 +1,41 @@ +// +// ChatBskyConvoUpdateRead.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension ChatBskyLexicon.Conversation { + + /// A request body model for updating the conversation to mark it as read. + /// + /// - SeeAlso: This is based on the [`chat.bsky.convo.updateRead`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/convo/updateRead.json + public struct UpdateReadRequestBody: Codable { + + /// The ID of the conversation to be marked as read. + public let conversationID: String + + /// The ID of the message. + public let messageID: String? + + enum CodingKeys: String, CodingKey { + case conversationID = "convoId" + case messageID = "messageId" + } + } + + /// An output model for updating the conversation to mark it as read. + /// + /// - SeeAlso: This is based on the [`chat.bsky.convo.updateRead`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/convo/updateRead.json + public struct UpdateReadOutput: Codable { + + /// The conversation itself. + public let conversationView: ConversationViewDefinition + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Moderation/ChatBskyModerationGetActorMetadata.swift b/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Moderation/ChatBskyModerationGetActorMetadata.swift new file mode 100644 index 0000000000..f07fb6f1c1 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Moderation/ChatBskyModerationGetActorMetadata.swift @@ -0,0 +1,61 @@ +// +// ChatBskyModerationGetActorMetadata.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension ChatBskyLexicon.Moderation { + + /// The main data model for getting the user account's metadata. + public struct GetActorMetadata: Codable { + + /// The metadata given to the moderator. + public struct Metadata: Codable { + + /// The number of messages sent from the user account. + public let messagesSent: Int + + /// The number of messages the user account received. + public let messagesReceived: Int + + /// The number of conversations the user account participates in. + public let conversations: Int + + /// The number of conversations the user account had started. + public let conversationsStarted: Int + + enum CodingKeys: String, CodingKey { + case messagesSent + case messagesReceived + case conversations = "convos" + case conversationsStarted = "convosStarted" + } + } + } + + /// An output model for getting the user account's metadata. + /// + /// - SeeAlso: This is based on the [`chat.bsky.moderation.getActorMetadata`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/moderation/getActorMetadata.json + public struct GetActorMetadataOutput: Codable { + + /// The metadata that reflects the past day. + public let dayMetadata: GetActorMetadata.Metadata + + /// The metadata that reflects the past month. + public let monthMetadata: GetActorMetadata.Metadata + + /// The metadata that reflects the entire lifetime of the user account. + public let allMetadata: GetActorMetadata.Metadata + + enum CodingKeys: String, CodingKey { + case dayMetadata = "day" + case monthMetadata = "month" + case allMetadata = "all" + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Moderation/ChatBskyModerationGetMessageContext.swift b/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Moderation/ChatBskyModerationGetMessageContext.swift new file mode 100644 index 0000000000..6f1ddafe7f --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Moderation/ChatBskyModerationGetMessageContext.swift @@ -0,0 +1,22 @@ +// +// ChatBskyModerationGetMessageContext.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension ChatBskyLexicon.Moderation { + + /// An output model for getting the message context. + /// + /// - SeeAlso: This is based on the [`chat.bsky.moderation.getMessageContext`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/moderation/getMessageContext.json + public struct GetMessageContextOutput: Codable { + + /// An array of messages. + public let messages: [ATUnion.GetMessageContextOutputMessagesUnion] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Moderation/ChatBskyModerationUpdateActorAccess.swift b/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Moderation/ChatBskyModerationUpdateActorAccess.swift new file mode 100644 index 0000000000..ae4f020960 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/chat.bsky/Moderation/ChatBskyModerationUpdateActorAccess.swift @@ -0,0 +1,34 @@ +// +// ChatBskyModerationUpdateActorAccess.swift +// +// +// Created by Christopher Jr Riley on 2024-05-19. +// + +import Foundation + +extension ChatBskyLexicon.Moderation { + + /// A request body model for updating the user account's access to direct messages. + /// + /// - SeeAlso: This is based on the [`chat.bsky.moderation.updateActorAccess`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/moderation/updateActorAccess.json + public struct UpdateActorAccessRequestBody: Codable { + + /// The user account to change access to direct messages. + public let actorDID: String + + /// Indicates whether the user account has access to direct messages. + public let doesAllowAccess: Bool + + /// A reference object for the action taken. + public let reference: String? + + enum CodingKeys: String, CodingKey { + case actorDID = "did" + case doesAllowAccess = "allowAccess" + case reference = "ref" + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminDefs.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminDefs.swift deleted file mode 100644 index 1e2e41c054..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminDefs.swift +++ /dev/null @@ -1,599 +0,0 @@ -// -// AtprotoAdminDefs.swift -// -// -// Created by Christopher Jr Riley on 2024-01-25. -// - -import Foundation - -/// The main data model definition for admin status attributes. -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/defs.json -public struct AdminStatusAttributes: Codable { - /// Indicates whether the status attributes are being applied. - public let isApplied: Bool - /// The reference of the attributes. - public let reference: String? = nil - - enum CodingKeys: String, CodingKey { - case isApplied = "applied" - case reference = "ref" - } -} - -/// A data model for a report view definition. -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/defs.json -public struct AdminReportView: Codable { - /// The ID of the report. - public let id: Int - /// The reason for the report. - public let reasonType: ModerationReasonType - /// The additional comment provided for a report. Optional. - public let comment: String? = nil - /// The handle of the subject who's related to the report. Optional. - public let subjectRepoHandle: String? = nil - /// The subject reference of the report. - public let subject: RepositoryReferencesUnion - /// The user who created the report. - public let reportedBy: String - /// The date and time the report was created. - @DateFormatting public var createdAt: Date - /// An array of action IDs that relate to resolutions. - public let resolvedByActionIDs: [Int] - - public init(id: Int, reasonType: ModerationReasonType, subject: RepositoryReferencesUnion, reportedBy: String, createdAt: Date, - resolvedByActionIDs: [Int]) { - self.id = id - self.reasonType = reasonType - self.subject = subject - self.reportedBy = reportedBy - self._createdAt = DateFormatting(wrappedValue: createdAt) - self.resolvedByActionIDs = resolvedByActionIDs - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.id = try container.decode(Int.self, forKey: .id) - self.reasonType = try container.decode(ModerationReasonType.self, forKey: .reasonType) - self.subject = try container.decode(RepositoryReferencesUnion.self, forKey: .subject) - self.reportedBy = try container.decode(String.self, forKey: .reportedBy) - self.createdAt = try container.decode(DateFormatting.self, forKey: .createdAt).wrappedValue - self.resolvedByActionIDs = try container.decode([Int].self, forKey: .resolvedByActionIDs) - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - try container.encode(self.id, forKey: .id) - try container.encode(self.reasonType, forKey: .reasonType) - try container.encodeIfPresent(self.comment, forKey: .comment) - try container.encodeIfPresent(self.subjectRepoHandle, forKey: .subjectRepoHandle) - try container.encode(self.subject, forKey: .subject) - try container.encode(self.reportedBy, forKey: .reportedBy) - try container.encode(self._createdAt, forKey: .createdAt) - try container.encode(self.resolvedByActionIDs, forKey: .resolvedByActionIDs) - } - - enum CodingKeys: String, CodingKey { - case id - case reasonType - case comment - case subjectRepoHandle - case subject - case reportedBy - case createdAt - case resolvedByActionIDs = "resolvedByActionIds" - } -} - -/// A data model for a detailed report view definition. -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/defs.json -public struct AdminReportViewDetail: Codable { - /// The ID of a report. - public let id: Int - /// The reason for the report. - public let reasonType: ModerationReasonType - /// Any additional comments about the report. Optional. - public var comment: String? = nil - /// The subject of the report. - /// - /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ - /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ - /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ - /// \ - /// Clarifications from Bluesky are needed in order to fully understand this item. - public let subject: RepositoryViewUnion - /// The status for the subject of the report. Optional. - /// - /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ - /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ - /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ - /// \ - /// Clarifications from Bluesky are needed in order to fully understand this item. - public var subjectStatus: OzoneSubjectStatusView? = nil - /// The user who created the report. - public let reportedBy: String - /// The date and time the report was created. - @DateFormatting public var createdAt: Date - /// An array of resolved actions made in relation to the report. - public let resolvedByActions: [OzoneModerationEventView] - - public init(id: Int, reasonType: ModerationReasonType, comment: String? = nil, subject: RepositoryViewUnion, subjectStatus: OzoneSubjectStatusView? = nil, - reportedBy: String, createdAt: Date, resolvedByActions: [OzoneModerationEventView]) { - self.id = id - self.reasonType = reasonType - self.comment = comment - self.subject = subject - self.subjectStatus = subjectStatus - self.reportedBy = reportedBy - self._createdAt = DateFormatting(wrappedValue: createdAt) - self.resolvedByActions = resolvedByActions - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.id = try container.decode(Int.self, forKey: .id) - self.reasonType = try container.decode(ModerationReasonType.self, forKey: .reasonType) - self.comment = try container.decodeIfPresent(String.self, forKey: .comment) - self.subject = try container.decode(RepositoryViewUnion.self, forKey: .subject) - self.subjectStatus = try container.decodeIfPresent(OzoneSubjectStatusView.self, forKey: .subjectStatus) - self.reportedBy = try container.decode(String.self, forKey: .reportedBy) - self.createdAt = try container.decode(DateFormatting.self, forKey: .createdAt).wrappedValue - self.resolvedByActions = try container.decode([OzoneModerationEventView].self, forKey: .resolvedByActions) - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - try container.encode(self.id, forKey: .id) - try container.encode(self.reasonType, forKey: .reasonType) - try container.encodeIfPresent(self.comment, forKey: .comment) - try container.encode(self.subject, forKey: .subject) - try container.encodeIfPresent(self.subjectStatus, forKey: .subjectStatus) - try container.encode(self.reportedBy, forKey: .reportedBy) - try container.encode(self._createdAt, forKey: .createdAt) - try container.encode(self.resolvedByActions, forKey: .resolvedByActions) - } - - enum CodingKeys: CodingKey { - case id - case reasonType - case comment - case subject - case subjectStatus - case reportedBy - case createdAt - case resolvedByActions - } -} - -/// A data model for a definition of an account view. -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/defs.json -public struct AdminAccountView: Codable { - /// The decentralized identifier (DID) of the user. - public let actorDID: String - /// The handle of the user. - public let handle: String - /// The email of the user. Optional. - public var email: String? = nil - /// The user's related records. Optional. - /// - /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ - /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ - /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ - /// \ - /// Clarifications from Bluesky are needed in order to fully understand this item. - public var relatedRecords: [UnknownType]? = nil - /// The date and time the user was last indexed. - @DateFormatting public var indexedAt: Date - /// The invite code used by the user to sign up. Optional. - public var invitedBy: ServerInviteCode? = nil - /// An array of invite codes held by the user. Optional. - public var invites: [ServerInviteCode]? = nil - /// Indicates whether the invite codes held by the user are diabled. Optional. - public var areInvitesDisabled: Bool? = nil - /// The date and time the email of the user was confirmed. Optional. - @DateFormattingOptional public var emailConfirmedAt: Date? = nil - /// Any notes related to inviting the user. Optional. - public var inviteNote: String? = nil - - public init(actorDID: String, handle: String, email: String?, relatedRecords: [UnknownType]?, indexedAt: Date, invitedBy: ServerInviteCode?, - invites: [ServerInviteCode]?, areInvitesDisabled: Bool?, emailConfirmedAt: Date? = nil, inviteNote: String?) { - self.actorDID = actorDID - self.handle = handle - self.email = email - self.relatedRecords = relatedRecords - self._indexedAt = DateFormatting(wrappedValue: indexedAt) - self.invitedBy = invitedBy - self.invites = invites - self.areInvitesDisabled = areInvitesDisabled - self._emailConfirmedAt = DateFormattingOptional(wrappedValue: emailConfirmedAt) - self.inviteNote = inviteNote - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.actorDID = try container.decode(String.self, forKey: .actorDID) - self.handle = try container.decode(String.self, forKey: .handle) - self.email = try container.decodeIfPresent(String.self, forKey: .email) - self.relatedRecords = try container.decodeIfPresent([UnknownType].self, forKey: .relatedRecords) - self.indexedAt = try container.decode(DateFormatting.self, forKey: .indexedAt).wrappedValue - self.invitedBy = try container.decodeIfPresent(ServerInviteCode.self, forKey: .invitedBy) - self.invites = try container.decodeIfPresent([ServerInviteCode].self, forKey: .invites) - self.areInvitesDisabled = try container.decodeIfPresent(Bool.self, forKey: .areInvitesDisabled) - self.emailConfirmedAt = try container.decodeIfPresent(DateFormattingOptional.self, forKey: .emailConfirmedAt)?.wrappedValue - self.inviteNote = try container.decodeIfPresent(String.self, forKey: .inviteNote) - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - try container.encode(self.actorDID, forKey: .actorDID) - try container.encode(self.handle, forKey: .handle) - try container.encodeIfPresent(self.email, forKey: .email) - try container.encodeIfPresent(self.relatedRecords, forKey: .relatedRecords) - try container.encode(self._indexedAt, forKey: .indexedAt) - try container.encodeIfPresent(self.invitedBy, forKey: .invitedBy) - try container.encodeIfPresent(self.invites, forKey: .invites) - try container.encodeIfPresent(self.areInvitesDisabled, forKey: .areInvitesDisabled) - try container.encode(self._emailConfirmedAt, forKey: .emailConfirmedAt) - try container.encodeIfPresent(self.inviteNote, forKey: .inviteNote) - } - - enum CodingKeys: String, CodingKey { - case actorDID = "did" - case handle - case email - case relatedRecords - case indexedAt - case invitedBy - case invites - case areInvitesDisabled = "invitesDisabled" - case emailConfirmedAt - case inviteNote - } -} - -/// A data model for a definition of a repository reference. -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/defs.json -public struct AdminRepositoryReference: Codable { - /// The decentralized identifier (DID) of the repository. - public let repositoryDID: String - - enum CodingKeys: String, CodingKey { - case repositoryDID = "did" - } -} - -/// A data model for a blob reference definition. -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/defs.json -public struct AdminRepoBlobReference: Codable { - /// The decentralized identifier (DID) of the blob reference. - public let blobDID: String - /// The CID hash of the blob reference. - public let cidHash: String - /// The URI of the record that contains the blob reference. - public let recordURI: String? - - enum CodingKeys: String, CodingKey { - case blobDID = "did" - case cidHash = "cid" - case recordURI = "recordUri" - } -} - -// MARK: - Union types -/// A reference containing the list of event views. -public enum AdminEventViewUnion: Codable { - /// A takedown event. - case moderationEventTakedown(OzoneModerationEventTakedown) - /// A reverse takedown event. - case moderationEventReverseTakedown(OzoneModerationEventReverseTakedown) - /// A comment event. - case moderationEventComment(OzoneModerationEventComment) - /// A report event. - case moderationEventReport(OzoneModerationEventReport) - /// A label event. - case moderationEventLabel(OzoneModerationEventLabel) - /// An acknowledgement event. - case moderationEventAcknowledge(OzoneModerationEventAcknowledge) - /// An escalation event. - case moderationEventEscalate(OzoneModerationEventEscalate) - /// A mute event. - case moderationEventMute(OzoneModerationEventMute) - /// An unmute event. - case moderationEventUnmute(OzoneModerationEventUnmute) - /// A mute reporter event. - case moderationEventMuteReporter(OzoneModerationEventMuteReporter) - /// An unmute reporter event. - case moderationEventUnmuteReporter(OzoneModerationEventUnmuteReporter) - /// An email event. - case moderationEventEmail(OzoneModerationEventEmail) - /// A resolve appeal event. - case moderationEventResolveAppeal(OzoneModerationEventResolveAppeal) - /// A diversion event. - case moderationEventDivert(OzoneModerationEventDivert) - - public init(from decoder: Decoder) throws { - let container = try decoder.singleValueContainer() - - if let value = try? container.decode(OzoneModerationEventTakedown.self) { - self = .moderationEventTakedown(value) - } else if let value = try? container.decode(OzoneModerationEventReverseTakedown.self) { - self = .moderationEventReverseTakedown(value) - } else if let value = try? container.decode(OzoneModerationEventComment.self) { - self = .moderationEventComment(value) - } else if let value = try? container.decode(OzoneModerationEventReport.self) { - self = .moderationEventReport(value) - } else if let value = try? container.decode(OzoneModerationEventLabel.self) { - self = .moderationEventLabel(value) - } else if let value = try? container.decode(OzoneModerationEventAcknowledge.self) { - self = .moderationEventAcknowledge(value) - } else if let value = try? container.decode(OzoneModerationEventEscalate.self) { - self = .moderationEventEscalate(value) - } else if let value = try? container.decode(OzoneModerationEventMute.self) { - self = .moderationEventMute(value) - } else if let value = try? container.decode(OzoneModerationEventUnmute.self) { - self = .moderationEventUnmute(value) - } else if let value = try? container.decode(OzoneModerationEventMuteReporter.self) { - self = .moderationEventMuteReporter(value) - } else if let value = try? container.decode(OzoneModerationEventUnmuteReporter.self) { - self = .moderationEventUnmuteReporter(value) - } else if let value = try? container.decode(OzoneModerationEventEmail.self) { - self = .moderationEventEmail(value) - } else if let value = try? container.decode(OzoneModerationEventResolveAppeal.self) { - self = .moderationEventResolveAppeal(value) - } else if let value = try? container.decode(OzoneModerationEventDivert.self) { - self = .moderationEventDivert(value) - } else { - throw DecodingError.typeMismatch( - AdminEventViewUnion.self, DecodingError.Context( - codingPath: decoder.codingPath, debugDescription: "Unknown EventViewUnion type")) - } - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.singleValueContainer() - - switch self { - case .moderationEventTakedown(let moderationEventTakedown): - try container.encode(moderationEventTakedown) - case .moderationEventReverseTakedown(let moderationEventReverseTakedown): - try container.encode(moderationEventReverseTakedown) - case .moderationEventComment(let moderationEventComment): - try container.encode(moderationEventComment) - case .moderationEventReport(let moderationEventReport): - try container.encode(moderationEventReport) - case .moderationEventLabel(let moderationEventLabel): - try container.encode(moderationEventLabel) - case .moderationEventAcknowledge(let moderationEventAcknowledge): - try container.encode(moderationEventAcknowledge) - case .moderationEventEscalate(let moderationEventEscalate): - try container.encode(moderationEventEscalate) - case .moderationEventMute(let moderationEventMute): - try container.encode(moderationEventMute) - case .moderationEventUnmute(let moderationEventUnmute): - try container.encode(moderationEventUnmute) - case .moderationEventMuteReporter(let moderationEventMuteReporter): - try container.encode(moderationEventMuteReporter) - case .moderationEventUnmuteReporter(let moderationEventUnmuteReporter): - try container.encode(moderationEventUnmuteReporter) - case .moderationEventEmail(let moderationEventEmail): - try container.encode(moderationEventEmail) - case .moderationEventResolveAppeal(let moderationEventResolveAppeal): - try container.encode(moderationEventResolveAppeal) - case .moderationEventDivert(let moderationEventDivert): - try container.encode(moderationEventDivert) - } - } -} - -// Create the custom init and encode methods. -/// A reference containing the list of repository references. -public enum RepositoryReferencesUnion: Codable { - /// A repository reference. - case repositoryReference(AdminRepositoryReference) - /// A strong reference. - case strongReference(StrongReference) - - public init(from decoder: Decoder) throws { - let container = try decoder.singleValueContainer() - - if let value = try? container.decode(AdminRepositoryReference.self) { - self = .repositoryReference(value) - } else if let value = try? container.decode(StrongReference.self) { - self = .strongReference(value) - } else { - throw DecodingError.typeMismatch( - ActorPreferenceUnion.self, DecodingError.Context( - codingPath: decoder.codingPath, debugDescription: "Unknown RepositoryReferencesUnion type")) - } - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.singleValueContainer() - - switch self { - case .repositoryReference(let repositoryReference): - try container.encode(repositoryReference) - case .strongReference(let strongReference): - try container.encode(strongReference) - } - } -} - -// Create the custom init and encode methods. -/// A reference containing the list of moderator events. -public enum EventViewDetailUnion: Codable { - /// A takedown event. - case moderationEventTakedown(OzoneModerationEventTakedown) - /// A reverse takedown event. - case moderationEventReverseTakedown(OzoneModerationEventReverseTakedown) - /// A comment event. - case moderationEventComment(OzoneModerationEventComment) - /// A report event. - case moderationEventReport(OzoneModerationEventReport) - /// A label event. - case moderationEventLabel(OzoneModerationEventLabel) - /// An acknowledgment event. - case moderationEventAcknowledge(OzoneModerationEventAcknowledge) - /// An escalation event. - case moderationEventEscalate(OzoneModerationEventEscalate) - /// A mute event. - case moderationEventMute(OzoneModerationEventMute) - /// A resolve appeal event. - case moderationEventResolveAppeal(OzoneModerationEventResolveAppeal) - - public init(from decoder: Decoder) throws { - let container = try decoder.singleValueContainer() - - if let value = try? container.decode(OzoneModerationEventTakedown.self) { - self = .moderationEventTakedown(value) - } else if let value = try? container.decode(OzoneModerationEventReverseTakedown.self) { - self = .moderationEventReverseTakedown(value) - } else if let value = try? container.decode(OzoneModerationEventComment.self) { - self = .moderationEventComment(value) - } else if let value = try? container.decode(OzoneModerationEventReport.self) { - self = .moderationEventReport(value) - } else if let value = try? container.decode(OzoneModerationEventLabel.self) { - self = .moderationEventLabel(value) - } else if let value = try? container.decode(OzoneModerationEventAcknowledge.self) { - self = .moderationEventAcknowledge(value) - } else if let value = try? container.decode(OzoneModerationEventEscalate.self) { - self = .moderationEventEscalate(value) - } else if let value = try? container.decode(OzoneModerationEventMute.self) { - self = .moderationEventMute(value) - } else if let value = try? container.decode(OzoneModerationEventResolveAppeal.self) { - self = .moderationEventResolveAppeal(value) - } else { - throw DecodingError.typeMismatch( - ActorPreferenceUnion.self, DecodingError.Context( - codingPath: decoder.codingPath, debugDescription: "Unknown EventViewDetailUnion type")) - } - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.singleValueContainer() - - switch self { - case .moderationEventTakedown(let moderationEventTakedown): - try container.encode(moderationEventTakedown) - case .moderationEventReverseTakedown(let moderationEventDetail): - try container.encode(moderationEventDetail) - case .moderationEventComment(let moderationEventComment): - try container.encode(moderationEventComment) - case .moderationEventReport(let moderationEventReport): - try container.encode(moderationEventReport) - case .moderationEventLabel(let moderationEventLabel): - try container.encode(moderationEventLabel) - case .moderationEventAcknowledge(let moderationEventAcknowledge): - try container.encode(moderationEventAcknowledge) - case .moderationEventEscalate(let moderationEventEscalate): - try container.encode(moderationEventEscalate) - case .moderationEventMute(let moderationEventMute): - try container.encode(moderationEventMute) - case .moderationEventResolveAppeal(let moderationEventResolveAppeal): - try container.encode(moderationEventResolveAppeal) - } - } -} - -// Create the custom init and encode methods. -/// A reference containing the list of the types of repository or record views. -public enum RepositoryViewUnion: Codable { - /// A normal repository view. - case repositoryView(AdminReportView) - /// A repository view that may not have been found. - case repositoryViewNotFound(OzoneModerationRepositoryViewNotFound) - /// A normal record. - case recordView(OzoneModerationRecordView) - /// A record view that may not have been found. - case recordViewNotFound(OzoneModerationRecordViewNotFound) - - public init(from decoder: Decoder) throws { - let container = try decoder.singleValueContainer() - - if let value = try? container.decode(AdminReportView.self) { - self = .repositoryView(value) - } else if let value = try? container.decode(OzoneModerationRepositoryViewNotFound.self) { - self = .repositoryViewNotFound(value) - } else if let value = try? container.decode(OzoneModerationRecordView.self) { - self = .recordView(value) - } else if let value = try? container.decode(OzoneModerationRecordViewNotFound.self) { - self = .recordViewNotFound(value) - } else { - throw DecodingError.typeMismatch( - ActorPreferenceUnion.self, DecodingError.Context( - codingPath: decoder.codingPath, debugDescription: "Unknown RepositoryViewUnion type")) - } - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.singleValueContainer() - - switch self { - case .repositoryView(let repositoryView): - try container.encode(repositoryView) - case .repositoryViewNotFound(let repositoryViewNotFound): - try container.encode(repositoryViewNotFound) - case .recordView(let recordView): - try container.encode(recordView) - case .recordViewNotFound(let recordViewNotFound): - try container.encode(recordViewNotFound) - } - } -} - -/// A reference containing the list of the types of media details. -public enum MediaDetailUnion: Codable { - /// The details for an image. - case mediaImageDetails(OzoneModerationMediaImageDetails) - /// The details for a video. - case mediaVideoDetails(OzoneModerationMediaVideoDetails) - - public init(from decoder: Decoder) throws { - let container = try decoder.singleValueContainer() - - if let value = try? container.decode(OzoneModerationMediaImageDetails.self) { - self = .mediaImageDetails(value) - } else if let value = try? container.decode(OzoneModerationMediaVideoDetails.self) { - self = .mediaVideoDetails(value) - } else { - throw DecodingError.typeMismatch( - ActorPreferenceUnion.self, DecodingError.Context( - codingPath: decoder.codingPath, debugDescription: "Unknown MediaDetailUnion type")) - } - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.singleValueContainer() - - switch self { - case .mediaImageDetails(let mediaImageDetails): - try container.encode(mediaImageDetails) - case .mediaVideoDetails(let mediaVideoDetails): - try container.encode(mediaVideoDetails) - } - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminDeleteAccount.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminDeleteAccount.swift deleted file mode 100644 index caef63bd27..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminDeleteAccount.swift +++ /dev/null @@ -1,21 +0,0 @@ -// -// AtprotoAdminDeleteAccount.swift -// -// -// Created by Christopher Jr Riley on 2024-02-27. -// - -import Foundation - -/// The main data model definition for deleting a user's account as an administrator. -/// -/// - Note: According to the AT Protocol specifications: "Delete a user account as -/// an administrator." -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.deleteAccount`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/deleteAccount.json -public struct AdminDeleteAccount: Codable { - /// The decentralized identifier (DID) of the account to be deleted. - public let accountDID: String -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminDisableAccountInvites.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminDisableAccountInvites.swift deleted file mode 100644 index 4edbb2fb48..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminDisableAccountInvites.swift +++ /dev/null @@ -1,32 +0,0 @@ -// -// AtprotoAdminDisableAccountInvites.swift -// -// -// Created by Christopher Jr Riley on 2024-02-28. -// - -import Foundation - -/// The main data model definition for disabling a user account's ability to receive new -/// invite codes. -/// -/// - Note: According to the AT Protocol specifications: "Disable an account from receiving new -/// invite codes, but does not invalidate existing codes." -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.disableAccountInvites`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/disableAccountInvites.json -public struct AdminDisableAccountInvites: Codable { - /// The decentralized identifier (DID) of the user account. - public let accountDID: String - /// A comment explaining why the user won't receive new account invites. Optional. - /// - /// - Note: According to the AT Protocol specifications: "Optional reason for - /// disabled invites." - public let note: String? - - enum CodingKeys: String, CodingKey { - case accountDID = "account" - case note - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminDisableInviteCodes.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminDisableInviteCodes.swift deleted file mode 100644 index 24336747f3..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminDisableInviteCodes.swift +++ /dev/null @@ -1,29 +0,0 @@ -// -// AtprotoAdminDisableInviteCodes.swift -// -// -// Created by Christopher Jr Riley on 2024-02-28. -// - -import Foundation - -/// The main data model definition for disabling some or all of the invite codes for one or more -/// user accounts. -/// -/// - Note: According to the AT Protocol specifications: "Disable some set of codes and/or all -/// codes associated with a set of users." -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.disableInviteCodes`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/disableInviteCodes.json -public struct AdminDisableInviteCodes: Codable { - /// The invite codes to disable. - public let codes: [String] - /// The decentralized identifiers (DIDs) of the user accounts. - public let accountDIDs: [String] - - enum CodingKeys: String, CodingKey { - case codes - case accountDIDs = "accounts" - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminEnableAccountInvites.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminEnableAccountInvites.swift deleted file mode 100644 index 91110da85a..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminEnableAccountInvites.swift +++ /dev/null @@ -1,30 +0,0 @@ -// -// AtprotoAdminEnableAccountInvites.swift -// -// -// Created by Christopher Jr Riley on 2024-02-29. -// - -import Foundation - -/// The main data model definition for giving the user account access to receive invite -/// codes again. -/// -/// - Note: According to the AT Protocol specifications: "Re-enable an account's ability to -/// receive invite codes." -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.enableAccountInvites`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/enableAccountInvites.json -public struct AdminEnableAccountInvites: Codable { - /// The decentralized identifier (DID) of the account that will regain access to receiving - /// invite codes. - public let accountDID: String - /// A note as to why this action is being done. Optional. - public let note: String? - - enum CodingKeys: String, CodingKey { - case accountDID = "account" - case note - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminGetAccountInfos.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminGetAccountInfos.swift deleted file mode 100644 index 9324778620..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminGetAccountInfos.swift +++ /dev/null @@ -1,20 +0,0 @@ -// -// AtprotoAdminGetAccountInfos.swift -// -// -// Created by Christopher Jr Riley on 2024-02-29. -// - -import Foundation - -/// A data model definition for the output of retrieving an array of user accounts. -/// -/// - Note: According to the AT Protocol specifications: "Get details about some accounts." -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.getAccountInfos`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/getAccountInfos.json -public struct AdminGetAccountInfosOutput: Codable { - /// An array of user account information. - public let infos: [AdminAccountView] -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminGetInviteCodes.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminGetInviteCodes.swift deleted file mode 100644 index 008abfaf2b..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminGetInviteCodes.swift +++ /dev/null @@ -1,30 +0,0 @@ -// -// AtprotoAdminGetInviteCodes.swift -// -// -// Created by Christopher Jr Riley on 2024-02-29. -// - -import Foundation - -/// A data model definition for the output of getting the invite codes from a user account. -/// -/// - Note: According to the AT Protocol specifications: "Get an admin view of invite codes." -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.getInviteCodes`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/getInviteCodes.json -public struct AdminGetInviteCodesOutput: Codable { - /// The mark used to indicate the starting point for the next set of results. Optional. - public let cursor: String? - /// An array of invite codes. - public let codes: [ServerInviteCode] -} - -/// Sorts the invite codes by a particular order. -public enum AdminGetInviteCodesSort { - /// Sorts the invite codes by the most recently made. - case recent - /// Sorts the invite codes by the number of times it's been used. - case usage -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminGetSubjectStatus.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminGetSubjectStatus.swift deleted file mode 100644 index ddca60d9e7..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminGetSubjectStatus.swift +++ /dev/null @@ -1,60 +0,0 @@ -// -// AtprotoAdminGetSubjectStatus.swift -// -// -// Created by Christopher Jr Riley on 2024-03-01. -// - -import Foundation - -/// A data model definition for the output of getting the status of a subject as an administrator. -/// -/// - Note: According to the AT Protocol specifications: "Get the service-specific admin status of -/// a subject (account, record, or blob)." -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.getSubjectStatus`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/getSubjectStatus.json -public struct AdminGetSubjectStatusOutput: Codable { - public let subject: AdminGetSubjectStatusUnion - public let takedown: AdminStatusAttributes -} - -/// A reference containing the list of repository references. -public enum AdminGetSubjectStatusUnion: Codable { - /// A repository reference. - case repositoryReference(AdminRepositoryReference) - /// A strong reference. - case strongReference(StrongReference) - /// A repository blob reference. - case repoBlobReference(AdminRepoBlobReference) - - public init(from decoder: Decoder) throws { - let container = try decoder.singleValueContainer() - - if let value = try? container.decode(AdminRepositoryReference.self) { - self = .repositoryReference(value) - } else if let value = try? container.decode(StrongReference.self) { - self = .strongReference(value) - } else if let value = try? container.decode(AdminRepoBlobReference.self) { - self = .repoBlobReference(value) - } else { - throw DecodingError.typeMismatch( - AdminEventViewUnion.self, DecodingError.Context( - codingPath: decoder.codingPath, debugDescription: "UnknownAdminGetSubjectStatusUnion type")) - } - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.singleValueContainer() - - switch self { - case .repositoryReference(let repositoryReference): - try container.encode(repositoryReference) - case .strongReference(let strongReference): - try container.encode(strongReference) - case .repoBlobReference(let repoBlobReference): - try container.encode(repoBlobReference) - } - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminQueryModerationStatuses.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminQueryModerationStatuses.swift deleted file mode 100644 index 759e8219fd..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminQueryModerationStatuses.swift +++ /dev/null @@ -1,38 +0,0 @@ -// -// AtprotoAdminQueryModerationStatuses.swift -// -// -// Created by Christopher Jr Riley on 2024-03-02. -// - -import Foundation - -/// A data model definition for the output of listing all of moderation statuses of records and repositories. -/// -/// - Note: According to the AT Protocol specifications: "View moderation statuses of subjects (record or repo)." -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.queryModerationStatuses`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/queryModerationStatuses.json -public struct AdminQueryModerationStatusesOutput: Codable { - /// The mark used to indicate the starting point for the next set of results. Optional. - public let cursor: String - /// An array of subject statuses. - public let subjectStatuses: [OzoneSubjectStatusView] -} - -/// Indicates the sorting field for the moderation status array. -public enum AdminQueryModerationStatusesSortField { - /// Indicates the moderation status array will be sorted by the last reported user. - case lastReportedAt - /// Indicates the moderation status array will be sorted by the last reviwed user. - case lastReviewedAt -} - -/// Indicates the sorting direction for the array of moderation statuses. -public enum AdminQueryModerationStatusesSortDirection: String { - /// Indicates the moderation events will be sorted in ascending order. - case ascending = "asc" - /// Indicates the moderation events will be sorted in descending order. - case descending = "desc" -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminSearchRepos.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminSearchRepos.swift deleted file mode 100644 index 8d6b79381e..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminSearchRepos.swift +++ /dev/null @@ -1,23 +0,0 @@ -// -// AtprotoAdminSearchRepos.swift -// -// -// Created by Christopher Jr Riley on 2024-03-02. -// - -import Foundation - -/// The main data model definition for the output of searching repositories. -/// -/// - Note: According to the AT Protocol specifications: "Find repositories based on a -/// search term." -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.searchRepos`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/searchRepos.json -public struct AdminSearchReposOutput: Codable { - /// The mark used to indicate the starting point for the next set of results. Optional. - public let cursor: String? - /// An array of repositories. - public let repos: OzoneModerationRepositoryView -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminSendEmail.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminSendEmail.swift deleted file mode 100644 index f36f79137d..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminSendEmail.swift +++ /dev/null @@ -1,52 +0,0 @@ -// -// AtprotoAdminSendEmail.swift -// -// -// Created by Christopher Jr Riley on 2024-03-02. -// - -import Foundation - -/// The main data model definition for sending an email to a user. -/// -/// - Note: According to the AT Protocol specifications: "Send email to a user's account email address." -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.sendEmail`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/sendEmail.json -public struct AdminSendEmail: Codable { - /// The decentralized identifier (DID) of the recipient. - public let recipientDID: String - /// The content of the email. - public let content: String - /// The subject line of the email. Optional. - public let subject: String? - /// The decentralized identifier (DID) of the sender. - public let senderDID: String - /// Any additional comments viewable to other moderators and administrators. - public let comment: String? - - enum CodingKeys: String, CodingKey { - case recipientDID = "recipientDid" - case content - case subject - case senderDID = "senderDid" - case comment - } -} - -/// A data model definition for the output of sending an email to a user. -/// -/// - Note: According to the AT Protocol specifications: "Send email to a user's account email address." -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.sendEmail`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/sendEmail.json -public struct AdminSendEmailOutput: Codable { - /// Indicates whether the email has been sent. - public let isSent: Bool - - enum CodingKeys: String, CodingKey { - case isSent = "sent" - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminUpdateAccountEmail.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminUpdateAccountEmail.swift deleted file mode 100644 index a0c8b31b77..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminUpdateAccountEmail.swift +++ /dev/null @@ -1,29 +0,0 @@ -// -// AtprotoAdminUpdateAccountEmail.swift -// -// -// Created by Christopher Jr Riley on 2024-03-02. -// - -import Foundation - -/// The main data model definition for updating the email address of a user account as -/// an administrator. -/// -/// - Note: According to the AT Protocol specifications: "Administrative action to update an -/// account's email." -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.updateAccountEmail`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/updateAccountEmail.json -public struct AdminUpdateAccountEmail: Codable { - /// The decentralized identifier (DID) of the account. - public let accountDID: String - /// The new email account the user wants to change to. - public let accountEmail: String - - enum CodingKeys: String, CodingKey { - case accountDID = "account" - case accountEmail = "email" - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminUpdateAccountHandle.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminUpdateAccountHandle.swift deleted file mode 100644 index e9b90e21aa..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminUpdateAccountHandle.swift +++ /dev/null @@ -1,29 +0,0 @@ -// -// AtprotoAdminUpdateAccountHandle.swift -// -// -// Created by Christopher Jr Riley on 2024-03-03. -// - -import Foundation - -/// The main data model definition for updating the handle of a user account as -/// an administrator. -/// -/// - Note: According to the AT Protocol specifications: "Administrative action to update -/// an account's handle." -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.updateAccountHandle`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/updateAccountHandle.json -public struct AdminUpdateAccountHandle: Codable { - /// The decentralized identifier (DID) of the account. - public let accountDID: String - /// The new account handle the user wants to change to. - public let accountHandle: String - - enum CodingKeys: String, CodingKey { - case accountDID = "did" - case accountHandle = "handle" - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminUpdateAccountPassword.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminUpdateAccountPassword.swift deleted file mode 100644 index c7adec35a7..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminUpdateAccountPassword.swift +++ /dev/null @@ -1,28 +0,0 @@ -// -// AtprotoAdminUpdateAccountPassword.swift -// -// -// Created by Christopher Jr Riley on 2024-03-03. -// - -import Foundation - -/// The main data model definition for updating the handle of a user account as an administrator. -/// -/// - Note: According to the AT Protocol specifications: "Update the password for a user account -/// as an administrator." -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.updateAccountPassword`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/updateAccountPassword.json -public struct AdminUpdateAccountPassword: Codable { - /// The decentralized identifier (DID) of the account. - public let accountDID: String - /// The new password for the user account. - public let newPassword: String - - enum CodingKeys: String, CodingKey { - case accountDID = "did" - case newPassword = "password" - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminUpdateSubjectStatus.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminUpdateSubjectStatus.swift deleted file mode 100644 index 16233bf284..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/AtprotoAdminUpdateSubjectStatus.swift +++ /dev/null @@ -1,38 +0,0 @@ -// -// AtprotoAdminUpdateSubjectStatus.swift -// -// -// Created by Christopher Jr Riley on 2024-03-03. -// - -import Foundation - -/// The main data model definition for updating a subject status of an account, record, or blob. -/// -/// - Note: According to the AT Protocol specifications: "Update the service-specific admin status -/// of a subject (account, record, or blob)." -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.updateSubjectStatus`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/updateSubjectStatus.json -public struct AdminUpdateSubjectStatus: Codable { - /// The subject associated with the subject status. - public let subject: AdminGetSubjectStatusUnion - /// The status attributes of the subject. Optional. - public let takedown: AdminStatusAttributes? -} - -/// A data model definition for the output of updating a subject status of an account, record, or blob. -/// -/// - Note: According to the AT Protocol specifications: "Update the service-specific admin status -/// of a subject (account, record, or blob)." -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.updateSubjectStatus`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/updateSubjectStatus.json -public struct AdminUpdateSubjectStatusOutput: Codable { - /// The subject associated with the subject status. - public let subject: AdminGetSubjectStatusUnion - /// The status attributes of the subject. Optional. - public let takedown: AdminStatusAttributes? -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/ComAtprotoAdminDefs.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/ComAtprotoAdminDefs.swift new file mode 100644 index 0000000000..33c2633657 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/ComAtprotoAdminDefs.swift @@ -0,0 +1,170 @@ +// +// ComAtprotoAdminDefs.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Admin { + + /// A definition model for admin status attributes. + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/defs.json + public struct StatusAttributesDefinition: Codable { + + /// Indicates whether the status attributes are being applied. + public let isApplied: Bool + + /// The reference of the attributes. + public let reference: String? + + enum CodingKeys: String, CodingKey { + case isApplied = "applied" + case reference = "ref" + } + } + + /// A definition model for an account view. + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/defs.json + public struct AccountViewDefinition: Codable { + + /// The decentralized identifier (DID) of the user. + public let actorDID: String + + /// The handle of the user. + public let handle: String + + /// The email of the user. Optional. + public var email: String? + + /// The user's related records. Optional. + /// + /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ + /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ + /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ + /// \ + /// Clarifications from Bluesky are needed in order to fully understand this item. + public var relatedRecords: [UnknownType]? + + /// The date and time the user was last indexed. + @DateFormatting public var indexedAt: Date + + /// The invite code used by the user to sign up. Optional. + public var invitedBy: ComAtprotoLexicon.Server.InviteCodeDefinition? + + /// An array of invite codes held by the user. Optional. + public var invites: [ComAtprotoLexicon.Server.InviteCodeDefinition]? + + /// Indicates whether the invite codes held by the user are diabled. Optional. + public var areInvitesDisabled: Bool? + + /// The date and time the email of the user was confirmed. Optional. + @DateFormattingOptional public var emailConfirmedAt: Date? + + /// Any notes related to inviting the user. Optional. + public var inviteNote: String? + + public init(actorDID: String, handle: String, email: String?, relatedRecords: [UnknownType]?, indexedAt: Date, + invitedBy: ComAtprotoLexicon.Server.InviteCodeDefinition?, + invites: [ComAtprotoLexicon.Server.InviteCodeDefinition]?, areInvitesDisabled: Bool?, emailConfirmedAt: Date? = nil, inviteNote: String?) { + self.actorDID = actorDID + self.handle = handle + self.email = email + self.relatedRecords = relatedRecords + self._indexedAt = DateFormatting(wrappedValue: indexedAt) + self.invitedBy = invitedBy + self.invites = invites + self.areInvitesDisabled = areInvitesDisabled + self._emailConfirmedAt = DateFormattingOptional(wrappedValue: emailConfirmedAt) + self.inviteNote = inviteNote + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.actorDID = try container.decode(String.self, forKey: .actorDID) + self.handle = try container.decode(String.self, forKey: .handle) + self.email = try container.decodeIfPresent(String.self, forKey: .email) + self.relatedRecords = try container.decodeIfPresent([UnknownType].self, forKey: .relatedRecords) + self.indexedAt = try container.decode(DateFormatting.self, forKey: .indexedAt).wrappedValue + self.invitedBy = try container.decodeIfPresent(ComAtprotoLexicon.Server.InviteCodeDefinition.self, forKey: .invitedBy) + self.invites = try container.decodeIfPresent([ComAtprotoLexicon.Server.InviteCodeDefinition].self, forKey: .invites) + self.areInvitesDisabled = try container.decodeIfPresent(Bool.self, forKey: .areInvitesDisabled) + self.emailConfirmedAt = try container.decodeIfPresent(DateFormattingOptional.self, forKey: .emailConfirmedAt)?.wrappedValue + self.inviteNote = try container.decodeIfPresent(String.self, forKey: .inviteNote) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.actorDID, forKey: .actorDID) + try container.encode(self.handle, forKey: .handle) + try container.encodeIfPresent(self.email, forKey: .email) + try container.encodeIfPresent(self.relatedRecords, forKey: .relatedRecords) + try container.encode(self._indexedAt, forKey: .indexedAt) + try container.encodeIfPresent(self.invitedBy, forKey: .invitedBy) + try container.encodeIfPresent(self.invites, forKey: .invites) + try container.encodeIfPresent(self.areInvitesDisabled, forKey: .areInvitesDisabled) + try container.encode(self._emailConfirmedAt, forKey: .emailConfirmedAt) + try container.encodeIfPresent(self.inviteNote, forKey: .inviteNote) + } + + enum CodingKeys: String, CodingKey { + case actorDID = "did" + case handle + case email + case relatedRecords + case indexedAt + case invitedBy + case invites + case areInvitesDisabled = "invitesDisabled" + case emailConfirmedAt + case inviteNote + } + } + + /// A definition model for a repository reference. + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/defs.json + public struct RepositoryReferenceDefinition: Codable { + + /// The decentralized identifier (DID) of the repository. + public let repositoryDID: String + + enum CodingKeys: String, CodingKey { + case repositoryDID = "did" + } + } + + /// A definition model for a blob reference. + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/defs.json + public struct RepositoryBlobReferenceDefinition: Codable { + + /// The decentralized identifier (DID) of the blob reference. + public let blobDID: String + + /// The CID hash of the blob reference. + public let cidHash: String + + /// The URI of the record that contains the blob reference. + public let recordURI: String? + + enum CodingKeys: String, CodingKey { + case blobDID = "did" + case cidHash = "cid" + case recordURI = "recordUri" + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/ComAtprotoAdminDeleteAccount.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/ComAtprotoAdminDeleteAccount.swift new file mode 100644 index 0000000000..d7555fbd42 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/ComAtprotoAdminDeleteAccount.swift @@ -0,0 +1,25 @@ +// +// ComAtprotoAdminDeleteAccount.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Admin { + + /// A request body model for deleting a user's account as an administrator. + /// + /// - Note: According to the AT Protocol specifications: "Delete a user account as + /// an administrator." + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.deleteAccount`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/deleteAccount.json + public struct DeleteAccountRequestBody: Codable { + + /// The decentralized identifier (DID) of the account to be deleted. + public let accountDID: String + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/ComAtprotoAdminDisableAccountInvites.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/ComAtprotoAdminDisableAccountInvites.swift new file mode 100644 index 0000000000..ccb6b08f91 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/ComAtprotoAdminDisableAccountInvites.swift @@ -0,0 +1,36 @@ +// +// ComAtprotoAdminDisableAccountInvites.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Admin { + + /// A request body model for disabling a user account's ability to receive new invite codes. + /// + /// - Note: According to the AT Protocol specifications: "Disable an account from receiving new + /// invite codes, but does not invalidate existing codes." + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.disableAccountInvites`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/disableAccountInvites.json + public struct DisableAccountInvitesRequestBody: Codable { + + /// The decentralized identifier (DID) of the user account. + public let accountDID: String + + /// A comment explaining why the user won't receive new account invites. Optional. + /// + /// - Note: According to the AT Protocol specifications: "Optional reason for + /// disabled invites." + public let note: String? + + enum CodingKeys: String, CodingKey { + case accountDID = "account" + case note + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/ComAtprotoAdminDisableInviteCodes.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/ComAtprotoAdminDisableInviteCodes.swift new file mode 100644 index 0000000000..b71e99417d --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/ComAtprotoAdminDisableInviteCodes.swift @@ -0,0 +1,34 @@ +// +// ComAtprotoAdminDisableInviteCodes.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Admin { + + /// A request body model for disabling some or all of the invite codes for one or more + /// user accounts. + /// + /// - Note: According to the AT Protocol specifications: "Disable some set of codes and/or all + /// codes associated with a set of users." + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.disableInviteCodes`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/disableInviteCodes.json + public struct DisableInviteCodesRequestBody: Codable { + + /// The invite codes to disable. + public let codes: [String] + + /// The decentralized identifiers (DIDs) of the user accounts. + public let accountDIDs: [String] + + enum CodingKeys: String, CodingKey { + case codes + case accountDIDs = "accounts" + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/ComAtprotoAdminEnableAccountInvites.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/ComAtprotoAdminEnableAccountInvites.swift new file mode 100644 index 0000000000..760af0fae4 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/ComAtprotoAdminEnableAccountInvites.swift @@ -0,0 +1,34 @@ +// +// ComAtprotoAdminEnableAccountInvites.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Admin { + + /// A request body model for giving the user account access to receive invite codes again. + /// + /// - Note: According to the AT Protocol specifications: "Re-enable an account's ability to + /// receive invite codes." + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.enableAccountInvites`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/enableAccountInvites.json + public struct EnableAccountInvitesRequestBody: Codable { + + /// The decentralized identifier (DID) of the account that will regain access to receiving + /// invite codes. + public let accountDID: String + + /// A note as to why this action is being done. Optional. + public let note: String? + + enum CodingKeys: String, CodingKey { + case accountDID = "account" + case note + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/ComAtprotoAdminGetAccountInfos.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/ComAtprotoAdminGetAccountInfos.swift new file mode 100644 index 0000000000..f159fe4f2e --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/ComAtprotoAdminGetAccountInfos.swift @@ -0,0 +1,24 @@ +// +// ComAtprotoAdminGetAccountInfos.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Admin { + + /// An output model for retrieving an array of user accounts. + /// + /// - Note: According to the AT Protocol specifications: "Get details about some accounts." + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.getAccountInfos`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/getAccountInfos.json + public struct GetAccountInfosOutput: Codable { + + /// An array of user account information. + public let infos: [AccountViewDefinition] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/ComAtprotoAdminGetInviteCodes.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/ComAtprotoAdminGetInviteCodes.swift new file mode 100644 index 0000000000..a49b31afcd --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/ComAtprotoAdminGetInviteCodes.swift @@ -0,0 +1,45 @@ +// +// ComAtprotoAdminGetInviteCodes.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Admin { + + /// The main data model for getting the invite codes from a user account. + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.getInviteCodes`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/getInviteCodes.json + public struct GetInviteCodes: Codable { + + /// Sorts the invite codes by a particular order. + public enum Sort { + + /// Sorts the invite codes by the most recently made. + case recent + + /// Sorts the invite codes by the number of times it's been used. + case usage + } + } + + /// An output model for getting the invite codes from a user account. + /// + /// - Note: According to the AT Protocol specifications: "Get an admin view of invite codes." + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.getInviteCodes`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/getInviteCodes.json + public struct GetInviteCodesOutput: Codable { + + /// The mark used to indicate the starting point for the next set of results. Optional. + public let cursor: String? + + /// An array of invite codes. + public let codes: [ComAtprotoLexicon.Server.InviteCodeDefinition] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/ComAtprotoAdminGetSubjectStatus.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/ComAtprotoAdminGetSubjectStatus.swift new file mode 100644 index 0000000000..726b76f4d3 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/ComAtprotoAdminGetSubjectStatus.swift @@ -0,0 +1,28 @@ +// +// ComAtprotoAdminGetSubjectStatus.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Admin { + + /// An output model for getting the status of a subject as an administrator. + /// + /// - Note: According to the AT Protocol specifications: "Get the service-specific admin status of + /// a subject (account, record, or blob)." + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.getSubjectStatus`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/getSubjectStatus.json + public struct GetSubjectStatusOutput: Codable { + + /// The subject itself. + public let subject: ATUnion.AdminGetSubjectStatusUnion + + /// The attributes of the takedown event. + public let takedown: StatusAttributesDefinition + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/ComAtprotoAdminSearchRepos.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/ComAtprotoAdminSearchRepos.swift new file mode 100644 index 0000000000..1db95856fa --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/ComAtprotoAdminSearchRepos.swift @@ -0,0 +1,33 @@ +// +// ComAtprotoAdminSearchRepos.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Admin { + + /// An output model for searching repositories. + /// + /// - Note: According to the AT Protocol specifications: "Find repositories based on a + /// search term." + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.searchRepos`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/searchRepos.json + public struct SearchRepositoriesOutput: Codable { + + /// The mark used to indicate the starting point for the next set of results. Optional. + public let cursor: String? + + /// An array of repositories. + public let repositories: ToolsOzoneLexicon.Moderation.RepositoryViewDefinition + + enum CodingKeys: String, CodingKey { + case cursor + case repositories = "repos" + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/ComAtprotoAdminSendEmail.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/ComAtprotoAdminSendEmail.swift new file mode 100644 index 0000000000..5a30c56e47 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/ComAtprotoAdminSendEmail.swift @@ -0,0 +1,63 @@ +// +// ComAtprotoAdminSendEmail.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Admin { + + /// A request body model for sending an email to a user. + /// + /// - Note: According to the AT Protocol specifications: "Send email to a user's account + /// email address." + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.sendEmail`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/sendEmail.json + public struct SendEmailRequestBody: Codable { + + /// The decentralized identifier (DID) of the recipient. + public let recipientDID: String + + /// The content of the email. + public let content: String + + /// The subject line of the email. Optional. + public let subject: String? + + /// The decentralized identifier (DID) of the sender. + public let senderDID: String + + /// Any additional comments viewable to other moderators and administrators. + public let comment: String? + + enum CodingKeys: String, CodingKey { + case recipientDID = "recipientDid" + case content + case subject + case senderDID = "senderDid" + case comment + } + } + + /// A data model definition for the output of sending an email to a user. + /// + /// - Note: According to the AT Protocol specifications: "Send email to a user's account + /// email address." + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.sendEmail`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/sendEmail.json + public struct SendEmailOutput: Codable { + + /// Indicates whether the email has been sent. + public let isSent: Bool + + enum CodingKeys: String, CodingKey { + case isSent = "sent" + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/ComAtprotoAdminUpdateAccountEmail.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/ComAtprotoAdminUpdateAccountEmail.swift new file mode 100644 index 0000000000..7062b3035d --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/ComAtprotoAdminUpdateAccountEmail.swift @@ -0,0 +1,33 @@ +// +// ComAtprotoAdminUpdateAccountEmail.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Admin { + + /// A request body model for updating the email address of a user account as an administrator. + /// + /// - Note: According to the AT Protocol specifications: "Administrative action to update an + /// account's email." + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.updateAccountEmail`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/updateAccountEmail.json + public struct UpdateAccountEmailRequestBody: Codable { + + /// The decentralized identifier (DID) of the account. + public let accountDID: String + + /// The new email account the user wants to change to. + public let accountEmail: String + + enum CodingKeys: String, CodingKey { + case accountDID = "account" + case accountEmail = "email" + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/ComAtprotoAdminUpdateAccountHandle.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/ComAtprotoAdminUpdateAccountHandle.swift new file mode 100644 index 0000000000..992c8db934 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/ComAtprotoAdminUpdateAccountHandle.swift @@ -0,0 +1,33 @@ +// +// ComAtprotoAdminUpdateAccountHandle.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Admin { + + /// A request body model for updating the handle of a user account as an administrator. + /// + /// - Note: According to the AT Protocol specifications: "Administrative action to update + /// an account's handle." + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.updateAccountHandle`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/updateAccountHandle.json + public struct UpdateAccountHandleRequestBody: Codable { + + /// The decentralized identifier (DID) of the account. + public let accountDID: String + + /// The new account handle the user wants to change to. + public let accountHandle: String + + enum CodingKeys: String, CodingKey { + case accountDID = "did" + case accountHandle = "handle" + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/ComAtprotoAdminUpdateAccountPassword.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/ComAtprotoAdminUpdateAccountPassword.swift new file mode 100644 index 0000000000..61d0cf684d --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/ComAtprotoAdminUpdateAccountPassword.swift @@ -0,0 +1,33 @@ +// +// ComAtprotoAdminUpdateAccountPassword.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Admin { + + /// A request body model for updating the handle of a user account as an administrator. + /// + /// - Note: According to the AT Protocol specifications: "Update the password for a + /// user account as an administrator." + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.updateAccountPassword`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/updateAccountPassword.json + public struct UpdateAccountPasswordRequestBody: Codable { + + /// The decentralized identifier (DID) of the account. + public let accountDID: String + + /// The new password for the user account. + public let newPassword: String + + enum CodingKeys: String, CodingKey { + case accountDID = "did" + case newPassword = "password" + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/ComAtprotoAdminUpdateSubjectStatus.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/ComAtprotoAdminUpdateSubjectStatus.swift new file mode 100644 index 0000000000..0b0b8e1b41 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Admin/ComAtprotoAdminUpdateSubjectStatus.swift @@ -0,0 +1,45 @@ +// +// ComAtprotoAdminUpdateSubjectStatus.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Admin { + + /// A request body model for updating a subject status of an account, record, or blob. + /// + /// - Note: According to the AT Protocol specifications: "Update the service-specific + /// admin status of a subject (account, record, or blob)." + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.updateSubjectStatus`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/updateSubjectStatus.json + public struct UpdateSubjectStatusRequestBody: Codable { + + /// The subject associated with the subject status. + public let subject: ATUnion.AdminUpdateSubjectStatusUnion + + /// The status attributes of the subject. Optional. + public let takedown: ComAtprotoLexicon.Admin.StatusAttributesDefinition? + } + + /// An output model for updating a subject status of an account, record, or blob. + /// + /// - Note: According to the AT Protocol specifications: "Update the service-specific admin + /// status of a subject (account, record, or blob)." + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.updateSubjectStatus`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/updateSubjectStatus.json + public struct UpdateSubjectStatusOutput: Codable { + + /// The subject associated with the subject status. + public let subject: ATUnion.AdminUpdateSubjectStatusUnion + + /// The status attributes of the subject. Optional. + public let takedown: ComAtprotoLexicon.Admin.StatusAttributesDefinition? + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/ComAtprotoLexicon.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/ComAtprotoLexicon.swift new file mode 100644 index 0000000000..0562b70379 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/ComAtprotoLexicon.swift @@ -0,0 +1,35 @@ +// +// ComAtprotoLexicon.swift +// +// +// Created by Christopher Jr Riley on 2024-05-16. +// + +import Foundation + +extension ComAtprotoLexicon { + + /// A group of lexicons within the `com.atproto.admin` namespace. + public struct Admin {} + + /// A group of lexicons within the `com.atproto.identity` namespace. + public struct Identity {} + + /// A group of lexicons within the `com.atproto.label` namespace. + public struct Label {} + + /// A group of lexicons within the `com.atproto.moderation` namespace. + public struct Moderation {} + + /// A group of lexicons within the `com.atproto.repo` namespace. + public struct Repository {} + + /// A group of lexicons within the `com.atproto.server` namespace. + public struct Server {} + + /// A group of lexicons within the `com.atproto.sync` namespace. + public struct Sync {} + + /// A group of lexicons within the `com.atproto.temp` namespace. + public struct Temp {} +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Identity/AtprotoIdentityGetRecommendedDidCredentials.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Identity/AtprotoIdentityGetRecommendedDidCredentials.swift deleted file mode 100644 index ed37376e43..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Identity/AtprotoIdentityGetRecommendedDidCredentials.swift +++ /dev/null @@ -1,31 +0,0 @@ -// -// AtprotoIdentityGetRecommendedDidCredentials.swift -// -// -// Created by Christopher Jr Riley on 2024-03-15. -// - -import Foundation - -/// The main data model definition for the output of getting the required information of a -/// Personal Data Server's (PDS) DID document for migration. -/// -/// - Note: According to the AT Protocol specifications: "Describe the credentials that should -/// be included in the DID doc of an account that is migrating to this service." -/// -/// - SeeAlso: This is based on the [`com.atproto.identity.getRecommendedDidCredentials`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/identity/getRecommendedDidCredentials.json -public struct IdentityGetRecommendedDidCredentialsOutput: Codable { - /// The rotation keys recommended to be added in the DID document. Optional. - /// - /// - Note: According to the AT Protocol specifications: "Recommended rotation keys for PLC - /// dids. Should be undefined (or ignored) for did:webs." - public let rotationKeys: [String]? - /// An array of aliases of the user account. Optional. - public let alsoKnownAs: [String]? - /// A verification method recommeneded to be added in the DID document. Optional. - public let verificationMethods: VerificationMethod? - /// The service endpoint recommended in the DID document. Optional. - public let service: ATService? -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Identity/AtprotoIdentityResolveHandle.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Identity/AtprotoIdentityResolveHandle.swift deleted file mode 100644 index 2b54108269..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Identity/AtprotoIdentityResolveHandle.swift +++ /dev/null @@ -1,35 +0,0 @@ -// -// AtprotoIdentityResolveHandle.swift -// -// -// Created by Christopher Jr Riley on 2024-01-27. -// - -import Foundation - -// MARK: - Main definition -/// The main data model definition for resolving handles. -/// -/// - Note: According to the AT Protocol specifications: "Resolves a handle (domain name) to -/// a DID." -/// -/// - SeeAlso: This is based on the [`com.atproto.identity.resolveHandle`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/identity/resolveHandle.json -public struct ResolveHandleQuery: Encodable { - /// The handle to be resolved. - /// - /// - Important: Be sure to remove the "@" before entering the value. - public let handle: String -} - -// MARK: - -/// A data model that represents the output of resolving handles. -/// -/// - SeeAlso: This is based on the [`com.atproto.identity.resolveHandle`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/identity/resolveHandle.json -public struct ResolveHandleOutput: Decodable { - /// The resolved handle's decentralized identifier (DID). - public let handleDID: String -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Identity/AtprotoIdentitySignPLCOperation.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Identity/AtprotoIdentitySignPLCOperation.swift deleted file mode 100644 index 3ca89706d5..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Identity/AtprotoIdentitySignPLCOperation.swift +++ /dev/null @@ -1,45 +0,0 @@ -// -// AtprotoIdentitySignPLCOperation.swift -// -// -// Created by Christopher Jr Riley on 2024-03-16. -// - -import Foundation - -/// The main data model definition for signing a PLC operation to a DID document. -/// -/// - Note: According to the AT Protocol specifications: "Signs a PLC operation to update some -/// value(s) in the requesting DID's document." -/// -/// - SeeAlso: This is based on the [`com.atproto.identity.signPlcOperation`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/identity/signPlcOperation.json -public struct IdentitySignPLCOperation: Codable { - /// A token received from ``ATProtoKit/ATProtoKit/requestPLCOperationSignature()``. Optional. - /// - /// - Note: According to the AT Protocol specifications: "A token received - /// through com.atproto.identity.requestPlcOperationSignature" - public let token: String? - /// The rotation keys recommended to be added in the DID document. Optional. - public let rotationKeys: [String]? - /// An array of aliases of the user account. Optional. - public let alsoKnownAs: [String]? - /// A verification method recommeneded to be added in the DID document. Optional. - public let verificationMethods: VerificationMethod? - /// The service endpoint recommended in the DID document. Optional. - public let service: ATService? -} - -/// The main data model definition for the output of signing a PLC operation to a DID document. -/// -/// - Note: According to the AT Protocol specifications: "Signs a PLC operation to update some -/// value(s) in the requesting DID's document." -/// -/// - SeeAlso: This is based on the [`com.atproto.identity.signPlcOperation`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/identity/signPlcOperation.json -public struct IdentitySignPLCOperationOutput: Codable { - /// The operation itself. - public let operation: UnknownType -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Identity/AtprotoIdentitySubmitPLCOperation.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Identity/AtprotoIdentitySubmitPLCOperation.swift deleted file mode 100644 index 805c2d7f50..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Identity/AtprotoIdentitySubmitPLCOperation.swift +++ /dev/null @@ -1,22 +0,0 @@ -// -// AtprotoIdentitySubmitPLCOperation.swift -// -// -// Created by Christopher Jr Riley on 2024-03-16. -// - -import Foundation - -/// The main data model definition for the output of validating a PLC operation. -/// -/// - Note: According to the AT Protocol specifications: "Validates a PLC operation to ensure -/// that it doesn't violate a service's constraints or get the identity into a bad state, then -/// submits it to the PLC registry." -/// -/// - SeeAlso: This is based on the [`com.atproto.identity.submitPlcOperation`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/identity/submitPlcOperation.json -public struct IdentitySubmitPLCOperationOutput: Codable { - /// The operation itself. - public let operation: UnknownType -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Identity/AtprotoIdentityUpdateHandle.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Identity/AtprotoIdentityUpdateHandle.swift deleted file mode 100644 index 3c869f3072..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Identity/AtprotoIdentityUpdateHandle.swift +++ /dev/null @@ -1,25 +0,0 @@ -// -// AtprotoIdentityUpdateHandle.swift -// -// -// Created by Christopher Jr Riley on 2024-01-27. -// - -import Foundation - -// MARK: - Main definition -/// The main data model definition for updating a handle. -/// -/// - Note: According to the AT Protocol specifications: "Updates the current account's handle. -/// Verifies handle validity, and updates did:plc document if necessary. Implemented by PDS, -/// and requires auth." -/// -/// - SeeAlso: This is based on the [`com.atproto.identity.updateHandle`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/identity/updateHandle.json -public struct UpdateHandleQuery: Encodable { - /// The handle the user would like to change to. - /// - /// - Note: According to the AT Protocol specifications: "The new handle." - public let handle: String -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Identity/ComAtprotoIdentityGetRecommendedDidCredentials.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Identity/ComAtprotoIdentityGetRecommendedDidCredentials.swift new file mode 100644 index 0000000000..7b4b872f88 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Identity/ComAtprotoIdentityGetRecommendedDidCredentials.swift @@ -0,0 +1,38 @@ +// +// ComAtprotoIdentityGetRecommendedDidCredentials.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Identity { + + /// An output model for getting the required information of a + /// Personal Data Server's (PDS) DID document for migration. + /// + /// - Note: According to the AT Protocol specifications: "Describe the credentials that should + /// be included in the DID doc of an account that is migrating to this service." + /// + /// - SeeAlso: This is based on the [`com.atproto.identity.getRecommendedDidCredentials`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/identity/getRecommendedDidCredentials.json + public struct GetRecommendedDidCredentialsOutput: Codable { + + /// The rotation keys recommended to be added in the DID document. Optional. + /// + /// - Note: According to the AT Protocol specifications: "Recommended rotation keys for PLC + /// dids. Should be undefined (or ignored) for did:webs." + public let rotationKeys: [String]? + + /// An array of aliases of the user account. Optional. + public let alsoKnownAs: [String]? + + /// A verification method recommeneded to be added in the DID document. Optional. + public let verificationMethods: VerificationMethod? + + /// The service endpoint recommended in the DID document. Optional. + public let service: ATService? + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Identity/ComAtprotoIdentityRequestPlcOperationSignature.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Identity/ComAtprotoIdentityRequestPlcOperationSignature.swift new file mode 100644 index 0000000000..bfea706936 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Identity/ComAtprotoIdentityRequestPlcOperationSignature.swift @@ -0,0 +1,21 @@ +// +// ComAtprotoIdentityRequestPlcOperationSignature.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Identity { + + /// A request body model for requesting a signed PLC operation. + /// + /// - Note: According to the AT Protocol specifications: "Request an email with a code to in + /// order to request a signed PLC operation. Requires Auth." + /// + /// - SeeAlso: This is based on the [`com.atproto.identity.requestPlcOperationSignature`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/identity/requestPlcOperationSignature.json + public struct RequestPlcOperationSignatureRequestBody: Codable {} +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Identity/ComAtprotoIdentityResolveHandle.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Identity/ComAtprotoIdentityResolveHandle.swift new file mode 100644 index 0000000000..3f3fb1259e --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Identity/ComAtprotoIdentityResolveHandle.swift @@ -0,0 +1,22 @@ +// +// ComAtprotoIdentityResolveHandle.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Identity { + + /// An output model for esolving handles. + /// + /// - SeeAlso: This is based on the [`com.atproto.identity.resolveHandle`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/identity/resolveHandle.json + public struct ResolveHandleOutput: Decodable { + + /// The resolved handle's decentralized identifier (DID). + public let handleDID: String + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Identity/ComAtprotoIdentitySignPLCOperation.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Identity/ComAtprotoIdentitySignPLCOperation.swift new file mode 100644 index 0000000000..c459c534ae --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Identity/ComAtprotoIdentitySignPLCOperation.swift @@ -0,0 +1,55 @@ +// +// ComAtprotoIdentitySignPLCOperation.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Identity { + + /// A request body model for signing a PLC operation to a DID document. + /// + /// - Note: According to the AT Protocol specifications: "Signs a PLC operation to update some + /// value(s) in the requesting DID's document." + /// + /// - SeeAlso: This is based on the [`com.atproto.identity.signPlcOperation`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/identity/signPlcOperation.json + public struct SignPLCOperationRequestBody: Codable { + + /// A token received from + /// ``ATProtoKit/ATProtoKit/requestPLCOperationSignature()``. Optional. + /// + /// - Note: According to the AT Protocol specifications: "A token received + /// through com.atproto.identity.requestPlcOperationSignature" + public let token: String? + + /// The rotation keys recommended to be added in the DID document. Optional. + public let rotationKeys: [String]? + + /// An array of aliases of the user account. Optional. + public let alsoKnownAs: [String]? + + /// A verification method recommeneded to be added in the DID document. Optional. + public let verificationMethods: VerificationMethod? + + /// The service endpoint recommended in the DID document. Optional. + public let service: ATService? + } + + /// An output model for signing a PLC operation to a DID document. + /// + /// - Note: According to the AT Protocol specifications: "Signs a PLC operation to update some + /// value(s) in the requesting DID's document." + /// + /// - SeeAlso: This is based on the [`com.atproto.identity.signPlcOperation`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/identity/signPlcOperation.json + public struct SignPLCOperationOutput: Codable { + + /// The operation itself. + public let operation: UnknownType + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Identity/ComAtprotoIdentitySubmitPLCOperation.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Identity/ComAtprotoIdentitySubmitPLCOperation.swift new file mode 100644 index 0000000000..85ca7e9fc6 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Identity/ComAtprotoIdentitySubmitPLCOperation.swift @@ -0,0 +1,26 @@ +// +// ComAtprotoIdentitySubmitPLCOperation.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Identity { + + /// An output model for validating a PLC operation. + /// + /// - Note: According to the AT Protocol specifications: "Validates a PLC operation to ensure + /// that it doesn't violate a service's constraints or get the identity into a bad state, then + /// submits it to the PLC registry." + /// + /// - SeeAlso: This is based on the [`com.atproto.identity.submitPlcOperation`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/identity/submitPlcOperation.json + public struct SubmitPLCOperationRequestBody: Codable { + + /// The operation itself. + public let operation: UnknownType + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Identity/ComAtprotoIdentityUpdateHandle.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Identity/ComAtprotoIdentityUpdateHandle.swift new file mode 100644 index 0000000000..c7c6c97138 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Identity/ComAtprotoIdentityUpdateHandle.swift @@ -0,0 +1,28 @@ +// +// ComAtprotoIdentityUpdateHandle.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Identity { + + /// A request body model for updating a handle. + /// + /// - Note: According to the AT Protocol specifications: "Updates the current account's handle. + /// Verifies handle validity, and updates did:plc document if necessary. Implemented by PDS, + /// and requires auth." + /// + /// - SeeAlso: This is based on the [`com.atproto.identity.updateHandle`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/identity/updateHandle.json + public struct UpdateHandleRequestBody: Encodable { + + /// The handle the user would like to change to. + /// + /// - Note: According to the AT Protocol specifications: "The new handle." + public let handle: String + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Label/AtprotoLabelDefs.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Label/AtprotoLabelDefs.swift deleted file mode 100644 index 6f24e617da..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Label/AtprotoLabelDefs.swift +++ /dev/null @@ -1,363 +0,0 @@ -// -// AtProtoLabelDefs.swift -// -// -// Created by Christopher Jr Riley on 2024-01-25. -// - -import Foundation - -/// The main data model definition for a label. -/// -/// - Note: According to the AT Protocol specifications: "Metadata tag on an atproto resource (eg, -/// repo or record)." -/// -/// - SeeAlso: This is based on the [`com.atproto.label.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/label/defs.json -public struct Label: Codable { - /// The version number of the label. Optional. - /// - /// - Note: According to the AT Protocol specifications: "The AT Protocol version of the - /// label object." - public let version: Int? - /// The decentralized identifier (DID) of the label creator. - /// - /// - Note: According to the AT Protocol specifications: "DID of the actor who created - /// this label." - public let actorDID: String - /// The URI of the resource the label applies to. - /// - /// - Note: According to the AT Protocol specifications: "AT URI of the record, repository - /// (account), or other resource that this label applies to." - public let atURI: String - /// The CID hash of the resource the label applies to. Optional. - /// - /// - Note: According to the AT Protocol specifications: "Optionally, CID specifying the - /// specific version of 'uri' resource this label applies to." - public let cidHash: String? - /// The name of the label. - /// - /// - Note: According to the AT Protocol specifications: "The short string name of the value or - /// type of this label." - /// - /// - Important: Current maximum length is 128 characters. This library will automatically - /// truncate the `String` to the maximum length if it does go over the limit. - public var name: String - /// Indicates whether this label is negating a previously-used label. Optional. - /// - /// - Note: According to the AT Protocol specifications: "If true, this is a negation label, - /// overwriting a previous label." - public let isNegated: Bool? - /// The date and time the label was created. - /// - /// - Note: According to the AT Protocol specifications: "Timestamp when this label - /// was created." - @DateFormatting public var timestamp: Date - /// The date and time the label expires on. - /// - /// - Note: According to the AT Protocol specifications: "Timestamp at which this label - /// expires (no longer applies)." - @DateFormattingOptional public var expiresOn: Date? - /// The DAG-CBOR-encoded signature. Optional. - /// - /// - Note: According to the AT Protocol specifications: "Signature of dag-cbor encoded label." - public let signature: Data? - - public init(version: Int?, actorDID: String, atURI: String, cidHash: String?, name: String, isNegated: Bool?, timestamp: Date, - expiresOn: Date?, signature: Data) { - self.version = version - self.actorDID = actorDID - self.atURI = atURI - self.cidHash = cidHash - self.name = name - self.isNegated = isNegated - self._timestamp = DateFormatting(wrappedValue: timestamp) - self._expiresOn = DateFormattingOptional(wrappedValue: expiresOn) - self.signature = signature - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.version = try container.decodeIfPresent(Int.self, forKey: .version) - self.actorDID = try container.decode(String.self, forKey: .actorDID) - self.atURI = try container.decode(String.self, forKey: .atURI) - self.cidHash = try container.decodeIfPresent(String.self, forKey: .cidHash) - self.name = try container.decode(String.self, forKey: .name) - self.isNegated = try container.decodeIfPresent(Bool.self, forKey: .isNegated) - self.timestamp = try container.decode(DateFormatting.self, forKey: .timestamp).wrappedValue - self.expiresOn = try container.decodeIfPresent(DateFormattingOptional.self, forKey: .expiresOn)?.wrappedValue - self.signature = try container.decodeIfPresent(Data.self, forKey: .signature) - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - try container.encodeIfPresent(self.version, forKey: .version) - try container.encode(self.actorDID, forKey: .actorDID) - try container.encode(self.atURI, forKey: .atURI) - try container.encodeIfPresent(self.cidHash, forKey: .cidHash) - - // Truncate `name` to 128 characters before encoding - try truncatedEncode(self.name, withContainer: &container, forKey: .name, upToLength: 128) - - try container.encodeIfPresent(self.isNegated, forKey: .isNegated) - try container.encode(self._timestamp, forKey: .timestamp) - try container.encodeIfPresent(self._expiresOn, forKey: .expiresOn) - try container.encodeIfPresent(self.signature, forKey: .signature) - } - - enum CodingKeys: String, CodingKey { - case version = "ver" - case actorDID = "src" - case atURI = "uri" - case cidHash = "cid" - case name = "val" - case isNegated = "neg" - case timestamp = "cts" - case expiresOn = "exp" - case signature = "sig" - } -} - -/// A data model for a definition for an array of self-defined labels. -public struct SelfLabels: Codable { - /// An array of self-defined tags on a record. - /// - /// - Note: According to the AT Protocol specifications: "Metadata tags on an atproto record, - /// published by the author within the record." - /// - /// - Important: Current maximum length is 10 tags. This library will automatically truncate - /// the `Array` to the maximum length if it does go over the limit. - /// - /// - SeeAlso: This is based on the [`com.atproto.label.defs`][github] lexicon. - /// - /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/label/defs.json - public let values: [SelfLabel] - - public init(values: [SelfLabel]) { - self.values = values - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.values = try container.decode([SelfLabel].self, forKey: .values) - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - // Truncate `values` to 10 items before encoding - try truncatedEncode(self.values, withContainer: &container, forKey: .values, upToLength: 10) - } - - enum CodingKeys: CodingKey { - case values - } -} - -/// A data model for a definition for a user-defined label. -/// -/// - Note: According to the AT Protocol specifications: "Metadata tag on an atproto record, -/// published by the author within the record. Note that schemas should use #selfLabels, -/// not #selfLabel.", -/// -/// - SeeAlso: This is based on the [`com.atproto.label.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/label/defs.json -public struct SelfLabel: Codable { - /// A user-defined label. - /// - /// - Note: According to the AT Protocol specifications: "The short string name of the value or - /// type of this label." - /// - /// - Important: Current maximum length is 128 characters. This library will automatically - /// truncate the `String` to the maximum length if it does go over the limit. - public let value: String - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - // Truncate `value` to 128 characters before encoding - try truncatedEncode(self.value, withContainer: &container, forKey: .value, upToLength: 128) - } - - enum CodingKeys: String, CodingKey { - case value = "val" - } -} - -/// A data model definition for labeler-created labels. -/// -/// - Note: According to the AT Protocol specifications: "Declares a label value and its expected -/// interpertations and behaviors." -/// -/// - SeeAlso: This is based on the [`com.atproto.label.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/label/defs.json -public struct LabelValueDefinition: Codable { - /// The value of the label. - /// - /// - Important: This field can only contain lowercased letter and the hypen (-) character. - /// This library will automatically convert uppercased letters to lowercased, as well as any - /// hashes other than the hypen into a hypen. All additional characters will be removed. - /// - /// - Note: According to the AT Protocol specifications: "The value of the label being defined. - /// Must only include lowercase ascii and the '-' character ([a-z-]+)." - public let identifier: String - // TODO: Make this into an enum. - /// The visual indicator of the label that indicates the severity. - /// - /// - Note: According to the AT Protocol specifications: "How should a client visually convey - /// this label? 'inform' means neutral and informational; 'alert' means negative and warning; - /// 'none' means show nothing." - public let severity: Severity - // TODO: Make this into an enum. - /// Indicates how much of the content should be hidden for the user. - /// - /// - Note: According to the AT Protocol specifications: "What should this label hide in the - /// UI, if applied? 'content' hides all of the target; 'media' hides the images/video/audio; - /// 'none' hides nothing." - public let blurs: Blurs - // TODO: Make this into an enum. - /// The default setting for the label. - /// - /// - Note: According to the AT Protocol specifications: "The default setting for this label." - public let defaultSetting: DefaultSetting = .warn - /// Indicates whether the "Adult Content" preference needs to be enabled in order to use - /// this label. Optional. - /// - /// - Note: According to the AT Protocol specifications: "Does the user need to have adult - /// content enabled in order to configure this label?" - public let isAdultOnly: Bool? - /// An array of localized strings for the label. Optional. - public let locales: [LabelValueDefinitionStrings] - - public func encode(to encoder: any Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - // Ensure `value` is lowercased and only has the standard hyphen (-). - // Then, truncate `value` to 100 characters before encoding. - try truncatedEncode(self.identifier.transformToLowerASCIIAndHyphen(), withContainer: &container, forKey: .identifier, upToLength: 100) - try container.encode(self.severity, forKey: .severity) - try container.encode(self.blurs, forKey: .blurs) - try container.encode(self.defaultSetting, forKey: .defaultSetting) - try container.encodeIfPresent(self.isAdultOnly, forKey: .isAdultOnly) - try container.encode(self.locales, forKey: .locales) - } - - enum CodingKeys: CodingKey { - case identifier - case severity - case blurs - case defaultSetting - case isAdultOnly - case locales - } - - // Enums - /// The visual indicator of the label that indicates the severity. - public enum Severity: String, Codable { - /// Indicates the labeler should only inform the user of the content. - case inform - /// Indicates the labeler should alert the user of the content. - case alert - /// Indicates the labeler should do nothing. - case none - } - - /// Indicates how much of the content should be hidden for the user. - public enum Blurs: String, Codable { - /// Indicates the labeler should hide the entire content from the user. - case content - /// Indicates the labeler should hide only the media of the content, but keeps the - /// text intact. - case media - /// Indicates the labeler should hide nothing. - case none - } - - /// The default setting for the label. - public enum DefaultSetting: String, Codable { - /// Indicates the user will ignore the label. - case ignore - /// Indicates the user will be warned. - case warn - /// Indicates the user will hide the label. - case hide - } -} - -/// A data model definition for a localized description of a label. -/// -/// - Note: According to the AT Protocol specifications: "Strings which describe the label in -/// the UI, localized into a specific language." -/// -/// - SeeAlso: This is based on the [`com.atproto.label.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/label/defs.json -public struct LabelValueDefinitionStrings: Codable { - /// The language code of the label's definition. - /// - /// - Note: According to the AT Protocol specifications: "The code of the language these - /// strings are written in." - public let language: Locale - /// The localized name of the label. - /// - /// - Note: According to the AT Protocol specifications: "A short human-readable name for - /// the label." - public let name: String - /// The localized description of the label. - /// - /// - Note: According to the AT Protocol specifications: "A longer description of what the - /// label means and why it might be applied." - public let description: String - - public init(from decoder: any Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.language = try container.decode(Locale.self, forKey: .language) - self.name = try container.decode(String.self, forKey: .name) - self.description = try container.decode(String.self, forKey: .description) - } - - public func encode(to encoder: any Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - try container.encode(self.language, forKey: .language) - // Truncate `name` to 640 characters before encoding. - try truncatedEncode(self.name, withContainer: &container, forKey: .name, upToLength: 640) - - try truncatedEncode(self.description, withContainer: &container, forKey: .description, upToLength: 100_000) - } - - enum CodingKeys: String, CodingKey { - case language = "lang" - case name - case description - } -} - -/// An enumuation that defines the value of a label. -/// -/// - Note: According to the AT Protocol specifications: "Strings which describe the label in the -/// UI, localized into a specific language." -/// -/// - SeeAlso: This is based on the [`com.atproto.label.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/label/defs.json -public enum LabelValue: String, Codable { - case hide = "!hide" - case noPromote = "!no-promote" - case warn = "!warn" - case noUnauthenticated = "!no-unauthenticated" - case dmcaViolation = "dmca-violation" - case doxxing - case porn - case sexual - case nudity - case nsfl - case gore -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Label/AtprotoLabelQueryLabels.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Label/AtprotoLabelQueryLabels.swift deleted file mode 100644 index d4c711ec56..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Label/AtprotoLabelQueryLabels.swift +++ /dev/null @@ -1,22 +0,0 @@ -// -// AtprotoLabelQueryLabels.swift -// -// -// Created by Christopher Jr Riley on 2024-03-16. -// - -import Foundation - -/// The main data model definition for the output of finding relevant labels based on a given URI. -/// -/// - Note: According to the AT Protocol specifications: "Find labels relevant to the provided -/// AT-URI patterns. Public endpoint for moderation services, though may return different or -/// additional results with auth." -/// -/// - SeeAlso: This is based on the [`com.atproto.label.queryLabels`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/label/queryLabels.json -public struct LabelQueryLabelsOutput: Codable { - /// An array of labels. - public let labels: [Label] -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Label/ComAtprotoLabelDefs.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Label/ComAtprotoLabelDefs.swift new file mode 100644 index 0000000000..209772a96d --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Label/ComAtprotoLabelDefs.swift @@ -0,0 +1,423 @@ +// +// ComAtprotoLabelDefs.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Label { + + /// A definition model for a label. + /// + /// - Note: According to the AT Protocol specifications: "Metadata tag on an atproto resource + /// (eg, repo or record)." + /// + /// - SeeAlso: This is based on the [`com.atproto.label.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/label/defs.json + public struct LabelDefinition: Codable { + + /// The version number of the label. Optional. + /// + /// - Note: According to the AT Protocol specifications: "The AT Protocol version of the + /// label object." + public let version: Int? + + /// The decentralized identifier (DID) of the label creator. + /// + /// - Note: According to the AT Protocol specifications: "DID of the actor who created + /// this label." + public let actorDID: String + + /// The URI of the resource the label applies to. + /// + /// - Note: According to the AT Protocol specifications: "AT URI of the record, repository + /// (account), or other resource that this label applies to." + public let atURI: String + + /// The CID hash of the resource the label applies to. Optional. + /// + /// - Note: According to the AT Protocol specifications: "Optionally, CID specifying the + /// specific version of 'uri' resource this label applies to." + public let cidHash: String? + + /// The name of the label. + /// + /// - Note: According to the AT Protocol specifications: "The short string name of the + /// value or type of this label." + /// + /// - Important: Current maximum length is 128 characters. This library will automatically + /// truncate the `String` to the maximum length if it does go over the limit. + public var name: String + + /// Indicates whether this label is negating a previously-used label. Optional. + /// + /// - Note: According to the AT Protocol specifications: "If true, this is a negation label, + /// overwriting a previous label." + public let isNegated: Bool? + + /// The date and time the label was created. + /// + /// - Note: According to the AT Protocol specifications: "Timestamp when this label + /// was created." + @DateFormatting public var timestamp: Date + + /// The date and time the label expires on. + /// + /// - Note: According to the AT Protocol specifications: "Timestamp at which this label + /// expires (no longer applies)." + @DateFormattingOptional public var expiresOn: Date? + + /// The DAG-CBOR-encoded signature. Optional. + /// + /// - Note: According to the AT Protocol specifications: "Signature of dag-cbor + /// encoded label." + public let signature: Data? + + public init(version: Int?, actorDID: String, atURI: String, cidHash: String?, name: String, isNegated: Bool?, timestamp: Date, + expiresOn: Date?, signature: Data) { + self.version = version + self.actorDID = actorDID + self.atURI = atURI + self.cidHash = cidHash + self.name = name + self.isNegated = isNegated + self._timestamp = DateFormatting(wrappedValue: timestamp) + self._expiresOn = DateFormattingOptional(wrappedValue: expiresOn) + self.signature = signature + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.version = try container.decodeIfPresent(Int.self, forKey: .version) + self.actorDID = try container.decode(String.self, forKey: .actorDID) + self.atURI = try container.decode(String.self, forKey: .atURI) + self.cidHash = try container.decodeIfPresent(String.self, forKey: .cidHash) + self.name = try container.decode(String.self, forKey: .name) + self.isNegated = try container.decodeIfPresent(Bool.self, forKey: .isNegated) + self.timestamp = try container.decode(DateFormatting.self, forKey: .timestamp).wrappedValue + self.expiresOn = try container.decodeIfPresent(DateFormattingOptional.self, forKey: .expiresOn)?.wrappedValue + self.signature = try container.decodeIfPresent(Data.self, forKey: .signature) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encodeIfPresent(self.version, forKey: .version) + try container.encode(self.actorDID, forKey: .actorDID) + try container.encode(self.atURI, forKey: .atURI) + try container.encodeIfPresent(self.cidHash, forKey: .cidHash) + + // Truncate `name` to 128 characters before encoding + try truncatedEncode(self.name, withContainer: &container, forKey: .name, upToLength: 128) + + try container.encodeIfPresent(self.isNegated, forKey: .isNegated) + try container.encode(self._timestamp, forKey: .timestamp) + try container.encodeIfPresent(self._expiresOn, forKey: .expiresOn) + try container.encodeIfPresent(self.signature, forKey: .signature) + } + + enum CodingKeys: String, CodingKey { + case version = "ver" + case actorDID = "src" + case atURI = "uri" + case cidHash = "cid" + case name = "val" + case isNegated = "neg" + case timestamp = "cts" + case expiresOn = "exp" + case signature = "sig" + } + } + + /// A definition model for an array of self-defined labels. + /// + /// - SeeAlso: This is based on the [`com.atproto.label.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/label/defs.json + public struct SelfLabelsDefinition: Codable { + + /// An array of self-defined tags on a record. + /// + /// - Note: According to the AT Protocol specifications: "Metadata tags on an atproto + /// record, published by the author within the record." + /// + /// - Important: Current maximum length is 10 tags. This library will automatically + /// truncate the `Array` to the maximum length if it does go over the limit. + /// + /// - SeeAlso: This is based on the [`com.atproto.label.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/label/defs.json + public let values: [SelfLabelDefinition] + + public init(values: [SelfLabelDefinition]) { + self.values = values + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.values = try container.decode([SelfLabelDefinition].self, forKey: .values) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + // Truncate `values` to 10 items before encoding + try truncatedEncode(self.values, withContainer: &container, forKey: .values, upToLength: 10) + } + + enum CodingKeys: CodingKey { + case values + } + } + + /// A definition model for a user-defined label. + /// + /// - Note: According to the AT Protocol specifications: "Metadata tag on an atproto record, + /// published by the author within the record. Note that schemas should use #selfLabels, + /// not #selfLabel.", + /// + /// - SeeAlso: This is based on the [`com.atproto.label.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/label/defs.json + public struct SelfLabelDefinition: Codable { + + /// A user-defined label. + /// + /// - Note: According to the AT Protocol specifications: "The short string name of the + /// value or type of this label." + /// + /// - Important: Current maximum length is 128 characters. This library will automatically + /// truncate the `String` to the maximum length if it does go over the limit. + public let value: String + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + // Truncate `value` to 128 characters before encoding + try truncatedEncode(self.value, withContainer: &container, forKey: .value, upToLength: 128) + } + + enum CodingKeys: String, CodingKey { + case value = "val" + } + } + + /// A definition model for labeler-created labels. + /// + /// - Note: According to the AT Protocol specifications: "Declares a label value and its expected + /// interpertations and behaviors." + /// + /// - SeeAlso: This is based on the [`com.atproto.label.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/label/defs.json + public struct LabelValueDefinition: Codable { + + /// The value of the label. + /// + /// - Important: This field can only contain lowercased letter and the hypen (-) character. + /// This library will automatically convert uppercased letters to lowercased, as well as any + /// hashes other than the hypen into a hypen. All additional characters will be removed. + /// + /// - Note: According to the AT Protocol specifications: "The value of the label + /// being defined. Must only include lowercase ascii and the '-' character ([a-z-]+)." + public let identifier: String + + /// The visual indicator of the label that indicates the severity. + /// + /// - Note: According to the AT Protocol specifications: "How should a client visually + /// convey this label? 'inform' means neutral and informational; 'alert' means negative + /// and warning; 'none' means show nothing." + public let severity: Severity + + /// Indicates how much of the content should be hidden for the user. + /// + /// - Note: According to the AT Protocol specifications: "What should this label hide in + /// the UI, if applied? 'content' hides all of the target; 'media' hides the + /// images/video/audio; 'none' hides nothing." + public let blurs: Blurs + + /// The default setting for the label. + /// + /// - Note: According to the AT Protocol specifications: "The default setting for + /// this label." + public let defaultSetting: DefaultSetting = .warn + + /// Indicates whether the "Adult Content" preference needs to be enabled in order to use + /// this label. Optional. + /// + /// - Note: According to the AT Protocol specifications: "Does the user need to have adult + /// content enabled in order to configure this label?" + public let isAdultOnly: Bool? + + /// An array of localized strings for the label. Optional. + public let locales: [LabelValueDefinitionStringsDefinition] + + public func encode(to encoder: any Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + // Ensure `value` is lowercased and only has the standard hyphen (-). + // Then, truncate `value` to 100 characters before encoding. + try truncatedEncode(self.identifier.transformToLowerASCIIAndHyphen(), withContainer: &container, forKey: .identifier, upToLength: 100) + try container.encode(self.severity, forKey: .severity) + try container.encode(self.blurs, forKey: .blurs) + try container.encode(self.defaultSetting, forKey: .defaultSetting) + try container.encodeIfPresent(self.isAdultOnly, forKey: .isAdultOnly) + try container.encode(self.locales, forKey: .locales) + } + + enum CodingKeys: CodingKey { + case identifier + case severity + case blurs + case defaultSetting + case isAdultOnly + case locales + } + + // Enums + /// The visual indicator of the label that indicates the severity. + public enum Severity: String, Codable { + + /// Indicates the labeler should only inform the user of the content. + case inform + + /// Indicates the labeler should alert the user of the content. + case alert + + /// Indicates the labeler should do nothing. + case none + } + + /// Indicates how much of the content should be hidden for the user. + public enum Blurs: String, Codable { + + /// Indicates the labeler should hide the entire content from the user. + case content + + /// Indicates the labeler should hide only the media of the content, but keeps the + /// text intact. + case media + + /// Indicates the labeler should hide nothing. + case none + } + + /// The default setting for the label. + public enum DefaultSetting: String, Codable { + + /// Indicates the user will ignore the label. + case ignore + + /// Indicates the user will be warned. + case warn + + /// Indicates the user will hide the label. + case hide + } + } + + /// A definition model for a localized description of a label. + /// + /// - Note: According to the AT Protocol specifications: "Strings which describe the label in + /// the UI, localized into a specific language." + /// + /// - SeeAlso: This is based on the [`com.atproto.label.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/label/defs.json + public struct LabelValueDefinitionStringsDefinition: Codable { + + /// The language code of the label's definition. + /// + /// - Note: According to the AT Protocol specifications: "The code of the language these + /// strings are written in." + public let language: Locale + + /// The localized name of the label. + /// + /// - Note: According to the AT Protocol specifications: "A short human-readable name for + /// the label." + public let name: String + + /// The localized description of the label. + /// + /// - Note: According to the AT Protocol specifications: "A longer description of what the + /// label means and why it might be applied." + public let description: String + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.language = try container.decode(Locale.self, forKey: .language) + self.name = try container.decode(String.self, forKey: .name) + self.description = try container.decode(String.self, forKey: .description) + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.language, forKey: .language) + // Truncate `name` to 640 characters before encoding. + try truncatedEncode(self.name, withContainer: &container, forKey: .name, upToLength: 640) + + try truncatedEncode(self.description, withContainer: &container, forKey: .description, upToLength: 100_000) + } + + enum CodingKeys: String, CodingKey { + case language = "lang" + case name + case description + } + } + + /// An enumuation that defines the value of a label. + /// + /// - Note: According to the AT Protocol specifications: "Strings which describe the label + /// in the UI, localized into a specific language." + /// + /// - SeeAlso: This is based on the [`com.atproto.label.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/label/defs.json + public enum LabelValue: String, Codable { + + /// Marked as hidden. + case hide = "!hide" + + /// Marked as no promotion. + case noPromote = "!no-promote" + + /// Marked as a warning. + case warn = "!warn" + + /// Marked as no authentication. + /// + /// This would be used for user accounts that requests clients to not show their + /// content for logged-out users. + case noUnauthenticated = "!no-unauthenticated" + + /// Marked as a DMCA violation. + case dmcaViolation = "dmca-violation" + + /// Marked as doxxing. + case doxxing + + /// Marked as porn. + case porn + + /// Marked as sexual content. + case sexual + + /// Marked as nudity. + case nudity + + /// Marked as Not Safe For Life (NSFL). + case nsfl + + /// Marked as gory. + case gore + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Label/ComAtprotoLabelQueryLabels.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Label/ComAtprotoLabelQueryLabels.swift new file mode 100644 index 0000000000..84e3f6bbab --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Label/ComAtprotoLabelQueryLabels.swift @@ -0,0 +1,26 @@ +// +// ComAtprotoLabelQueryLabels.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Label { + + /// An output model for inding relevant labels based on a given URI. + /// + /// - Note: According to the AT Protocol specifications: "Find labels relevant to the provided + /// AT-URI patterns. Public endpoint for moderation services, though may return different or + /// additional results with auth." + /// + /// - SeeAlso: This is based on the [`com.atproto.label.queryLabels`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/label/queryLabels.json + public struct QueryLabelsOutput: Codable { + + /// An array of labels. + public let labels: [ComAtprotoLexicon.Label.LabelDefinition] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Moderation/AtprotoModerationCreateReport.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Moderation/AtprotoModerationCreateReport.swift deleted file mode 100644 index f780a039b6..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Moderation/AtprotoModerationCreateReport.swift +++ /dev/null @@ -1,107 +0,0 @@ -// -// AtprotoModerationCreateReport.swift -// -// -// Created by Christopher Jr Riley on 2024-02-25. -// - -import Foundation - -/// The main data model definition for creating a report. -/// -/// - Note: According to the AT Protocol specifications: "Submit a moderation report regarding -/// an atproto account or record. Implemented by moderation services (with PDS proxying), and -/// requires auth." -/// -/// - SeeAlso: This is based on the [`com.atproto.moderation.createReport`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/moderation/createReport.json -public struct ModerationCreateReport: Codable { - /// The reason for the report. - /// - /// - Note: According to the AT Protocol specifications: "Indicates the broad category of - /// violation the report is for." - public let reasonType: ModerationReasonType - /// Any clarifying comments accompanying the report. Optional. - /// - /// - Note: According to the AT Protocol specifications: "Additional context about the - /// content and violation." - public let reason: String? - /// The subject reference. - /// - /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ - /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ - /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ - /// \ - /// Clarifications from Bluesky are needed in order to fully understand this item. - public let subject: RepositoryReferencesUnion -} - -/// A data model definition for the output of creating a report. -/// -/// - SeeAlso: This is based on the [`com.atproto.moderation.createReport`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/moderation/createReport.json -public struct ModerationCreateReportOutput: Codable { - /// The ID of the report. - public let id: Int - /// The reason for the report. - public let reasonType: ModerationReasonType - /// The reason for the report. Optional. - public let reason: String? - /// The subject reference. - /// - /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ - /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ - /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ - /// \ - /// Clarifications from Bluesky are needed in order to fully understand this item. - public let subject: RepositoryReferencesUnion - /// The decentralized identifier (DID) of the user who created the report. - public let reportedBy: String - /// The date and time the report was created. - @DateFormatting public var createdAt: Date - - public init(id: Int, reasonType: ModerationReasonType, reason: String?, subject: RepositoryReferencesUnion, reportedBy: String, createdAt: Date) { - self.id = id - self.reasonType = reasonType - self.reason = reason - self.subject = subject - self.reportedBy = reportedBy - self._createdAt = DateFormatting(wrappedValue: createdAt) - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.id = try container.decode(Int.self, forKey: .id) - self.reasonType = try container.decode(ModerationReasonType.self, forKey: .reasonType) - self.reason = try container.decodeIfPresent(String.self, forKey: .reason) - self.subject = try container.decode(RepositoryReferencesUnion.self, forKey: .subject) - self.reportedBy = try container.decode(String.self, forKey: .reportedBy) - self.createdAt = try container.decode(DateFormatting.self, forKey: .createdAt).wrappedValue - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - try container.encode(self.id, forKey: .id) - try container.encode(self.reasonType, forKey: .reasonType) - - // Truncate `reason` to 20,000 characters before encoding - // `maxGraphemes`'s limit is 2,000, but `String.count` should respect that limit implictly - try truncatedEncodeIfPresent(self.reason, withContainer: &container, forKey: .reason, upToLength: 20_000) - try container.encode(self.subject, forKey: .subject) - try container.encode(self.reportedBy, forKey: .reportedBy) - try container.encode(self._createdAt, forKey: .createdAt) - } - - public enum CodingKeys: CodingKey { - case id - case reasonType - case reason - case subject - case reportedBy - case createdAt - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Moderation/AtprotoModerationDefs.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Moderation/AtprotoModerationDefs.swift deleted file mode 100644 index 74a31ebdd2..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Moderation/AtprotoModerationDefs.swift +++ /dev/null @@ -1,57 +0,0 @@ -// -// AtprotoModerationDefs.swift -// -// -// Created by Christopher Jr Riley on 2024-01-25. -// - -import Foundation - -/// A data model for the definition of the moderator's reason for reporting. -/// -/// - SeeAlso: This is based on the [`com.atproto.moderation.defs`][github] lexicon. -/// -/// - Important: The item associated with this enum is undocumented in the AT Protocol specifications. The documentation here is based on:\ -/// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ -/// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ -/// \ -/// Clarifications from Bluesky are needed in order to fully understand this item. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/moderation/defs.json -public enum ModerationReasonType: String, Codable { - /// Indicates spam as the reason. - /// - /// - Note: According to the AT Protocol specifications: "Spam: frequent unwanted promotion, - /// replies, mentions." - case reasonSpam - /// Indicates a rule violation as the reason. - /// - /// - Note: According to the AT Protocol specifications: "Direct violation of server rules, - /// laws, terms of service." - case reasonViolation - /// Indicates misleading content as the reason. - /// - /// - Note: According to the AT Protocol specifications: "Misleading identity, - /// affiliation, or content." - case reasonMisleading - /// Indicates mislabeled/unwanted sexual content as the reason. - /// - /// - Note: According to the AT Protocol specifications: "Unwanted or mislabeled - /// sexual content." - case reasonSexual - /// Indicates rude behavior as the reason. - /// - /// - Note: According to the AT Protocol specifications: "Rude, harassing, explicit, or - /// otherwise unwelcoming behavior." - case reasonRude - /// Indicates a reason not otherwise specified. - /// - /// - Note: According to the AT Protocol specifications: "Other: reports not falling under - /// another report category." - case reasonOther - /// Indicates an appeal to a previous moderation ruling as the reason. - /// - /// - Note: According to the AT Protocol specifications: "Appeal: appeal a previously taken - /// moderation action." - case reasonAppeal -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Moderation/ComAtprotoModerationCreateReport.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Moderation/ComAtprotoModerationCreateReport.swift new file mode 100644 index 0000000000..71f9509bde --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Moderation/ComAtprotoModerationCreateReport.swift @@ -0,0 +1,120 @@ +// +// ComAtprotoModerationCreateReport.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Moderation { + + /// A request body model for creating a report. + /// + /// - Note: According to the AT Protocol specifications: "Submit a moderation report regarding + /// an atproto account or record. Implemented by moderation services (with PDS proxying), and + /// requires auth." + /// + /// - SeeAlso: This is based on the [`com.atproto.moderation.createReport`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/moderation/createReport.json + public struct CreateReportRequestBody: Codable { + + /// The reason for the report. + /// + /// - Note: According to the AT Protocol specifications: "Indicates the broad category of + /// violation the report is for." + public let reasonType: ComAtprotoLexicon.Moderation.ReasonTypeDefinition + + /// Any clarifying comments accompanying the report. Optional. + /// + /// - Note: According to the AT Protocol specifications: "Additional context about the + /// content and violation." + public let reason: String? + + /// The subject reference. + /// + /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ + /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ + /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ + /// \ + /// Clarifications from Bluesky are needed in order to fully understand this item. + public let subject: ATUnion.CreateReportSubjectUnion + } + + /// An output model for creating a report. + /// + /// - SeeAlso: This is based on the [`com.atproto.moderation.createReport`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/moderation/createReport.json + public struct CreateReportOutput: Codable { + + /// The ID of the report. + public let id: Int + + /// The reason for the report. + public let reasonType: ComAtprotoLexicon.Moderation.ReasonTypeDefinition + + /// The reason for the report. Optional. + public let reason: String? + + /// The subject reference. + /// + /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ + /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ + /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ + /// \ + /// Clarifications from Bluesky are needed in order to fully understand this item. + public let subject: ATUnion.CreateReportSubjectUnion + + /// The decentralized identifier (DID) of the user who created the report. + public let reportedBy: String + + /// The date and time the report was created. + @DateFormatting public var createdAt: Date + + public init(id: Int, reasonType: ComAtprotoLexicon.Moderation.ReasonTypeDefinition, reason: String?, subject: ATUnion.CreateReportSubjectUnion, + reportedBy: String, createdAt: Date) { + self.id = id + self.reasonType = reasonType + self.reason = reason + self.subject = subject + self.reportedBy = reportedBy + self._createdAt = DateFormatting(wrappedValue: createdAt) + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.id = try container.decode(Int.self, forKey: .id) + self.reasonType = try container.decode(ComAtprotoLexicon.Moderation.ReasonTypeDefinition.self, forKey: .reasonType) + self.reason = try container.decodeIfPresent(String.self, forKey: .reason) + self.subject = try container.decode(ATUnion.CreateReportSubjectUnion.self, forKey: .subject) + self.reportedBy = try container.decode(String.self, forKey: .reportedBy) + self.createdAt = try container.decode(DateFormatting.self, forKey: .createdAt).wrappedValue + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.id, forKey: .id) + try container.encode(self.reasonType, forKey: .reasonType) + + // Truncate `reason` to 20,000 characters before encoding + // `maxGraphemes`'s limit is 2,000, but `String.count` should respect that limit implictly + try truncatedEncodeIfPresent(self.reason, withContainer: &container, forKey: .reason, upToLength: 20_000) + try container.encode(self.subject, forKey: .subject) + try container.encode(self.reportedBy, forKey: .reportedBy) + try container.encode(self._createdAt, forKey: .createdAt) + } + + public enum CodingKeys: CodingKey { + case id + case reasonType + case reason + case subject + case reportedBy + case createdAt + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Moderation/ComAtprotoModerationDefs.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Moderation/ComAtprotoModerationDefs.swift new file mode 100644 index 0000000000..eacda0f949 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Moderation/ComAtprotoModerationDefs.swift @@ -0,0 +1,67 @@ +// +// ComAtprotoModerationDefs.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Moderation { + + /// A definition model for the moderator's reason for reporting. + /// + /// - SeeAlso: This is based on the [`com.atproto.moderation.defs`][github] lexicon. + /// + /// - Important: The item associated with this enum is undocumented in the AT Protocol specifications. The documentation here is based on:\ + /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ + /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ + /// \ + /// Clarifications from Bluesky are needed in order to fully understand this item. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/moderation/defs.json + public enum ReasonTypeDefinition: String, Codable { + + /// Indicates spam as the reason. + /// + /// - Note: According to the AT Protocol specifications: "Spam: frequent unwanted + /// promotion, replies, mentions." + case reasonSpam + + /// Indicates a rule violation as the reason. + /// + /// - Note: According to the AT Protocol specifications: "Direct violation of server rules, + /// laws, terms of service." + case reasonViolation + + /// Indicates misleading content as the reason. + /// + /// - Note: According to the AT Protocol specifications: "Misleading identity, + /// affiliation, or content." + case reasonMisleading + + /// Indicates mislabeled/unwanted sexual content as the reason. + /// + /// - Note: According to the AT Protocol specifications: "Unwanted or mislabeled + /// sexual content." + case reasonSexual + + /// Indicates rude behavior as the reason. + /// + /// - Note: According to the AT Protocol specifications: "Rude, harassing, explicit, or + /// otherwise unwelcoming behavior." + case reasonRude + + /// Indicates a reason not otherwise specified. + /// + /// - Note: According to the AT Protocol specifications: "Other: reports not falling under + /// another report category." + case reasonOther + + /// Indicates an appeal to a previous moderation ruling as the reason. + /// + /// - Note: According to the AT Protocol specifications: "Appeal: appeal a previously taken + /// moderation action." + case reasonAppeal + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/AtprotoRepoApplyWrites.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/AtprotoRepoApplyWrites.swift deleted file mode 100644 index 586259c6bc..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/AtprotoRepoApplyWrites.swift +++ /dev/null @@ -1,131 +0,0 @@ -// -// AtprotoRepoApplyWrites.swift -// -// -// Created by Christopher Jr Riley on 2024-03-11. -// - -import Foundation - -/// The main data model definition for applying batch CRUD transactions. -/// -/// - Note: According to the AT Protocol specifications: "Apply a batch transaction of repository -/// creates, updates, and deletes. Requires auth, implemented by PDS." -/// -/// - SeeAlso: This is based on the [`com.atproto.repo.applyWrites`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/repo/applyWrites.json -public struct RepoApplyWrites: Codable { - /// The decentralized identifier (DID) or handle of the repository. - /// - /// - Note: According to the AT Protocol specifications: "The handle or DID of the repo (aka, - /// current account)." - public let repositoryDID: String - /// Indicates whether the operation should be validated. Optional. Defaults to `true`. - /// - /// - Note: According to the AT Protocol specifications: "Can be set to 'false' to skip Lexicon - /// schema validation of record data, for all operations." - public let shouldValidate: Bool? - /// The write operation itself. - public let writes: [ApplyWritesUnion]? - /// Swaps out an operation based on the CID. Optional. - /// - /// - Important: If a value is entered in here, the entire operation will fail if there is no - /// matching value in the repository. - /// - /// - Note: According to the AT Protocol specifications: "If provided, the entire operation - /// will fail if the current repo commit CID does not match this value. Used to prevent - /// conflicting repo mutations." - public let swapCommit: String? - - enum CodingKeys: String, CodingKey { - case repositoryDID = "repo" - case shouldValidate = "validate" - case writes - case swapCommit - } -} - -/// A data model definition for a "Create" write operation. -public struct RepoApplyWritesCreate: Codable { - /// The NSID of the collection. - public let collection: String - /// The record key of the write operation. Optional. - public let recordKey: String? - /// The value of the write operation. - public let value: UnknownType - - enum CodingKeys: String, CodingKey { - case collection - case recordKey = "rkey" - case value - } -} - -/// A data model definition for an "Update" write operation. -public struct RepoApplyWritesUpdate: Codable { - /// The NSID of the collection. - public let collection: String - /// The record key of the write operation. - public let recordKey: String - /// The value of the write operation. - public let value: UnknownType - - enum CodingKeys: String, CodingKey { - case collection - case recordKey = "rkey" - case value - } -} - -/// A data model definition for a "Delete" write operation. -public struct RepoApplyWritesDelete: Codable { - /// The NSID of the collection. - public let collection: String - /// The record key of the write operation. - public let recordKey: String - - enum CodingKeys: String, CodingKey { - case collection - case recordKey = "rkey" - } -} - -/// A reference containing the list of write operations. -public enum ApplyWritesUnion: Codable { - /// A "Create" write operation. - case create(RepoApplyWritesCreate) - /// An "Update" write operation. - case update(RepoApplyWritesUpdate) - /// A "Delete" write operation. - case delete(RepoApplyWritesDelete) - - public init(from decoder: Decoder) throws { - let container = try decoder.singleValueContainer() - - if let value = try? container.decode(RepoApplyWritesCreate.self) { - self = .create(value) - } else if let value = try? container.decode(RepoApplyWritesUpdate.self) { - self = .update(value) - } else if let value = try? container.decode(RepoApplyWritesDelete.self) { - self = .delete(value) - } else { - throw DecodingError.typeMismatch( - EmbedViewUnion.self, DecodingError.Context( - codingPath: decoder.codingPath, debugDescription: "Unknown ApplyWritesUnion type")) - } - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.singleValueContainer() - - switch self { - case .create(let embedView): - try container.encode(embedView) - case .update(let embedView): - try container.encode(embedView) - case .delete(let embedView): - try container.encode(embedView) - } - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/AtprotoRepoCreateRecord.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/AtprotoRepoCreateRecord.swift deleted file mode 100644 index 7e29cae99d..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/AtprotoRepoCreateRecord.swift +++ /dev/null @@ -1,67 +0,0 @@ -// -// AtprotoRepoCreateRecord.swift -// -// -// Created by Christopher Jr Riley on 2024-03-11. -// - -import Foundation - -/// The main data model definition for creating a record. -/// -/// - Note: According to the AT Protocol specifications: "Create a single new repository record -/// Requires auth, implemented by PDS." -/// -/// - SeeAlso: This is based on the [`com.atproto.repo.createRecord`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/repo/createRecord.json -public struct RepoCreateRecord: Codable { - /// The decentralized identifier (DID) or handle of the user account. - /// - /// - Note: According to the AT Protocol specifications: "The handle or DID of the repo - /// (aka, current account)." - public let repositoryDID: String - /// The NSID of the record. - /// - /// - Note: According to the AT Protocol specifications: "The NSID of the record collection." - public let collection: String - /// The record key of the collection. Optional. - /// - /// - Important: Current maximum length is 15 characters. This library will automatically - /// truncate the `String` to the maximum length if it does go over the limit. - /// - /// - Note: According to the AT Protocol specifications: "The Record Key." - public let recordKey: String? - /// Indicates whether the record should be validated. Optional. Defaults to `true`. - public let shouldValidate: Bool? - /// The record itself. - public let record: UnknownType - /// Swaps out an operation based on the CID. Optional. - /// - /// - Important: If a value is entered in here, the entire operation will fail if there is no - /// matching value in the repository. - /// - /// - Note: According to the AT Protocol specifications: "Compare and swap with the previous - /// commit by CID." - public let swapCommit: String? - - public func encode(to encoder: any Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - try container.encode(self.repositoryDID, forKey: .repositoryDID) - try container.encode(self.collection, forKey: .collection) - try truncatedEncodeIfPresent(self.recordKey, withContainer: &container, forKey: .recordKey, upToLength: 15) - try container.encodeIfPresent(self.shouldValidate, forKey: .shouldValidate) - try container.encode(self.record, forKey: .record) - try container.encodeIfPresent(self.swapCommit, forKey: .swapCommit) - } - - enum CodingKeys: String, CodingKey { - case repositoryDID = "repo" - case collection - case recordKey = "rkey" - case shouldValidate = "validate" - case record - case swapCommit - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/AtprotoRepoDeleteRecord.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/AtprotoRepoDeleteRecord.swift deleted file mode 100644 index fb1b55eb2b..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/AtprotoRepoDeleteRecord.swift +++ /dev/null @@ -1,52 +0,0 @@ -// -// AtprotoRepoDeleteRecord.swift -// -// -// Created by Christopher Jr Riley on 2024-03-11. -// - -import Foundation - -/// The main data model definition for deleting a record. -/// -/// - Note: According to the AT Protocol specifications: "Delete a repository record, or ensure it -/// doesn't exist. Requires auth, implemented by PDS." -/// -/// - SeeAlso: This is based on the [`com.atproto.repo.deleteRecord`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/repo/deleteRecord.json -public struct RepoDeleteRecord: Codable { - /// The decentralized identifier (DID) or handle of the user account. - /// - /// - Note: According to the AT Protocol specifications: "The handle or DID of the repo - /// (aka, current account)." - public let repositoryDID: String - /// The NSID of the record. - /// - /// - Note: According to the AT Protocol specifications: "The NSID of the record collection." - public let collection: String - /// The record key of the record. - /// - /// - Note: According to the AT Protocol specifications: "The Record Key." - public let recordKey: String - /// Swap the record on the server with this current record based on the CID of the record on - /// the server. - /// - /// - Note: According to the AT Protocol specifications: "Compare and swap with the - /// previous record by CID." - public let swapRecord: String? - /// Swap the commit on the server with this current commit based on the CID of the commit - /// on the server. - /// - /// - Note: According to the AT Protocol specifications: "Compare and swap with the - /// previous commit by CID." - public let swapCommit: String? - - enum CodingKeys: String, CodingKey { - case repositoryDID = "repo" - case collection - case recordKey = "rkey" - case swapRecord - case swapCommit - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/AtprotoRepoDescribeRepo.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/AtprotoRepoDescribeRepo.swift deleted file mode 100644 index 09cbe5df5d..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/AtprotoRepoDescribeRepo.swift +++ /dev/null @@ -1,46 +0,0 @@ -// -// AtprotoRepoDescribeRepo.swift -// -// -// Created by Christopher Jr Riley on 2024-03-11. -// - -import Foundation - -/// The main data model definition for the output of describing the repository. -/// -/// - Note: According to the AT Protocol specifications: "Get information about an account -/// and repository, including the list of collections. Does not require auth." -/// -/// - SeeAlso: This is based on the [`com.atproto.repo.describeRepo`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/repo/describeRepo.json -public struct RepoDescribeRepoOutput: Codable { - /// The handle of the repository. - public let repositoryHandle: String - /// The decentralized identitifer (DID) of the repository. - public let repositoryDID: String - /// The DID Document of the repository. - /// - /// - Note: According to the AT Protocol specifications: "The complete DID document for - /// this account." - public let didDocument: DIDDocument - /// An array of collections related to the repository. - /// - /// - Note: According to the AT Protocol specifications: "List of all the collections (NSIDs) - /// for which this repo contains at least one record." - public let collections: [String] - /// Indicates whether the repository's handle is valid. - /// - /// - Note: According to the AT Protocol specifications: "Indicates if handle is currently - /// valid (resolves bi-directionally)." - public let isHandleCorrect: Bool - - enum CodingKeys: String, CodingKey { - case repositoryHandle = "handle" - case repositoryDID = "did" - case didDocument = "didDoc" - case collections - case isHandleCorrect = "handleIsCorrect" - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/AtprotoRepoGetRecord.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/AtprotoRepoGetRecord.swift deleted file mode 100644 index e9328a9cd3..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/AtprotoRepoGetRecord.swift +++ /dev/null @@ -1,83 +0,0 @@ -// -// AtprotoRepoGetRecord.swift -// -// -// Created by Christopher Jr Riley on 2024-01-29. -// - -import Foundation - -// MARK: - Main definition -/// The main data model definition for a record. -/// -/// - Note: According to the AT Protocol specifications: "Get a single record from a repository. -/// Does not require auth." -/// -/// - SeeAlso: This is based on the [`com.atproto.repo.getRecord`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/repo/getRecord.json -public struct RecordQuery: Codable { - /// The handle or decentralized identifier (DID) of the repo." - /// - /// - Note: According to the AT Protocol specifications: "The handle or DID of the repo." - public let repo: String - /// The NSID of the record. - /// - /// - Note: According to the AT Protocol specifications: "The NSID of the record collection." - public let collection: String - /// The record's key. - /// - //// - Note: According to the AT Protocol specifications: "The Record Key." - public let recordKey: String - /// The CID of the version of the record. Optional. If not specified, then return the most - /// recent version. - /// - /// - Note: According to the AT Protocol specifications: "The CID of the version of the record. - /// If not specified, then return the most recent version." - public let recordCID: String? = nil - - public init(repo: String, collection: String, recordKey: String) { - self.repo = repo - self.collection = collection - self.recordKey = recordKey - } - - enum CodingKeys: String, CodingKey { - case repo = "repo" - case collection = "collection" - case recordKey = "rkey" - case recordCID = "cid" - } -} - -// MARK: - -/// The main data model definition for the outpot of a record. -/// -/// - SeeAlso: This is based on the [`com.atproto.repo.getRecord`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/repo/getRecord.json -public struct RecordOutput: Codable { - /// The URI of the record. - public let recordURI: String - /// The CID hash for the record. - public let recordCID: String - /// The value for the record. - public let value: RecordValueReply? - - enum CodingKeys: String, CodingKey { - case recordURI = "uri" - case recordCID = "cid" - case value = "value" - } -} - -// MARK: - -/// The main data model definition for the outpot . -/// -/// - SeeAlso: This is based on the [`com.atproto.repo.getRecord`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/repo/getRecord.json -public struct RecordValueReply: Codable { - /// The reply reference of the record. - public let reply: ReplyReference? -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/AtprotoRepoImportRepo.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/AtprotoRepoImportRepo.swift deleted file mode 100644 index c722d6e7d8..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/AtprotoRepoImportRepo.swift +++ /dev/null @@ -1,21 +0,0 @@ -// -// AtprotoRepoImportRepo.swift -// -// -// Created by Christopher Jr Riley on 2024-03-11. -// - -import Foundation - -/// The main data model definition for importing a CAR file. -/// -/// - Note: According to the AT Protocol specifications: "Import a repo in the form of a CAR file. -/// Requires Content-Length HTTP header to be set." -/// -/// - SeeAlso: This is based on the [`com.atproto.repo.importRepo`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/repo/importRepo.json -public struct RepoImportRepo: Codable { - /// The repository data in the form of a CAR file. - public let repository: Data -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/AtprotoRepoListMissingBlobs.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/AtprotoRepoListMissingBlobs.swift deleted file mode 100644 index 78b1134275..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/AtprotoRepoListMissingBlobs.swift +++ /dev/null @@ -1,29 +0,0 @@ -// -// AtprotoRepoListMissingBlobs.swift -// -// -// Created by Christopher Jr Riley on 2024-03-11. -// - -import Foundation - -/// The main data model definition for the output of listing any missing blobs attached to the -/// user account. -/// -/// - Note: According to the AT Protocol specifications: "Returns a list of missing blobs for the -/// requesting account. Intended to be used in the account migration flow." -/// -/// - SeeAlso: This is based on the [`com.atproto.repo.listMissingBlobs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/repo/listMissingBlobs.json -public struct RepoListMissingBlobsOutput: Codable { - public let blobs: [RecordBlob] -} - -/// A data model definition for a record blob. -public struct RecordBlob: Codable { - /// The CID hash of the record. - public let recordCID: String - /// The URI of the record. - public let recordURI: String -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/AtprotoRepoListRecords.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/AtprotoRepoListRecords.swift deleted file mode 100644 index bfece951b3..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/AtprotoRepoListRecords.swift +++ /dev/null @@ -1,23 +0,0 @@ -// -// AtprotoRepoListRecords.swift -// -// -// Created by Christopher Jr Riley on 2024-03-11. -// - -import Foundation - -/// The main data model definition for the output of listing records. -/// -/// - Note: According to the AT Protocol specifications: "List a range of records in a repository, -/// matching a specific collection. Does not require auth." -/// -/// - SeeAlso: This is based on the [`com.atproto.repo.listRecords`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/repo/listRecords.json -public struct RepoListRecordsOutput: Codable { - /// The mark used to indicate the starting point for the next set of result. Optional. - public let cursor: String? - /// An array of records. - public let records: [RecordOutput] -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/AtprotoRepoPutRecord.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/AtprotoRepoPutRecord.swift deleted file mode 100644 index 3dd4689e8c..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/AtprotoRepoPutRecord.swift +++ /dev/null @@ -1,64 +0,0 @@ -// -// AtprotoRepoPutRecord.swift -// -// -// Created by Christopher Jr Riley on 2024-03-11. -// - -import Foundation - -/// The main data model definition for creating a record that replaces a previous record. -/// -/// - Note: According to the AT Protocol specifications: "Write a repository record, creating -/// or updating it as needed. Requires auth, implemented by PDS." -/// -/// - SeeAlso: This is based on the [`com.atproto.repo.putRecord`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/repo/putRecord.json -public struct RepoPutRecord: Codable { - /// The decentralized identifier (DID) or handle of the repository. - /// - /// - Note: According to the AT Protocol specifications: "The handle or DID of the repo - /// (aka, current account)." - public let repositoryDID: String - /// The NSID of the record. - /// - /// - Note: According to the AT Protocol specifications: "The NSID of the record collection." - public let collection: String - /// The record key of the collection. - /// - /// - Note: According to the AT Protocol specifications: "The Record Key." - public let recordKey: String - /// Indicates whether the record should be validated. Optional. - /// - /// - Note: According to the AT Protocol specifications: "Can be set to 'false' to skip Lexicon - /// schema validation of record data." - public let shouldValidate: Bool? - /// The record itself. - /// - /// - Note: According to the AT Protocol specifications: "The record to write." - public let record: UnknownType - /// Swaps the record in the server with the record contained in here. Optional. - /// - /// - Important: This field can be left blank. - /// - /// - Note: According to the AT Protocol specifications: "Compare and swap with the previous - /// record by CID. WARNING: nullable and optional field; may cause problems with - /// golang implementation" - public let swapRecord: String? - /// Swaps the commit in the server with the commit contained in here. Optional. - /// - /// - Note: According to the AT Protocol specifications: "Compare and swap with the previous - /// commit by CID." - public let swapCommit: String? - - enum CodingKeys: String, CodingKey { - case repositoryDID = "repo" - case collection - case recordKey = "rkey" - case shouldValidate = "validate" - case record - case swapRecord - case swapCommit - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/AtprotoRepoStrongRef.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/AtprotoRepoStrongRef.swift deleted file mode 100644 index b38293e7c5..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/AtprotoRepoStrongRef.swift +++ /dev/null @@ -1,39 +0,0 @@ -// -// AtProtoRepoStrongRef.swift -// -// -// Created by Christopher Jr Riley on 2024-01-25. -// - -import Foundation - -// MARK: - Main definition -/// The main data model definition for a strong reference. -/// -/// - Note: According to the AT Protocol specifications: "A URI with a content-hash fingerprint." -/// -/// - SeeAlso: This is based on the [`com.atproto.repo.strongRef`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/repo/strongRef.json -public struct StrongReference: Codable { - /// The URI for the record. - public let recordURI: String - /// The CID hash for the record. - public let cidHash: String - - public init(recordURI: String, cidHash: String) { - self.recordURI = recordURI - self.cidHash = cidHash - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - self.recordURI = try container.decode(String.self, forKey: .recordURI) - self.cidHash = try container.decode(String.self, forKey: .cidHash) - } - - enum CodingKeys: String, CodingKey { - case recordURI = "uri" - case cidHash = "cid" - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/AtprotoRepoUploadBlob.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/AtprotoRepoUploadBlob.swift deleted file mode 100644 index 6a8474f38b..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/AtprotoRepoUploadBlob.swift +++ /dev/null @@ -1,68 +0,0 @@ -// -// AtprotoRepoUploadBlob.swift -// -// -// Created by Christopher Jr Riley on 2024-02-05. -// - -import Foundation - -// MARK: - Main definition -/// The main data model definition for the image's query. -public struct ImageQuery: Encodable { - /// The data of the image. - public let imageData: Data - /// The file name of the image. - public let fileName: String - /// The alt text of the image, - public let altText: String? - - public init(imageData: Data, fileName: String, altText: String?) { - self.imageData = imageData - self.fileName = fileName - self.altText = altText - } -} - -// MARK: - -// TODO: Find a way to remove BlobContainer without breaking the JSON encoding. -// This will be here until a way to remove this without the issues of -// the JSON encoding are solved. -/// The container used for storing blobs within a record. -/// -/// - Note: This is a temporary measure and will be deleted once a better solution is made. -public struct BlobContainer: Codable { - /// The blob itself. - public let blob: UploadBlobOutput -} - -/// A data model for a definition of an output of uploading a blob. -public struct UploadBlobOutput: Codable { - /// The type of blob. - public let type: String? - /// The strong reference of the blob. - public let reference: BlobReference - /// The the MIME type. - /// - /// This can be a `.jpg`, `.png`, and `.gif` - public let mimeType: String - /// The size of the blob. - public let size: Int - - enum CodingKeys: String, CodingKey { - case type = "$type" - case reference = "ref" - case mimeType - case size - } -} - -/// A data model for a blob reference definition. -public struct BlobReference: Codable { - /// The link of the blob reference. - public let link: String - - enum CodingKeys: String, CodingKey { - case link = "$link" - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/ComAtProtoRepoStrongRef.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/ComAtProtoRepoStrongRef.swift new file mode 100644 index 0000000000..00372a7a59 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/ComAtProtoRepoStrongRef.swift @@ -0,0 +1,44 @@ +// +// ComAtProtoRepoStrongRef.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Repository { + + /// A main data model definition for a strong reference. + /// + /// - Note: According to the AT Protocol specifications: "A URI with a + /// content-hash fingerprint." + /// + /// - SeeAlso: This is based on the [`com.atproto.repo.strongRef`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/repo/strongRef.json + public struct StrongReference: Codable { + + /// The URI for the record. + public let recordURI: String + + /// The CID hash for the record. + public let cidHash: String + + public init(recordURI: String, cidHash: String) { + self.recordURI = recordURI + self.cidHash = cidHash + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + self.recordURI = try container.decode(String.self, forKey: .recordURI) + self.cidHash = try container.decode(String.self, forKey: .cidHash) + } + + enum CodingKeys: String, CodingKey { + case recordURI = "uri" + case cidHash = "cid" + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/ComAtprotoRepoApplyWrites.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/ComAtprotoRepoApplyWrites.swift new file mode 100644 index 0000000000..d68f400a35 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/ComAtprotoRepoApplyWrites.swift @@ -0,0 +1,139 @@ +// +// ComAtprotoRepoApplyWrites.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Repository { + + /// The main data model definition for applying batch CRUD transactions. + /// + /// - Note: According to the AT Protocol specifications: "Apply a batch transaction of + /// repository creates, updates, and deletes. Requires auth, implemented by PDS." + /// + /// - SeeAlso: This is based on the [`com.atproto.repo.applyWrites`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/repo/applyWrites.json + public struct ApplyWrites: Codable { + + /// A data model definition for a "Create" write operation. + /// + /// - Note: According to the AT Protocol specifications: "Operation which creates a + /// new record." + /// + /// - SeeAlso: This is based on the [`com.atproto.repo.applyWrites`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/repo/applyWrites.json + public struct Create: Codable { + + /// The NSID of the collection. + public let collection: String + + /// The record key of the write operation. Optional. + public let recordKey: String? + + /// The value of the write operation. + public let value: UnknownType + + enum CodingKeys: String, CodingKey { + case collection + case recordKey = "rkey" + case value + } + } + + /// A data model definition for an "Update" write operation. + /// + /// - Note: According to the AT Protocol specifications: "Operation which updates an + /// existing record." + /// + /// - SeeAlso: This is based on the [`com.atproto.repo.applyWrites`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/repo/applyWrites.json + public struct Update: Codable { + + /// The NSID of the collection. + public let collection: String + + /// The record key of the write operation. + public let recordKey: String + + /// The value of the write operation. + public let value: UnknownType + + enum CodingKeys: String, CodingKey { + case collection + case recordKey = "rkey" + case value + } + } + + /// A data model definition for a "Delete" write operation. + /// + /// - Note: According to the AT Protocol specifications: "Operation which deletes an + /// existing record." + /// + /// - SeeAlso: This is based on the [`com.atproto.repo.applyWrites`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/repo/applyWrites.json + public struct Delete: Codable { + + /// The NSID of the collection. + public let collection: String + + /// The record key of the write operation. + public let recordKey: String + + enum CodingKeys: String, CodingKey { + case collection + case recordKey = "rkey" + } + } + } + + /// A request body model for applying batch CRUD transactions. + /// + /// - Note: According to the AT Protocol specifications: "Apply a batch transaction of + /// repository creates, updates, and deletes. Requires auth, implemented by PDS." + /// + /// - SeeAlso: This is based on the [`com.atproto.repo.applyWrites`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/repo/applyWrites.json + public struct ApplyWritesRequestBody: Codable { + + /// The decentralized identifier (DID) or handle of the repository. + /// + /// - Note: According to the AT Protocol specifications: "The handle or DID of the repo + /// (aka, current account)." + public let repositoryDID: String + + /// Indicates whether the operation should be validated. Optional. Defaults to `true`. + /// + /// - Note: According to the AT Protocol specifications: "Can be set to 'false' to skip + /// Lexicon schema validation of record data, for all operations." + public let shouldValidate: Bool? + + /// The write operation itself. + public let writes: [ATUnion.ApplyWritesUnion]? + + /// Swaps out an operation based on the CID. Optional. + /// + /// - Important: If a value is entered in here, the entire operation will fail if there is + /// no matching value in the repository. + /// + /// - Note: According to the AT Protocol specifications: "If provided, the entire operation + /// will fail if the current repo commit CID does not match this value. Used to prevent + /// conflicting repo mutations." + public let swapCommit: String? + + enum CodingKeys: String, CodingKey { + case repositoryDID = "repo" + case shouldValidate = "validate" + case writes + case swapCommit + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/ComAtprotoRepoCreateRecord.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/ComAtprotoRepoCreateRecord.swift new file mode 100644 index 0000000000..03723ce3b0 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/ComAtprotoRepoCreateRecord.swift @@ -0,0 +1,76 @@ +// +// ComAtprotoRepoCreateRecord.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Repository { + + /// A request body model for creating a record. + /// + /// - Note: According to the AT Protocol specifications: "Create a single new repository record + /// Requires auth, implemented by PDS." + /// + /// - SeeAlso: This is based on the [`com.atproto.repo.createRecord`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/repo/createRecord.json + public struct CreateRecordRequestBody: Codable { + + /// The decentralized identifier (DID) or handle of the user account. + /// + /// - Note: According to the AT Protocol specifications: "The handle or DID of the repo + /// (aka, current account)." + public let repositoryDID: String + + /// The NSID of the record. + /// + /// - Note: According to the AT Protocol specifications: "The NSID of the record collection." + public let collection: String + + /// The record key of the collection. Optional. + /// + /// - Important: Current maximum length is 15 characters. This library will automatically + /// truncate the `String` to the maximum length if it does go over the limit. + /// + /// - Note: According to the AT Protocol specifications: "The Record Key." + public let recordKey: String? + + /// Indicates whether the record should be validated. Optional. Defaults to `true`. + public let shouldValidate: Bool? + + /// The record itself. + public let record: UnknownType + + /// Swaps out an operation based on the CID. Optional. + /// + /// - Important: If a value is entered in here, the entire operation will fail if there is no + /// matching value in the repository. + /// + /// - Note: According to the AT Protocol specifications: "Compare and swap with the previous + /// commit by CID." + public let swapCommit: String? + + public func encode(to encoder: any Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.repositoryDID, forKey: .repositoryDID) + try container.encode(self.collection, forKey: .collection) + try truncatedEncodeIfPresent(self.recordKey, withContainer: &container, forKey: .recordKey, upToLength: 15) + try container.encodeIfPresent(self.shouldValidate, forKey: .shouldValidate) + try container.encode(self.record, forKey: .record) + try container.encodeIfPresent(self.swapCommit, forKey: .swapCommit) + } + + enum CodingKeys: String, CodingKey { + case repositoryDID = "repo" + case collection + case recordKey = "rkey" + case shouldValidate = "validate" + case record + case swapCommit + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/ComAtprotoRepoDeleteRecord.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/ComAtprotoRepoDeleteRecord.swift new file mode 100644 index 0000000000..d5920e28b1 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/ComAtprotoRepoDeleteRecord.swift @@ -0,0 +1,61 @@ +// +// ComAtprotoRepoDeleteRecord.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Repository { + + /// A request body model for deleting a record. + /// + /// - Note: According to the AT Protocol specifications: "Delete a repository record, or ensure + /// it doesn't exist. Requires auth, implemented by PDS." + /// + /// - SeeAlso: This is based on the [`com.atproto.repo.deleteRecord`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/repo/deleteRecord.json + public struct DeleteRecordRequestBody: Codable { + + /// The decentralized identifier (DID) or handle of the user account. + /// + /// - Note: According to the AT Protocol specifications: "The handle or DID of the repo + /// (aka, current account)." + public let repositoryDID: String + + /// The NSID of the record. + /// + /// - Note: According to the AT Protocol specifications: "The NSID of the + /// record collection." + public let collection: String + + /// The record key of the record. + /// + /// - Note: According to the AT Protocol specifications: "The Record Key." + public let recordKey: String + + /// Swap the record on the server with this current record based on the CID of the record + /// on the server. + /// + /// - Note: According to the AT Protocol specifications: "Compare and swap with the + /// previous record by CID." + public let swapRecord: String? + + /// Swap the commit on the server with this current commit based on the CID of the commit + /// on the server. + /// + /// - Note: According to the AT Protocol specifications: "Compare and swap with the + /// previous commit by CID." + public let swapCommit: String? + + enum CodingKeys: String, CodingKey { + case repositoryDID = "repo" + case collection + case recordKey = "rkey" + case swapRecord + case swapCommit + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/ComAtprotoRepoDescribeRepo.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/ComAtprotoRepoDescribeRepo.swift new file mode 100644 index 0000000000..e284494ddd --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/ComAtprotoRepoDescribeRepo.swift @@ -0,0 +1,54 @@ +// +// ComAtprotoRepoDescribeRepo.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Repository { + + /// An output model for describing the repository. + /// + /// - Note: According to the AT Protocol specifications: "Get information about an account + /// and repository, including the list of collections. Does not require auth." + /// + /// - SeeAlso: This is based on the [`com.atproto.repo.describeRepo`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/repo/describeRepo.json + public struct DescribeRepositoryOutput: Codable { + + /// The handle of the repository. + public let repositoryHandle: String + + /// The decentralized identitifer (DID) of the repository. + public let repositoryDID: String + + /// The DID Document of the repository. + /// + /// - Note: According to the AT Protocol specifications: "The complete DID document for + /// this account." + public let didDocument: DIDDocument + + /// An array of collections related to the repository. + /// + /// - Note: According to the AT Protocol specifications: "List of all the collections + /// (NSIDs) for which this repo contains at least one record." + public let collections: [String] + + /// Indicates whether the repository's handle is valid. + /// + /// - Note: According to the AT Protocol specifications: "Indicates if handle is currently + /// valid (resolves bi-directionally)." + public let isHandleCorrect: Bool + + enum CodingKeys: String, CodingKey { + case repositoryHandle = "handle" + case repositoryDID = "did" + case didDocument = "didDoc" + case collections + case isHandleCorrect = "handleIsCorrect" + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/ComAtprotoRepoGetRecord.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/ComAtprotoRepoGetRecord.swift new file mode 100644 index 0000000000..d4ea7e8219 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/ComAtprotoRepoGetRecord.swift @@ -0,0 +1,34 @@ +// +// ComAtprotoRepoGetRecord.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Repository { + + /// An output model for a record. + /// + /// - SeeAlso: This is based on the [`com.atproto.repo.getRecord`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/repo/getRecord.json + public struct GetRecordOutput: Codable { + + /// The URI of the record. + public let recordURI: String + + /// The CID hash for the record. + public let recordCID: String + + /// The value for the record. + public let value: UnknownType? + + enum CodingKeys: String, CodingKey { + case recordURI = "uri" + case recordCID = "cid" + case value = "value" + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/ComAtprotoRepoImportRepo.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/ComAtprotoRepoImportRepo.swift new file mode 100644 index 0000000000..47d3d73eed --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/ComAtprotoRepoImportRepo.swift @@ -0,0 +1,25 @@ +// +// ComAtprotoRepoImportRepo.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Repository { + + /// A request body model for importing a CAR file. + /// + /// - Note: According to the AT Protocol specifications: "Import a repo in the form of a + /// CAR file. Requires Content-Length HTTP header to be set." + /// + /// - SeeAlso: This is based on the [`com.atproto.repo.importRepo`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/repo/importRepo.json + public struct ImportRepositoryRequestBody: Codable { + + /// The repository data in the form of a CAR file. + public let repository: Data + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/ComAtprotoRepoListMissingBlobs.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/ComAtprotoRepoListMissingBlobs.swift new file mode 100644 index 0000000000..0dc40fc1ed --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/ComAtprotoRepoListMissingBlobs.swift @@ -0,0 +1,39 @@ +// +// ComAtprotoRepoListMissingBlobs.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Repository { + + /// The main data model for a record blob. + public struct ListMissingBlobs: Codable { + + /// A data model definition for a record blob. + public struct RecordBlob: Codable { + + /// The CID hash of the record. + public let recordCID: String + + /// The URI of the record. + public let recordURI: String + } + } + + /// An output model for listing any missing blobs attached to the user account. + /// + /// - Note: According to the AT Protocol specifications: "Returns a list of missing blobs for + /// the requesting account. Intended to be used in the account migration flow." + /// + /// - SeeAlso: This is based on the [`com.atproto.repo.listMissingBlobs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/repo/listMissingBlobs.json + public struct ListMissingBlobsOutput: Codable { + + /// An array of blobs. + public let blobs: [ComAtprotoLexicon.Repository.ListMissingBlobs.RecordBlob] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/ComAtprotoRepoListRecords.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/ComAtprotoRepoListRecords.swift new file mode 100644 index 0000000000..06f7f86482 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/ComAtprotoRepoListRecords.swift @@ -0,0 +1,28 @@ +// +// ComAtprotoRepoListRecords.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Repository { + + /// An output model for listing records. + /// + /// - Note: According to the AT Protocol specifications: "List a range of records in a + /// repository, matching a specific collection. Does not require auth." + /// + /// - SeeAlso: This is based on the [`com.atproto.repo.listRecords`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/repo/listRecords.json + public struct ListRecordsOutput: Codable { + + /// The mark used to indicate the starting point for the next set of result. Optional. + public let cursor: String? + + /// An array of records. + public let records: [ComAtprotoLexicon.Repository.GetRecordOutput] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/ComAtprotoRepoPutRecord.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/ComAtprotoRepoPutRecord.swift new file mode 100644 index 0000000000..21c4d93d40 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/ComAtprotoRepoPutRecord.swift @@ -0,0 +1,75 @@ +// +// ComAtprotoRepoPutRecord.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Repository { + + /// A request body model for creating a record that replaces a previous record. + /// + /// - Note: According to the AT Protocol specifications: "Write a repository record, creating + /// or updating it as needed. Requires auth, implemented by PDS." + /// + /// - SeeAlso: This is based on the [`com.atproto.repo.putRecord`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/repo/putRecord.json + public struct PutRecordRequestBody: Codable { + + /// The decentralized identifier (DID) or handle of the repository. + /// + /// - Note: According to the AT Protocol specifications: "The handle or DID of the repo + /// (aka, current account)." + public let repositoryDID: String + + /// The NSID of the record. + /// + /// - Note: According to the AT Protocol specifications: "The NSID of the + /// record collection." + public let collection: String + + /// The record key of the collection. + /// + /// - Note: According to the AT Protocol specifications: "The Record Key." + public let recordKey: String + + /// Indicates whether the record should be validated. Optional. + /// + /// - Note: According to the AT Protocol specifications: "Can be set to 'false' to skip + /// Lexicon schema validation of record data." + public let shouldValidate: Bool? + + /// The record itself. + /// + /// - Note: According to the AT Protocol specifications: "The record to write." + public let record: UnknownType + + /// Swaps the record in the server with the record contained in here. Optional. + /// + /// - Important: This field can be left blank. + /// + /// - Note: According to the AT Protocol specifications: "Compare and swap with the + /// previous record by CID. WARNING: nullable and optional field; may cause problems + /// with golang implementation" + public let swapRecord: String? + + /// Swaps the commit in the server with the commit contained in here. Optional. + /// + /// - Note: According to the AT Protocol specifications: "Compare and swap with the + /// previous commit by CID." + public let swapCommit: String? + + enum CodingKeys: String, CodingKey { + case repositoryDID = "repo" + case collection + case recordKey = "rkey" + case shouldValidate = "validate" + case record + case swapRecord + case swapCommit + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/ComAtprotoRepoUploadBlob.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/ComAtprotoRepoUploadBlob.swift new file mode 100644 index 0000000000..3341c59904 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Repo/ComAtprotoRepoUploadBlob.swift @@ -0,0 +1,91 @@ +// +// ComAtprotoRepoUploadBlob.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Repository { + + /// The main data model definition for the image's query. + public struct ImageQuery: Encodable { + + /// The data of the image. + public let imageData: Data + + /// The file name of the image. + public let fileName: String + + /// The alt text of the image, + public let altText: String? + + public init(imageData: Data, fileName: String, altText: String?) { + self.imageData = imageData + self.fileName = fileName + self.altText = altText + } + } + + /// A request body model for uploading a blob. + /// + /// - Note: According to the AT Protocol specifications: "Upload a new blob, to be referenced + /// from a repository record. The blob will be deleted if it is not referenced within a time + /// window (eg, minutes). Blob restrictions (mimetype, size, etc) are enforced when the + /// reference is created. Requires auth, implemented by PDS." + /// + /// - SeeAlso: This is based on the [`com.atproto.repo.uploadBlob`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/repo/uploadBlob.json + public struct UploadBlobRequestBody: Codable {} + + // MARK: - + // TODO: Find a way to remove BlobContainer without breaking the JSON encoding. + // This will be here until a way to remove this without the issues of + // the JSON encoding are solved. + /// The container used for storing blobs within a record. + /// + /// - Note: This is a temporary measure and will be deleted once a better solution is made. + public struct BlobContainer: Codable { + + /// The blob itself. + public let blob: UploadBlobOutput + } + + /// A data model for a definition of an output of uploading a blob. + public struct UploadBlobOutput: Codable { + + /// The type of blob. + public let type: String? + + /// The strong reference of the blob. + public let reference: ComAtprotoLexicon.Repository.BlobReference + + /// The the MIME type. + /// + /// This can be a `.jpg`, `.png`, and `.gif` + public let mimeType: String + + /// The size of the blob. + public let size: Int + + enum CodingKeys: String, CodingKey { + case type = "$type" + case reference = "ref" + case mimeType + case size + } + } + + /// A data model for a blob reference definition. + public struct BlobReference: Codable { + + /// The link of the blob reference. + public let link: String + + enum CodingKeys: String, CodingKey { + case link = "$link" + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerCheckAccountStatus.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerCheckAccountStatus.swift deleted file mode 100644 index b230f08087..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerCheckAccountStatus.swift +++ /dev/null @@ -1,65 +0,0 @@ -// -// AtprotoServerCheckAccountStatus.swift -// -// -// Created by Christopher Jr Riley on 2024-02-23. -// - -import Foundation - -/// A data model definition for the output of checking the user's account status. -/// -/// - Note: According to the AT Protocol specifications: "Returns the status of an account, especially as pertaining to import or recovery. Can be called many times over the course of an account migration. -/// Requires auth and can only be called pertaining to oneself." -/// -/// - SeeAlso: This is based on the [`com.atproto.server.checkAccountStatus`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/checkAccountStatus.json -public struct ServerCheckAccountStatusOutput: Codable { - /// Indicates whether the user's account has been activated. - public let isActivated: Bool - /// Indicates whether the user's account has a valid decentralized identifier (DID). - public let isValidDID: Bool - /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ - /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ - /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ - /// \ - /// Clarifications from Bluesky are needed in order to fully understand this item. - public let repositoryCommit: String - /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ - /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ - /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ - /// \ - /// Clarifications from Bluesky are needed in order to fully understand this item. - public let repositoryRev: String - /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ - /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ - /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ - /// \ - /// Clarifications from Bluesky are needed in order to fully understand this item. - public let repositoryBlocks: Int - /// The number of indexed records in the user's account. - public let indexedRecords: Int - /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ - /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ - /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ - /// \ - /// Clarifications from Bluesky are needed in order to fully understand this item. - public let privateStateValues: Int - /// The expected number of blobs in the user's account. - public let expectedBlobs: Int - /// The number of blobs imported into the user's account. - public let importedBlobs: Int - - enum CodingKeys: String, CodingKey { - case isActivated = "activated" - case isValidDID = "validDid" - case repositoryCommit = "repoCommit" - case repositoryRev = "repoRev" - case repositoryBlocks = "repoBlocks" - case indexedRecords - case privateStateValues - case expectedBlobs - case importedBlobs - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerConfirmEmail.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerConfirmEmail.swift deleted file mode 100644 index 80ee2fe0b9..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerConfirmEmail.swift +++ /dev/null @@ -1,22 +0,0 @@ -// -// AtprotoServerConfirmEmail.swift -// -// -// Created by Christopher Jr Riley on 2024-02-23. -// - -import Foundation - -/// The main data model of a definition for confirming emails. -/// -/// - Note: According to the AT Protocol specifications: "Confirm an email using a token from com.atproto.server.requestEmailConfirmation." -/// -/// - SeeAlso: This is based on the [`com.atproto.server.confirmEmail`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/confirmEmail.json -public struct ServerConfirmEmail: Codable { - /// The email of the user. - public let email: String - /// The token given to the user via email. - public let token: String -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerCreateAccount.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerCreateAccount.swift deleted file mode 100644 index bfd2ad791b..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerCreateAccount.swift +++ /dev/null @@ -1,73 +0,0 @@ -// -// AtprotoServerCreateAccount.swift -// -// -// Created by Christopher Jr Riley on 2024-02-23. -// - -import Foundation - -/// The main data model definition for creating an account. -/// -/// - Note: According to the AT Protocol specifications: "Create an account. Implemented by PDS." -/// -/// - SeeAlso: This is based on the [`com.atproto.server.createAccount`][github] lexicon. -/// -/// [github]: https://docs.bsky.app/docs/api/com-atproto-server-create-account -public struct ServerCreateAccount: Codable { - /// The email of the user. Optional. - public var email: String? = nil - /// The handle the user wishes to use. - /// - /// - Note: According to the AT Protocol specifications: "Requested handle for the account." - public let handle: String - /// A decentralized identifier (DID) that has existed before and will be used to be imported to the new account. Optional. - /// - /// - Note: According to the AT Protocol specifications: "Pre-existing atproto DID, being imported to a new account." - public var existingDID: String? = nil - /// The invite code for the user. Optional. - /// - /// - Note: Invite codes are no longer used in Bluesky. This is left here for legacy purposes, as well as for any federated networks that may use this feature. - public var inviteCode: String? = nil - /// A verification code. - public var verificationCode: String? = nil - /// A code that has come from a text message in the user's phone. Optional. - public var verificationPhone: String? = nil - /// The password the user will use for the account. Optional. - /// - /// - Note: According to the AT Protocol specifications: "Initial account password. May need to meet instance-specific password strength requirements." - public var password: String? = nil - /// DID PLC rotation key (aka, recovery key) to be included in PLC creation operation. Optional. - /// - /// - Note: The above documentation is taken directly from the AT Protocol apecifications. - public var recoveryKey: String? = nil - /// A signed DID PLC operation to be submitted as part of importing an existing account to this instance. NOTE: this optional field may be updated when full account migration is implemented. Optional. - /// - /// - Note: The above documentation is taken directly from the AT Protocol apecifications. - public var plcOp: UnknownType? = nil - - public init(email: String?, handle: String, existingDID: String?, inviteCode: String?, verificationCode: String?, verificationPhone: String?, - password: String?, recoveryKey: String?, plcOp: UnknownType?) { - self.email = email - self.handle = handle - self.existingDID = existingDID - self.inviteCode = inviteCode - self.verificationCode = verificationCode - self.verificationPhone = verificationCode - self.password = password - self.recoveryKey = recoveryKey - self.plcOp = plcOp - } - - enum CodingKeys: String, CodingKey { - case email - case handle - case existingDID = "did" - case inviteCode - case verificationCode - case verificationPhone - case password - case recoveryKey - case plcOp - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerCreateAppPassword.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerCreateAppPassword.swift deleted file mode 100644 index 2d131c9b8f..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerCreateAppPassword.swift +++ /dev/null @@ -1,61 +0,0 @@ -// -// AtprotoServerCreateAppPassword.swift -// -// -// Created by Christopher Jr Riley on 2024-02-24. -// - -import Foundation - -/// The main data model definition for creating an App Password. -/// -/// - Note: According to the AT Protocol specifications: "Create an App Password." -/// -/// - SeeAlso: This is based on the [`com.atproto.server.createAppPassword`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/createAppPassword.json -public struct ServerCreateAppPassword: Codable { - /// The name given to the App Password to help distingush it from others. - /// - /// - Note: According to the AT Protocol specifications: "A short name for the App Password, to help distinguish them." - public let name: String -} - -/// A data model definition for creating an App Password. -public struct ServerCreateAppPasswordOutput: Codable { - /// The name given to the App Password to help distingush it from others. - /// - /// - Note: According to the AT Protocol specifications: "A short name for the App Password, to help distinguish them." - public let name: String - /// The password itself. - public let password: String - /// The date and time the App Password was created. - @DateFormatting public var createdAt: Date - - public init(name: String, password: String, createdAt: Date) { - self.name = name - self.password = password - self._createdAt = DateFormatting(wrappedValue: createdAt) - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.name = try container.decode(String.self, forKey: .name) - self.password = try container.decode(String.self, forKey: .password) - self.createdAt = try container.decode(DateFormatting.self.self, forKey: .createdAt).wrappedValue - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(self.name, forKey: .name) - try container.encode(self.password, forKey: .password) - try container.encode(self._createdAt, forKey: .createdAt) - } - - enum CodingKeys: CodingKey { - case name - case password - case createdAt - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerCreateInviteCode.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerCreateInviteCode.swift deleted file mode 100644 index 2f71167631..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerCreateInviteCode.swift +++ /dev/null @@ -1,38 +0,0 @@ -// -// AtprotoServerCreateInviteCode.swift -// -// -// Created by Christopher Jr Riley on 2024-02-24. -// - -import Foundation - -/// The main data model definition for creating an invite code. -/// -/// - Note: According to the AT Protocol specifications: "Create invite code." -/// -/// - SeeAlso: This is based on the [`com.atproto.server.createInviteCode`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/createInviteCode.json -public struct ServerCreateInviteCode: Codable { - /// The number of times the invite code(s) can be used. - public let useCount: Int - /// The decentralized identifier (DIDs) of the user that can use the invite code. Optional. - /// - /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ - /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ - /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ - /// \ - /// Clarifications from Bluesky are needed in order to fully understand this item. - public let forAccount: [String]? -} - -/// A data model definition of the output for creating an invite code. -/// -/// - SeeAlso: This is based on the [`com.atproto.server.createInviteCode`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/createInviteCode.json -public struct ServerCreateInviteCodeOutput: Codable { - /// An array of invite codes. - public let code: [String] -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerCreateInviteCodes.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerCreateInviteCodes.swift deleted file mode 100644 index 804b8b7073..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerCreateInviteCodes.swift +++ /dev/null @@ -1,58 +0,0 @@ -// -// AtprotoServerCreateInviteCodes.swift -// -// -// Created by Christopher Jr Riley on 2024-02-24. -// - -import Foundation - -/// The main data model definition for creating invite codes. -/// -/// - Note: According to the AT Protocol specifications: "Create invite codes." -/// -/// - SeeAlso: This is based on the [`com.atproto.server.createInviteCodes`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/createInviteCodes.json -public struct ServerCreateInviteCodes: Codable { - /// The number of invite codes to create. Defaults to 1. - public var codeCount: Int = 1 - /// The number of times the invite code(s) can be used. - public let useCount: Int - /// An array of decentralized identifiers (DIDs) that can use the invite codes. Optional. - /// - /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ - /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ - /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ - /// \ - /// Clarifications from Bluesky are needed in order to fully understand this item. - public let forAccounts: [String]? -} - -/// A data model definition of the output for creating invite codes. -/// -/// - SeeAlso: This is based on the [`com.atproto.server.createInviteCodes`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/createInviteCodes.json -public struct ServerCreateInviteCodesOutput: Codable { - /// An array of invite codes. - public let codes: [ServerAccountCodes] -} - -/// A data model definition of the server invite codes generated from ``ServerCreateInviteCodes``. -/// -/// - SeeAlso: This is based on the [`com.atproto.server.createInviteCodes`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/createInviteCodes.json -public struct ServerAccountCodes: Codable { - /// The account that holds the invite codes. - /// - /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ - /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ - /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ - /// \ - /// Clarifications from Bluesky are needed in order to fully understand this item. - public let account: String - /// An array of invite codes. - public let codes: [String] -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerCreateSession.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerCreateSession.swift deleted file mode 100644 index b4f87c8031..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerCreateSession.swift +++ /dev/null @@ -1,27 +0,0 @@ -// -// AtprotoServerCreateSession.swift -// -// -// Created by Christopher Jr Riley on 2024-02-07. -// - -import Foundation - -// MARK: - Main definition -/// The main data model definition for creating a session. -/// -/// - Note: According to the AT Protocol specifications: "Create an authentication session." -/// -/// - SeeAlso: This is based on the [`com.atproto.server.createSession`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/createSession.json -public struct SessionCredentials: Encodable { - /// The indentifier of the user's account (typically a handle). - /// - /// - Note: According to the AT Protocol specifications: "Handle or other identifier supported by the server for the authenticating user." - let identifier: String - /// The App Password of the user's account. - let password: String - /// A token used for Two-Factor Authentication. Optional. - let authenticationFactorToken: String? -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerDeactivateAccount.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerDeactivateAccount.swift deleted file mode 100644 index f5cadd6a1b..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerDeactivateAccount.swift +++ /dev/null @@ -1,43 +0,0 @@ -// -// AtprotoServerDeactivateAccount.swift -// -// -// Created by Christopher Jr Riley on 2024-02-24. -// - -import Foundation - -/// The main data model definition for deactivating an account. -/// -/// - Note: According to the AT Protocol specifications: "Deactivates a currently active account. Stops serving of repo, and future writes to repo until reactivated. Used to finalize account migration with the old host -/// after the account has been activated on the new host." -/// -/// - SeeAlso: This is based on the [`com.atproto.server.deactivateAccount`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/deactivateAccount.json -public struct ServerDeactivateAccount: Codable { - /// The date and time of when the server should delete the account. - /// - /// - Note: According to the AT Protocol specifications: "A recommendation to server as to how long they should hold onto the deactivated account before deleting." - @DateFormatting public var deleteAfter: Date - - public init(deleteAfter: Date) { - self._deleteAfter = DateFormatting(wrappedValue: deleteAfter) - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.deleteAfter = try container.decode(DateFormatting.self, forKey: .deleteAfter).wrappedValue - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - try container.encode(self.deleteAfter, forKey: .deleteAfter) - } - - enum CodingKeys: CodingKey { - case deleteAfter - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerDefs.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerDefs.swift deleted file mode 100644 index 9e2c6bbab5..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerDefs.swift +++ /dev/null @@ -1,99 +0,0 @@ -// -// AtprotoServerDefs.swift -// -// -// Created by Christopher Jr Riley on 2024-01-25. -// - -import Foundation - -// MARK: - Main definition -/// The main data model definition for a server invite code. -/// -/// - SeeAlso: This is based on the [`com.atproto.server.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/defs.json -public struct ServerInviteCode: Codable { - /// The actual invite code. - public let code: String - /// The number of codes available. - public let available: Int - /// Indicates whether the invite code is disabled. - public let isDisabled: Bool - /// The user who holds the invite codes. - public let forAccount: String - /// The name of the user who currently holds the account. - public let createdBy: String - /// The date and time the invite codes were created. - @DateFormatting public var createdAt: Date - /// An array of the invite code uses. - public let uses: [ServerInviteCodeUse] - - public init(code: String, available: Int, isDisabled: Bool, forAccount: String, createdBy: String, createdAt: Date, uses: [ServerInviteCodeUse]) { - self.code = code - self.available = available - self.isDisabled = isDisabled - self.forAccount = forAccount - self.createdBy = createdBy - self._createdAt = DateFormatting(wrappedValue: createdAt) - self.uses = uses - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.code = try container.decode(String.self, forKey: .code) - self.available = try container.decode(Int.self, forKey: .available) - self.isDisabled = try container.decode(Bool.self, forKey: .isDisabled) - self.forAccount = try container.decode(String.self, forKey: .forAccount) - self.createdBy = try container.decode(String.self, forKey: .createdBy) - self.createdAt = try container.decode(DateFormatting.self, forKey: .createdAt).wrappedValue - self.uses = try container.decode([ServerInviteCodeUse].self, forKey: .uses) - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - try container.encode(self.code, forKey: .code) - try container.encode(self.available, forKey: .available) - try container.encode(self.isDisabled, forKey: .isDisabled) - try container.encode(self.forAccount, forKey: .forAccount) - try container.encode(self.createdBy, forKey: .createdBy) - try container.encode(self._createdAt, forKey: .createdAt) - try container.encode(self.uses, forKey: .uses) - } - - enum CodingKeys: String, CodingKey { - case code - case available - case isDisabled = "disabled" - case forAccount - case createdBy - case createdAt - case uses - } -} - -/// A data model for a definition for the invite code's use. -/// -/// - SeeAlso: This is based on the [`com.atproto.server.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/defs.json -public struct ServerInviteCodeUse: Codable { - /// Who used the invite code. - public let usedBy: String - /// The date and time the service code was used. - @DateFormatting public var usedAt: Date - - public init(usedBy: String, usedAt: Date) { - self.usedBy = usedBy - self._usedAt = DateFormatting(wrappedValue: usedAt) - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.usedBy = try container.decode(String.self, forKey: .usedBy) - self.usedAt = try container.decode(DateFormatting.self, forKey: .usedAt).wrappedValue - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerDeleteAccount.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerDeleteAccount.swift deleted file mode 100644 index 2a7f1ea016..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerDeleteAccount.swift +++ /dev/null @@ -1,30 +0,0 @@ -// -// AtprotoServerDeleteAccount.swift -// -// -// Created by Christopher Jr Riley on 2024-02-24. -// - -import Foundation - -/// The main data model definition for deleting an account. -/// -/// - Note: According to the AT Protocol specifications: "Delete an actor's account with a token and password. Can only be called after requesting a deletion token. Requires auth." -/// -/// - SeeAlso: This is based on the [`com.atproto.server.deleteAccount`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/deleteAccount.json -public struct ServerDeleteAccount: Codable { - /// The decentralized identifier (DID) of the account. - public let accountDID: String - /// The main password of the account. - /// - /// - Note: This is not the App Password. - public let accountPassword: String - /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ - /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ - /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ - /// \ - /// Clarifications from Bluesky are needed in order to fully understand this item. - public let token: String -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerDescribeServer.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerDescribeServer.swift deleted file mode 100644 index 7c0755171a..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerDescribeServer.swift +++ /dev/null @@ -1,78 +0,0 @@ -// -// AtprotoServerDescribeServer.swift -// -// -// Created by Christopher Jr Riley on 2024-02-25. -// - -import Foundation - -/// A data model definition for the output of retrieving a description of the server. -/// -/// - Note: According to the AT Protocol specifications: "Describes the server's account creation requirements and capabilities. Implemented by PDS." -/// -/// - SeeAlso: This is based on the [`com.atproto.server.describeServer`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/describeServer.json -public struct ServerDescribeServerOutput: Codable { - /// Indicates whether an invite code is required to join the server. Optional. - /// - /// - Note: According to the AT Protocol specifications: "If true, an invite code must be supplied to create an account on this instance." - public let isInviteCodeRequired: Bool? - /// Indicates whether the user is required to verify using a phone number. Optional. - /// - /// - Note: According to the AT Protocol specifications: "If true, a phone verification token must be supplied to create an account on this instance." - public let isPhoneVerificationRequired: Bool? - /// An array of available user domains. - /// - /// - Note: According to the AT Protocol specifications: "List of domain suffixes that can be used in account handles." - public let availableUserDomains: [String] - /// A group of URLs for the server's service policies. Optional. - /// - /// - Note: According to the AT Protocol specifications: "URLs of service policy documents." - public let servicePolicyURLs: ServerServicePolicyURLs - /// The contact information for the server. - /// - /// - Note: According to the AT Protocol specifications: "Contact information." - public let contactInformation: ServerContactInformation - /// The decentralized identifier (DID) of the server. - public let serverDID: String - - enum CodingKeys: String, CodingKey { - case isInviteCodeRequired = "inviteCodeRequired" - case isPhoneVerificationRequired = "phoneVerificationRequired" - case availableUserDomains - case servicePolicyURLs = "links" - case contactInformation = "contact" - case serverDID = "did" - } -} - -/// A data model definition of service policy URLs. -/// -/// - Note: According to the AT Protocol specifications: "Describes the server's account creation requirements and capabilities. Implemented by PDS." -/// -/// - SeeAlso: This is based on the [`com.atproto.server.describeServer`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/describeServer.json -public struct ServerServicePolicyURLs: Codable { - /// The URL for the server's Privacy Policy. Optional. - public let privacyPolicyURL: URL? - /// The URL for the server's Terms of Service. Optional. - public let termsOfServiceURL: URL? - - enum CodingKeys: String, CodingKey { - case privacyPolicyURL = "privacyPolicy" - case termsOfServiceURL = "termsOfService" - } -} - -/// A data model definition of the server's contact information. -/// -/// - SeeAlso: This is based on the [`com.atproto.server.describeServer`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/describeServer.json -public struct ServerContactInformation: Codable { - /// The email address users can use to contact the server owner. - public let email: String -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerGetAccountInviteCodes.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerGetAccountInviteCodes.swift deleted file mode 100644 index 94de42c099..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerGetAccountInviteCodes.swift +++ /dev/null @@ -1,18 +0,0 @@ -// -// AtprotoServerGetAccountInviteCodes.swift -// -// -// Created by Christopher Jr Riley on 2024-02-25. -// - -import Foundation - -/// A data model definition for the output of getting the invite codes of the user's account. -/// -/// - SeeAlso: This is based on the [`com.atproto.server.getAccountInviteCodes`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/getAccountInviteCodes.json -public struct ServerGetAccountInviteCodesOutput: Codable { - /// An array of the user's invite codes. - public let code: [ServerInviteCode] -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerGetServiceAuth.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerGetServiceAuth.swift deleted file mode 100644 index 7b08c32630..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerGetServiceAuth.swift +++ /dev/null @@ -1,20 +0,0 @@ -// -// AtprotoServerGetServiceAuth.swift -// -// -// Created by Christopher Jr Riley on 2024-02-25. -// - -import Foundation - -/// A data model definition for the output of getting the signed token for the service. -/// -/// - Note: According to the AT Protocol specifications: "Get a signed token on behalf of the requesting DID for the requested service." -/// -/// - SeeAlso: This is based on the [`com.atproto.server.getServiceAuth`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/getServiceAuth.json -public struct ServerGetServiceAuthOutput: Codable { - /// The token for the requested service. - public let token: String -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerListAppPasswords.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerListAppPasswords.swift deleted file mode 100644 index 6f4f0c7e2b..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerListAppPasswords.swift +++ /dev/null @@ -1,56 +0,0 @@ -// -// AtprotoServerListAppPasswords.swift -// -// -// Created by Christopher Jr Riley on 2024-02-25. -// - -import Foundation - -/// A data model definition of the of listing App Passwords. -/// -/// - Note: According to the AT Protocol specifications: "List all App Passwords." -/// -/// - SeeAlso: This is based on the [`com.atproto.server.listAppPasswords`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/listAppPasswords.json -public struct ServerListAppPasswordsOutput: Codable { - /// An array of App Passwords. - public let passwords: [ServerAppPassword] -} - -/// A data model definition of App Password information. -/// -/// - SeeAlso: This is based on the [`com.atproto.server.listAppPasswords`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/listAppPasswords.json -public struct ServerAppPassword: Codable { - /// The name associated with the App Password. - public let name: String - /// The date and date the App Password was created. - @DateFormatting public var createdAt: Date - - public init(name: String, createdAt: Date) { - self.name = name - self._createdAt = DateFormatting(wrappedValue: createdAt) - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.name = try container.decode(String.self, forKey: .name) - self.createdAt = try container.decode(DateFormatting.self, forKey: .createdAt).wrappedValue - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - try container.encode(self.name, forKey: .name) - try container.encode(self._createdAt, forKey: .createdAt) - } - - enum CodingKeys: CodingKey { - case name - case createdAt - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerRequestEmailUpdate.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerRequestEmailUpdate.swift deleted file mode 100644 index 4edcf3310a..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerRequestEmailUpdate.swift +++ /dev/null @@ -1,24 +0,0 @@ -// -// AtprotoServerRequestEmailUpdate.swift -// -// -// Created by Christopher Jr Riley on 2024-02-26. -// - -import Foundation - -/// A data model definition for the output of requesting to update the user's email address. -/// -/// - Note: According to the AT Protocol specifications: "Request a token in order to update email." -/// -/// - SeeAlso: This is based on the [`com.atproto.server.requestEmailUpdate`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/requestEmailUpdate.json -public struct RequestEmailUpdateOutput: Codable { - /// Indicates whether a token is required. - public let isTokenRequired: Bool - - enum CodingKeys: String, CodingKey { - case isTokenRequired = "tokenRequired" - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerRequestPasswordReset.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerRequestPasswordReset.swift deleted file mode 100644 index a321fe1d09..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerRequestPasswordReset.swift +++ /dev/null @@ -1,20 +0,0 @@ -// -// AtprotoServerRequestPasswordReset.swift -// -// -// Created by Christopher Jr Riley on 2024-02-26. -// - -import Foundation - -/// The main data model definition for resetting the user's password. -/// -/// - Note: According to the AT Protocol specifications: "Initiate a user account password reset via email." -/// -/// - SeeAlso: This is based on the [`com.atproto.server.requestPasswordReset`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/requestPasswordReset.json -public struct ServerRequestPasswordReset: Codable { - /// The email address associated with the user's account. - public let email: String -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerReserveSigningKey.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerReserveSigningKey.swift deleted file mode 100644 index 50e4dde1b3..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerReserveSigningKey.swift +++ /dev/null @@ -1,39 +0,0 @@ -// -// AtprotoServerReserveSigningKey.swift -// -// -// Created by Christopher Jr Riley on 2024-02-25. -// - -import Foundation - -/// The main data model definition for reversing signing keys. -/// -/// - Note: According to the AT Protocol specifications: "Reserve a repo signing key, for use with account creation. Necessary so that a DID PLC update operation can be constructed during an account migraiton. -/// Public and does not require auth; implemented by PDS. NOTE: this endpoint may change when full account migration is implemented." -/// -/// - SeeAlso: This is based on the [`com.atproto.server.reserveSigningKey`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/reserveSigningKey.json -public struct ServerReserveSigningKey: Codable { - /// The decentralized identifier (DID) of the repository that will use the signing key. - /// - /// - Note: According to the AT Protocol specifications: "The DID to reserve a key for." - public let repositoryDID: String - - enum CodingKeys: String, CodingKey { - case repositoryDID = "did" - } -} - -/// A data model definition for the output of reversing a signing keys. -/// -/// - SeeAlso: This is based on the [`com.atproto.server.reserveSigningKey`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/reserveSigningKey.json -public struct ServerReserveSigningKeyOutput: Codable { - /// The signing key itself. - /// - /// - Note: According to the AT Protocol specifications: "The public key for the reserved signing key, in did:key serialization." - public let signingKey: String -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerResetPassword.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerResetPassword.swift deleted file mode 100644 index 9cf9992e11..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerResetPassword.swift +++ /dev/null @@ -1,27 +0,0 @@ -// -// AtprotoServerResetPassword.swift -// -// -// Created by Christopher Jr Riley on 2024-02-26. -// - -import Foundation - -/// The main data model definition for resetting a password. -/// -/// - Note: According to the AT Protocol specifications: "Reset a user account password using a token." -/// -/// - SeeAlso: This is based on the [`com.atproto.server.resetPassword`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/resetPassword.json -public struct ServerResetPassword: Codable { - /// The token used to reset the password. - public let token: String - /// The new password for the user's account. - public let newPassword: String - - enum CodingKeys: String, CodingKey { - case token - case newPassword = "password" - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerRevokeAppPassword.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerRevokeAppPassword.swift deleted file mode 100644 index 35a04507de..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerRevokeAppPassword.swift +++ /dev/null @@ -1,24 +0,0 @@ -// -// AtprotoServerRevokeAppPassword.swift -// -// -// Created by Christopher Jr Riley on 2024-02-27. -// - -import Foundation - -/// The main data model definition for revoking a password. -/// -/// - Note: According to the AT Protocol specifications: "Revoke an App Password by name." -/// -/// - SeeAlso: This is based on the [`com.atproto.server.revokeAppPassword`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/revokeAppPassword.json -public struct ServerRevokeAppPassword: Codable { - /// The name associated with the App Password. - public let appPasswordName: String - - enum CodingKeys: String, CodingKey { - case appPasswordName = "name" - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerUpdateEmail.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerUpdateEmail.swift deleted file mode 100644 index 110db608c2..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/AtprotoServerUpdateEmail.swift +++ /dev/null @@ -1,33 +0,0 @@ -// -// AtprotoServerUpdateEmail.swift -// -// -// Created by Christopher Jr Riley on 2024-02-27. -// - -import Foundation - -/// The main data model definition for updating the user's email address. -/// -/// - Note: According to the AT Protocol specifications: "Update an account's email." -/// -/// - SeeAlso: This is based on the [`com.atproto.server.updateEmail`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/updateEmail.json -public struct ServerUpdateEmail: Codable { - /// The email associated with the user's account. - public let email: String - /// Indicates whether Two-Factor Authentication (via email) is enabled. Optional. - public let isEmailAuthenticationFactorEnabled: Bool? - /// The token that's used if the email has been confirmed. Optional. - /// - /// - Note: According to the AT Protocol specifications: "Requires a token from com.atproto.sever.requestEmailUpdate if the account's email has - /// been confirmed." - public let token: String? - - enum CodingKeys: String, CodingKey { - case email - case isEmailAuthenticationFactorEnabled = "emailAuthFactor" - case token - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerActivateAccount.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerActivateAccount.swift new file mode 100644 index 0000000000..ae65bab4de --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerActivateAccount.swift @@ -0,0 +1,22 @@ +// +// ComAtprotoServerActivateAccount.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Server { + + /// A request body model for activating an account. + /// + /// - Note: According to the AT Protocol specifications: "Activates a currently deactivated + /// account. Used to finalize account migration after the account's repo is imported and + /// identity is setup." + /// + /// - SeeAlso: This is based on the [`com.atproto.server.activateAccount`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/activateAccount.json + public struct ActivateAccountRequestBody: Codable {} +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerCheckAccountStatus.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerCheckAccountStatus.swift new file mode 100644 index 0000000000..7a8a72d31d --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerCheckAccountStatus.swift @@ -0,0 +1,78 @@ +// +// ComAtprotoServerCheckAccountStatus.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Server { + + /// An output model for checking the user's account status. + /// + /// - Note: According to the AT Protocol specifications: "Returns the status of an account, + /// especially as pertaining to import or recovery. Can be called many times over the course + /// of an account migration. Requires auth and can only be called pertaining to oneself." + /// + /// - SeeAlso: This is based on the [`com.atproto.server.checkAccountStatus`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/checkAccountStatus.json + public struct CheckAccountStatusOutput: Codable { + + /// Indicates whether the user's account has been activated. + public let isActivated: Bool + + /// Indicates whether the user's account has a valid decentralized identifier (DID). + public let isValidDID: Bool + + /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ + /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ + /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ + /// \ + /// Clarifications from Bluesky are needed in order to fully understand this item. + public let repositoryCommit: String + + /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ + /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ + /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ + /// \ + /// Clarifications from Bluesky are needed in order to fully understand this item. + public let repositoryRev: String + + /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ + /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ + /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ + /// \ + /// Clarifications from Bluesky are needed in order to fully understand this item. + public let repositoryBlocks: Int + + /// The number of indexed records in the user's account. + public let indexedRecords: Int + + /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ + /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ + /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ + /// \ + /// Clarifications from Bluesky are needed in order to fully understand this item. + public let privateStateValues: Int + + /// The expected number of blobs in the user's account. + public let expectedBlobs: Int + + /// The number of blobs imported into the user's account. + public let importedBlobs: Int + + enum CodingKeys: String, CodingKey { + case isActivated = "activated" + case isValidDID = "validDid" + case repositoryCommit = "repoCommit" + case repositoryRev = "repoRev" + case repositoryBlocks = "repoBlocks" + case indexedRecords + case privateStateValues + case expectedBlobs + case importedBlobs + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerConfirmEmail.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerConfirmEmail.swift new file mode 100644 index 0000000000..421c10a804 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerConfirmEmail.swift @@ -0,0 +1,27 @@ +// +// ComAtprotoServerConfirmEmail.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Server { + + /// A request body model for confirming emails. + /// + /// - Note: According to the AT Protocol specifications: "Confirm an email using a token from com.atproto.server.requestEmailConfirmation." + /// + /// - SeeAlso: This is based on the [`com.atproto.server.confirmEmail`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/confirmEmail.json + public struct ConfirmEmailRequestBody: Codable { + + /// The email of the user. + public let email: String + + /// The token given to the user via email. + public let token: String + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerCreateAccount.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerCreateAccount.swift new file mode 100644 index 0000000000..8230705f7b --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerCreateAccount.swift @@ -0,0 +1,94 @@ +// +// ComAtprotoServerCreateAccount.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Server { + + /// A request body model for creating an account. + /// + /// - Note: According to the AT Protocol specifications: "Create an account. Implemented + /// by PDS." + /// + /// - SeeAlso: This is based on the [`com.atproto.server.createAccount`][github] lexicon. + /// + /// [github]: https://docs.bsky.app/docs/api/com-atproto-server-create-account + public struct CreateAccountRequestBody: Codable { + + /// The email of the user. Optional. + public var email: String? + + /// The handle the user wishes to use. + /// + /// - Note: According to the AT Protocol specifications: "Requested handle for + /// the account." + public let handle: String + + /// A decentralized identifier (DID) that has existed before and will be used to be + /// imported to the new account. Optional. + /// + /// - Note: According to the AT Protocol specifications: "Pre-existing atproto DID, being + /// imported to a new account." + public var existingDID: String? + + /// The invite code for the user. Optional. + /// + /// - Note: Invite codes are no longer used in Bluesky. This is left here for legacy + /// purposes, as well as for any federated networks that may use this feature. + public var inviteCode: String? + + /// A verification code. + public var verificationCode: String? + + /// A code that has come from a text message in the user's phone. Optional. + public var verificationPhone: String? + + /// The password the user will use for the account. Optional. + /// + /// - Note: According to the AT Protocol specifications: "Initial account password. + /// May need to meet instance-specific password strength requirements." + public var password: String? + + /// DID PLC rotation key (aka, recovery key) to be included in PLC + /// creation operation. Optional. + /// + /// - Note: The above documentation is taken directly from the AT Protocol apecifications. + public var recoveryKey: String? + + /// A signed DID PLC operation to be submitted as part of importing an existing account + /// to this instance. NOTE: this optional field may be updated when full account migration + /// is implemented. Optional. + /// + /// - Note: The above documentation is taken directly from the AT Protocol apecifications. + public var plcOp: UnknownType? + + public init(email: String?, handle: String, existingDID: String?, inviteCode: String?, verificationCode: String?, verificationPhone: String?, + password: String?, recoveryKey: String?, plcOp: UnknownType?) { + self.email = email + self.handle = handle + self.existingDID = existingDID + self.inviteCode = inviteCode + self.verificationCode = verificationCode + self.verificationPhone = verificationCode + self.password = password + self.recoveryKey = recoveryKey + self.plcOp = plcOp + } + + enum CodingKeys: String, CodingKey { + case email + case handle + case existingDID = "did" + case inviteCode + case verificationCode + case verificationPhone + case password + case recoveryKey + case plcOp + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerCreateAppPassword.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerCreateAppPassword.swift new file mode 100644 index 0000000000..a0549196f9 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerCreateAppPassword.swift @@ -0,0 +1,77 @@ +// +// ComAtprotoServerCreateAppPassword.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Server { + + /// A request body model for creating an App Password. + /// + /// - Note: According to the AT Protocol specifications: "Create an App Password." + /// + /// - SeeAlso: This is based on the [`com.atproto.server.createAppPassword`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/createAppPassword.json + public struct CreateAppPasswordRequestBody: Codable { + + /// The name given to the App Password to help distingush it from others. + /// + /// - Note: According to the AT Protocol specifications: "A short name for the + /// App Password, to help distinguish them." + public let name: String + } + + /// An output model for creating an App Password. + /// + /// - Note: According to the AT Protocol specifications: "Create an App Password." + /// + /// - SeeAlso: This is based on the [`com.atproto.server.createAppPassword`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/createAppPassword.json + public struct CreateAppPasswordOutput: Codable { + + /// The name given to the App Password to help distingush it from others. + /// + /// - Note: According to the AT Protocol specifications: "A short name for the + /// App Password, to help distinguish them." + public let name: String + + /// The password itself. + public let password: String + + /// The date and time the App Password was created. + @DateFormatting public var createdAt: Date + + public init(name: String, password: String, createdAt: Date) { + self.name = name + self.password = password + self._createdAt = DateFormatting(wrappedValue: createdAt) + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.name = try container.decode(String.self, forKey: .name) + self.password = try container.decode(String.self, forKey: .password) + self.createdAt = try container.decode(DateFormatting.self.self, forKey: .createdAt).wrappedValue + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.name, forKey: .name) + try container.encode(self.password, forKey: .password) + try container.encode(self._createdAt, forKey: .createdAt) + } + + enum CodingKeys: CodingKey { + case name + case password + case createdAt + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerCreateInviteCode.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerCreateInviteCode.swift new file mode 100644 index 0000000000..86ba4fc871 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerCreateInviteCode.swift @@ -0,0 +1,44 @@ +// +// ComAtprotoServerCreateInviteCode.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Server { + + /// A request body model for creating an invite code. + /// + /// - Note: According to the AT Protocol specifications: "Create invite code." + /// + /// - SeeAlso: This is based on the [`com.atproto.server.createInviteCode`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/createInviteCode.json + public struct CreateInviteCodeRequestBody: Codable { + + /// The number of times the invite code(s) can be used. + public let useCount: Int + + /// The decentralized identifier (DIDs) of the user that can use the invite code. Optional. + /// + /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ + /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ + /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ + /// \ + /// Clarifications from Bluesky are needed in order to fully understand this item. + public let forAccount: [String]? + } + + /// An output model for creating an invite code. + /// + /// - SeeAlso: This is based on the [`com.atproto.server.createInviteCode`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/createInviteCode.json + public struct CreateInviteCodeOutput: Codable { + + /// An array of invite codes. + public let code: [String] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerCreateInviteCodes.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerCreateInviteCodes.swift new file mode 100644 index 0000000000..676ec433ad --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerCreateInviteCodes.swift @@ -0,0 +1,67 @@ +// +// ComAtprotoServerCreateInviteCodes.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Server { + + /// A request body model for creating invite codes. + /// + /// - Note: According to the AT Protocol specifications: "Create invite codes." + /// + /// - SeeAlso: This is based on the [`com.atproto.server.createInviteCodes`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/createInviteCodes.json + public struct CreateInviteCodesRequestBody: Codable { + + /// The number of invite codes to create. Defaults to 1. + public var codeCount: Int = 1 + + /// The number of times the invite code(s) can be used. + public let useCount: Int + + /// An array of decentralized identifiers (DIDs) that can use the invite codes. Optional. + /// + /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ + /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ + /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ + /// \ + /// Clarifications from Bluesky are needed in order to fully understand this item. + public let forAccounts: [String]? + } + + /// An output model for creating invite codes. + /// + /// - SeeAlso: This is based on the [`com.atproto.server.createInviteCodes`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/createInviteCodes.json + public struct CreateInviteCodesOutput: Codable { + + /// An array of invite codes. + public let codes: [ServerAccountCodes] + } + + /// The server invite codes generated from ``ServerCreateInviteCodes``. + /// + /// - SeeAlso: This is based on the [`com.atproto.server.createInviteCodes`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/createInviteCodes.json + public struct ServerAccountCodes: Codable { + + /// The account that holds the invite codes. + /// + /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ + /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ + /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ + /// \ + /// Clarifications from Bluesky are needed in order to fully understand this item. + public let account: String + + /// An array of invite codes. + public let codes: [String] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerCreateSession.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerCreateSession.swift new file mode 100644 index 0000000000..343829eb39 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerCreateSession.swift @@ -0,0 +1,33 @@ +// +// ComAtprotoServerCreateSession.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Server { + + /// A request body model for creating a session. + /// + /// - Note: According to the AT Protocol specifications: "Create an authentication session." + /// + /// - SeeAlso: This is based on the [`com.atproto.server.createSession`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/createSession.json + public struct CreateSessionRequestBody: Encodable { + + /// The indentifier of the user's account (typically a handle). + /// + /// - Note: According to the AT Protocol specifications: "Handle or other identifier + /// supported by the server for the authenticating user." + let identifier: String + + /// The App Password of the user's account. + let password: String + + /// A token used for Two-Factor Authentication. Optional. + let authenticationFactorToken: String? + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerDeactivateAccount.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerDeactivateAccount.swift new file mode 100644 index 0000000000..3725e959b2 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerDeactivateAccount.swift @@ -0,0 +1,50 @@ +// +// ComAtprotoServerDeactivateAccount.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Server { + + /// A request body model for deactivating an account. + /// + /// - Note: According to the AT Protocol specifications: "Deactivates a currently + /// active account. Stops serving of repo, and future writes to repo until reactivated. + /// Used to finalize account migration with the old host after the account has been + /// activated on the new host." + /// + /// - SeeAlso: This is based on the [`com.atproto.server.deactivateAccount`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/deactivateAccount.json + public struct DeactivateAccountRequestBody: Codable { + + /// The date and time of when the server should delete the account. + /// + /// - Note: According to the AT Protocol specifications: "A recommendation to server as + /// to how long they should hold onto the deactivated account before deleting." + @DateFormatting public var deleteAfter: Date + + public init(deleteAfter: Date) { + self._deleteAfter = DateFormatting(wrappedValue: deleteAfter) + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.deleteAfter = try container.decode(DateFormatting.self, forKey: .deleteAfter).wrappedValue + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.deleteAfter, forKey: .deleteAfter) + } + + enum CodingKeys: CodingKey { + case deleteAfter + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerDefs.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerDefs.swift new file mode 100644 index 0000000000..81a828784f --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerDefs.swift @@ -0,0 +1,111 @@ +// +// ComAtprotoServerDefs.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Server { + + /// A definition model for a server invite code. + /// + /// - SeeAlso: This is based on the [`com.atproto.server.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/defs.json + public struct InviteCodeDefinition: Codable { + + /// The actual invite code. + public let code: String + + /// The number of codes available. + public let available: Int + + /// Indicates whether the invite code is disabled. + public let isDisabled: Bool + + /// The user who holds the invite codes. + public let forAccount: String + + /// The name of the user who currently holds the account. + public let createdBy: String + + /// The date and time the invite codes were created. + @DateFormatting public var createdAt: Date + + /// An array of the invite code uses. + public let uses: [ComAtprotoLexicon.Server.InviteCodeUseDefinition] + + public init(code: String, available: Int, isDisabled: Bool, forAccount: String, createdBy: String, createdAt: Date, + uses: [ComAtprotoLexicon.Server.InviteCodeUseDefinition]) { + self.code = code + self.available = available + self.isDisabled = isDisabled + self.forAccount = forAccount + self.createdBy = createdBy + self._createdAt = DateFormatting(wrappedValue: createdAt) + self.uses = uses + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.code = try container.decode(String.self, forKey: .code) + self.available = try container.decode(Int.self, forKey: .available) + self.isDisabled = try container.decode(Bool.self, forKey: .isDisabled) + self.forAccount = try container.decode(String.self, forKey: .forAccount) + self.createdBy = try container.decode(String.self, forKey: .createdBy) + self.createdAt = try container.decode(DateFormatting.self, forKey: .createdAt).wrappedValue + self.uses = try container.decode([ComAtprotoLexicon.Server.InviteCodeUseDefinition].self, forKey: .uses) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.code, forKey: .code) + try container.encode(self.available, forKey: .available) + try container.encode(self.isDisabled, forKey: .isDisabled) + try container.encode(self.forAccount, forKey: .forAccount) + try container.encode(self.createdBy, forKey: .createdBy) + try container.encode(self._createdAt, forKey: .createdAt) + try container.encode(self.uses, forKey: .uses) + } + + enum CodingKeys: String, CodingKey { + case code + case available + case isDisabled = "disabled" + case forAccount + case createdBy + case createdAt + case uses + } + } + + /// A definition model for the invite code's use. + /// + /// - SeeAlso: This is based on the [`com.atproto.server.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/defs.json + public struct InviteCodeUseDefinition: Codable { + + /// Who used the invite code. + public let usedBy: String + + /// The date and time the service code was used. + @DateFormatting public var usedAt: Date + + public init(usedBy: String, usedAt: Date) { + self.usedBy = usedBy + self._usedAt = DateFormatting(wrappedValue: usedAt) + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.usedBy = try container.decode(String.self, forKey: .usedBy) + self.usedAt = try container.decode(DateFormatting.self, forKey: .usedAt).wrappedValue + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerDeleteAccount.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerDeleteAccount.swift new file mode 100644 index 0000000000..6ba02ff1e2 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerDeleteAccount.swift @@ -0,0 +1,37 @@ +// +// ComAtprotoServerDeleteAccount.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Server { + + /// A request body model for deleting an account. + /// + /// - Note: According to the AT Protocol specifications: "Delete an actor's account with a + /// token and password. Can only be called after requesting a deletion token. Requires auth." + /// + /// - SeeAlso: This is based on the [`com.atproto.server.deleteAccount`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/deleteAccount.json + public struct DeleteAccountRequestBody: Codable { + + /// The decentralized identifier (DID) of the account. + public let accountDID: String + + /// The main password of the account. + /// + /// - Note: This is not the App Password. + public let accountPassword: String + + /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ + /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ + /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ + /// \ + /// Clarifications from Bluesky are needed in order to fully understand this item. + public let token: String + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerDescribeServer.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerDescribeServer.swift new file mode 100644 index 0000000000..260e3c8505 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerDescribeServer.swift @@ -0,0 +1,100 @@ +// +// ComAtprotoServerDescribeServer.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Server { + + /// A data model for etrieving a description of the server. + public struct DescribeServer: Codable { + + /// A data model of service policy URLs. + /// + /// - Note: According to the AT Protocol specifications: "Describes the server's account + /// creation requirements and capabilities. Implemented by PDS." + /// + /// - SeeAlso: This is based on the [`com.atproto.server.describeServer`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/describeServer.json + public struct ServicePolicyURLs: Codable { + + /// The URL for the server's Privacy Policy. Optional. + public let privacyPolicyURL: URL? + + /// The URL for the server's Terms of Service. Optional. + public let termsOfServiceURL: URL? + + enum CodingKeys: String, CodingKey { + case privacyPolicyURL = "privacyPolicy" + case termsOfServiceURL = "termsOfService" + } + } + + /// A data model definition of the server's contact information. + /// + /// - SeeAlso: This is based on the [`com.atproto.server.describeServer`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/describeServer.json + public struct ContactInformation: Codable { + + /// The email address users can use to contact the server owner. + public let email: String + } + } + + /// An output model for retrieving a description of the server. + /// + /// - Note: According to the AT Protocol specifications: "Describes the server's account + /// creation requirements and capabilities. Implemented by PDS." + /// + /// - SeeAlso: This is based on the [`com.atproto.server.describeServer`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/describeServer.json + public struct DescribeServerOutput: Codable { + + /// Indicates whether an invite code is required to join the server. Optional. + /// + /// - Note: According to the AT Protocol specifications: "If true, an invite code must + /// be supplied to create an account on this instance." + public let isInviteCodeRequired: Bool? + + /// Indicates whether the user is required to verify using a phone number. Optional. + /// + /// - Note: According to the AT Protocol specifications: "If true, a phone verification + /// token must be supplied to create an account on this instance." + public let isPhoneVerificationRequired: Bool? + + /// An array of available user domains. + /// + /// - Note: According to the AT Protocol specifications: "List of domain suffixes that + /// can be used in account handles." + public let availableUserDomains: [String] + + /// A group of URLs for the server's service policies. Optional. + /// + /// - Note: According to the AT Protocol specifications: "URLs of service + /// policy documents." + public let servicePolicyURLs: DescribeServer.ServicePolicyURLs + + /// The contact information for the server. + /// + /// - Note: According to the AT Protocol specifications: "Contact information." + public let contactInformation: DescribeServer.ContactInformation + + /// The decentralized identifier (DID) of the server. + public let serverDID: String + + enum CodingKeys: String, CodingKey { + case isInviteCodeRequired = "inviteCodeRequired" + case isPhoneVerificationRequired = "phoneVerificationRequired" + case availableUserDomains + case servicePolicyURLs = "links" + case contactInformation = "contact" + case serverDID = "did" + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerGetAccountInviteCodes.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerGetAccountInviteCodes.swift new file mode 100644 index 0000000000..9a37494787 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerGetAccountInviteCodes.swift @@ -0,0 +1,22 @@ +// +// ComAtprotoServerGetAccountInviteCodes.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Server { + + /// An output model for getting the invite codes of the user's account. + /// + /// - SeeAlso: This is based on the [`com.atproto.server.getAccountInviteCodes`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/getAccountInviteCodes.json + public struct GetAccountInviteCodesOutput: Codable { + + /// An array of the user's invite codes. + public let code: [ComAtprotoLexicon.Server.InviteCodeDefinition] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerGetServiceAuth.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerGetServiceAuth.swift new file mode 100644 index 0000000000..eb7a51041c --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerGetServiceAuth.swift @@ -0,0 +1,25 @@ +// +// ComAtprotoServerGetServiceAuth.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Server { + + /// An output model for getting the signed token for the service. + /// + /// - Note: According to the AT Protocol specifications: "Get a signed token on behalf of the + /// requesting DID for the requested service." + /// + /// - SeeAlso: This is based on the [`com.atproto.server.getServiceAuth`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/getServiceAuth.json + public struct GetServiceAuthOutput: Codable { + + /// The token for the requested service. + public let token: String + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerListAppPasswords.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerListAppPasswords.swift new file mode 100644 index 0000000000..676261a25c --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerListAppPasswords.swift @@ -0,0 +1,62 @@ +// +// ComAtprotoServerListAppPasswords.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Server { + + /// An output model for listing App Passwords. + /// + /// - Note: According to the AT Protocol specifications: "List all App Passwords." + /// + /// - SeeAlso: This is based on the [`com.atproto.server.listAppPasswords`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/listAppPasswords.json + public struct ListAppPasswordsOutput: Codable { + + /// An array of App Passwords. + public let passwords: [AppPassword] + + /// An App Password. + /// + /// - SeeAlso: This is based on the [`com.atproto.server.listAppPasswords`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/listAppPasswords.json + public struct AppPassword: Codable { + + /// The name associated with the App Password. + public let name: String + + /// The date and date the App Password was created. + @DateFormatting public var createdAt: Date + + public init(name: String, createdAt: Date) { + self.name = name + self._createdAt = DateFormatting(wrappedValue: createdAt) + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.name = try container.decode(String.self, forKey: .name) + self.createdAt = try container.decode(DateFormatting.self, forKey: .createdAt).wrappedValue + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.name, forKey: .name) + try container.encode(self._createdAt, forKey: .createdAt) + } + + enum CodingKeys: CodingKey { + case name + case createdAt + } + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerRequestEmailUpdate.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerRequestEmailUpdate.swift new file mode 100644 index 0000000000..5d404fa0aa --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerRequestEmailUpdate.swift @@ -0,0 +1,29 @@ +// +// ComAtprotoServerRequestEmailUpdate.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Server { + + /// An output model for requesting to update the user's email address. + /// + /// - Note: According to the AT Protocol specifications: "Request a token in order to + /// update email." + /// + /// - SeeAlso: This is based on the [`com.atproto.server.requestEmailUpdate`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/requestEmailUpdate.json + public struct RequestEmailUpdateOutput: Codable { + + /// Indicates whether a token is required. + public let isTokenRequired: Bool + + enum CodingKeys: String, CodingKey { + case isTokenRequired = "tokenRequired" + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerRequestPasswordReset.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerRequestPasswordReset.swift new file mode 100644 index 0000000000..61d99fb8aa --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerRequestPasswordReset.swift @@ -0,0 +1,25 @@ +// +// ComAtprotoServerRequestPasswordReset.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Server { + + /// A request body model for resetting the user's password. + /// + /// - Note: According to the AT Protocol specifications: "Initiate a user account password + /// reset via email." + /// + /// - SeeAlso: This is based on the [`com.atproto.server.requestPasswordReset`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/requestPasswordReset.json + public struct RequestPasswordResetRequestBody: Codable { + + /// The email address associated with the user's account. + public let email: String + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerReserveSigningKey.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerReserveSigningKey.swift new file mode 100644 index 0000000000..1cd60fc740 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerReserveSigningKey.swift @@ -0,0 +1,45 @@ +// +// ComAtprotoServerReserveSigningKey.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Server { + + /// A request body model for reversing signing keys. + /// + /// - Note: According to the AT Protocol specifications: "Reserve a repo signing key, for + /// use with account creation. Necessary so that a DID PLC update operation can be constructed + /// during an account migraiton. Public and does not require auth; implemented by PDS. + /// NOTE: this endpoint may change when full account migration is implemented." + /// + /// - SeeAlso: This is based on the [`com.atproto.server.reserveSigningKey`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/reserveSigningKey.json + public struct ReserveSigningKeyRequestBody: Codable { + /// The decentralized identifier (DID) of the repository that will use the signing key. + /// + /// - Note: According to the AT Protocol specifications: "The DID to reserve a key for." + public let repositoryDID: String + + enum CodingKeys: String, CodingKey { + case repositoryDID = "did" + } + } + + /// An output model for reversing signing keys. + /// + /// - SeeAlso: This is based on the [`com.atproto.server.reserveSigningKey`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/reserveSigningKey.json + public struct ReserveSigningKeyOutput: Codable { + /// The signing key itself. + /// + /// - Note: According to the AT Protocol specifications: "The public key for the reserved + /// signing key, in did:key serialization." + public let signingKey: String + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerResetPassword.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerResetPassword.swift new file mode 100644 index 0000000000..c09959f582 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerResetPassword.swift @@ -0,0 +1,32 @@ +// +// ComAtprotoServerResetPassword.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Server { + + /// A request body model for resetting a password. + /// + /// - Note: According to the AT Protocol specifications: "Reset a user account password using a token." + /// + /// - SeeAlso: This is based on the [`com.atproto.server.resetPassword`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/resetPassword.json + public struct ResetPasswordRequestBody: Codable { + + /// The token used to reset the password. + public let token: String + + /// The new password for the user's account. + public let newPassword: String + + enum CodingKeys: String, CodingKey { + case token + case newPassword = "password" + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerRevokeAppPassword.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerRevokeAppPassword.swift new file mode 100644 index 0000000000..7edc5156a3 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerRevokeAppPassword.swift @@ -0,0 +1,28 @@ +// +// ComAtprotoServerRevokeAppPassword.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Server { + +/// A request body model for revoking a password. + /// + /// - Note: According to the AT Protocol specifications: "Revoke an App Password by name." + /// + /// - SeeAlso: This is based on the [`com.atproto.server.revokeAppPassword`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/revokeAppPassword.json + public struct RevokeAppPasswordRequestBody: Codable { + + /// The name associated with the App Password. + public let appPasswordName: String + + enum CodingKeys: String, CodingKey { + case appPasswordName = "name" + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerUpdateEmail.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerUpdateEmail.swift new file mode 100644 index 0000000000..cf52421465 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Server/ComAtprotoServerUpdateEmail.swift @@ -0,0 +1,39 @@ +// +// ComAtprotoServerUpdateEmail.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Server { + + /// A request body model for updating the user's email address. + /// + /// - Note: According to the AT Protocol specifications: "Update an account's email." + /// + /// - SeeAlso: This is based on the [`com.atproto.server.updateEmail`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/updateEmail.json + public struct UpdateEmailRequestBody: Codable { + + /// The email associated with the user's account. + public let email: String + + /// Indicates whether Two-Factor Authentication (via email) is enabled. Optional. + public let isEmailAuthenticationFactorEnabled: Bool? + + /// The token that's used if the email has been confirmed. Optional. + /// + /// - Note: According to the AT Protocol specifications: "Requires a token from com.atproto.sever.requestEmailUpdate if the account's email has + /// been confirmed." + public let token: String? + + enum CodingKeys: String, CodingKey { + case email + case isEmailAuthenticationFactorEnabled = "emailAuthFactor" + case token + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/AtprotoSyncCrawler.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/AtprotoSyncCrawler.swift deleted file mode 100644 index 291fcd0696..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/AtprotoSyncCrawler.swift +++ /dev/null @@ -1,36 +0,0 @@ -// -// AtprotoSyncCrawler.swift -// -// -// Created by Christopher Jr Riley on 2024-03-14. -// - -import Foundation - -/// The main data model definition for the crawling service. -/// -/// - Note: According to the AT Protocol specifications:\ -/// `com.atproto.sync.notifyOfUpdate`: "Notify a crawling service of a recent update, and that -/// crawling should resume. Intended use is after a gap between repo stream events caused the -/// crawling service to disconnect. Does not require auth; implemented by Relay." \ -/// \ -/// `com.atproto.sync.requestCrawl`: "Request a service to persistently crawl hosted repos. -/// Expected use is new PDS instances declaring their existence to Relays. Does not require auth." -/// -/// - SeeAlso: This is based on the following lexicons:\ -/// \- [`com.atproto.sync.notifyOfUpdate`][notifyOfUpdate]\ -/// \- [`com.atproto.sync.requestCrawl`][requestCrawl] -/// -/// [notifyOfUpdate]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/sync/notifyOfUpdate.json -/// [requestCrawl]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/sync/requestCrawl.json -public struct SyncCrawler: Codable { - /// The hostname that the crawling service resides in. - /// - /// - Note: According to the AT Protocol specifications: "Hostname of the current service - /// (usually a PDS) that is notifying of update." - public let crawlingHostname: URL - - enum CodingKeys: String, CodingKey { - case crawlingHostname = "hostname" - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/AtprotoSyncGetBlob.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/AtprotoSyncGetBlob.swift deleted file mode 100644 index 82223dd76a..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/AtprotoSyncGetBlob.swift +++ /dev/null @@ -1,36 +0,0 @@ -// -// AtprotoSyncGetBlob.swift -// -// -// Created by Christopher Jr Riley on 2024-02-10. -// - -import Foundation - -// MARK: - Main definition -/// The main data model definition for getting a blob. -/// -/// - Note: According to the AT Protocol specifications: "Get a blob associated with a -/// given account. Returns the full blob as originally uploaded. Does not require auth; -/// implemented by PDS." -/// -/// - SeeAlso: This is based on the [`com.atproto.sync.getBlob`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/sync/getBlob.json -public struct BlobQuery: Encodable { - /// The decentralized identifier (DID) of the user's account. - /// - /// - Note: According to the AT Protocol specifications: "The DID of the account." - public let accountDID: String - /// The CID hash of the blob. - /// - /// - Note: According to the AT Protocol specifications: "The CID of the blob to fetch." - /// - Note: Make sure to use `BlobReference.link` if you're grabbing it straight - /// from ``UploadBlobOutput``. - public let cidHash: String - - public init(accountDID: String, cidHash: String) { - self.accountDID = accountDID - self.cidHash = cidHash - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/AtprotoSyncGetBlocks.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/AtprotoSyncGetBlocks.swift deleted file mode 100644 index 7703ae7fc6..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/AtprotoSyncGetBlocks.swift +++ /dev/null @@ -1,29 +0,0 @@ -// -// AtprotoSyncGetBlocks.swift -// -// -// Created by Christopher Jr Riley on 2024-03-12. -// - -import Foundation - -/// The main data model definition for the output of getting a repository's blocks. -/// -/// - Note: According to the AT Protocol specifications: "Get data blocks from a given repo, by -/// CID. For example, intermediate MST nodes, or records. Does not require auth; implemented -/// by PDS." -/// -/// - SeeAlso: This is based on the [`com.atproto.sync.getBlocks`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/sync/getBlocks.json -public struct SyncGetBlocksOutput: Codable { - /// The decentralized identifier (DID) of the repository. - public let repositoryDID: String - /// An array of CID hashes from the repository. - public let repositoryCIDHashes: [String] - - enum CodingKeys: String, CodingKey { - case repositoryDID = "did" - case repositoryCIDHashes = "cids" - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/AtprotoSyncGetLatestCommit.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/AtprotoSyncGetLatestCommit.swift deleted file mode 100644 index e4ada303ee..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/AtprotoSyncGetLatestCommit.swift +++ /dev/null @@ -1,28 +0,0 @@ -// -// AtprotoSyncGetLatestCommit.swift -// -// -// Created by Christopher Jr Riley on 2024-03-12. -// - -import Foundation - -/// The main data model definition for the output of getting a repository's latest commit CID. -/// -/// - Note: According to the AT Protocol specifications: "Get the current commit CID & revision -/// of the specified repo. Does not require auth." -/// -/// - SeeAlso: This is based on the [`com.atproto.sync.getLatestCommit`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/sync/getLatestCommit.json -public struct SyncGetLatestCommitOutput: Codable { - /// The commit CID of the repository. - public let commitCID: String - /// The repository's revision. - public let revision: String - - enum CodingKeys: String, CodingKey { - case commitCID = "cid" - case revision = "rev" - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/AtprotoSyncListBlobs.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/AtprotoSyncListBlobs.swift deleted file mode 100644 index 0710fccf02..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/AtprotoSyncListBlobs.swift +++ /dev/null @@ -1,28 +0,0 @@ -// -// AtprotoSyncListBlobs.swift -// -// -// Created by Christopher Jr Riley on 2024-03-13. -// - -import Foundation - -/// The main data model definition for the output of a user account's blob CID hashes. -/// -/// - Note: According to the AT Protocol specifications: "List blob CIDs for an account, since -/// some repo revision. Does not require auth; implemented by PDS." -/// -/// - SeeAlso: This is based on the [`com.atproto.sync.listBlobs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/sync/listBlobs.json -public struct SyncListBlobsOutput: Codable { - /// The mark used to indicate the starting point for the next set of results. Optional. - public let cursor: String? - /// An array of CID hashes from a user account. - public let accountCIDHashes: [String] - - enum CodingKeys: String, CodingKey { - case cursor - case accountCIDHashes = "cids" - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/AtprotoSyncListRepos.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/AtprotoSyncListRepos.swift deleted file mode 100644 index 2af96b731c..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/AtprotoSyncListRepos.swift +++ /dev/null @@ -1,48 +0,0 @@ -// -// AtprotoSyncListRepos.swift -// -// -// Created by Christopher Jr Riley on 2024-03-14. -// - -import Foundation - -/// The main data model definition for the output of listing all decentralized identifiers (DIDs), -/// revisions, and commit CID hashes of given repositiories. -/// -/// - Note: According to the AT Protocol specifications: "Enumerates all the DID, rev, and commit -/// CID for all repos hosted by this service. Does not require auth; -/// implemented by PDS and Relay." -/// -/// - SeeAlso: This is based on the [`com.atproto.sync.listRepos`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/sync/listRepos.json -public struct SyncListReposOutput: Codable { - /// The mark used to indicate the starting point for the next set of results. Optional. - public let cursor: String? - /// An array of repositories. - public let repositories: [SyncRepository] - - enum CodingKeys: String, CodingKey { - case cursor - case repositories = "repos" - } -} - -/// A data model definition for a repository. -public struct SyncRepository: Codable { - /// The decentralized identifier (DID) of the repository. - public let repositoryDID: String - /// The commit CID hash of the repository. - /// - /// - Note: According to the AT Protocol specifications: "Current repo commit CID." - public let commitCID: String - /// The repository's revision. - public let revision: String - - enum CodingKeys: String, CodingKey { - case repositoryDID = "did" - case commitCID = "head" - case revision = "rev" - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/AtprotoSyncSubscribeRepos.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/AtprotoSyncSubscribeRepos.swift deleted file mode 100644 index c4266d57b2..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/AtprotoSyncSubscribeRepos.swift +++ /dev/null @@ -1,23 +0,0 @@ -// -// AtprotoSyncSubscribeRepos.swift -// -// -// Created by Christopher Jr Riley on 2024-03-14. -// - -import Foundation - -/// The main data model definition for the firehose service. -/// -/// - Note: According to the AT Protocol specifications: "Repository event stream, aka Firehose -/// endpoint. Outputs repo commits with diff data, and identity update events, for all repositories -/// on the current server. See the atproto specifications for details around stream sequencing, -/// repo versioning, CAR diff format, and more. Public and does not require auth; implemented -/// by PDS and Relay." -/// -/// - SeeAlso: This is based on the [`com.atproto.sync.subscribeRepos`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/sync/subscribeRepos.json -public struct SyncSubscribeRepos: Codable { - -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/ComAtprotoSyncCrawler.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/ComAtprotoSyncCrawler.swift new file mode 100644 index 0000000000..9455d5fd0e --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/ComAtprotoSyncCrawler.swift @@ -0,0 +1,40 @@ +// +// ComAtprotoSyncCrawler.swift +// +// +// Created by Christopher Jr Riley on 2024-05-23. +// + +import Foundation + +extension ComAtprotoLexicon.Sync { + + /// A request body model for the crawling service. + /// + /// - Note: According to the AT Protocol specifications:\ + /// `com.atproto.sync.notifyOfUpdate`: "Notify a crawling service of a recent update, and that + /// crawling should resume. Intended use is after a gap between repo stream events caused the + /// crawling service to disconnect. Does not require auth; implemented by Relay." \ + /// \ + /// `com.atproto.sync.requestCrawl`: "Request a service to persistently crawl hosted repos. + /// Expected use is new PDS instances declaring their existence to Relays. Does not require auth." + /// + /// - SeeAlso: This is based on the following lexicons:\ + /// \- [`com.atproto.sync.notifyOfUpdate`][notifyOfUpdate]\ + /// \- [`com.atproto.sync.requestCrawl`][requestCrawl] + /// + /// [notifyOfUpdate]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/sync/notifyOfUpdate.json + /// [requestCrawl]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/sync/requestCrawl.json + public struct Crawler: Codable { + + /// The hostname that the crawling service resides in. + /// + /// - Note: According to the AT Protocol specifications: "Hostname of the current service + /// (usually a PDS) that is notifying of update." + public let crawlingHostname: URL + + enum CodingKeys: String, CodingKey { + case crawlingHostname = "hostname" + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/ComAtprotoSyncGetBlob.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/ComAtprotoSyncGetBlob.swift new file mode 100644 index 0000000000..70e4027649 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/ComAtprotoSyncGetBlob.swift @@ -0,0 +1,22 @@ +// +// ComAtprotoSyncGetBlob.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Sync { + + /// A request body model for getting a blob. + /// + /// - Note: According to the AT Protocol specifications: "Get a blob associated with a + /// given account. Returns the full blob as originally uploaded. Does not require auth; + /// implemented by PDS." + /// + /// - SeeAlso: This is based on the [`com.atproto.sync.getBlob`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/sync/getBlob.json + public struct GetBlobOutput: Decodable {} +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/ComAtprotoSyncGetBlocks.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/ComAtprotoSyncGetBlocks.swift new file mode 100644 index 0000000000..af9bae8948 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/ComAtprotoSyncGetBlocks.swift @@ -0,0 +1,22 @@ +// +// ComAtprotoSyncGetBlocks.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Sync { + + /// The main data model definition for the output of getting a repository's blocks. + /// + /// - Note: According to the AT Protocol specifications: "Get data blocks from a given repo, by + /// CID. For example, intermediate MST nodes, or records. Does not require auth; implemented + /// by PDS." + /// + /// - SeeAlso: This is based on the [`com.atproto.sync.getBlocks`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/sync/getBlocks.json + public struct GetBlocksOutput: Codable {} +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/ComAtprotoSyncGetLatestCommit.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/ComAtprotoSyncGetLatestCommit.swift new file mode 100644 index 0000000000..4eb4b4b5e7 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/ComAtprotoSyncGetLatestCommit.swift @@ -0,0 +1,33 @@ +// +// ComAtprotoSyncGetLatestCommit.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Sync { + + /// An output model for getting a repository's latest commit CID. + /// + /// - Note: According to the AT Protocol specifications: "Get the current commit CID & revision + /// of the specified repo. Does not require auth." + /// + /// - SeeAlso: This is based on the [`com.atproto.sync.getLatestCommit`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/sync/getLatestCommit.json + public struct GetLatestCommitOutput: Codable { + + /// The commit CID of the repository. + public let commitCID: String + + /// The repository's revision. + public let revision: String + + enum CodingKeys: String, CodingKey { + case commitCID = "cid" + case revision = "rev" + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/ComAtprotoSyncGetRepoStatus.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/ComAtprotoSyncGetRepoStatus.swift new file mode 100644 index 0000000000..550da207a6 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/ComAtprotoSyncGetRepoStatus.swift @@ -0,0 +1,69 @@ +// +// ComAtprotoSyncGetRepoStatus.swift +// +// +// Created by Christopher Jr Riley on 2024-05-31. +// + +import Foundation + +extension ComAtprotoLexicon.Sync { + + /// The main data model definition for getting the status for a repository in the + /// Personal Data Server (PDS). + /// + /// - Note: According to the AT Protocol specifications: "Get the hosting status for a + /// repository, on this server. Expected to be implemented by PDS and Relay." + /// + /// - SeeAlso: This is based on the [`com.atproto.sync.getRepoStatus`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/sync/getRepoStatus.json + public struct GetRepositoryStatus: Codable { + + /// The status of the repository. + public enum Status: String, Codable { + + /// Indicates the repository has been taken down. + case takedown + + /// Indicates the repository has been suspended. + case suspended + + /// Indicates the repository has been deactivated. + case deactivated + } + } + + /// An output model for getting the status for a repository in the Personal Data Server (PDS). + /// + /// - Note: According to the AT Protocol specifications: "Get the hosting status for a + /// repository, on this server. Expected to be implemented by PDS and Relay." + /// + /// - SeeAlso: This is based on the [`com.atproto.sync.getRepoStatus`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/sync/getRepoStatus.json + public struct GetRepositoryStatusOutput: Codable { + + /// The decentralized identifier (DID) of the repository. + public let repositoryDID: String + + /// Indicates whether the repository is active. + public let isActive: Bool + + /// The status of the repository. Optional. + public let status: GetRepositoryStatus.Status + + /// The revision of the repository. + /// + /// - Note: According to the AT Protocol specifications: "Optional field, the current rev + /// of the repo, if active=true" + public let revision: String + + enum CodingKeys: String, CodingKey { + case repositoryDID = "did" + case isActive = "active" + case status + case revision = "rev" + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/ComAtprotoSyncListBlobs.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/ComAtprotoSyncListBlobs.swift new file mode 100644 index 0000000000..8be794757d --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/ComAtprotoSyncListBlobs.swift @@ -0,0 +1,33 @@ +// +// ComAtprotoSyncListBlobs.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Sync { + + /// An output model for a user account's blob CID hashes. + /// + /// - Note: According to the AT Protocol specifications: "List blob CIDs for an account, since + /// some repo revision. Does not require auth; implemented by PDS." + /// + /// - SeeAlso: This is based on the [`com.atproto.sync.listBlobs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/sync/listBlobs.json + public struct ListBlobsOutput: Codable { + + /// The mark used to indicate the starting point for the next set of results. Optional. + public let cursor: String? + + /// An array of CID hashes from a user account. + public let accountCIDHashes: [String] + + enum CodingKeys: String, CodingKey { + case cursor + case accountCIDHashes = "cids" + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/ComAtprotoSyncListRepos.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/ComAtprotoSyncListRepos.swift new file mode 100644 index 0000000000..f6f38bb485 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/ComAtprotoSyncListRepos.swift @@ -0,0 +1,57 @@ +// +// ComAtprotoSyncListRepos.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Sync { + + /// An output model for isting all decentralized identifiers (DIDs), revisions, and + /// commit CID hashes of given repositiories. + /// + /// - Note: According to the AT Protocol specifications: "Enumerates all the DID, rev, and + /// commit CID for all repos hosted by this service. Does not require auth; + /// implemented by PDS and Relay." + /// + /// - SeeAlso: This is based on the [`com.atproto.sync.listRepos`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/sync/listRepos.json + public struct ListRepositoriesOutput: Codable { + + /// The mark used to indicate the starting point for the next set of results. Optional. + public let cursor: String? + + /// An array of repositories. + public let repositories: [Repository] + + enum CodingKeys: String, CodingKey { + case cursor + case repositories = "repo" + } + + // Enums + /// A data model definition for a repository. + public struct Repository: Codable { + + /// The decentralized identifier (DID) of the repository. + public let repositoryDID: String + + /// The commit CID hash of the repository. + /// + /// - Note: According to the AT Protocol specifications: "Current repo commit CID." + public let commitCID: String + + /// The repository's revision. + public let revision: String + + enum CodingKeys: String, CodingKey { + case repositoryDID = "did" + case commitCID = "head" + case revision = "rev" + } + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/ComAtprotoSyncSubscribeRepos.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/ComAtprotoSyncSubscribeRepos.swift new file mode 100644 index 0000000000..b6ba83e24c --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Sync/ComAtprotoSyncSubscribeRepos.swift @@ -0,0 +1,26 @@ +// +// ComAtprotoSyncSubscribeRepos.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Sync { + + /// The main data model definition for the firehose service. + /// + /// - Note: According to the AT Protocol specifications: "Repository event stream, aka Firehose + /// endpoint. Outputs repo commits with diff data, and identity update events, for all + /// repositories on the current server. See the atproto specifications for details around + /// stream sequencing, repo versioning, CAR diff format, and more. Public and does not require + /// auth; implemented by PDS and Relay." + /// + /// - SeeAlso: This is based on the [`com.atproto.sync.subscribeRepos`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/sync/subscribeRepos.json + public struct SubscribeRepos: Codable { + + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Temp/AtprotoTempCheckSignupQueue.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Temp/AtprotoTempCheckSignupQueue.swift deleted file mode 100644 index 34430d385d..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Temp/AtprotoTempCheckSignupQueue.swift +++ /dev/null @@ -1,26 +0,0 @@ -// -// AtprotoTempCheckSignupQueue.swift -// -// -// Created by Christopher Jr Riley on 2024-03-17. -// - -import Foundation - -/// The main data model definition for the output of retrieving information about the sign up queue. -/// -/// - Important: The lexicon associated with this model may be removed at any time. This may not work. -/// -/// - Note: According to the AT Protocol specifications: "Check accounts location in signup queue." -/// -/// - SeeAlso: This is based on the [`com.atproto.temp.checkSignupQueue`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/temp/checkSignupQueue.json -public struct TempCheckSignupQueueOutput: Codable { - /// Indicates whether the user with the queried username has been activated. - public let isActivated: Bool - /// The user's place in queue. Optional. - public let placeInQueue: Int? - /// The estimated amount of time before the user can use the service (in minutes). Optional. - public let estimatedTimeinMinutes: Int -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Temp/AtprotoTempRequestPhoneVerification.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Temp/AtprotoTempRequestPhoneVerification.swift deleted file mode 100644 index f063550f71..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Temp/AtprotoTempRequestPhoneVerification.swift +++ /dev/null @@ -1,22 +0,0 @@ -// -// AtprotoTempRequestPhoneVerification.swift -// -// -// Created by Christopher Jr Riley on 2024-03-17. -// - -import Foundation - -/// The main data model definition for requesting a text code from a phone number. -/// -/// - Important: The lexicon associated with this model may be removed at any time. This may not work. -/// -/// - Note: According to the AT Protocol specifications: "Request a verification code to be sent to the supplied phone number." -/// -/// - SeeAlso: This is based on the [`com.atproto.temp.requestPhoneVerification`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/temp/requestPhoneVerification.json -public struct TempRequestPhoneVerification: Codable { - /// The user's mobile phone number. - public let phoneNumber: String -} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Temp/ComAtprotoTempCheckSignupQueue.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Temp/ComAtprotoTempCheckSignupQueue.swift new file mode 100644 index 0000000000..7654dac3ad --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Temp/ComAtprotoTempCheckSignupQueue.swift @@ -0,0 +1,42 @@ +// +// ComAtprotoTempCheckSignupQueue.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + + +extension ComAtprotoLexicon.Temp { + + /// An output model for etrieving information about the sign up queue. + /// + /// - Important: The lexicon associated with this model may be removed at any time. This may + /// not work. + /// + /// - Note: According to the AT Protocol specifications: "Check accounts location in + /// signup queue." + /// + /// - SeeAlso: This is based on the [`com.atproto.temp.checkSignupQueue`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/temp/checkSignupQueue.json + public struct CheckSignupQueueOutput: Codable { + + /// Indicates whether the user with the queried username has been activated. + public let isActivated: Bool + + /// The user's place in queue. Optional. + public let placeInQueue: Int? + + /// The estimated amount of time before the user can use the service + /// (in minutes). Optional. + public let estimatedTimeinMinutes: Int + + enum CodingKeys: String, CodingKey { + case isActivated = "activated" + case placeInQueue = "placeInQueue" + case estimatedTimeinMinutes = "estimatedTimeMs" + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/com.atproto/Temp/ComAtprotoTempRequestPhoneVerification.swift b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Temp/ComAtprotoTempRequestPhoneVerification.swift new file mode 100644 index 0000000000..abf13d16bd --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/com.atproto/Temp/ComAtprotoTempRequestPhoneVerification.swift @@ -0,0 +1,28 @@ +// +// ComAtprotoTempRequestPhoneVerification.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ComAtprotoLexicon.Temp { + + /// A request body model for requesting a text code from a phone number. + /// + /// - Important: The lexicon associated with this model may be removed at any time. This may + /// not work. + /// + /// - Note: According to the AT Protocol specifications: "Request a verification code to be + /// sent to the supplied phone number." + /// + /// - SeeAlso: This is based on the [`com.atproto.temp.requestPhoneVerification`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/temp/requestPhoneVerification.json + public struct RequestPhoneVerificationRequestBody: Codable { + + /// The user's mobile phone number. + public let phoneNumber: String + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Communication/OzoneCommunicationCreateTemplate.swift b/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Communication/OzoneCommunicationCreateTemplate.swift deleted file mode 100644 index 46597dbdab..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Communication/OzoneCommunicationCreateTemplate.swift +++ /dev/null @@ -1,38 +0,0 @@ -// -// OzoneCommunicationCreateTemplate.swift -// -// -// Created by Christopher Jr Riley on 2024-02-27. -// - -import Foundation - -/// The main data model definition for creating a communication template. -/// -/// - Note: According to the AT Protocol specifications: "Administrative action to create a -/// new, re-usable communication (email for now) template." -/// -/// - SeeAlso: This is based on the [`tools.ozone.communication.createTemplate`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/communication/createTemplate.json -public struct CommunicationCreateTemplate: Codable { - /// The name of the template. - /// - /// - Note: According to the AT Protocol specifications: "Name of the template." - public let name: String - /// A Markdown-formatted content of the communitcation template. - /// - /// - Note: According to the AT Protocol specifications: "Content of the template, markdown - /// supported, can contain variable placeholders." - public let contentMarkdown: String - /// The subject line of the communication template. - /// - /// - Note: According to the AT Protocol specifications: "Subject of the message, used - /// in emails." - public let subject: String - /// The decentralized identifier (DID) of the creator of the communication template. Optional. - /// - /// - Note: According to the AT Protocol specifications: "DID of the user who is creating - /// the template." - public let createdBy: String? -} diff --git a/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Communication/OzoneCommunicationDefs.swift b/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Communication/OzoneCommunicationDefs.swift deleted file mode 100644 index 11b4deb829..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Communication/OzoneCommunicationDefs.swift +++ /dev/null @@ -1,94 +0,0 @@ -// -// OzoneCommunicationDefs.swift -// -// -// Created by Christopher Jr Riley on 2024-03-14. -// - -import Foundation - -/// A data model definition for a communication template. -/// -/// - SeeAlso: This is based on the [`tools.ozone.communication.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/communication/defs.json -public struct OzoneCommunicationTemplateView: Codable { - /// The ID of the communication template. - public let id: Int - /// The name of the communication template. - /// - /// - Note: According to the AT Protocol specifications: "Name of the template." - public let name: String - /// The subject of the message. Optional. - /// - /// - Note: According to the AT Protocol specifications: "Subject of the message, used - /// in emails." - public var subject: String? = nil - /// The content of the communication template. Optional. - /// - /// This may contain Markdown placeholders and variable placeholders. - /// - /// - Note: According to the AT Protocol specifications: "Content of the template, can contain - /// markdown and variable placeholders." - public let contentMarkdown: String - /// Indicates whether the communication template has been disabled. - public let isDisabled: Bool - /// The decentralized identifier (DID) of the user who last updated the communication template. - /// - /// - Note: According to the AT Protocol specifications: "DID of the user who last updated - /// the template." - public let lastUpdatedBy: String - /// The date and time the communication template was created. - @DateFormatting public var createdAt: Date - /// The date and time the communication template was updated. - @DateFormatting public var updatedAt: Date - - public init(id: Int, name: String, subject: String? = nil, contentMarkdown: String, isDisabled: Bool, lastUpdatedBy: String, - createdAt: Date, updatedAt: Date) { - self.id = id - self.name = name - self.subject = subject - self.contentMarkdown = contentMarkdown - self.isDisabled = isDisabled - self.lastUpdatedBy = lastUpdatedBy - self._createdAt = DateFormatting(wrappedValue: createdAt) - self._updatedAt = DateFormatting(wrappedValue: updatedAt) - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.id = try container.decode(Int.self, forKey: .id) - self.name = try container.decode(String.self, forKey: .name) - self.subject = try container.decodeIfPresent(String.self, forKey: .subject) - self.contentMarkdown = try container.decode(String.self, forKey: .contentMarkdown) - self.isDisabled = try container.decode(Bool.self, forKey: .isDisabled) - self.lastUpdatedBy = try container.decode(String.self, forKey: .lastUpdatedBy) - self.createdAt = try container.decode(DateFormatting.self, forKey: .createdAt).wrappedValue - self.updatedAt = try container.decode(DateFormatting.self, forKey: .updatedAt).wrappedValue - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - try container.encode(self.id, forKey: .id) - try container.encode(self.name, forKey: .name) - try container.encodeIfPresent(self.subject, forKey: .subject) - try container.encode(self.contentMarkdown, forKey: .contentMarkdown) - try container.encode(self.isDisabled, forKey: .isDisabled) - try container.encode(self.lastUpdatedBy, forKey: .lastUpdatedBy) - try container.encode(self._createdAt, forKey: .createdAt) - try container.encode(self._updatedAt, forKey: .updatedAt) - } - - enum CodingKeys: String, CodingKey { - case id - case name - case subject - case contentMarkdown - case isDisabled = "disabled" - case lastUpdatedBy - case createdAt - case updatedAt - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Communication/OzoneCommunicationDeleteTemplate.swift b/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Communication/OzoneCommunicationDeleteTemplate.swift deleted file mode 100644 index e90d20ec04..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Communication/OzoneCommunicationDeleteTemplate.swift +++ /dev/null @@ -1,20 +0,0 @@ -// -// OzoneCommunicationDeleteTemplate.swift -// -// -// Created by Christopher Jr Riley on 2024-02-28. -// - -import Foundation - -/// The main data model definition for deleting a communication template as an administrator. -/// -/// - Note: According to the AT Protocol specifications: "Delete a communication template." -/// -/// - SeeAlso: This is based on the [`tools.ozone.communication.deleteTemplate`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/communication/deleteTemplate.json -public struct CommunicationDeleteTemplate: Codable { - /// The ID of the communication template. - public let id: String -} diff --git a/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Communication/OzoneCommunicationListTemplates.swift b/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Communication/OzoneCommunicationListTemplates.swift deleted file mode 100644 index 30713f3ef7..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Communication/OzoneCommunicationListTemplates.swift +++ /dev/null @@ -1,20 +0,0 @@ -// -// OzoneCommunicationListTemplates.swift -// -// -// Created by Christopher Jr Riley on 2024-05-01. -// - -import Foundation - -/// The output definition for retrieves a list of communication templates. -/// -/// - Note: According to the AT Protocol specifications: "Get list of all communication templates." -/// -/// - SeeAlso: This is based on the [`tools.ozone.communication.listTemplates`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/communication/listTemplates.json -public struct CommunicationListTemplatesOutput: Codable { - /// An array of communication templates. - public let communicationTemplates: [OzoneCommunicationTemplateView] -} diff --git a/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Communication/OzoneCommunicationUpdateTemplate.swift b/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Communication/OzoneCommunicationUpdateTemplate.swift deleted file mode 100644 index 0fbf2046bd..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Communication/OzoneCommunicationUpdateTemplate.swift +++ /dev/null @@ -1,43 +0,0 @@ -// -// OzoneCommunicationUpdateTemplate.swift -// -// -// Created by Christopher Jr Riley on 2024-05-01. -// - -import Foundation - -/// The main data model definition for updating a communication template. -/// -/// - Note: According to the AT Protocol specifications: "Administrative action to update an -/// existing communication template. Allows passing partial fields to patch specific fields only." -/// -/// - SeeAlso: This is based on the [`tools.ozone.communication.updateTemplate`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/communication/updateTemplate.json -public struct CommunicationUpdateTemplate: Codable { - /// The ID of the communication template. - public let id: String - /// The name of the communication template. Optional. - public let name: String? - /// The content of the communication template. Optional. - /// - /// This may contain Markdown placeholders and variable placeholders. - public let contentMarkdown: String? - /// The subject line of the message itself. Optional. - public let subject: String? - /// The decentralized identifier (DID) of the user who updated the - /// communication template. Optional. - public let updatedBy: String? - /// Indicates whether the communication template is disabled. Optional. - public let isDisabled: Bool? - - enum CodingKeys: String, CodingKey { - case id - case name - case contentMarkdown - case subject - case updatedBy - case isDisabled = "disabled" - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Communication/ToolsOzoneCommunicationCreateTemplate.swift b/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Communication/ToolsOzoneCommunicationCreateTemplate.swift new file mode 100644 index 0000000000..4147019165 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Communication/ToolsOzoneCommunicationCreateTemplate.swift @@ -0,0 +1,46 @@ +// +// ToolsOzoneCommunicationCreateTemplate.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ToolsOzoneLexicon.Communication { + + /// A request body model for creating a communication template. + /// + /// - Note: According to the AT Protocol specifications: "Administrative action to create a + /// new, re-usable communication (email for now) template." + /// + /// - SeeAlso: This is based on the [`tools.ozone.communication.createTemplate`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/communication/createTemplate.json + public struct CreateTemplateRequestBody: Codable { + + /// The name of the template. + /// + /// - Note: According to the AT Protocol specifications: "Name of the template." + public let name: String + + /// A Markdown-formatted content of the communitcation template. + /// + /// - Note: According to the AT Protocol specifications: "Content of the template, markdown + /// supported, can contain variable placeholders." + public let contentMarkdown: String + + /// The subject line of the communication template. + /// + /// - Note: According to the AT Protocol specifications: "Subject of the message, used + /// in emails." + public let subject: String + + /// The decentralized identifier (DID) of the creator of the + /// communication template. Optional. + /// + /// - Note: According to the AT Protocol specifications: "DID of the user who is creating + /// the template." + public let createdBy: String? + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Communication/ToolsOzoneCommunicationDefs.swift b/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Communication/ToolsOzoneCommunicationDefs.swift new file mode 100644 index 0000000000..630e40b298 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Communication/ToolsOzoneCommunicationDefs.swift @@ -0,0 +1,106 @@ +// +// ToolsOzoneCommunicationDefs.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ToolsOzoneLexicon.Communication { + + /// A definition model for a communication template. + /// + /// - SeeAlso: This is based on the [`tools.ozone.communication.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/communication/defs.json + public struct TemplateViewDefinition: Codable { + + /// The ID of the communication template. + public let id: Int + + /// The name of the communication template. + /// + /// - Note: According to the AT Protocol specifications: "Name of the template." + public let name: String + + /// The subject of the message. Optional. + /// + /// - Note: According to the AT Protocol specifications: "Subject of the message, used + /// in emails." + public var subject: String? + + /// The content of the communication template. Optional. + /// + /// This may contain Markdown placeholders and variable placeholders. + /// + /// - Note: According to the AT Protocol specifications: "Content of the template, can + /// contain markdown and variable placeholders." + public let contentMarkdown: String + + /// Indicates whether the communication template has been disabled. + public let isDisabled: Bool + + /// The decentralized identifier (DID) of the user who last updated the + /// communication template. + /// + /// - Note: According to the AT Protocol specifications: "DID of the user who last updated + /// the template." + public let lastUpdatedBy: String + + /// The date and time the communication template was created. + @DateFormatting public var createdAt: Date + + /// The date and time the communication template was updated. + @DateFormatting public var updatedAt: Date + + public init(id: Int, name: String, subject: String? = nil, contentMarkdown: String, isDisabled: Bool, lastUpdatedBy: String, + createdAt: Date, updatedAt: Date) { + self.id = id + self.name = name + self.subject = subject + self.contentMarkdown = contentMarkdown + self.isDisabled = isDisabled + self.lastUpdatedBy = lastUpdatedBy + self._createdAt = DateFormatting(wrappedValue: createdAt) + self._updatedAt = DateFormatting(wrappedValue: updatedAt) + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.id = try container.decode(Int.self, forKey: .id) + self.name = try container.decode(String.self, forKey: .name) + self.subject = try container.decodeIfPresent(String.self, forKey: .subject) + self.contentMarkdown = try container.decode(String.self, forKey: .contentMarkdown) + self.isDisabled = try container.decode(Bool.self, forKey: .isDisabled) + self.lastUpdatedBy = try container.decode(String.self, forKey: .lastUpdatedBy) + self.createdAt = try container.decode(DateFormatting.self, forKey: .createdAt).wrappedValue + self.updatedAt = try container.decode(DateFormatting.self, forKey: .updatedAt).wrappedValue + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.id, forKey: .id) + try container.encode(self.name, forKey: .name) + try container.encodeIfPresent(self.subject, forKey: .subject) + try container.encode(self.contentMarkdown, forKey: .contentMarkdown) + try container.encode(self.isDisabled, forKey: .isDisabled) + try container.encode(self.lastUpdatedBy, forKey: .lastUpdatedBy) + try container.encode(self._createdAt, forKey: .createdAt) + try container.encode(self._updatedAt, forKey: .updatedAt) + } + + enum CodingKeys: String, CodingKey { + case id + case name + case subject + case contentMarkdown + case isDisabled = "disabled" + case lastUpdatedBy + case createdAt + case updatedAt + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Communication/ToolsOzoneCommunicationDeleteTemplate.swift b/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Communication/ToolsOzoneCommunicationDeleteTemplate.swift new file mode 100644 index 0000000000..2525142872 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Communication/ToolsOzoneCommunicationDeleteTemplate.swift @@ -0,0 +1,24 @@ +// +// ToolsOzoneCommunicationDeleteTemplate.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ToolsOzoneLexicon.Communication { + + /// A request body model for deleting a communication template as an administrator. + /// + /// - Note: According to the AT Protocol specifications: "Delete a communication template." + /// + /// - SeeAlso: This is based on the [`tools.ozone.communication.deleteTemplate`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/communication/deleteTemplate.json + public struct DeleteTemplateRequestBody: Codable { + + /// The ID of the communication template. + public let id: String + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Communication/ToolsOzoneCommunicationListTemplates.swift b/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Communication/ToolsOzoneCommunicationListTemplates.swift new file mode 100644 index 0000000000..4571840ed9 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Communication/ToolsOzoneCommunicationListTemplates.swift @@ -0,0 +1,25 @@ +// +// ToolsOzoneCommunicationListTemplates.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ToolsOzoneLexicon.Communication { + + /// An output model for retrieves a list of communication templates. + /// + /// - Note: According to the AT Protocol specifications: "Get list of all + /// communication templates." + /// + /// - SeeAlso: This is based on the [`tools.ozone.communication.listTemplates`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/communication/listTemplates.json + public struct ListTemplatesOutput: Codable { + + /// An array of communication templates. + public let communicationTemplates: [TemplateViewDefinition] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Communication/ToolsOzoneCommunicationUpdateTemplate.swift b/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Communication/ToolsOzoneCommunicationUpdateTemplate.swift new file mode 100644 index 0000000000..fda11068d4 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Communication/ToolsOzoneCommunicationUpdateTemplate.swift @@ -0,0 +1,53 @@ +// +// ToolsOzoneCommunicationUpdateTemplate.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ToolsOzoneLexicon.Communication { + + /// A request body model for updating a communication template. + /// + /// - Note: According to the AT Protocol specifications: "Administrative action to update an + /// existing communication template. Allows passing partial fields to patch specific + /// fields only." + /// + /// - SeeAlso: This is based on the [`tools.ozone.communication.updateTemplate`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/communication/updateTemplate.json + public struct UpdateTemplateRequestBody: Codable { + + /// The ID of the communication template. + public let id: String + + /// The name of the communication template. Optional. + public let name: String? + + /// The content of the communication template. Optional. + /// + /// This may contain Markdown placeholders and variable placeholders. + public let contentMarkdown: String? + + /// The subject line of the message itself. Optional. + public let subject: String? + + /// The decentralized identifier (DID) of the user who updated the + /// communication template. Optional. + public let updatedBy: String? + + /// Indicates whether the communication template is disabled. Optional. + public let isDisabled: Bool? + + enum CodingKeys: String, CodingKey { + case id + case name + case contentMarkdown + case subject + case updatedBy + case isDisabled = "disabled" + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Moderation/OzoneModerationDefs.swift b/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Moderation/OzoneModerationDefs.swift deleted file mode 100644 index 59583bebc3..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Moderation/OzoneModerationDefs.swift +++ /dev/null @@ -1,1085 +0,0 @@ -// -// OzoneModerationDefs.swift -// -// -// Created by Christopher Jr Riley on 2024-03-14. -// - -import Foundation - -/// A data model for a moderation event view definition. -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/defs.json -public struct OzoneModerationEventView: Codable { - /// The ID of the moderator's event view. - public let id: Int - /// The type of the moderator's event view. - public let event: AdminEventViewUnion - /// The subject reference of the moderator's event view. - public let subject: RepositoryReferencesUnion - /// An array of CID hashes related to blobs for the moderator's event view. - public let subjectBlobCIDHashes: [String] - /// The creator of the event view. - public let createdBy: String - /// The date and time the event view was created. - @DateFormatting public var createdAt: Date - /// The handle of the moderator. Optional. - public var creatorHandle: String? = nil - /// The subject handle of the event view. Optional. - public var subjectHandle: String? = nil - - public init(id: Int, event: AdminEventViewUnion, subject: RepositoryReferencesUnion, subjectBlobCIDHashes: [String], createdBy: String, - createdAt: Date, creatorHandle: String?, subjectHandle: String?) { - self.id = id - self.event = event - self.subject = subject - self.subjectBlobCIDHashes = subjectBlobCIDHashes - self.createdBy = createdBy - self._createdAt = DateFormatting(wrappedValue: createdAt) - self.creatorHandle = creatorHandle - self.subjectHandle = subjectHandle - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.id = try container.decode(Int.self, forKey: .id) - self.event = try container.decode(AdminEventViewUnion.self, forKey: .event) - self.subject = try container.decode(RepositoryReferencesUnion.self, forKey: .subject) - self.subjectBlobCIDHashes = try container.decode([String].self, forKey: .subjectBlobCIDHashes) - self.createdBy = try container.decode(String.self, forKey: .createdBy) - self.createdAt = try container.decode(DateFormatting.self, forKey: .createdAt).wrappedValue - self.creatorHandle = try container.decodeIfPresent(String.self, forKey: .creatorHandle) - self.subjectHandle = try container.decodeIfPresent(String.self, forKey: .subjectHandle) - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - try container.encode(self.id, forKey: .id) - try container.encode(self.event, forKey: .event) - try container.encode(self.subject, forKey: .subject) - try container.encode(self.subjectBlobCIDHashes, forKey: .subjectBlobCIDHashes) - try container.encode(self.createdBy, forKey: .createdBy) - try container.encode(self._createdAt, forKey: .createdAt) - try container.encodeIfPresent(self.creatorHandle, forKey: .creatorHandle) - try container.encodeIfPresent(self.subjectHandle, forKey: .subjectHandle) - } - - enum CodingKeys: String, CodingKey { - case id - case event - case subject - case subjectBlobCIDHashes = "subjectBlobCids" - case createdBy - case createdAt - case creatorHandle - case subjectHandle - } -} - -/// A data model for a detailed moderation event view definition. -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/defs.json -public struct OzoneModerationEventViewDetail: Codable { - /// The ID of the moderator's event view. - public let id: Int - /// The type of the moderator's event view. - public let event: EventViewDetailUnion - /// The subject reference of the moderator's event view. - public let subject: RepositoryViewUnion - /// An array of blobs for a moderator to look at. - public let subjectBlobs: [OzoneModerationBlobView] - /// The creator of the event view. - public let createdBy: String - /// The date and time the event view was created. - @DateFormatting public var createdAt: Date - - public init(id: Int, event: EventViewDetailUnion, subject: RepositoryViewUnion, subjectBlobs: [OzoneModerationBlobView], - createdBy: String, createdAt: Date) { - self.id = id - self.event = event - self.subject = subject - self.subjectBlobs = subjectBlobs - self.createdBy = createdBy - self._createdAt = DateFormatting(wrappedValue: createdAt) - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.id = try container.decode(Int.self, forKey: .id) - self.event = try container.decode(EventViewDetailUnion.self, forKey: .event) - self.subject = try container.decode(RepositoryViewUnion.self, forKey: .subject) - self.subjectBlobs = try container.decode([OzoneModerationBlobView].self, forKey: .subjectBlobs) - self.createdBy = try container.decode(String.self, forKey: .createdBy) - self.createdAt = try container.decode(DateFormatting.self, forKey: .createdAt).wrappedValue - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - try container.encode(self.id, forKey: .id) - try container.encode(self.event, forKey: .event) - try container.encode(self.subject, forKey: .subject) - try container.encode(self.subjectBlobs, forKey: .subjectBlobs) - try container.encode(self.createdBy, forKey: .createdBy) - try container.encode(self._createdAt, forKey: .createdAt) - } - - enum CodingKeys: CodingKey { - case id - case event - case subject - case subjectBlobs - case createdBy - case createdAt - } -} - -/// A data model for a subject's status view definition. -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/defs.json -public struct OzoneSubjectStatusView: Codable { - /// The ID of the status view. - public let id: Int - /// The subject reference of the status view. - public let subject: RepositoryReferencesUnion - /// An array of CID hashes related to blobs. Optional. - public var subjectBlobCIDHashes: [String]? = nil - /// The handle of the subject related to the status. Optional. - public var subjectRepoHandle: String? = nil - /// The date and time of the last update for the status view. - /// - /// - Note: According to the AT Protocol specifications: "Timestamp referencing when the last update was made to the moderation status of the subject." - @DateFormatting public var updatedAt: Date - /// The date and time of the day the first event occured. - /// - /// - Note: According to the AT Protocol specifications: "Timestamp referencing the first moderation status impacting event was emitted on the subject." - @DateFormatting public var createdAt: Date - /// The review status of the subject. - public let reviewState: OzoneSubjectReviewState - /// Any additional comments written about the subject. Optional. - public var comment: String? = nil - /// The date and time the subject's time to be muted has been lifted. Optional. - /// - /// - Note: According to the AT Protocol specifications: "Sticky comment on the subject." - @DateFormattingOptional public var muteUntil: Date? = nil - /// The date and time until which reporting on the subject is muted. Optional. - /// - /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ - /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ - /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ - /// \ - /// Clarifications from Bluesky are needed in order to fully understand this item. - @DateFormattingOptional public var muteReportingUntil: Date? - /// The name of the reviewer that reviewed the subject. Optional. - public var lastReviewedBy: String? = nil - /// The date and time the last reviewer looked at the subject. Optional. - @DateFormattingOptional public var lastReviewedAt: Date? = nil - /// The date and time of the last report about the subject. Optional. - @DateFormattingOptional public var lastReportedAt: Date? = nil - /// The date and time of the last appeal. Optional. - @DateFormattingOptional public var lastAppealedAt: Date? = nil - /// Indicates whether the subject was taken down. Optional. - public var isTakenDown: Bool? = nil - /// Indicates whether an appeal has been made. Optional. - public var wasAppealed: Bool? = nil - /// The date and time the subject's suspension will be lifted. Optional. - @DateFormattingOptional public var suspendUntil: Date? = nil - /// An array of tags. Optional. - public var tags: [String]? = nil - - public init(id: Int, subject: RepositoryReferencesUnion, subjectBlobCIDHashes: [String]?, subjectRepoHandle: String?, updatedAt: Date, createdAt: Date, - reviewState: OzoneSubjectReviewState, comment: String?, muteUntil: Date?, muteReportingUntil: Date?, lastReviewedBy: String?, - lastReviewedAt: Date?, lastReportedAt: Date?, lastAppealedAt: Date?, isTakenDown: Bool?, wasAppealed: Bool?, suspendUntil: Date?, - tags: [String]?) { - self.id = id - self.subject = subject - self.subjectBlobCIDHashes = subjectBlobCIDHashes - self.subjectRepoHandle = subjectRepoHandle - self._updatedAt = DateFormatting(wrappedValue: updatedAt) - self._createdAt = DateFormatting(wrappedValue: createdAt) - self.reviewState = reviewState - self.comment = comment - self.muteUntil = muteUntil - self._muteReportingUntil = DateFormattingOptional(wrappedValue: muteReportingUntil) - self.lastReviewedBy = lastReviewedBy - self._lastReviewedAt = DateFormattingOptional(wrappedValue: lastReviewedAt) - self._lastReportedAt = DateFormattingOptional(wrappedValue: lastReportedAt) - self._lastAppealedAt = DateFormattingOptional(wrappedValue: lastAppealedAt) - self.isTakenDown = isTakenDown - self.wasAppealed = wasAppealed - self._suspendUntil = DateFormattingOptional(wrappedValue: suspendUntil) - self.tags = tags - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.id = try container.decode(Int.self, forKey: .id) - self.subject = try container.decode(RepositoryReferencesUnion.self, forKey: .subject) - self.subjectBlobCIDHashes = try container.decodeIfPresent([String].self, forKey: .subjectBlobCIDHashes) - self.subjectRepoHandle = try container.decodeIfPresent(String.self, forKey: .subjectRepoHandle) - self.updatedAt = try container.decode(DateFormatting.self, forKey: .updatedAt).wrappedValue - self.createdAt = try container.decode(DateFormatting.self, forKey: .createdAt).wrappedValue - self.reviewState = try container.decode(OzoneSubjectReviewState.self, forKey: .reviewState) - self.comment = try container.decodeIfPresent(String.self, forKey: .comment) - self.muteUntil = try container.decodeIfPresent(DateFormattingOptional.self, forKey: .muteUntil)?.wrappedValue - self.muteReportingUntil = try container.decodeIfPresent(DateFormattingOptional.self, forKey: .muteReportingUntil)?.wrappedValue - self.lastReviewedBy = try container.decodeIfPresent(String.self, forKey: .lastReviewedBy) - self.lastReviewedAt = try container.decodeIfPresent(DateFormattingOptional.self, forKey: .lastReviewedAt)?.wrappedValue - self.lastReportedAt = try container.decodeIfPresent(DateFormattingOptional.self, forKey: .lastReportedAt)?.wrappedValue - self.lastAppealedAt = try container.decodeIfPresent(DateFormattingOptional.self, forKey: .lastAppealedAt)?.wrappedValue - self.isTakenDown = try container.decodeIfPresent(Bool.self, forKey: .isTakenDown) - self.wasAppealed = try container.decodeIfPresent(Bool.self, forKey: .wasAppealed) - self.suspendUntil = try container.decodeIfPresent(DateFormattingOptional.self, forKey: .suspendUntil)?.wrappedValue - self.tags = try container.decode([String].self, forKey: .tags) - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - try container.encode(self.id, forKey: .id) - try container.encode(self.subject, forKey: .subject) - try container.encodeIfPresent(self.subjectBlobCIDHashes, forKey: .subjectBlobCIDHashes) - try container.encodeIfPresent(self.subjectRepoHandle, forKey: .subjectRepoHandle) - try container.encode(self._updatedAt, forKey: .updatedAt) - try container.encode(self._createdAt, forKey: .createdAt) - try container.encode(self.reviewState, forKey: .reviewState) - try container.encodeIfPresent(self.comment, forKey: .comment) - try container.encode(self._muteUntil, forKey: .muteUntil) - try container.encodeIfPresent(self._muteReportingUntil, forKey: .muteReportingUntil) - try container.encodeIfPresent(self.lastReviewedBy, forKey: .lastReviewedBy) - try container.encode(self._lastReviewedAt, forKey: .lastReviewedAt) - try container.encode(self._lastReportedAt, forKey: .lastReportedAt) - try container.encode(self._lastAppealedAt, forKey: .lastAppealedAt) - try container.encodeIfPresent(self.isTakenDown, forKey: .isTakenDown) - try container.encodeIfPresent(self.wasAppealed, forKey: .wasAppealed) - try container.encode(self._suspendUntil, forKey: .suspendUntil) - try container.encode(self.tags, forKey: .tags) - } - - enum CodingKeys: String, CodingKey { - case id - case subject - case subjectBlobCIDHashes = "subjectBlobCids" - case subjectRepoHandle - case updatedAt - case createdAt - case reviewState - case comment - case muteUntil - case muteReportingUntil - case lastReviewedBy - case lastReviewedAt - case lastReportedAt - case lastAppealedAt - case isTakenDown = "takendown" - case wasAppealed = "appealed" - case suspendUntil - case tags - } -} - -/// A data model for the subject review state definition. -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/defs.json -public enum OzoneSubjectReviewState: String, Codable { - /// Moderator review status of a subject: Open. Indicates that the subject needs to be reviewed by a moderator. - /// - /// - Note: The above documentation was taken directly from the AT Protocol specifications. - case reviewOpen - - /// Moderator review status of a subject: Escalated. Indicates that the subject was escalated for review by a moderator. - /// - /// - Note: The above documentation was taken directly from the AT Protocol specifications. - case reviewEscalated - - /// Moderator review status of a subject: Closed. Indicates that the subject was already reviewed and resolved by a moderator. - /// - /// - Note: The above documentation was taken directly from the AT Protocol specifications. - case reviewClosed - - /// Moderator review status of a subject: Unnecessary. Indicates that the subject does not need a review at the moment but there - /// is probably some moderation related metadata available for it - /// - /// - Note: The above documentation was taken directly from the AT Protocol specifications. - case reviewNone -} - -/// A data model for an event takedown definition. -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/defs.json -public struct OzoneModerationEventTakedown: Codable { - /// Any additional comments for the takedown event. Optional. - /// - /// - Note: According to the AT Protocol specifications: "Take down a subject permanently or temporarily." - public let comment: String? - /// The amount of time (in hours) for the user to be considered takendown. Optional. - /// - /// - Note: According to the AT Protocol specifications: "Indicates how long the takedown should be in effect before automatically expiring." - public let durationInHours: Int? -} - -/// A data model for a reverse takedown event definition. -/// -/// - Note: According to the AT Protocol specifications: "Revert take down action on a subject." -/// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/defs.json -public struct OzoneModerationEventReverseTakedown: Codable { - /// Any comments for the reverse takedown event. Optional. - /// - /// - Note: According to the AT Protocol specifications: "Describe reasoning behind the reversal." - public let comment: String? -} - -/// A data model for a definition of an resolved appeal event. -/// -/// - Note: According to the AT Protocol specifications: "Resolve appeal on a subject." -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/defs.json -public struct OzoneModerationEventResolveAppeal: Codable { - /// Any comments for the moderator's appeal resolution event. Optional. - /// - /// - Note: According to the AT Protocol specifications: "Describe resolution." - public let comment: String? -} - -/// A data model for a definition of a comment event. -/// -/// - Note: According to the AT Protocol specifications: "Add a comment to a subject." -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/defs.json -public struct OzoneModerationEventComment: Codable { - /// Any comment for the moderator's comment event. - public let comment: String - /// Indicates whether the moderator event is sticky. Optional. - /// - /// - Note: According to the AT Protocol specifications: "Make the comment persistent on the subject." - public let isSticky: Bool? - - enum CodingKeys: String, CodingKey { - case comment - case isSticky = "sticky" - } -} - -/// A data model for a report event definition. -/// -/// - Note: According to the AT Protocol specifications: "Report a subject." -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/defs.json -public struct OzoneModerationEventReport: Codable { - /// Any comments for the moderator's report event. Optional. - public var comment: String? = nil - /// Indicates whether the reporter has been muted. Optional. - /// - /// - Note: According to the AT Protocol specifications: "Set to true if the reporter was muted from reporting at the time of the event. - /// These reports won't impact the reviewState of the subject." - public let isReporterMuted: Bool? - /// The type of report. - public let reportType: ModerationReasonType -} - -/// A data model for a label event definition. -/// -/// - Note: According to the AT Protocol specifications: "Apply/Negate labels on a subject" -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/defs.json -public struct OzoneModerationEventLabel: Codable { - /// Any comments for the moderator's label event. Optional. - public let comment: String? - /// An array of labels that apply to a user. - public let createLabelValues: [String] - /// An array of labels that's applied to a user for the purpose of negating. - public let negateLabelValues: [String] - - enum CodingKeys: String, CodingKey { - case comment - case createLabelValues = "createLabelVals" - case negateLabelValues = "negateLabelVals" - } -} - -/// A data model for a definition of an acknowledgement event. -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/defs.json -public struct OzoneModerationEventAcknowledge: Codable { - /// Any comments for the moderator's acknowledge event. Optional. - public var comment: String? = nil -} - -/// A data model for a definition of an escalation event. -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/defs.json -public struct OzoneModerationEventEscalate: Codable { - /// Any additional comments for escalating a report. Optional. - public var comment: String? = nil -} - -/// A data model for a definition of a mute event. -/// -/// - Note: According to the AT Protocol specifications: "Mute incoming reports on a subject." -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/defs.json -public struct OzoneModerationEventMute: Codable { - /// Any additional comments for the mute event. Optional. - public var comment: String? = nil - /// The amount of time (in hours) that the moderator has put in for muting a user. - /// - /// - Note: According to the AT Protocol specifications: "Indicates how long the subject should remain muted." - public let durationInHours: Int -} - -/// A data model for an unmute event definition. -/// -/// - Note: According to the AT Protocol specifications: "Unmute action on a subject." -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/defs.json -public struct OzoneModerationEventUnmute: Codable { - /// Any comments for the moderator's unmute event. Optional. - /// - /// - Note: According to the AT Protocol specifications: "Describe reasoning behind the reversal." - public var comment: String? = nil -} - -/// A data model definition for a mute reporter event. -/// -/// - Note: According to the AT Protocol specifications: "Mute incoming reports from an account." -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/defs.json -public struct OzoneModerationEventMuteReporter: Codable { - /// Indicates how long the account should remain muted (in hours). - /// - /// - Note: According to the AT Protocol specifications: "Indicates how long the account should remain muted." - public let durationInHours: Int - /// Any additional comments about the event. Optional. - public let comment: String? -} - -/// A data model definition for an unmute reporter event. -/// -/// - Note: According to the AT Protocol specifications: "Unmute incoming reports from an account." -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/defs.json -public struct OzoneModerationEventUnmuteReporter: Codable { - /// Any additional comments about the event. - /// - /// - Note: According to the AT Protocol specifications: "Describe reasoning behind the reversal." - public let comment: String? -} - -/// A data model for a definition of an email event. -/// -/// - Note: According to the AT Protocol specifications: "Keep a log of outgoing email to a user." -/// -/// - SeeAlso: This is based on the [`tools.ozone.moderation.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/defs.json -public struct OzoneModerationEventEmail: Codable { - /// The subject line of the email. - /// - /// - Note: According to the AT Protocol specifications: "The subject line of the email sent to the user." - public let subjectLine: String - /// The body of the email. - /// - /// - Note: According to the AT Protocol specifications: "The content of the email sent to the user." - public let content: String - /// Any additional comments about the email. Optional. - /// - /// - Note: According to the AT Protocol specifications: "Additional comment about the outgoing comm." - public var comment: String? = nil -} - -/// A data model for a definition of a diversion event. -/// -/// - Note: According to the AT Protocol specifications: "Divert a record's blobs to a 3rd party service for further scanning/tagging" -/// -/// - SeeAlso: This is based on the [`tools.ozone.moderation.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/defs.json -public struct OzoneModerationEventDivert: Codable { - /// Any additional comments about the diversion. - public let comment: String? -} - -/// A data model for a tag event definition. -/// -/// - Note: According to the AT Protocol specifications: "Add/Remove a tag on a subject." -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/defs.json -public struct OzoneModerationEventTag: Codable { - /// An array of tags to be added to the user. - /// - /// If a tag in the array already exists on the user, then the tag will be ignored. - /// - /// - Note: According to the AT Protocol specifications: "Tags to be added to the subject. If already exists, won't be duplicated." - public let add: [String] - /// An array of tags to be removed from the user. - /// - /// If a tag in the array doesn't exist on the user, then the tag will be ignored. - /// - /// - Note: According to the AT Protocol specifications: "Tags to be removed to the subject. Ignores a tag If it doesn't exist, won't be duplicated." - public let remove: [String] - /// Any additional comments about the moderator's tag event. - /// - /// - Note: According to the AT Protocol specifications: "Additional comment about added/removed tags." - public let comment: String? -} - -/// A data model for a definition of a repository view. -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/defs.json -public struct OzoneModerationRepositoryView: Codable { - /// The decentralized identifier (DID) of the user. - public let actorDID: String - /// The handle of the user. - public let handle: String - /// The email of the user. Optional. - public var email: String? = nil - /// The related records of the user. - /// - /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ - /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ - /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ - /// \ - /// Clarifications from Bluesky are needed in order to fully understand this item. - public let relatedRecords: UnknownType - /// The date and time the user was indexed. - @DateFormatting public var indexedAt: Date - /// The moderation status of the user. - public let moderation: OzoneModeration - /// The invite code used by the user to sign up. Optional. - public var invitedBy: ServerInviteCode? = nil - /// Indicates whether the invite codes held by the user are diabled. Optional. - public var areInvitesDisabled: Bool? = nil - /// The note of the invite. Optional. - public var inviteNote: String? = nil - - public init(actorDID: String, handle: String, email: String? = nil, relatedRecords: UnknownType, indexedAt: Date, moderation: OzoneModeration, - invitedBy: ServerInviteCode? = nil, areInvitesDisabled: Bool? = nil, inviteNote: String? = nil) { - self.actorDID = actorDID - self.handle = handle - self.email = email - self.relatedRecords = relatedRecords - self._indexedAt = DateFormatting(wrappedValue: indexedAt) - self.moderation = moderation - self.invitedBy = invitedBy - self.areInvitesDisabled = areInvitesDisabled - self.inviteNote = inviteNote - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.actorDID = try container.decode(String.self, forKey: .actorDID) - self.handle = try container.decode(String.self, forKey: .handle) - self.email = try container.decodeIfPresent(String.self, forKey: .email) - self.relatedRecords = try container.decode(UnknownType.self, forKey: .relatedRecords) - self.indexedAt = try container.decode(DateFormatting.self, forKey: .indexedAt).wrappedValue - self.moderation = try container.decode(OzoneModeration.self, forKey: .moderation) - self.invitedBy = try container.decodeIfPresent(ServerInviteCode.self, forKey: .invitedBy) - self.areInvitesDisabled = try container.decodeIfPresent(Bool.self, forKey: .areInvitesDisabled) - self.inviteNote = try container.decodeIfPresent(String.self, forKey: .inviteNote) - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - try container.encode(self.actorDID, forKey: .actorDID) - try container.encode(self.handle, forKey: .handle) - try container.encodeIfPresent(self.email, forKey: .email) - try container.encode(self.relatedRecords, forKey: .relatedRecords) - try container.encode(self._indexedAt, forKey: .indexedAt) - try container.encode(self.moderation, forKey: .moderation) - try container.encodeIfPresent(self.invitedBy, forKey: .invitedBy) - try container.encodeIfPresent(self.areInvitesDisabled, forKey: .areInvitesDisabled) - try container.encodeIfPresent(self.inviteNote, forKey: .inviteNote) - } - - enum CodingKeys: String, CodingKey { - case actorDID = "did" - case handle - case email - case relatedRecords - case indexedAt - case moderation - case invitedBy - case areInvitesDisabled = "invitesDisabled" - case inviteNote - } -} - -/// A data model for a definition of a detailed repository view. -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/defs.json -public struct OzoneModerationRepositoryViewDetail: Codable { - /// The decentralized identifier (DID) of the user. - public let actorDID: String - /// The handle of the user. - public let handle: String - /// The email of the user. Optional. - public var email: String? = nil - /// The user's related records. - /// - /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ - /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ - /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ - /// \ - /// Clarifications from Bluesky are needed in order to fully understand this item. - public let relatedRecords: UnknownType - /// The date and time the user was last indexed. - @DateFormatting public var indexedAt: Date - /// The detailed moderation status of the user. - public let moderation: OzoneModerationDetail - /// An array of labels associated with the user. Optional. - public var labels: [Label]? = nil - /// The invite code used by the user to sign up. Optional. - public var invitedBy: ServerInviteCode? = nil - /// An array of invite codes held by the user. Optional. - public var invites: [ServerInviteCode]? = nil - /// Indicates whether the invite codes held by the user are diabled. Optional. - public var areInvitesDisabled: Bool? = nil - /// The note of the invite. Optional. - public var inviteNote: String? = nil - /// The date and time the email of the user was confirmed. Optional. - @DateFormattingOptional public var emailConfirmedAt: Date? = nil - - public init(actorDID: String, handle: String, email: String?, relatedRecords: UnknownType, indexedAt: Date, moderation: OzoneModerationDetail, - labels: [Label]?, invitedBy: ServerInviteCode?, invites: [ServerInviteCode]?, areInvitesDisabled: Bool?, inviteNote: String?, - emailConfirmedAt: Date? = nil) { - self.actorDID = actorDID - self.handle = handle - self.email = email - self.relatedRecords = relatedRecords - self._indexedAt = DateFormatting(wrappedValue: indexedAt) - self.moderation = moderation - self.labels = labels - self.invitedBy = invitedBy - self.invites = invites - self.areInvitesDisabled = areInvitesDisabled - self.inviteNote = inviteNote - self._emailConfirmedAt = DateFormattingOptional(wrappedValue: emailConfirmedAt) - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.actorDID = try container.decode(String.self, forKey: .actorDID) - self.handle = try container.decode(String.self, forKey: .handle) - self.email = try container.decodeIfPresent(String.self, forKey: .email) - self.relatedRecords = try container.decode(UnknownType.self, forKey: .relatedRecords) - self.indexedAt = try container.decode(DateFormatting.self, forKey: .indexedAt).wrappedValue - self.moderation = try container.decode(OzoneModerationDetail.self, forKey: .moderation) - self.labels = try container.decodeIfPresent([Label].self, forKey: .labels) - self.invitedBy = try container.decodeIfPresent(ServerInviteCode.self, forKey: .invitedBy) - self.invites = try container.decodeIfPresent([ServerInviteCode].self, forKey: .invites) - self.areInvitesDisabled = try container.decodeIfPresent(Bool.self, forKey: .areInvitesDisabled) - self.inviteNote = try container.decodeIfPresent(String.self, forKey: .inviteNote) - self.emailConfirmedAt = try container.decodeIfPresent(DateFormattingOptional.self, forKey: .emailConfirmedAt)?.wrappedValue - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - try container.encode(self.actorDID, forKey: .actorDID) - try container.encode(self.handle, forKey: .handle) - try container.encodeIfPresent(self.email, forKey: .email) - try container.encode(self.relatedRecords, forKey: .relatedRecords) - try container.encode(self._indexedAt, forKey: .indexedAt) - try container.encode(self.moderation, forKey: .moderation) - try container.encodeIfPresent(self.labels, forKey: .labels) - try container.encodeIfPresent(self.invitedBy, forKey: .invitedBy) - try container.encodeIfPresent(self.invites, forKey: .invites) - try container.encodeIfPresent(self.areInvitesDisabled, forKey: .areInvitesDisabled) - try container.encodeIfPresent(self.inviteNote, forKey: .inviteNote) - try container.encode(self._emailConfirmedAt, forKey: .emailConfirmedAt) - } - - enum CodingKeys: String, CodingKey { - case actorDID = "did" - case handle - case email - case relatedRecords - case indexedAt - case moderation - case labels - case invitedBy - case invites - case areInvitesDisabled = "invitesDisabled" - case inviteNote - case emailConfirmedAt - } -} - -/// A data model for a definition of a respository view that may not have been found. -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/defs.json -public struct OzoneModerationRepositoryViewNotFound: Codable { - /// The decentralized identifier (DID) of the repository. - public let repositoryDID: String - - enum CodingKeys: String, CodingKey { - case repositoryDID = "did" - } -} - -/// A data model for the definition of a record view. -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/defs.json -public struct OzoneModerationRecordView: Codable { - /// The URI of the record. - public let recordURI: String - /// The CID hash of the record. - public let cidHash: String - /// The value of the record. - /// - /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ - /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ - /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ - /// \ - /// Clarifications from Bluesky are needed in order to fully understand this item. - public let value: UnknownType - /// An array of CID hashes for blobs. - public let blobCIDHashes: [String] - /// The date and time the record is indexed. - @DateFormatting public var indexedAt: Date - /// The status of the subject. - /// - /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ - /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ - /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ - /// \ - /// Clarifications from Bluesky are needed in order to fully understand this item. - public let moderation: OzoneModeration - /// The repository view of the record. - /// - /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ - /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ - /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ - /// \ - /// Clarifications from Bluesky are needed in order to fully understand this item. - public let repository: OzoneModerationRepositoryView - - public init(recordURI: String, cidHash: String, value: UnknownType, blobCIDHashes: [String], indexedAt: Date, - moderation: OzoneModeration, repository: OzoneModerationRepositoryView) { - self.recordURI = recordURI - self.cidHash = cidHash - self.value = value - self.blobCIDHashes = blobCIDHashes - self._indexedAt = DateFormatting(wrappedValue: indexedAt) - self.moderation = moderation - self.repository = repository - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.recordURI = try container.decode(String.self, forKey: .recordURI) - self.cidHash = try container.decode(String.self, forKey: .cidHash) - self.value = try container.decode(UnknownType.self, forKey: .value) - self.blobCIDHashes = try container.decode([String].self, forKey: .blobCIDHashes) - self.indexedAt = try container.decode(DateFormatting.self, forKey: .indexedAt).wrappedValue - self.moderation = try container.decode(OzoneModeration.self, forKey: .moderation) - self.repository = try container.decode(OzoneModerationRepositoryView.self, forKey: .repository) - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - try container.encode(self.recordURI, forKey: .recordURI) - try container.encode(self.cidHash, forKey: .cidHash) - try container.encode(self.value, forKey: .value) - try container.encode(self.blobCIDHashes, forKey: .blobCIDHashes) - try container.encode(self._indexedAt, forKey: .indexedAt) - try container.encode(self.moderation, forKey: .moderation) - try container.encode(self.repository, forKey: .repository) - } - - enum CodingKeys: String, CodingKey { - case recordURI = "uri" - case cidHash = "cid" - case value - case blobCIDHashes = "blobCids" - case indexedAt - case moderation - case repository = "repo" - } -} - -/// A data model for a definition a detailed view of a record. -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/defs.json -public struct OzoneModerationRecordViewDetail: Codable { - /// The URI of a record. - public let recordURI: String - /// The CID hash of the record. - public let cidHash: String - /// The value of the record. - /// - /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ - /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ - /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ - /// \ - /// Clarifications from Bluesky are needed in order to fully understand this item. - public let value: String - /// An array of CID hashes for blobs. - public let blobs: [OzoneModerationBlobView] - /// An array of labels attached to the record. Optional. - public var labels: [Label]? = nil - /// The date and time the record is indexed. - @DateFormatting public var indexedAt: Date - /// The repository view of the record. - /// - /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ - /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ - /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ - /// \ - /// Clarifications from Bluesky are needed in order to fully understand this item. - public let moderation: OzoneModerationDetail - /// The repository view of the record. - /// - /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ - /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ - /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ - /// \ - /// Clarifications from Bluesky are needed in order to fully understand this item. - public let repository: OzoneModerationRepositoryView - - public init(recordURI: String, cidHash: String, value: String, blobs: [OzoneModerationBlobView], labels: [Label]? = nil, indexedAt: Date, - moderation: OzoneModerationDetail, repository: OzoneModerationRepositoryView) { - self.recordURI = recordURI - self.cidHash = cidHash - self.value = value - self.blobs = blobs - self.labels = labels - self._indexedAt = DateFormatting(wrappedValue: indexedAt) - self.moderation = moderation - self.repository = repository - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.recordURI = try container.decode(String.self, forKey: .recordURI) - self.cidHash = try container.decode(String.self, forKey: .cidHash) - self.value = try container.decode(String.self, forKey: .value) - self.blobs = try container.decode([OzoneModerationBlobView].self, forKey: .blobs) - self.labels = try container.decodeIfPresent([Label].self, forKey: .labels) - self.indexedAt = try container.decode(DateFormatting.self, forKey: .indexedAt).wrappedValue - self.moderation = try container.decode(OzoneModerationDetail.self, forKey: .moderation) - self.repository = try container.decode(OzoneModerationRepositoryView.self, forKey: .repository) - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - try container.encode(self.recordURI, forKey: .recordURI) - try container.encode(self.cidHash, forKey: .cidHash) - try container.encode(self.value, forKey: .value) - try container.encode(self.blobs, forKey: .blobs) - try container.encodeIfPresent(self.labels, forKey: .labels) - try container.encode(self._indexedAt, forKey: .indexedAt) - try container.encode(self.moderation, forKey: .moderation) - try container.encode(self.repository, forKey: .repository) - } - - enum CodingKeys: String, CodingKey { - case recordURI = "uri" - case cidHash = "cid" - case value - case blobs - case labels - case indexedAt - case moderation - case repository = "repo" - } -} - -/// A data model for a definition of a record that may not have been found. -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/defs.json -public struct OzoneModerationRecordViewNotFound: Codable { - /// The URI of the record. - public let recordURI: String - - enum CodingKeys: String, CodingKey { - case recordURI = "uri" - } -} - -/// A data model of a definition for moderation. -/// -/// - Important: The item associated with this struct is undocumented in the AT Protocol specifications. The documentation here is based on:\ -/// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ -/// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ -/// \ -/// Clarifications from Bluesky are needed in order to fully understand this item. -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/defs.json -public struct OzoneModeration: Codable { - /// The status of the subject. Optional. - /// - /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ - /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ - /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ - /// \ - /// Clarifications from Bluesky are needed in order to fully understand this item. - public var subjectStatus: OzoneSubjectStatusView? = nil -} - -/// A data model of a definition for a detailed moderation. -/// -/// - Important: The item associated with this struct is undocumented in the AT Protocol specifications. The documentation here is based on:\ -/// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ -/// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ -/// \ -/// Clarifications from Bluesky are needed in order to fully understand this item. -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/defs.json -public struct OzoneModerationDetail: Codable { - /// The status of the subject. Optional. - /// - /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ - /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ - /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ - /// \ - /// Clarifications from Bluesky are needed in order to fully understand this item. - public var subjectStatus: OzoneSubjectStatusView? = nil -} - -/// The data model for a definition of a blob view. -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/defs.json -public struct OzoneModerationBlobView: Codable { - /// The CID hash of the blob. - public let cidHash: String - /// The MIME type of the blob. - public let mimeType: String - /// The size of the blob. Written in bytes. - public let size: Int - /// The date and time the blob was created. - @DateFormatting public var createdAt: Date - /// The type of media in the blob. - public let details: MediaDetailUnion - /// The status of the subject. - public let moderation: OzoneModeration - - public init(cidHash: String, mimeType: String, size: Int, createdAt: Date, details: MediaDetailUnion, moderation: OzoneModeration) { - self.cidHash = cidHash - self.mimeType = mimeType - self.size = size - self._createdAt = DateFormatting(wrappedValue: createdAt) - self.details = details - self.moderation = moderation - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.cidHash = try container.decode(String.self, forKey: .cidHash) - self.mimeType = try container.decode(String.self, forKey: .mimeType) - self.size = try container.decode(Int.self, forKey: .size) - self.createdAt = try container.decode(DateFormatting.self, forKey: .createdAt).wrappedValue - self.details = try container.decode(MediaDetailUnion.self, forKey: .details) - self.moderation = try container.decode(OzoneModeration.self, forKey: .moderation) - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - try container.encode(self.cidHash, forKey: .cidHash) - try container.encode(self.mimeType, forKey: .mimeType) - try container.encode(self.size, forKey: .size) - try container.encode(self._createdAt, forKey: .createdAt) - try container.encode(self.details, forKey: .details) - try container.encode(self.moderation, forKey: .moderation) - } - - enum CodingKeys: String, CodingKey { - case cidHash = "cid" - case mimeType - case size - case createdAt - case details - case moderation - } -} - -/// A data model for a definition of details for an image. -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/defs.json -public struct OzoneModerationMediaImageDetails: Codable { - /// The width of the image. - public let width: Int - /// The height of the image. - public let height: Int -} - -/// A data model for a definition of details for a video. -/// -/// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/defs.json -public struct OzoneModerationMediaVideoDetails: Codable { - /// The width of the video. - public let width: Int - /// The height of the video. - public let height: Int - /// The duration of the video. - public let length: Int -} diff --git a/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Moderation/OzoneModerationEmitEvent.swift b/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Moderation/OzoneModerationEmitEvent.swift deleted file mode 100644 index b315bb803d..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Moderation/OzoneModerationEmitEvent.swift +++ /dev/null @@ -1,33 +0,0 @@ -// -// OzoneModerationEmitEvent.swift -// -// -// Created by Christopher Jr Riley on 2024-05-01. -// - -import Foundation - -/// The main data model definition for enacting on an action against a user's account. -/// -/// - Note: According to the AT Protocol specifications: "Take a moderation action on an actor." -/// -/// - SeeAlso: This is based on the [`tools.ozone.moderation.emitEvent`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/emitEvent.json -public struct ModerationEmitEvent: Codable { - /// The type of event the moderator is taking, - public let event: AdminEventViewUnion - /// The type of repository reference. - public let subject: RepositoryReferencesUnion - /// An array of CID hashes related to blobs for the moderator's event view. Optional. - public let subjectBlobCIDHashes: [String]? - /// The decentralized identifier (DID) of the moderator taking this action. - public let createdBy: String - - enum CodingKeys: String, CodingKey { - case event - case subject - case subjectBlobCIDHashes = "subjectBlobCids" - case createdBy - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Moderation/OzoneModerationQueryEvents.swift b/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Moderation/OzoneModerationQueryEvents.swift deleted file mode 100644 index 69ca02e21f..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Moderation/OzoneModerationQueryEvents.swift +++ /dev/null @@ -1,31 +0,0 @@ -// -// OzoneModerationQueryEvents.swift -// -// -// Created by Christopher Jr Riley on 2024-03-01. -// - -import Foundation - -/// The main data model definition for listing all moderation events pertaining a subject. -/// -/// - Note: According to the AT Protocol specifications: "List moderation events related -/// to a subject." -/// -/// - SeeAlso: This is based on the [`tools.ozone.moderation.queryEvents`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/queryEvents.json -public struct ModerationQueryEventsOutput: Codable { - /// The mark used to indicate the starting point for the next set of results. Optional. - public let cursor: String? - /// An array of moderator events. - public let events: [OzoneModerationEventView] -} - -/// Indicates the sorting direction for the array of moderation events. -public enum AdminQueryModerationEventSortDirection: String { - /// Indicates the moderation events will be sorted in ascending order. - case ascending = "asc" - /// Indicates the moderation events will be sorted in descending order. - case descending = "desc" -} diff --git a/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Moderation/OzoneModerationQueryStatuses.swift b/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Moderation/OzoneModerationQueryStatuses.swift deleted file mode 100644 index c2ae6a7ee0..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Moderation/OzoneModerationQueryStatuses.swift +++ /dev/null @@ -1,23 +0,0 @@ -// -// OzoneModerationQueryStatuses.swift -// -// -// Created by Christopher Jr Riley on 2024-05-01. -// - -import Foundation - -/// The main data model definition for listing all moderation events pertaining a subject. -/// -/// - Note: According to the AT Protocol specifications: "View moderation statuses of subjects -/// (record or repo)." -/// -/// - SeeAlso: This is based on the [`ools.ozone.moderation.queryStatuses`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/queryEvents.json -public struct ModerationQueryStatusesOutput: Codable { - /// The mark used to indicate the starting point for the next set of results. Optional. - public let cursor: String? - /// An array of subject status views. - public let subjectStatuses: [OzoneSubjectStatusView] -} diff --git a/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Moderation/OzoneModerationSearchRepos.swift b/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Moderation/OzoneModerationSearchRepos.swift deleted file mode 100644 index c800ba0758..0000000000 --- a/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Moderation/OzoneModerationSearchRepos.swift +++ /dev/null @@ -1,28 +0,0 @@ -// -// OzoneModerationSearchRepos.swift -// -// -// Created by Christopher Jr Riley on 2024-05-01. -// - -import Foundation - -/// The output model definition for searching for repositories as an administrator or moderator. -/// -/// - Note: According to the AT Protocol specifications: "Find repositories based on a -/// search term." -/// -/// - SeeAlso: This is based on the [`tools.ozone.moderation.searchRepos`][github] lexicon. -/// -/// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/searchRepos.json -public struct ModerationSearchRepositoryOutput: Codable { - /// The mark used to indicate the starting point for the next set of results. Optional. - public let cursor: String? - /// An array of repository views. - public let repositories: [OzoneModerationRepositoryView] - - enum CodingKeys: String, CodingKey { - case cursor - case repositories = "repos" - } -} diff --git a/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Moderation/ToolsOzoneModerationDefs.swift b/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Moderation/ToolsOzoneModerationDefs.swift new file mode 100644 index 0000000000..f17b21ac59 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Moderation/ToolsOzoneModerationDefs.swift @@ -0,0 +1,1229 @@ +// +// ToolsOzoneModerationDefs.swift +// +// +// Created by Christopher Jr Riley on 2024-05-20. +// + +import Foundation + +extension ToolsOzoneLexicon.Moderation { + + /// A definition model for a moderation event view. + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/defs.json + public struct ModerationEventViewDefinition: Codable { + + /// The ID of the moderator's event view. + public let id: Int + + /// The type of the moderator's event view. + public let event: ATUnion.ModerationEventViewUnion + + /// The subject reference of the moderator's event view. + public let subject: ATUnion.ModerationEventViewSubjectUnion + + /// An array of CID hashes related to blobs for the moderator's event view. + public let subjectBlobCIDHashes: [String] + + /// The creator of the event view. + public let createdBy: String + + /// The date and time the event view was created. + @DateFormatting public var createdAt: Date + + /// The handle of the moderator. Optional. + public var creatorHandle: String? + + /// The subject handle of the event view. Optional. + public var subjectHandle: String? + + public init(id: Int, event: ATUnion.ModerationEventViewUnion, subject: ATUnion.ModerationEventViewSubjectUnion, subjectBlobCIDHashes: [String], createdBy: String, + createdAt: Date, creatorHandle: String?, subjectHandle: String?) { + self.id = id + self.event = event + self.subject = subject + self.subjectBlobCIDHashes = subjectBlobCIDHashes + self.createdBy = createdBy + self._createdAt = DateFormatting(wrappedValue: createdAt) + self.creatorHandle = creatorHandle + self.subjectHandle = subjectHandle + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.id = try container.decode(Int.self, forKey: .id) + self.event = try container.decode(ATUnion.ModerationEventViewUnion.self, forKey: .event) + self.subject = try container.decode(ATUnion.ModerationEventViewSubjectUnion.self, forKey: .subject) + self.subjectBlobCIDHashes = try container.decode([String].self, forKey: .subjectBlobCIDHashes) + self.createdBy = try container.decode(String.self, forKey: .createdBy) + self.createdAt = try container.decode(DateFormatting.self, forKey: .createdAt).wrappedValue + self.creatorHandle = try container.decodeIfPresent(String.self, forKey: .creatorHandle) + self.subjectHandle = try container.decodeIfPresent(String.self, forKey: .subjectHandle) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.id, forKey: .id) + try container.encode(self.event, forKey: .event) + try container.encode(self.subject, forKey: .subject) + try container.encode(self.subjectBlobCIDHashes, forKey: .subjectBlobCIDHashes) + try container.encode(self.createdBy, forKey: .createdBy) + try container.encode(self._createdAt, forKey: .createdAt) + try container.encodeIfPresent(self.creatorHandle, forKey: .creatorHandle) + try container.encodeIfPresent(self.subjectHandle, forKey: .subjectHandle) + } + + enum CodingKeys: String, CodingKey { + case id + case event + case subject + case subjectBlobCIDHashes = "subjectBlobCids" + case createdBy + case createdAt + case creatorHandle + case subjectHandle + } + } + + /// A definition model for a detailed moderation event view + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/defs.json + public struct EventViewDetailDefinition: Codable { + + /// The ID of the moderator's event view. + public let id: Int + + /// The type of the moderator's event view. + public let event: ATUnion.ModerationEventViewDetailUnion + + /// The subject reference of the moderator's event view. + public let subject: ATUnion.ModerationEventViewDetailSubjectUnion + + /// An array of blobs for a moderator to look at. + public let subjectBlobs: [ToolsOzoneLexicon.Moderation.BlobViewDefinition] + + /// The creator of the event view. + public let createdBy: String + + /// The date and time the event view was created. + @DateFormatting public var createdAt: Date + + public init(id: Int, event: ATUnion.ModerationEventViewDetailUnion, subject: ATUnion.ModerationEventViewDetailSubjectUnion, subjectBlobs: [ToolsOzoneLexicon.Moderation.BlobViewDefinition], + createdBy: String, createdAt: Date) { + self.id = id + self.event = event + self.subject = subject + self.subjectBlobs = subjectBlobs + self.createdBy = createdBy + self._createdAt = DateFormatting(wrappedValue: createdAt) + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.id = try container.decode(Int.self, forKey: .id) + self.event = try container.decode(ATUnion.ModerationEventViewDetailUnion.self, forKey: .event) + self.subject = try container.decode(ATUnion.ModerationEventViewDetailSubjectUnion.self, forKey: .subject) + self.subjectBlobs = try container.decode([ToolsOzoneLexicon.Moderation.BlobViewDefinition].self, forKey: .subjectBlobs) + self.createdBy = try container.decode(String.self, forKey: .createdBy) + self.createdAt = try container.decode(DateFormatting.self, forKey: .createdAt).wrappedValue + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.id, forKey: .id) + try container.encode(self.event, forKey: .event) + try container.encode(self.subject, forKey: .subject) + try container.encode(self.subjectBlobs, forKey: .subjectBlobs) + try container.encode(self.createdBy, forKey: .createdBy) + try container.encode(self._createdAt, forKey: .createdAt) + } + + enum CodingKeys: CodingKey { + case id + case event + case subject + case subjectBlobs + case createdBy + case createdAt + } + } + + /// A definition model for a subject's status view. + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/defs.json + public struct SubjectStatusViewDefinition: Codable { + + /// The ID of the status view. + public let id: Int + + /// The subject reference of the status view. + public let subject: ATUnion.SubjectStatusViewSubjectUnion + + /// An array of CID hashes related to blobs. Optional. + public var subjectBlobCIDHashes: [String]? + + /// The handle of the subject related to the status. Optional. + public var subjectRepoHandle: String? + + /// The date and time of the last update for the status view. + /// + /// - Note: According to the AT Protocol specifications: "Timestamp referencing when + /// the last update was made to the moderation status of the subject." + @DateFormatting public var updatedAt: Date + + /// The date and time of the day the first event occured. + /// + /// - Note: According to the AT Protocol specifications: "Timestamp referencing the first + /// moderation status impacting event was emitted on the subject." + @DateFormatting public var createdAt: Date + + /// The review status of the subject. + public let reviewState: ToolsOzoneLexicon.Moderation.SubjectReviewStateDefinition + + /// Any additional comments written about the subject. Optional. + public var comment: String? + + /// The date and time the subject's time to be muted has been lifted. Optional. + /// + /// - Note: According to the AT Protocol specifications: "Sticky comment on the subject." + @DateFormattingOptional public var muteUntil: Date? + + /// The date and time until which reporting on the subject is muted. Optional. + /// + /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ + /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ + /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ + /// \ + /// Clarifications from Bluesky are needed in order to fully understand this item. + @DateFormattingOptional public var muteReportingUntil: Date? + + /// The name of the reviewer that reviewed the subject. Optional. + public var lastReviewedBy: String? + + /// The date and time the last reviewer looked at the subject. Optional. + @DateFormattingOptional public var lastReviewedAt: Date? + + /// The date and time of the last report about the subject. Optional. + @DateFormattingOptional public var lastReportedAt: Date? + + /// The date and time of the last appeal. Optional. + @DateFormattingOptional public var lastAppealedAt: Date? + + /// Indicates whether the subject was taken down. Optional. + public var isTakenDown: Bool? + + /// Indicates whether an appeal has been made. Optional. + public var wasAppealed: Bool? + + /// The date and time the subject's suspension will be lifted. Optional. + @DateFormattingOptional public var suspendUntil: Date? + + /// An array of tags. Optional. + public var tags: [String]? + + public init(id: Int, subject: ATUnion.SubjectStatusViewSubjectUnion, subjectBlobCIDHashes: [String]?, subjectRepoHandle: String?, updatedAt: Date, createdAt: Date, + reviewState: ToolsOzoneLexicon.Moderation.SubjectReviewStateDefinition, comment: String?, muteUntil: Date?, muteReportingUntil: Date?, + lastReviewedBy: String?, lastReviewedAt: Date?, lastReportedAt: Date?, lastAppealedAt: Date?, isTakenDown: Bool?, wasAppealed: Bool?, + suspendUntil: Date?, tags: [String]?) { + self.id = id + self.subject = subject + self.subjectBlobCIDHashes = subjectBlobCIDHashes + self.subjectRepoHandle = subjectRepoHandle + self._updatedAt = DateFormatting(wrappedValue: updatedAt) + self._createdAt = DateFormatting(wrappedValue: createdAt) + self.reviewState = reviewState + self.comment = comment + self.muteUntil = muteUntil + self._muteReportingUntil = DateFormattingOptional(wrappedValue: muteReportingUntil) + self.lastReviewedBy = lastReviewedBy + self._lastReviewedAt = DateFormattingOptional(wrappedValue: lastReviewedAt) + self._lastReportedAt = DateFormattingOptional(wrappedValue: lastReportedAt) + self._lastAppealedAt = DateFormattingOptional(wrappedValue: lastAppealedAt) + self.isTakenDown = isTakenDown + self.wasAppealed = wasAppealed + self._suspendUntil = DateFormattingOptional(wrappedValue: suspendUntil) + self.tags = tags + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.id = try container.decode(Int.self, forKey: .id) + self.subject = try container.decode(ATUnion.SubjectStatusViewSubjectUnion.self, forKey: .subject) + self.subjectBlobCIDHashes = try container.decodeIfPresent([String].self, forKey: .subjectBlobCIDHashes) + self.subjectRepoHandle = try container.decodeIfPresent(String.self, forKey: .subjectRepoHandle) + self.updatedAt = try container.decode(DateFormatting.self, forKey: .updatedAt).wrappedValue + self.createdAt = try container.decode(DateFormatting.self, forKey: .createdAt).wrappedValue + self.reviewState = try container.decode(ToolsOzoneLexicon.Moderation.SubjectReviewStateDefinition.self, forKey: .reviewState) + self.comment = try container.decodeIfPresent(String.self, forKey: .comment) + self.muteUntil = try container.decodeIfPresent(DateFormattingOptional.self, forKey: .muteUntil)?.wrappedValue + self.muteReportingUntil = try container.decodeIfPresent(DateFormattingOptional.self, forKey: .muteReportingUntil)?.wrappedValue + self.lastReviewedBy = try container.decodeIfPresent(String.self, forKey: .lastReviewedBy) + self.lastReviewedAt = try container.decodeIfPresent(DateFormattingOptional.self, forKey: .lastReviewedAt)?.wrappedValue + self.lastReportedAt = try container.decodeIfPresent(DateFormattingOptional.self, forKey: .lastReportedAt)?.wrappedValue + self.lastAppealedAt = try container.decodeIfPresent(DateFormattingOptional.self, forKey: .lastAppealedAt)?.wrappedValue + self.isTakenDown = try container.decodeIfPresent(Bool.self, forKey: .isTakenDown) + self.wasAppealed = try container.decodeIfPresent(Bool.self, forKey: .wasAppealed) + self.suspendUntil = try container.decodeIfPresent(DateFormattingOptional.self, forKey: .suspendUntil)?.wrappedValue + self.tags = try container.decode([String].self, forKey: .tags) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.id, forKey: .id) + try container.encode(self.subject, forKey: .subject) + try container.encodeIfPresent(self.subjectBlobCIDHashes, forKey: .subjectBlobCIDHashes) + try container.encodeIfPresent(self.subjectRepoHandle, forKey: .subjectRepoHandle) + try container.encode(self._updatedAt, forKey: .updatedAt) + try container.encode(self._createdAt, forKey: .createdAt) + try container.encode(self.reviewState, forKey: .reviewState) + try container.encodeIfPresent(self.comment, forKey: .comment) + try container.encode(self._muteUntil, forKey: .muteUntil) + try container.encodeIfPresent(self._muteReportingUntil, forKey: .muteReportingUntil) + try container.encodeIfPresent(self.lastReviewedBy, forKey: .lastReviewedBy) + try container.encode(self._lastReviewedAt, forKey: .lastReviewedAt) + try container.encode(self._lastReportedAt, forKey: .lastReportedAt) + try container.encode(self._lastAppealedAt, forKey: .lastAppealedAt) + try container.encodeIfPresent(self.isTakenDown, forKey: .isTakenDown) + try container.encodeIfPresent(self.wasAppealed, forKey: .wasAppealed) + try container.encode(self._suspendUntil, forKey: .suspendUntil) + try container.encode(self.tags, forKey: .tags) + } + + enum CodingKeys: String, CodingKey { + case id + case subject + case subjectBlobCIDHashes = "subjectBlobCids" + case subjectRepoHandle + case updatedAt + case createdAt + case reviewState + case comment + case muteUntil + case muteReportingUntil + case lastReviewedBy + case lastReviewedAt + case lastReportedAt + case lastAppealedAt + case isTakenDown = "takendown" + case wasAppealed = "appealed" + case suspendUntil + case tags + } + } + + /// A definition model for the subject review state. + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/defs.json + public enum SubjectReviewStateDefinition: String, Codable { + + /// Moderator review status of a subject: Open. Indicates that the subject needs to be + /// reviewed by a moderator. + /// + /// - Note: The above documentation was taken directly from the AT Protocol specifications. + case reviewOpen + + /// Moderator review status of a subject: Escalated. Indicates that the subject was + /// escalated for review by a moderator. + /// + /// - Note: The above documentation was taken directly from the AT Protocol specifications. + case reviewEscalated + + /// Moderator review status of a subject: Closed. Indicates that the subject was already + /// reviewed and resolved by a moderator. + /// + /// - Note: The above documentation was taken directly from the AT Protocol specifications. + case reviewClosed + + /// Moderator review status of a subject: Unnecessary. Indicates that the subject does + /// not need a review at the moment but there + /// is probably some moderation related metadata available for it + /// + /// - Note: The above documentation was taken directly from the AT Protocol specifications. + case reviewNone + } + + /// A definition model for an event takedown. + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/defs.json + public struct EventTakedownDefinition: Codable { + + /// Any additional comments for the takedown event. Optional. + /// + /// - Note: According to the AT Protocol specifications: "Take down a subject permanently + /// or temporarily." + public let comment: String? + + /// The amount of time (in hours) for the user to be considered takendown. Optional. + /// + /// - Note: According to the AT Protocol specifications: "Indicates how long the takedown + /// should be in effect before automatically expiring." + public let durationInHours: Int? + } + + /// A definition model for a reverse takedown event. + /// + /// - Note: According to the AT Protocol specifications: "Revert take down action on + /// a subject." + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/defs.json + public struct EventReverseTakedownDefinition: Codable { + + /// Any comments for the reverse takedown event. Optional. + /// + /// - Note: According to the AT Protocol specifications: "Describe reasoning behind + /// the reversal." + public let comment: String? + } + + /// A definition model for an resolved appeal event. + /// + /// - Note: According to the AT Protocol specifications: "Resolve appeal on a subject." + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/defs.json + public struct EventResolveAppealDefinition: Codable { + + /// Any comments for the moderator's appeal resolution event. Optional. + /// + /// - Note: According to the AT Protocol specifications: "Describe resolution." + public let comment: String? + } + + /// A definition model for a comment event. + /// + /// - Note: According to the AT Protocol specifications: "Add a comment to a subject." + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/defs.json + public struct EventCommentDefinition: Codable { + + /// Any comment for the moderator's comment event. + public let comment: String + + /// Indicates whether the moderator event is sticky. Optional. + /// + /// - Note: According to the AT Protocol specifications: "Make the comment persistent on the subject." + public let isSticky: Bool? + + enum CodingKeys: String, CodingKey { + case comment + case isSticky = "sticky" + } + } + + /// A definition model for a report event. + /// + /// - Note: According to the AT Protocol specifications: "Report a subject." + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/defs.json + public struct EventReportDefinition: Codable { + + /// Any comments for the moderator's report event. Optional. + public var comment: String? + + /// Indicates whether the reporter has been muted. Optional. + /// + /// - Note: According to the AT Protocol specifications: "Set to true if the reporter + /// was muted from reporting at the time of the event. These reports won't impact + /// the reviewState of the subject." + public let isReporterMuted: Bool? + + /// The type of report. + public let reportType: ComAtprotoLexicon.Moderation.ReasonTypeDefinition + } + + /// A definition model for a label event. + /// + /// - Note: According to the AT Protocol specifications: "Apply/Negate labels on a subject" + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/defs.json + public struct EventLabelDefinition: Codable { + + /// Any comments for the moderator's label event. Optional. + public let comment: String? + + /// An array of labels that apply to a user. + public let createLabelValues: [String] + + /// An array of labels that's applied to a user for the purpose of negating. + public let negateLabelValues: [String] + + enum CodingKeys: String, CodingKey { + case comment + case createLabelValues = "createLabelVals" + case negateLabelValues = "negateLabelVals" + } + } + + /// A definition model for an acknowledgement event. + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/defs.json + public struct EventAcknowledgeDefinition: Codable { + + /// Any comments for the moderator's acknowledge event. Optional. + public var comment: String? + } + + /// A definition model for an acknowledgement event. + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/defs.json + public struct EventEscalateDefinition: Codable { + + /// Any additional comments for escalating a report. Optional. + public var comment: String? + } + + /// A definition model for a definition of a mute event. + /// + /// - Note: According to the AT Protocol specifications: "Mute incoming reports on a subject." + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/defs.json + public struct EventMuteDefinition: Codable { + + /// Any additional comments for the mute event. Optional. + public var comment: String? + + /// The amount of time (in hours) that the moderator has put in for muting a user. + /// + /// - Note: According to the AT Protocol specifications: "Indicates how long the + /// subject should remain muted." + public let durationInHours: Int + } + + /// A definition model for an unmute event definition. + /// + /// - Note: According to the AT Protocol specifications: "Unmute action on a subject." + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/defs.json + public struct EventUnmuteDefinition: Codable { + + /// Any comments for the moderator's unmute event. Optional. + /// + /// - Note: According to the AT Protocol specifications: "Describe reasoning behind + /// the reversal." + public var comment: String? + } + + /// A definition model for a mute reporter event. + /// + /// - Note: According to the AT Protocol specifications: "Mute incoming reports from + /// an account." + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/defs.json + public struct EventMuteReporterDefinition: Codable { + + /// Indicates how long the account should remain muted (in hours). + /// + /// - Note: According to the AT Protocol specifications: "Indicates how long the + /// account should remain muted." + public let durationInHours: Int + + /// Any additional comments about the event. Optional. + public let comment: String? + } + + /// A definition model for an unmute reporter event. + /// + /// - Note: According to the AT Protocol specifications: "Unmute incoming reports + /// from an account." + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/defs.json + public struct EventUnmuteReporterDefinition: Codable { + + /// Any additional comments about the event. + /// + /// - Note: According to the AT Protocol specifications: "Describe reasoning + /// behind the reversal." + public let comment: String? + } + + /// A definition model for an email event. + /// + /// - Note: According to the AT Protocol specifications: "Keep a log of outgoing email to a user." + /// + /// - SeeAlso: This is based on the [`tools.ozone.moderation.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/defs.json + public struct EventEmailDefinition: Codable { + + /// The subject line of the email. + /// + /// - Note: According to the AT Protocol specifications: "The subject line of the email + /// sent to the user." + public let subjectLine: String + + /// The body of the email. + /// + /// - Note: According to the AT Protocol specifications: "The content of the email + /// sent to the user." + public let content: String + + /// Any additional comments about the email. Optional. + /// + /// - Note: According to the AT Protocol specifications: "Additional comment about + /// the outgoing comm." + public var comment: String? + } + + /// A definition model for a diversion event. + /// + /// - Note: According to the AT Protocol specifications: "Divert a record's blobs to a + /// 3rd party service for further scanning/tagging" + /// + /// - SeeAlso: This is based on the [`tools.ozone.moderation.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/defs.json + public struct EventDivertDefinition: Codable { + + /// Any additional comments about the diversion. + public let comment: String? + } + + /// A definition model for a tag event definition. + /// + /// - Note: According to the AT Protocol specifications: "Add/Remove a tag on a subject." + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/defs.json + public struct EventTagDefinition: Codable { + + /// An array of tags to be added to the user. + /// + /// If a tag in the array already exists on the user, then the tag will be ignored. + /// + /// - Note: According to the AT Protocol specifications: "Tags to be added to + /// the subject. If already exists, won't be duplicated." + public let add: [String] + + /// An array of tags to be removed from the user. + /// + /// If a tag in the array doesn't exist on the user, then the tag will be ignored. + /// + /// - Note: According to the AT Protocol specifications: "Tags to be removed to + /// the subject. Ignores a tag If it doesn't exist, won't be duplicated." + public let remove: [String] + + /// Any additional comments about the moderator's tag event. + /// + /// - Note: According to the AT Protocol specifications: "Additional comment about + /// added/removed tags." + public let comment: String? + } + + /// A definition model for a repository view. + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/defs.json + public struct RepositoryViewDefinition: Codable { + + /// The decentralized identifier (DID) of the user. + public let actorDID: String + + /// The handle of the user. + public let handle: String + + /// The email of the user. Optional. + public var email: String? + + /// The related records of the user. + /// + /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ + /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ + /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ + /// \ + /// Clarifications from Bluesky are needed in order to fully understand this item. + public let relatedRecords: UnknownType + + /// The date and time the user was indexed. + @DateFormatting public var indexedAt: Date + + /// The moderation status of the user. + public let moderation: ToolsOzoneLexicon.Moderation.ModerationDefinition + + /// The invite code used by the user to sign up. Optional. + public var invitedBy: ComAtprotoLexicon.Server.InviteCodeDefinition? + + /// Indicates whether the invite codes held by the user are diabled. Optional. + public var areInvitesDisabled: Bool? + + /// The note of the invite. Optional. + public var inviteNote: String? + + public init(actorDID: String, handle: String, email: String? = nil, relatedRecords: UnknownType, indexedAt: Date, + moderation: ToolsOzoneLexicon.Moderation.ModerationDefinition, invitedBy: ComAtprotoLexicon.Server.InviteCodeDefinition? = nil, areInvitesDisabled: Bool? = nil, + inviteNote: String? = nil) { + self.actorDID = actorDID + self.handle = handle + self.email = email + self.relatedRecords = relatedRecords + self._indexedAt = DateFormatting(wrappedValue: indexedAt) + self.moderation = moderation + self.invitedBy = invitedBy + self.areInvitesDisabled = areInvitesDisabled + self.inviteNote = inviteNote + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.actorDID = try container.decode(String.self, forKey: .actorDID) + self.handle = try container.decode(String.self, forKey: .handle) + self.email = try container.decodeIfPresent(String.self, forKey: .email) + self.relatedRecords = try container.decode(UnknownType.self, forKey: .relatedRecords) + self.indexedAt = try container.decode(DateFormatting.self, forKey: .indexedAt).wrappedValue + self.moderation = try container.decode(ToolsOzoneLexicon.Moderation.ModerationDefinition.self, forKey: .moderation) + self.invitedBy = try container.decodeIfPresent(ComAtprotoLexicon.Server.InviteCodeDefinition.self, forKey: .invitedBy) + self.areInvitesDisabled = try container.decodeIfPresent(Bool.self, forKey: .areInvitesDisabled) + self.inviteNote = try container.decodeIfPresent(String.self, forKey: .inviteNote) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.actorDID, forKey: .actorDID) + try container.encode(self.handle, forKey: .handle) + try container.encodeIfPresent(self.email, forKey: .email) + try container.encode(self.relatedRecords, forKey: .relatedRecords) + try container.encode(self._indexedAt, forKey: .indexedAt) + try container.encode(self.moderation, forKey: .moderation) + try container.encodeIfPresent(self.invitedBy, forKey: .invitedBy) + try container.encodeIfPresent(self.areInvitesDisabled, forKey: .areInvitesDisabled) + try container.encodeIfPresent(self.inviteNote, forKey: .inviteNote) + } + + enum CodingKeys: String, CodingKey { + case actorDID = "did" + case handle + case email + case relatedRecords + case indexedAt + case moderation + case invitedBy + case areInvitesDisabled = "invitesDisabled" + case inviteNote + } + } + + /// A definition model for a detailed repository view. + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/defs.json + public struct RepositoryViewDetailDefinition: Codable { + + /// The decentralized identifier (DID) of the user. + public let actorDID: String + + /// The handle of the user. + public let handle: String + + /// The email of the user. Optional. + public var email: String? + + /// The user's related records. + /// + /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ + /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ + /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ + /// \ + /// Clarifications from Bluesky are needed in order to fully understand this item. + public let relatedRecords: UnknownType + + /// The date and time the user was last indexed. + @DateFormatting public var indexedAt: Date + + /// The detailed moderation status of the user. + public let moderation: ToolsOzoneLexicon.Moderation.ModerationDetailDefinition + + /// An array of labels associated with the user. Optional. + public var labels: [ComAtprotoLexicon.Label.LabelDefinition]? + + /// The invite code used by the user to sign up. Optional. + public let invitedBy: ComAtprotoLexicon.Server.InviteCodeDefinition? + + /// An array of invite codes held by the user. Optional. + public var invites: [ComAtprotoLexicon.Server.InviteCodeDefinition]? + + /// Indicates whether the invite codes held by the user are diabled. Optional. + public var areInvitesDisabled: Bool? + + /// The note of the invite. Optional. + public var inviteNote: String? + + /// The date and time the email of the user was confirmed. Optional. + @DateFormattingOptional public var emailConfirmedAt: Date? + + public init(actorDID: String, handle: String, email: String?, relatedRecords: UnknownType, indexedAt: Date, + moderation: ToolsOzoneLexicon.Moderation.ModerationDetailDefinition, labels: [ComAtprotoLexicon.Label.LabelDefinition]?, + invitedBy: ComAtprotoLexicon.Server.InviteCodeDefinition?, invites: [ComAtprotoLexicon.Server.InviteCodeDefinition]?, + areInvitesDisabled: Bool?, inviteNote: String?, emailConfirmedAt: Date? = nil) { + self.actorDID = actorDID + self.handle = handle + self.email = email + self.relatedRecords = relatedRecords + self._indexedAt = DateFormatting(wrappedValue: indexedAt) + self.moderation = moderation + self.labels = labels + self.invitedBy = invitedBy + self.invites = invites + self.areInvitesDisabled = areInvitesDisabled + self.inviteNote = inviteNote + self._emailConfirmedAt = DateFormattingOptional(wrappedValue: emailConfirmedAt) + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.actorDID = try container.decode(String.self, forKey: .actorDID) + self.handle = try container.decode(String.self, forKey: .handle) + self.email = try container.decodeIfPresent(String.self, forKey: .email) + self.relatedRecords = try container.decode(UnknownType.self, forKey: .relatedRecords) + self.indexedAt = try container.decode(DateFormatting.self, forKey: .indexedAt).wrappedValue + self.moderation = try container.decode(ToolsOzoneLexicon.Moderation.ModerationDetailDefinition.self, forKey: .moderation) + self.labels = try container.decodeIfPresent([ComAtprotoLexicon.Label.LabelDefinition].self, forKey: .labels) + self.invitedBy = try container.decodeIfPresent(ComAtprotoLexicon.Server.InviteCodeDefinition.self, forKey: .invitedBy) + self.invites = try container.decodeIfPresent([ComAtprotoLexicon.Server.InviteCodeDefinition].self, forKey: .invites) + self.areInvitesDisabled = try container.decodeIfPresent(Bool.self, forKey: .areInvitesDisabled) + self.inviteNote = try container.decodeIfPresent(String.self, forKey: .inviteNote) + self.emailConfirmedAt = try container.decodeIfPresent(DateFormattingOptional.self, forKey: .emailConfirmedAt)?.wrappedValue + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.actorDID, forKey: .actorDID) + try container.encode(self.handle, forKey: .handle) + try container.encodeIfPresent(self.email, forKey: .email) + try container.encode(self.relatedRecords, forKey: .relatedRecords) + try container.encode(self._indexedAt, forKey: .indexedAt) + try container.encode(self.moderation, forKey: .moderation) + try container.encodeIfPresent(self.labels, forKey: .labels) + try container.encodeIfPresent(self.invitedBy, forKey: .invitedBy) + try container.encodeIfPresent(self.invites, forKey: .invites) + try container.encodeIfPresent(self.areInvitesDisabled, forKey: .areInvitesDisabled) + try container.encodeIfPresent(self.inviteNote, forKey: .inviteNote) + try container.encode(self._emailConfirmedAt, forKey: .emailConfirmedAt) + } + + enum CodingKeys: String, CodingKey { + case actorDID = "did" + case handle + case email + case relatedRecords + case indexedAt + case moderation + case labels + case invitedBy + case invites + case areInvitesDisabled = "invitesDisabled" + case inviteNote + case emailConfirmedAt + } + } + + /// A definition model for a respository view that may not have been found. + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/defs.json + public struct RepositoryViewNotFoundDefinition: Codable { + + /// The decentralized identifier (DID) of the repository. + public let repositoryDID: String + + enum CodingKeys: String, CodingKey { + case repositoryDID = "did" + } + } + + /// A definition model for a record view. + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/defs.json + public struct RecordViewDefinition: Codable { + + /// The URI of the record. + public let recordURI: String + + /// The CID hash of the record. + public let cidHash: String + + /// The value of the record. + /// + /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ + /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ + /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ + /// \ + /// Clarifications from Bluesky are needed in order to fully understand this item. + public let value: UnknownType + + /// An array of CID hashes for blobs. + public let blobCIDHashes: [String] + + /// The date and time the record is indexed. + @DateFormatting public var indexedAt: Date + + /// The status of the subject. + /// + /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ + /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ + /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ + /// \ + /// Clarifications from Bluesky are needed in order to fully understand this item. + public let moderation: ToolsOzoneLexicon.Moderation.ModerationDefinition + + /// The repository view of the record. + /// + /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ + /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ + /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ + /// \ + /// Clarifications from Bluesky are needed in order to fully understand this item. + public let repository: ToolsOzoneLexicon.Moderation.RepositoryViewDefinition + + public init(recordURI: String, cidHash: String, value: UnknownType, blobCIDHashes: [String], indexedAt: Date, + moderation: ToolsOzoneLexicon.Moderation.ModerationDefinition, repository: ToolsOzoneLexicon.Moderation.RepositoryViewDefinition) { + self.recordURI = recordURI + self.cidHash = cidHash + self.value = value + self.blobCIDHashes = blobCIDHashes + self._indexedAt = DateFormatting(wrappedValue: indexedAt) + self.moderation = moderation + self.repository = repository + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.recordURI = try container.decode(String.self, forKey: .recordURI) + self.cidHash = try container.decode(String.self, forKey: .cidHash) + self.value = try container.decode(UnknownType.self, forKey: .value) + self.blobCIDHashes = try container.decode([String].self, forKey: .blobCIDHashes) + self.indexedAt = try container.decode(DateFormatting.self, forKey: .indexedAt).wrappedValue + self.moderation = try container.decode(ToolsOzoneLexicon.Moderation.ModerationDefinition.self, forKey: .moderation) + self.repository = try container.decode(ToolsOzoneLexicon.Moderation.RepositoryViewDefinition.self, forKey: .repository) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.recordURI, forKey: .recordURI) + try container.encode(self.cidHash, forKey: .cidHash) + try container.encode(self.value, forKey: .value) + try container.encode(self.blobCIDHashes, forKey: .blobCIDHashes) + try container.encode(self._indexedAt, forKey: .indexedAt) + try container.encode(self.moderation, forKey: .moderation) + try container.encode(self.repository, forKey: .repository) + } + + enum CodingKeys: String, CodingKey { + case recordURI = "uri" + case cidHash = "cid" + case value + case blobCIDHashes = "blobCids" + case indexedAt + case moderation + case repository = "repo" + } + } + + /// A definition model for a detailed view of a record. + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/defs.json + public struct RecordViewDetailDefinition: Codable { + + /// The URI of a record. + public let recordURI: String + + /// The CID hash of the record. + public let cidHash: String + + /// The value of the record. + /// + /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ + /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ + /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ + /// \ + /// Clarifications from Bluesky are needed in order to fully understand this item. + public let value: String + + /// An array of CID hashes for blobs. + public let blobs: [ToolsOzoneLexicon.Moderation.BlobViewDefinition] + + /// An array of labels attached to the record. Optional. + public var labels: [ComAtprotoLexicon.Label.LabelDefinition]? + + /// The date and time the record is indexed. + @DateFormatting public var indexedAt: Date + + /// The repository view of the record. + /// + /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ + /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ + /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ + /// \ + /// Clarifications from Bluesky are needed in order to fully understand this item. + public let moderation: ToolsOzoneLexicon.Moderation.ModerationDetailDefinition + + /// The repository view of the record. + /// + /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ + /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ + /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ + /// \ + /// Clarifications from Bluesky are needed in order to fully understand this item. + public let repository: ToolsOzoneLexicon.Moderation.RepositoryViewDefinition + + public init(recordURI: String, cidHash: String, value: String, blobs: [ToolsOzoneLexicon.Moderation.BlobViewDefinition], + labels: [ComAtprotoLexicon.Label.LabelDefinition]? = nil, indexedAt: Date, + moderation: ToolsOzoneLexicon.Moderation.ModerationDetailDefinition, + repository: ToolsOzoneLexicon.Moderation.RepositoryViewDefinition) { + self.recordURI = recordURI + self.cidHash = cidHash + self.value = value + self.blobs = blobs + self.labels = labels + self._indexedAt = DateFormatting(wrappedValue: indexedAt) + self.moderation = moderation + self.repository = repository + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.recordURI = try container.decode(String.self, forKey: .recordURI) + self.cidHash = try container.decode(String.self, forKey: .cidHash) + self.value = try container.decode(String.self, forKey: .value) + self.blobs = try container.decode([ToolsOzoneLexicon.Moderation.BlobViewDefinition].self, forKey: .blobs) + self.labels = try container.decodeIfPresent([ComAtprotoLexicon.Label.LabelDefinition].self, forKey: .labels) + self.indexedAt = try container.decode(DateFormatting.self, forKey: .indexedAt).wrappedValue + self.moderation = try container.decode(ToolsOzoneLexicon.Moderation.ModerationDetailDefinition.self, forKey: .moderation) + self.repository = try container.decode(ToolsOzoneLexicon.Moderation.RepositoryViewDefinition.self, forKey: .repository) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.recordURI, forKey: .recordURI) + try container.encode(self.cidHash, forKey: .cidHash) + try container.encode(self.value, forKey: .value) + try container.encode(self.blobs, forKey: .blobs) + try container.encodeIfPresent(self.labels, forKey: .labels) + try container.encode(self._indexedAt, forKey: .indexedAt) + try container.encode(self.moderation, forKey: .moderation) + try container.encode(self.repository, forKey: .repository) + } + + enum CodingKeys: String, CodingKey { + case recordURI = "uri" + case cidHash = "cid" + case value + case blobs + case labels + case indexedAt + case moderation + case repository = "repo" + } + } + + /// A definition model for a record that may not have been found. + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/defs.json + public struct RecordViewNotFoundDefinition: Codable { + + /// The URI of the record. + public let recordURI: String + + enum CodingKeys: String, CodingKey { + case recordURI = "uri" + } + } + + /// A definition model for moderation. + /// + /// - Important: The item associated with this struct is undocumented in the AT Protocol specifications. The documentation here is based on:\ + /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ + /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ + /// \ + /// Clarifications from Bluesky are needed in order to fully understand this item. + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/defs.json + public struct ModerationDefinition: Codable { + + /// The status of the subject. Optional. + /// + /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ + /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ + /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ + /// \ + /// Clarifications from Bluesky are needed in order to fully understand this item. + public let subjectStatus: ToolsOzoneLexicon.Moderation.SubjectStatusViewDefinition + } + + /// A definition model for a detailed moderation. + /// + /// - Important: The item associated with this struct is undocumented in the AT Protocol specifications. The documentation here is based on:\ + /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ + /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ + /// \ + /// Clarifications from Bluesky are needed in order to fully understand this item. + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/defs.json + public struct ModerationDetailDefinition: Codable { + + /// The status of the subject. Optional. + /// + /// - Important: The item associated with this property is undocumented in the AT Protocol specifications. The documentation here is based on:\ + /// \* **For items with some inferable context from property names or references**: its best interpretation, though not with full certainty.\ + /// \* **For items without enough context for even an educated guess**: a direct acknowledgment of their undocumented status.\ + /// \ + /// Clarifications from Bluesky are needed in order to fully understand this item. + public var subjectStatus: ToolsOzoneLexicon.Moderation.SubjectStatusViewDefinition? + } + + /// A definition model for a blob view. + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/defs.json + public struct BlobViewDefinition: Codable { + + /// The CID hash of the blob. + public let cidHash: String + + /// The MIME type of the blob. + public let mimeType: String + + /// The size of the blob. Written in bytes. + public let size: Int + + /// The date and time the blob was created. + @DateFormatting public var createdAt: Date + + /// The type of media in the blob. + public let details: ATUnion.BlobViewDetailUnion + + /// The status of the subject. + public let moderation: ToolsOzoneLexicon.Moderation.ModerationDefinition + + public init(cidHash: String, mimeType: String, size: Int, createdAt: Date, details: ATUnion.BlobViewDetailUnion, + moderation: ToolsOzoneLexicon.Moderation.ModerationDefinition) { + self.cidHash = cidHash + self.mimeType = mimeType + self.size = size + self._createdAt = DateFormatting(wrappedValue: createdAt) + self.details = details + self.moderation = moderation + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.cidHash = try container.decode(String.self, forKey: .cidHash) + self.mimeType = try container.decode(String.self, forKey: .mimeType) + self.size = try container.decode(Int.self, forKey: .size) + self.createdAt = try container.decode(DateFormatting.self, forKey: .createdAt).wrappedValue + self.details = try container.decode(ATUnion.BlobViewDetailUnion.self, forKey: .details) + self.moderation = try container.decode(ToolsOzoneLexicon.Moderation.ModerationDefinition.self, forKey: .moderation) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.cidHash, forKey: .cidHash) + try container.encode(self.mimeType, forKey: .mimeType) + try container.encode(self.size, forKey: .size) + try container.encode(self._createdAt, forKey: .createdAt) + try container.encode(self.details, forKey: .details) + try container.encode(self.moderation, forKey: .moderation) + } + + enum CodingKeys: String, CodingKey { + case cidHash = "cid" + case mimeType + case size + case createdAt + case details + case moderation + } + } + + /// A definition model for details for an image. + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/defs.json + public struct ImageDetailsDefinition: Codable { + + /// The width of the image. + public let width: Int + + /// The height of the image. + public let height: Int + } + + /// A definition model for details for a video. + /// + /// - SeeAlso: This is based on the [`com.atproto.admin.defs`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/defs.json + public struct VideoDetailsDefinition: Codable { + + /// The width of the video. + public let width: Int + + /// The height of the video. + public let height: Int + + /// The duration of the video. + public let length: Int + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Moderation/ToolsOzoneModerationEmitEvent.swift b/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Moderation/ToolsOzoneModerationEmitEvent.swift new file mode 100644 index 0000000000..34b1d844e6 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Moderation/ToolsOzoneModerationEmitEvent.swift @@ -0,0 +1,40 @@ +// +// ToolsOzoneModerationEmitEvent.swift +// +// +// Created by Christopher Jr Riley on 2024-05-21. +// + +import Foundation + +extension ToolsOzoneLexicon.Moderation { + + /// A request body model for enacting on an action against a user's account. + /// + /// - Note: According to the AT Protocol specifications: "Take a moderation action on an actor." + /// + /// - SeeAlso: This is based on the [`tools.ozone.moderation.emitEvent`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/emitEvent.json + public struct EmitEventRequestBody: Codable { + + /// The type of event the moderator is taking, + public let event: ATUnion.EmitEventUnion + + /// The type of repository reference. + public let subject: ATUnion.EmitEventSubjectUnion + + /// An array of CID hashes related to blobs for the moderator's event view. Optional. + public let subjectBlobCIDHashes: [String]? + + /// The decentralized identifier (DID) of the moderator taking this action. + public let createdBy: String + + enum CodingKeys: String, CodingKey { + case event + case subject + case subjectBlobCIDHashes = "subjectBlobCids" + case createdBy + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Moderation/ToolsOzoneModerationQueryEvents.swift b/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Moderation/ToolsOzoneModerationQueryEvents.swift new file mode 100644 index 0000000000..5577f25f30 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Moderation/ToolsOzoneModerationQueryEvents.swift @@ -0,0 +1,41 @@ +// +// ToolsOzoneModerationQueryEvents.swift +// +// +// Created by Christopher Jr Riley on 2024-05-21. +// + +import Foundation + +extension ToolsOzoneLexicon.Moderation { + + public struct QueryEvents: Codable { + + /// Indicates the sorting direction for the array of moderation events. + public enum SortDirection: String { + + /// Indicates the moderation events will be sorted in ascending order. + case ascending = "asc" + + /// Indicates the moderation events will be sorted in descending order. + case descending = "desc" + } + } + + /// An output model for listing all moderation events pertaining a subject. + /// + /// - Note: According to the AT Protocol specifications: "List moderation events related + /// to a subject." + /// + /// - SeeAlso: This is based on the [`tools.ozone.moderation.queryEvents`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/queryEvents.json + public struct QueryEventsOutput: Codable { + + /// The mark used to indicate the starting point for the next set of results. Optional. + public let cursor: String? + + /// An array of moderator events. + public let events: [ToolsOzoneLexicon.Moderation.ModerationEventViewDefinition] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Moderation/ToolsOzoneModerationQueryStatuses.swift b/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Moderation/ToolsOzoneModerationQueryStatuses.swift new file mode 100644 index 0000000000..0902af4c75 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Moderation/ToolsOzoneModerationQueryStatuses.swift @@ -0,0 +1,50 @@ +// +// ToolsOzoneModerationQueryStatuses.swift +// +// +// Created by Christopher Jr Riley on 2024-05-21. +// + +import Foundation + +extension ToolsOzoneLexicon.Moderation { + + public struct QueryStatuses: Codable { + + /// Indicates the sorting field for the moderation status array. + public enum SortField: Codable { + + /// Indicates the moderation status array will be sorted by the last reported user. + case lastReportedAt + + /// Indicates the moderation status array will be sorted by the last reviwed user. + case lastReviewedAt + } + + public enum SortDirection: String, Codable { + + /// Indicates the moderation events will be sorted in ascending order. + case ascending = "asc" + + /// Indicates the moderation events will be sorted in descending order. + case descending = "desc" + } + } + + /// An output model for listing all moderation events pertaining a subject. + /// + /// - Note: According to the AT Protocol specifications: "View moderation statuses of subjects + /// (record or repo)." + /// + /// - SeeAlso: This is based on the [`ools.ozone.moderation.queryStatuses`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/queryEvents.json + public struct QueryStatusesOutput: Codable { + + /// The mark used to indicate the starting point for the next set of results. Optional. + public let cursor: String? + + /// An array of subject status views. + public let subjectStatuses: [ToolsOzoneLexicon.Moderation.SubjectStatusViewDefinition] + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Moderation/ToolsOzoneModerationSearchRepos.swift b/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Moderation/ToolsOzoneModerationSearchRepos.swift new file mode 100644 index 0000000000..efdfdaa58f --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/tools.ozone/Moderation/ToolsOzoneModerationSearchRepos.swift @@ -0,0 +1,33 @@ +// +// ToolsOzoneModerationSearchRepos.swift +// +// +// Created by Christopher Jr Riley on 2024-05-21. +// + +import Foundation + +extension ToolsOzoneLexicon.Moderation { + + /// An output model for searching for repositories as an administrator or moderator. + /// + /// - Note: According to the AT Protocol specifications: "Find repositories based on a + /// search term." + /// + /// - SeeAlso: This is based on the [`tools.ozone.moderation.searchRepos`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/searchRepos.json + public struct SearchRepositoryOutput: Codable { + + /// The mark used to indicate the starting point for the next set of results. Optional. + public let cursor: String? + + /// An array of repository views. + public let repositories: [ToolsOzoneLexicon.Moderation.RepositoryViewDefinition] + + enum CodingKeys: String, CodingKey { + case cursor + case repositories = "repos" + } + } +} diff --git a/Sources/ATProtoKit/Models/Lexicons/tools.ozone/ToolsOzoneLexicon.swift b/Sources/ATProtoKit/Models/Lexicons/tools.ozone/ToolsOzoneLexicon.swift new file mode 100644 index 0000000000..f303d1af33 --- /dev/null +++ b/Sources/ATProtoKit/Models/Lexicons/tools.ozone/ToolsOzoneLexicon.swift @@ -0,0 +1,17 @@ +// +// ToolsOzoneLexicon.swift +// +// +// Created by Christopher Jr Riley on 2024-05-16. +// + +import Foundation + +extension ToolsOzoneLexicon { + + /// A group of lexicons within the `tools.ozone.communication` namespace. + public struct Communication {} + + /// A group of lexicons within the `tools.ozone.moderation` namespace. + public struct Moderation {} +} diff --git a/Sources/ATProtoKit/Networking/ATProtoAdmin/CreateCommunicationTemplateAsAdmin.swift b/Sources/ATProtoKit/Networking/ATProtoAdmin/CreateCommunicationTemplateAsAdmin.swift index 085deafedf..6bbe9a6b18 100644 --- a/Sources/ATProtoKit/Networking/ATProtoAdmin/CreateCommunicationTemplateAsAdmin.swift +++ b/Sources/ATProtoKit/Networking/ATProtoAdmin/CreateCommunicationTemplateAsAdmin.swift @@ -27,10 +27,14 @@ extension ATProtoAdmin { /// - subject: The subject line of the communication template. /// - createdBy: The decentralized identifier (DID) of the creator of the /// communication template. Optional. - /// - Returns: A `Result`, containing either ``OzoneCommunicationTemplateView`` + /// - Returns: A `Result`, containing either ``ToolsOzoneLexicon/Communication/TemplateViewDefinition`` /// if successful, or an `Error` if not. - public func createCommunicationTemplate(named name: String, contentMarkdown: String, subject: String, - createdBy: String?) async throws -> Result { + public func createCommunicationTemplate( + named name: String, + contentMarkdown: String, + subject: String, + createdBy: String? + ) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -41,7 +45,7 @@ extension ATProtoAdmin { return .failure(ATRequestPrepareError.invalidRequestURL) } - let requestBody = CommunicationCreateTemplate( + let requestBody = ToolsOzoneLexicon.Communication.CreateTemplateRequestBody( name: name, contentMarkdown: contentMarkdown, subject: subject, @@ -56,7 +60,7 @@ extension ATProtoAdmin { authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, withEncodingBody: requestBody, - decodeTo: OzoneCommunicationTemplateView.self) + decodeTo: ToolsOzoneLexicon.Communication.TemplateViewDefinition.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/ATProtoAdmin/DeleteAccountAsAdmin.swift b/Sources/ATProtoKit/Networking/ATProtoAdmin/DeleteAccountAsAdmin.swift index b83b0e48fe..f2a316efd8 100644 --- a/Sources/ATProtoKit/Networking/ATProtoAdmin/DeleteAccountAsAdmin.swift +++ b/Sources/ATProtoKit/Networking/ATProtoAdmin/DeleteAccountAsAdmin.swift @@ -33,7 +33,7 @@ extension ATProtoAdmin { throw ATRequestPrepareError.invalidRequestURL } - let requestBody = AdminDeleteAccount( + let requestBody = ComAtprotoLexicon.Admin.DeleteAccountRequestBody( accountDID: accountDID ) diff --git a/Sources/ATProtoKit/Networking/ATProtoAdmin/DeleteCommunicationTemplateAsAdmin.swift b/Sources/ATProtoKit/Networking/ATProtoAdmin/DeleteCommunicationTemplateAsAdmin.swift index 9b101b8581..eb8a1cfbee 100644 --- a/Sources/ATProtoKit/Networking/ATProtoAdmin/DeleteCommunicationTemplateAsAdmin.swift +++ b/Sources/ATProtoKit/Networking/ATProtoAdmin/DeleteCommunicationTemplateAsAdmin.swift @@ -32,7 +32,7 @@ extension ATProtoAdmin { throw ATRequestPrepareError.invalidRequestURL } - let requestBody = CommunicationDeleteTemplate( + let requestBody = ToolsOzoneLexicon.Communication.DeleteTemplateRequestBody( id: id ) diff --git a/Sources/ATProtoKit/Networking/ATProtoAdmin/DisableAccountInvitesAsAdmin.swift b/Sources/ATProtoKit/Networking/ATProtoAdmin/DisableAccountInvitesAsAdmin.swift index bab3fffa59..b8c152af0f 100644 --- a/Sources/ATProtoKit/Networking/ATProtoAdmin/DisableAccountInvitesAsAdmin.swift +++ b/Sources/ATProtoKit/Networking/ATProtoAdmin/DisableAccountInvitesAsAdmin.swift @@ -24,7 +24,10 @@ extension ATProtoAdmin { /// - Parameters: /// - accountDID: The decentralized identifier (DID) of the user account. /// - note: A note on why the account will lose the ability to get new invite codes. - public func disableAccountInvites(for accountDID: String, note: String?) async throws { + public func disableAccountInvites( + for accountDID: String, + note: String? + ) async throws { guard session != nil, let accessToken = session?.accessToken else { throw ATRequestPrepareError.missingActiveSession @@ -35,7 +38,7 @@ extension ATProtoAdmin { throw ATRequestPrepareError.invalidRequestURL } - let requestBody = AdminDisableAccountInvites( + let requestBody = ComAtprotoLexicon.Admin.DisableAccountInvitesRequestBody( accountDID: accountDID, note: note ) diff --git a/Sources/ATProtoKit/Networking/ATProtoAdmin/DisableInviteCodesAsAdmin.swift b/Sources/ATProtoKit/Networking/ATProtoAdmin/DisableInviteCodesAsAdmin.swift index c7152142ca..49d34ffb45 100644 --- a/Sources/ATProtoKit/Networking/ATProtoAdmin/DisableInviteCodesAsAdmin.swift +++ b/Sources/ATProtoKit/Networking/ATProtoAdmin/DisableInviteCodesAsAdmin.swift @@ -24,7 +24,10 @@ extension ATProtoAdmin { /// - Parameters: /// - codes: The invite codes to disable. /// - accountDIDs: The decentralized identifiers (DIDs) of the user accounts. - public func disableInviteCodes(codes: [String], accountDIDs: [String]) async throws { + public func disableInviteCodes( + codes: [String], + accountDIDs: [String] + ) async throws { guard session != nil, let accessToken = session?.accessToken else { throw ATRequestPrepareError.missingActiveSession @@ -35,7 +38,7 @@ extension ATProtoAdmin { throw ATRequestPrepareError.invalidRequestURL } - let requestBody = AdminDisableInviteCodes( + let requestBody = ComAtprotoLexicon.Admin.DisableInviteCodesRequestBody( codes: codes, accountDIDs: accountDIDs ) diff --git a/Sources/ATProtoKit/Networking/ATProtoAdmin/EmitEventAsAdmin.swift b/Sources/ATProtoKit/Networking/ATProtoAdmin/EmitEventAsAdmin.swift index ee0b9207c4..f408d71adc 100644 --- a/Sources/ATProtoKit/Networking/ATProtoAdmin/EmitEventAsAdmin.swift +++ b/Sources/ATProtoKit/Networking/ATProtoAdmin/EmitEventAsAdmin.swift @@ -27,10 +27,14 @@ extension ATProtoAdmin { /// - subjectBlobCIDHashes: An array of CID hashes related to blobs for the moderator's /// event view. Optional. /// - createdBy: The decentralized identifier (DID) of the moderator taking this action. - /// - Returns: A `Result`, containing either an ``OzoneModerationEventView`` if successful, + /// - Returns: A `Result`, containing either an ``ToolsOzoneLexicon/Moderation/ModerationEventViewDefinition`` if successful, /// or an `Error` if not. - public func emitEvent(_ event: AdminEventViewUnion, subject: RepositoryReferencesUnion, subjectBlobCIDHashes: [String]?, - createdBy: String) async throws -> Result { + public func emitEvent( + _ event: ATUnion.EmitEventUnion, + subject: ATUnion.EmitEventSubjectUnion, + subjectBlobCIDHashes: [String]?, + createdBy: String + ) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -41,7 +45,7 @@ extension ATProtoAdmin { return .failure(ATRequestPrepareError.invalidRequestURL) } - let requestBody = ModerationEmitEvent( + let requestBody = ToolsOzoneLexicon.Moderation.EmitEventRequestBody( event: event, subject: subject, subjectBlobCIDHashes: subjectBlobCIDHashes, @@ -56,7 +60,7 @@ extension ATProtoAdmin { authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, withEncodingBody: requestBody, - decodeTo: OzoneModerationEventView.self) + decodeTo: ToolsOzoneLexicon.Moderation.ModerationEventViewDefinition.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/ATProtoAdmin/EnableAccountInvitesAsAdmin.swift b/Sources/ATProtoKit/Networking/ATProtoAdmin/EnableAccountInvitesAsAdmin.swift index e97755e806..63478abf07 100644 --- a/Sources/ATProtoKit/Networking/ATProtoAdmin/EnableAccountInvitesAsAdmin.swift +++ b/Sources/ATProtoKit/Networking/ATProtoAdmin/EnableAccountInvitesAsAdmin.swift @@ -27,7 +27,10 @@ extension ATProtoAdmin { /// - accountDID: The decentralized identifier (DID) of the user's account. /// - note: A note as to why the user account is getting the ability to receive invite /// codes reinstated. Optional. - public func enableAccountInvites(for accountDID: String, note: String?) async throws { + public func enableAccountInvites( + for accountDID: String, + note: String? + ) async throws { guard session != nil, let accessToken = session?.accessToken else { throw ATRequestPrepareError.missingActiveSession @@ -38,7 +41,7 @@ extension ATProtoAdmin { throw ATRequestPrepareError.invalidRequestURL } - let requestBody = AdminEnableAccountInvites( + let requestBody = ComAtprotoLexicon.Admin.EnableAccountInvitesRequestBody( accountDID: accountDID, note: note ) diff --git a/Sources/ATProtoKit/Networking/ATProtoAdmin/GetAccountInfoAsAdmin.swift b/Sources/ATProtoKit/Networking/ATProtoAdmin/GetAccountInfoAsAdmin.swift index 2208037cac..c11783ce21 100644 --- a/Sources/ATProtoKit/Networking/ATProtoAdmin/GetAccountInfoAsAdmin.swift +++ b/Sources/ATProtoKit/Networking/ATProtoAdmin/GetAccountInfoAsAdmin.swift @@ -24,9 +24,9 @@ extension ATProtoAdmin { /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/getAccountInfo.json /// /// - Parameter accountDID: The decentralized identifier (DID) of the user account. - /// - Returns: A `Result`, containing either an ``AdminAccountView`` + /// - Returns: A `Result`, containing either an ``ComAtprotoLexicon/Admin/AccountViewDefinition`` /// if successful, or an `Error` if not. - public func getAccountInfo(_ accountDID: String) async throws -> Result { + public func getAccountInfo(_ accountDID: String) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { throw ATRequestPrepareError.missingActiveSession @@ -55,7 +55,7 @@ extension ATProtoAdmin { contentTypeValue: nil, authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, - decodeTo: AdminAccountView.self) + decodeTo: ComAtprotoLexicon.Admin.AccountViewDefinition.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/ATProtoAdmin/GetAccountInfosAsAdmin.swift b/Sources/ATProtoKit/Networking/ATProtoAdmin/GetAccountInfosAsAdmin.swift index 87febf5e75..66ceeec99f 100644 --- a/Sources/ATProtoKit/Networking/ATProtoAdmin/GetAccountInfosAsAdmin.swift +++ b/Sources/ATProtoKit/Networking/ATProtoAdmin/GetAccountInfosAsAdmin.swift @@ -24,9 +24,9 @@ extension ATProtoAdmin { /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/getAccountInfos.json /// /// - Parameter accountDIDs: An array of decentralized identifiers (DIDs) of user accounts. - /// - Returns: A `Result`, containing either an ``AdminGetInviteCodesOutput`` + /// - Returns: A `Result`, containing either an ``ComAtprotoLexicon/Admin/GetAccountInfosOutput`` /// if successful, or an `Error` if not. - public func getAccountInfos(_ accountDIDs: [String]) async throws -> Result { + public func getAccountInfos(_ accountDIDs: [String]) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -53,7 +53,7 @@ extension ATProtoAdmin { contentTypeValue: nil, authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, - decodeTo: AdminGetAccountInfosOutput.self) + decodeTo: ComAtprotoLexicon.Admin.GetAccountInfosOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/ATProtoAdmin/GetInviteCodesAsAdmin.swift b/Sources/ATProtoKit/Networking/ATProtoAdmin/GetInviteCodesAsAdmin.swift index 13140df6f4..f0670e4aae 100644 --- a/Sources/ATProtoKit/Networking/ATProtoAdmin/GetInviteCodesAsAdmin.swift +++ b/Sources/ATProtoKit/Networking/ATProtoAdmin/GetInviteCodesAsAdmin.swift @@ -24,10 +24,12 @@ extension ATProtoAdmin { /// - sort: The order the invite codes will be sorted by. Defaults to `.recent`. /// - limit: The number of invite codes in the list. Defaults to `100`. /// - cursor: The mark used to indicate the starting point for the next set of results. Optional. - /// - Returns: A `Result`, containing either an ``AdminGetInviteCodesOutput`` + /// - Returns: A `Result`, containing either an ``ComAtprotoLexicon/Admin/GetInviteCodesOutput`` /// if successful, or an `Error` if not. - public func getInviteCodes(sortedBy sort: AdminGetInviteCodesSort = .recent, withLimitOf limit: Int = 100, - cursor: String?) async throws -> Result { + public func getInviteCodes( + sortedBy sort: ComAtprotoLexicon.Admin.GetInviteCodes.Sort = .recent, + withLimitOf limit: Int = 100, + cursor: String?) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -63,7 +65,7 @@ extension ATProtoAdmin { contentTypeValue: nil, authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, - decodeTo: AdminGetInviteCodesOutput.self) + decodeTo: ComAtprotoLexicon.Admin.GetInviteCodesOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/ATProtoAdmin/GetModerationEventAsAdmin.swift b/Sources/ATProtoKit/Networking/ATProtoAdmin/GetModerationEventAsAdmin.swift index 62248ac450..9527ef7d12 100644 --- a/Sources/ATProtoKit/Networking/ATProtoAdmin/GetModerationEventAsAdmin.swift +++ b/Sources/ATProtoKit/Networking/ATProtoAdmin/GetModerationEventAsAdmin.swift @@ -22,9 +22,9 @@ extension ATProtoAdmin { /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/getEvent.json /// /// - Parameter id: The ID of the moderator event. - /// - Returns: A `Result`, containing either an ``OzoneModerationEventViewDetail`` + /// - Returns: A `Result`, containing either an ``ToolsOzoneLexicon/Moderation/EventViewDetailDefinition`` /// if successful, or an `Error` if not. - public func getEvent(_ id: String) async throws -> Result { + public func getEvent(_ id: String) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -53,7 +53,7 @@ extension ATProtoAdmin { contentTypeValue: nil, authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, - decodeTo: OzoneModerationEventViewDetail.self) + decodeTo: ToolsOzoneLexicon.Moderation.EventViewDetailDefinition.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/ATProtoAdmin/GetRecordAsAdmin.swift b/Sources/ATProtoKit/Networking/ATProtoAdmin/GetRecordAsAdmin.swift index 5e0639cdfd..dcab99fe5d 100644 --- a/Sources/ATProtoKit/Networking/ATProtoAdmin/GetRecordAsAdmin.swift +++ b/Sources/ATProtoKit/Networking/ATProtoAdmin/GetRecordAsAdmin.swift @@ -23,9 +23,12 @@ extension ATProtoAdmin { /// - Parameters: /// - recordURI: The URI of the record. /// - recordCID: The CID hash of the record. Optional. - /// - Returns: A `Result`, containing either an ``OzoneModerationRecordViewDetail`` + /// - Returns: A `Result`, containing either an ``ToolsOzoneLexicon/Moderation/RecordViewDetailDefinition`` /// if successful, or an `Error` if not. - public func getRecord(_ recordURI: String, recordCID: String?) async throws -> Result { + public func getRecord( + _ recordURI: String, + recordCID: String? + ) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -56,7 +59,7 @@ extension ATProtoAdmin { contentTypeValue: nil, authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, - decodeTo: OzoneModerationRecordViewDetail.self) + decodeTo: ToolsOzoneLexicon.Moderation.RecordViewDetailDefinition.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/ATProtoAdmin/GetRepositoryAsAdmin.swift b/Sources/ATProtoKit/Networking/ATProtoAdmin/GetRepositoryAsAdmin.swift index bb38b1b520..44bba1d5d9 100644 --- a/Sources/ATProtoKit/Networking/ATProtoAdmin/GetRepositoryAsAdmin.swift +++ b/Sources/ATProtoKit/Networking/ATProtoAdmin/GetRepositoryAsAdmin.swift @@ -21,9 +21,9 @@ extension ATProtoAdmin { /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/getRepo.json /// /// - Parameter repositoryDID: The decentralized identifier (DID) of the repository. - /// - Returns: A `Result`, containing either an ``OzoneModerationRepositoryView`` + /// - Returns: A `Result`, containing either an ``ToolsOzoneLexicon/Moderation/RepositoryViewDefinition`` /// if successful, or an `Error` if not. - public func getRepository(_ repositoryDID: String) async throws -> Result { + public func getRepository(_ repositoryDID: String) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -50,7 +50,7 @@ extension ATProtoAdmin { contentTypeValue: nil, authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, - decodeTo: OzoneModerationRepositoryView.self) + decodeTo: ToolsOzoneLexicon.Moderation.RepositoryViewDetailDefinition.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/ATProtoAdmin/GetSubjectStatusAsAdmin.swift b/Sources/ATProtoKit/Networking/ATProtoAdmin/GetSubjectStatusAsAdmin.swift index e9f98f5a93..4699e6b39e 100644 --- a/Sources/ATProtoKit/Networking/ATProtoAdmin/GetSubjectStatusAsAdmin.swift +++ b/Sources/ATProtoKit/Networking/ATProtoAdmin/GetSubjectStatusAsAdmin.swift @@ -25,10 +25,13 @@ extension ATProtoAdmin { /// - subjectDID: The decentralized identifier (DID) of the subject. /// - subjectURI: The URI of the subject. /// - subjectBlobCIDHash: The CID hash of the blob for the subject. - /// - Returns: A `Result`, containing either an ``AdminGetSubjectStatusOutput`` + /// - Returns: A `Result`, containing either an ``ComAtprotoLexicon/Admin/GetSubjectStatusOutput`` /// if successful, or an `Error` if not. - public func getSubjectStatus(_ subjectDID: String, subjectURI: String, - subjectBlobCIDHash: String) async throws -> Result { + public func getSubjectStatus( + _ subjectDID: String, + subjectURI: String, + subjectBlobCIDHash: String + ) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -59,7 +62,7 @@ extension ATProtoAdmin { contentTypeValue: nil, authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, - decodeTo: AdminGetSubjectStatusOutput.self) + decodeTo: ComAtprotoLexicon.Admin.GetSubjectStatusOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/ATProtoAdmin/ListCommunicationTemplatesAsAdmin.swift b/Sources/ATProtoKit/Networking/ATProtoAdmin/ListCommunicationTemplatesAsAdmin.swift index e14f0eee67..2376276537 100644 --- a/Sources/ATProtoKit/Networking/ATProtoAdmin/ListCommunicationTemplatesAsAdmin.swift +++ b/Sources/ATProtoKit/Networking/ATProtoAdmin/ListCommunicationTemplatesAsAdmin.swift @@ -21,9 +21,9 @@ extension ATProtoAdmin { /// /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/communication/listTemplates.json /// - /// - Returns: A `Result`, containing either an ``CommunicationListTemplatesOutput`` + /// - Returns: A `Result`, containing either an ``ToolsOzoneLexicon/Communication/ListTemplatesOutput`` /// if successful, or an `Error` if not. - public func listCommunicationTemplates() async throws -> Result { + public func listCommunicationTemplates() async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -41,7 +41,7 @@ extension ATProtoAdmin { contentTypeValue: nil, authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, - decodeTo: CommunicationListTemplatesOutput.self) + decodeTo: ToolsOzoneLexicon.Communication.ListTemplatesOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/ATProtoAdmin/QueryModerationEventsAsAdmin.swift b/Sources/ATProtoKit/Networking/ATProtoAdmin/QueryModerationEventsAsAdmin.swift index 1df0393c43..385ff2bca8 100644 --- a/Sources/ATProtoKit/Networking/ATProtoAdmin/QueryModerationEventsAsAdmin.swift +++ b/Sources/ATProtoKit/Networking/ATProtoAdmin/QueryModerationEventsAsAdmin.swift @@ -52,14 +52,26 @@ extension ATProtoAdmin { /// - reportTypes: An array of report types. /// - cursor: The mark used to indicate the starting point for the next set /// of results. Optional. - /// - Returns: A `Result`, containing either an ``ModerationQueryEventsOutput`` + /// - Returns: A `Result`, containing either an ``ToolsOzoneLexicon/Moderation/QueryEventsOutput`` /// if successful, or an `Error` if not. - public func queryEvents(_ eventTypes: [String]? = nil, createdBy: String? = nil, - sortDirection: AdminQueryModerationEventSortDirection? = .descending, createdAfter: Date? = nil, createdBefore: Date? = nil, - subject: String? = nil, canIncludeAllUserRecords: Bool? = false, limit: Int? = 50, doesHaveComment: Bool? = nil, - comment: String? = nil, addedLabels: [String]? = nil, - removedLabels: [String]? = nil, addedTags: [String]? = nil, removedTags: [String]? = nil, reportTypes: [String]? = nil, - cursor: String? = nil) async throws -> Result { + public func queryEvents( + _ eventTypes: [String]? = nil, + createdBy: String? = nil, + sortDirection: ToolsOzoneLexicon.Moderation.QueryEvents.SortDirection? = .descending, + createdAfter: Date? = nil, + createdBefore: Date? = nil, + subject: String? = nil, + canIncludeAllUserRecords: Bool? = false, + limit: Int? = 50, + doesHaveComment: Bool? = nil, + comment: String? = nil, + addedLabels: [String]? = nil, + removedLabels: [String]? = nil, + addedTags: [String]? = nil, + removedTags: [String]? = nil, + reportTypes: [String]? = nil, + cursor: String? = nil + ) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -167,7 +179,7 @@ extension ATProtoAdmin { contentTypeValue: nil, authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, - decodeTo: ModerationQueryEventsOutput.self) + decodeTo: ToolsOzoneLexicon.Moderation.QueryEventsOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/ATProtoAdmin/QueryModerationStatusesAsAdmin.swift b/Sources/ATProtoKit/Networking/ATProtoAdmin/QueryModerationStatusesAsAdmin.swift index a296b46255..e8c0c1f638 100644 --- a/Sources/ATProtoKit/Networking/ATProtoAdmin/QueryModerationStatusesAsAdmin.swift +++ b/Sources/ATProtoKit/Networking/ATProtoAdmin/QueryModerationStatusesAsAdmin.swift @@ -56,14 +56,29 @@ extension ATProtoAdmin { /// the added tags. Optional. /// - cursor: The mark used to indicate the starting point for the next set of /// results. Optional. - /// - Returns: A `Result`, containing either an ``AdminQueryModerationStatusesOutput`` + /// - Returns: A `Result`, containing either an ``ToolsOzoneLexicon/Moderation/QueryStatusesOutput`` /// if successful, or an `Error` if not. - public func queryStatuses(_ subject: String?, comment: String?, reportedAfter: Date?, reportedBefore: Date?, reviewedAfter: Date?, - reviewedBefore: Date?, shouldIncludeMuted: Bool? = false, isOnlyMuted: Bool?, reviewState: String?, - ignoreSubjects: [String]?, lastReviewedBy: String?, sortField: AdminQueryModerationStatusesSortField? = .lastReportedAt, - sortDirection: AdminQueryModerationStatusesSortDirection? = .descending, isTakenDown: Bool?, - isAppealed: Bool?, limit: Int? = 50, tags: [String]?, excludeTags: [String]?, - cursor: String?) async throws -> Result { + public func queryStatuses( + _ subject: String?, + comment: String?, + reportedAfter: Date?, + reportedBefore: Date?, + reviewedAfter: Date?, + reviewedBefore: Date?, + shouldIncludeMuted: Bool? = false, + isOnlyMuted: Bool?, + reviewState: String?, + ignoreSubjects: [String]?, + lastReviewedBy: String?, + sortField: ToolsOzoneLexicon.Moderation.QueryStatuses.SortField? = .lastReportedAt, + sortDirection: ToolsOzoneLexicon.Moderation.QueryStatuses.SortDirection? = .descending, + isTakenDown: Bool?, + isAppealed: Bool?, + limit: Int? = 50, + tags: [String]?, + excludeTags: [String]?, + cursor: String? + ) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -177,7 +192,7 @@ extension ATProtoAdmin { contentTypeValue: nil, authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, - decodeTo: AdminQueryModerationStatusesOutput.self) + decodeTo: ToolsOzoneLexicon.Moderation.QueryStatusesOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/ATProtoAdmin/SearchRepositoriesAsAdmin.swift b/Sources/ATProtoKit/Networking/ATProtoAdmin/SearchRepositoriesAsAdmin.swift index 15d4f44578..10c28e6c6b 100644 --- a/Sources/ATProtoKit/Networking/ATProtoAdmin/SearchRepositoriesAsAdmin.swift +++ b/Sources/ATProtoKit/Networking/ATProtoAdmin/SearchRepositoriesAsAdmin.swift @@ -26,10 +26,13 @@ extension ATProtoAdmin { /// choose between `1` and `100`. /// - cursor: The mark used to indicate the starting point for the next set of /// results. Optional. - /// - Returns: A `Result`, containing either an ``AdminSearchReposOutput`` + /// - Returns: A `Result`, containing either an ``ComAtprotoLexicon/Admin/SearchRepositoriesOutput`` /// if successful, or an `Error` if not. - public func searchRepositories(_ query: String?, withLimitOf limit: Int? = 50, - cursor: String?) async throws -> Result { + public func searchRepositories( + _ query: String?, + withLimitOf limit: Int? = 50, + cursor: String? + ) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -69,7 +72,7 @@ extension ATProtoAdmin { contentTypeValue: nil, authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, - decodeTo: AdminSearchReposOutput.self) + decodeTo: ComAtprotoLexicon.Admin.SearchRepositoriesOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/ATProtoAdmin/SendEmailAsAdmin.swift b/Sources/ATProtoKit/Networking/ATProtoAdmin/SendEmailAsAdmin.swift index 9721b02f8d..eade72f31b 100644 --- a/Sources/ATProtoKit/Networking/ATProtoAdmin/SendEmailAsAdmin.swift +++ b/Sources/ATProtoKit/Networking/ATProtoAdmin/SendEmailAsAdmin.swift @@ -27,10 +27,15 @@ extension ATProtoAdmin { /// - content: The content of the email. /// - senderDID: The decentralized identifier (DID) of the sender. /// - comment: Any additional comments viewable to other moderators and administrators. - /// - Returns: A `Result`, containing either an ``AdminSendEmailOutput`` + /// - Returns: A `Result`, containing either an ``ComAtprotoLexicon/Admin/SendEmailOutput`` /// if successful, or an `Error` if not. - public func sendEmail(to recipientDID: String, withSubjectLine subjectLine: String?, content: String, - senderDID: String, comment: String?) async throws -> Result { + public func sendEmail( + to recipientDID: String, + withSubjectLine subjectLine: String?, + content: String, + senderDID: String, + comment: String? + ) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -41,7 +46,7 @@ extension ATProtoAdmin { return .failure(ATRequestPrepareError.invalidRequestURL) } - let requestBody = AdminSendEmail( + let requestBody = ComAtprotoLexicon.Admin.SendEmailRequestBody( recipientDID: recipientDID, content: content, subject: subjectLine, @@ -57,7 +62,7 @@ extension ATProtoAdmin { authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, withEncodingBody: requestBody, - decodeTo: AdminSendEmailOutput.self) + decodeTo: ComAtprotoLexicon.Admin.SendEmailOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/ATProtoAdmin/UpdateAccountEmailAsAdmin.swift b/Sources/ATProtoKit/Networking/ATProtoAdmin/UpdateAccountEmailAsAdmin.swift index 8f66ef29cd..14b60574ff 100644 --- a/Sources/ATProtoKit/Networking/ATProtoAdmin/UpdateAccountEmailAsAdmin.swift +++ b/Sources/ATProtoKit/Networking/ATProtoAdmin/UpdateAccountEmailAsAdmin.swift @@ -24,7 +24,10 @@ extension ATProtoAdmin { /// - Parameters: /// - accountDID: The decentralized identifier (DID) of the user account. /// - newEmail: The new email address the user wants to change to. - public func updateAccountEmail(for accountDID: String, newEmail: String) async throws { + public func updateAccountEmail( + for accountDID: String, + newEmail: String + ) async throws { guard session != nil, let accessToken = session?.accessToken else { throw ATRequestPrepareError.missingActiveSession @@ -35,7 +38,7 @@ extension ATProtoAdmin { throw ATRequestPrepareError.invalidRequestURL } - let requestBody = AdminUpdateAccountEmail( + let requestBody = ComAtprotoLexicon.Admin.UpdateAccountEmailRequestBody( accountDID: accountDID, accountEmail: newEmail ) diff --git a/Sources/ATProtoKit/Networking/ATProtoAdmin/UpdateAccountHandleAsAdmin.swift b/Sources/ATProtoKit/Networking/ATProtoAdmin/UpdateAccountHandleAsAdmin.swift index dec8f356e0..d2ddac7fa9 100644 --- a/Sources/ATProtoKit/Networking/ATProtoAdmin/UpdateAccountHandleAsAdmin.swift +++ b/Sources/ATProtoKit/Networking/ATProtoAdmin/UpdateAccountHandleAsAdmin.swift @@ -24,7 +24,10 @@ extension ATProtoAdmin { /// - Parameters: /// - accountDID: The decentralized identifier (DID) of the user account. /// - newAccountHandle: The new handle for the user account. - public func updateAccountHandle(for accountDID: String, newAccountHandle: String) async throws { + public func updateAccountHandle( + for accountDID: String, + newAccountHandle: String + ) async throws { guard session != nil, let accessToken = session?.accessToken else { throw ATRequestPrepareError.missingActiveSession @@ -35,7 +38,7 @@ extension ATProtoAdmin { throw ATRequestPrepareError.invalidRequestURL } - let requestBody = AdminUpdateAccountHandle( + let requestBody = ComAtprotoLexicon.Admin.UpdateAccountHandleRequestBody( accountDID: accountDID, accountHandle: newAccountHandle ) diff --git a/Sources/ATProtoKit/Networking/ATProtoAdmin/UpdateAccountPasswordAsAdmin.swift b/Sources/ATProtoKit/Networking/ATProtoAdmin/UpdateAccountPasswordAsAdmin.swift index 4126eacb2e..9628213c3d 100644 --- a/Sources/ATProtoKit/Networking/ATProtoAdmin/UpdateAccountPasswordAsAdmin.swift +++ b/Sources/ATProtoKit/Networking/ATProtoAdmin/UpdateAccountPasswordAsAdmin.swift @@ -21,7 +21,10 @@ extension ATProtoAdmin { /// - Parameters: /// - accountDID: The decentralized identifier (DID) of the user account. /// - newPassword: The new password for the user account. - public func updateAccountPassword(for accountDID: String, newPassword: String) async throws { + public func updateAccountPassword( + for accountDID: String, + newPassword: String + ) async throws { guard session != nil, let accessToken = session?.accessToken else { throw ATRequestPrepareError.missingActiveSession @@ -32,7 +35,7 @@ extension ATProtoAdmin { throw ATRequestPrepareError.invalidRequestURL } - let requestBody = AdminUpdateAccountPassword( + let requestBody = ComAtprotoLexicon.Admin.UpdateAccountPasswordRequestBody( accountDID: accountDID, newPassword: newPassword ) diff --git a/Sources/ATProtoKit/Networking/ATProtoAdmin/UpdateCommunicationTemplateAsAdmin.swift b/Sources/ATProtoKit/Networking/ATProtoAdmin/UpdateCommunicationTemplateAsAdmin.swift index 8d4df8bef1..0b1fca1939 100644 --- a/Sources/ATProtoKit/Networking/ATProtoAdmin/UpdateCommunicationTemplateAsAdmin.swift +++ b/Sources/ATProtoKit/Networking/ATProtoAdmin/UpdateCommunicationTemplateAsAdmin.swift @@ -29,10 +29,16 @@ extension ATProtoKit { /// - updatedBy: The decentralized identifier (DID) of the user who updated the /// communication template. Optional. /// - isDisabled: Indicates whether the communication template is disabled. Optional. - /// - Returns: A `Result`, containing either an ``OzoneCommunicationTemplateView`` + /// - Returns: A `Result`, containing either an ``ToolsOzoneLexicon/Communication/TemplateViewDefinition`` /// if successful, or an `Error` if not. - public func updateCommunicationTemplate(_ id: String, name: String?, contentMarkdown: String?, subject: String?, updatedBy: String?, - isDisabled: Bool?) async throws -> Result { + public func updateCommunicationTemplate( + _ id: String, + name: String?, + contentMarkdown: String?, + subject: String?, + updatedBy: String?, + isDisabled: Bool? + ) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -43,7 +49,7 @@ extension ATProtoKit { return .failure(ATRequestPrepareError.invalidRequestURL) } - let requestBody = CommunicationUpdateTemplate( + let requestBody = ToolsOzoneLexicon.Communication.UpdateTemplateRequestBody( id: id, name: name, contentMarkdown: contentMarkdown, @@ -60,7 +66,7 @@ extension ATProtoKit { authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, withEncodingBody: requestBody, - decodeTo: OzoneCommunicationTemplateView.self) + decodeTo: ToolsOzoneLexicon.Communication.TemplateViewDefinition.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/ATProtoAdmin/UpdateSubjectStatusAsAdmin.swift b/Sources/ATProtoKit/Networking/ATProtoAdmin/UpdateSubjectStatusAsAdmin.swift index 0c8a66da4a..8025c3ad32 100644 --- a/Sources/ATProtoKit/Networking/ATProtoAdmin/UpdateSubjectStatusAsAdmin.swift +++ b/Sources/ATProtoKit/Networking/ATProtoAdmin/UpdateSubjectStatusAsAdmin.swift @@ -10,22 +10,26 @@ import Foundation extension ATProtoAdmin { /// Updates a subject status of an account, record, or blob. - /// + /// /// - Important: This is an administrator task and as such, regular users won't be able to /// access this; if they attempt to do so, an error will occur. - /// + /// /// - Note: According to the AT Protocol specifications: "Update the service-specific admin /// status of a subject (account, record, or blob)." - /// + /// /// - SeeAlso: This is based on the [`com.atproto.admin.updateSubjectStatus`][github] lexicon. - /// + /// /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/updateSubjectStatus.json - /// + /// /// - Parameters: /// - subject: The subject associated with the subject status. /// - takedown: The status attributes of the subject. Optional. - public func updateSubjectStatusAsAdmin(_ subject: AdminGetSubjectStatusUnion, - takedown: AdminStatusAttributes?) async throws -> Result { + /// - Returns: A `Result`, containing either an ``ComAtprotoLexicon`` + /// if successful, or an `Error` if not. + public func updateSubjectStatusAsAdmin( + _ subject: ATUnion.AdminUpdateSubjectStatusUnion, + takedown: ComAtprotoLexicon.Admin.StatusAttributesDefinition? + ) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -36,7 +40,7 @@ extension ATProtoAdmin { return .failure(ATRequestPrepareError.invalidRequestURL) } - let requestBody = AdminUpdateSubjectStatus( + let requestBody = ComAtprotoLexicon.Admin.UpdateSubjectStatusRequestBody( subject: subject, takedown: takedown ) @@ -49,7 +53,7 @@ extension ATProtoAdmin { authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, withEncodingBody: requestBody, - decodeTo: AdminUpdateSubjectStatusOutput.self) + decodeTo: ComAtprotoLexicon.Admin.UpdateSubjectStatusOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/ChatAPI/ChatDeleteAccount.swift b/Sources/ATProtoKit/Networking/ChatAPI/ChatDeleteAccount.swift new file mode 100644 index 0000000000..0dfa2e21d6 --- /dev/null +++ b/Sources/ATProtoKit/Networking/ChatAPI/ChatDeleteAccount.swift @@ -0,0 +1,45 @@ +// +// ChatDeleteAccount.swift +// +// +// Created by Christopher Jr Riley on 2024-05-31. +// + +import Foundation + +extension ATProtoBlueskyChat { + + /// Deletes a chat account. + /// + /// This only deletes the chat account; the Bluesky account remains in place. + /// + /// - SeeAlso: This is based on the [`chat.bsky.actor.deleteAccount`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/actor/deleteAccount.json + public func deleteAccount() async throws { + guard session != nil, + let accessToken = session?.accessToken else { + throw ATRequestPrepareError.missingActiveSession + } + + guard let sessionURL = session?.pdsURL, + let requestURL = URL(string: "\(sessionURL)/xrpc/chat.bsky.actor.deleteAccount") else { + throw ATRequestPrepareError.invalidRequestURL + } + + let requestBody = ChatBskyLexicon.Actor.DeleteAccount() + + do { + let request = APIClientService.createRequest(forRequest: requestURL, + andMethod: .get, + acceptValue: "application/json", + contentTypeValue: nil, + authorizationValue: "Bearer \(accessToken)") + + try await APIClientService.sendRequest(request, + withEncodingBody: requestBody) + } catch { + throw error + } + } +} diff --git a/Sources/ATProtoKit/Networking/ChatAPI/ChatDeleteMessageForSelf.swift b/Sources/ATProtoKit/Networking/ChatAPI/ChatDeleteMessageForSelf.swift new file mode 100644 index 0000000000..954711463e --- /dev/null +++ b/Sources/ATProtoKit/Networking/ChatAPI/ChatDeleteMessageForSelf.swift @@ -0,0 +1,57 @@ +// +// ChatDeleteMessageForSelf.swift +// +// +// Created by Christopher Jr Riley on 2024-05-31. +// + +import Foundation + +extension ATProtoBlueskyChat { + + /// Deletes a mesage only from the user account's end. + /// + /// - SeeAlso: This is based on the [`chat.bsky.convo.deleteMessageForSelf`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/convo/deleteMessageForSelf.json + /// + /// - Parameters: + /// - conversationID: The ID of the conversation. + /// - messageID: The ID of the message. + /// /// - Returns: A `Result`, containing either a ``ChatBskyLexicon/Conversation/DeletedMessageViewDefinition`` + /// if successful, or an `Error` if not. + public func DeleteMessageForSelf( + conversationID: String, + messageID: String + ) async throws -> Result { + guard session != nil, + let accessToken = session?.accessToken else { + throw ATRequestPrepareError.missingActiveSession + } + + guard let sessionURL = session?.pdsURL, + let requestURL = URL(string: "\(sessionURL)/xrpc/chat.bsky.convo.deleteMessageForSelf") else { + return .failure(ATRequestPrepareError.invalidRequestURL) + } + + let requestBody = ChatBskyLexicon.Conversation.DeleteMessageForSelfRequestBody( + conversationID: conversationID, + messageID: messageID + ) + + do { + let request = APIClientService.createRequest(forRequest: requestURL, + andMethod: .get, + acceptValue: "application/json", + contentTypeValue: "application/json", + authorizationValue: "Bearer \(accessToken)") + let response = try await APIClientService.sendRequest(request, + withEncodingBody: requestBody, + decodeTo: ChatBskyLexicon.Conversation.DeletedMessageViewDefinition.self) + + return .success(response) + } catch { + return .failure(error) + } + } +} diff --git a/Sources/ATProtoKit/Networking/ChatAPI/ChatExportAccountData.swift b/Sources/ATProtoKit/Networking/ChatAPI/ChatExportAccountData.swift new file mode 100644 index 0000000000..b39ec6a174 --- /dev/null +++ b/Sources/ATProtoKit/Networking/ChatAPI/ChatExportAccountData.swift @@ -0,0 +1,41 @@ +// +// ChatExportAccountData.swift +// +// +// Created by Christopher Jr Riley on 2024-05-31. +// + +import Foundation + +extension ATProtoBlueskyChat { + + /// Exports the user's account data. + /// + /// - SeeAlso: This is based on the [`chat.bsky.actor.exportAccountData`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/actor/exportAccountData.json + /// + public func exportAccountData() async throws { + guard session != nil, + let accessToken = session?.accessToken else { + throw ATRequestPrepareError.missingActiveSession + } + + guard let sessionURL = session?.pdsURL, + let requestURL = URL(string: "\(sessionURL)/xrpc/chat.bsky.actor.exportAccountData") else { + throw ATRequestPrepareError.invalidRequestURL + } + + do { + let request = APIClientService.createRequest(forRequest: requestURL, + andMethod: .get, + acceptValue: "application/jsonl", + contentTypeValue: nil, + authorizationValue: "Bearer \(accessToken)") + + _ = try await APIClientService.sendRequest(request) + } catch { + throw error + } + } +} diff --git a/Sources/ATProtoKit/Networking/ChatAPI/ChatGetActorMetadata.swift b/Sources/ATProtoKit/Networking/ChatAPI/ChatGetActorMetadata.swift new file mode 100644 index 0000000000..d3728dc1ed --- /dev/null +++ b/Sources/ATProtoKit/Networking/ChatAPI/ChatGetActorMetadata.swift @@ -0,0 +1,60 @@ +// +// ChatGetActorMetadata.swift +// +// +// Created by Christopher Jr Riley on 2024-05-31. +// + +import Foundation + +extension ATProtoBlueskyChat { + + /// Retrieves the user account's metadata as a moderator. + /// + /// - Important: This is a moderator task and as such, regular users won't be able to access + /// this; if they attempt to do so, an error will occur. + /// + /// - SeeAlso: This is based on the [`chat.bsky.moderation.getActorMetadata`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/moderation/getActorMetadata.json + /// + /// - Parameter actorDID: The decentralized identifier (DID) of the user account. + /// - Returns: A `Result`, containing either a ``ChatBskyLexicon/Moderation/GetActorMetadataOutput`` + /// if successful, or an `Error` if not. + public func getMessageContext(actorDID: String) async throws -> Result { + guard session != nil, + let accessToken = session?.accessToken else { + return .failure(ATRequestPrepareError.missingActiveSession) + } + + guard let sessionURL = session?.pdsURL, + let requestURL = URL(string: "\(sessionURL)/xrpc/chat.bsky.moderation.getActorMetadata") else { + return .failure(ATRequestPrepareError.invalidRequestURL) + } + + var queryItems = [(String, String)]() + + queryItems.append(("actor", actorDID)) + + let queryURL: URL + + do { + queryURL = try APIClientService.setQueryItems( + for: requestURL, + with: queryItems + ) + + let request = APIClientService.createRequest(forRequest: queryURL, + andMethod: .get, + acceptValue: "application/json", + contentTypeValue: nil, + authorizationValue: "Bearer \(accessToken)") + let response = try await APIClientService.sendRequest(request, + decodeTo: ChatBskyLexicon.Moderation.GetActorMetadataOutput.self) + + return .success(response) + } catch { + return .failure(error) + } + } +} diff --git a/Sources/ATProtoKit/Networking/ChatAPI/ChatGetConvo.swift b/Sources/ATProtoKit/Networking/ChatAPI/ChatGetConvo.swift new file mode 100644 index 0000000000..31de3f0c7a --- /dev/null +++ b/Sources/ATProtoKit/Networking/ChatAPI/ChatGetConvo.swift @@ -0,0 +1,59 @@ +// +// ChatGetConvo.swift +// +// +// Created by Christopher Jr Riley on 2024-05-31. +// + +import Foundation + +extension ATProtoBlueskyChat { + + /// Retrieves a conversation. + /// + /// - SeeAlso: This is based on the [`chat.bsky.convo.getConvo`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/convo/getConvo.json + /// + /// - Parameter members: An array of members within the conversation. Maximum amount is + /// 10 items. + /// - Returns: A `Result`, containing either a ``ChatBskyLexicon/Conversation/GetConversationOutput`` + /// if successful, or an `Error` if not. + public func getConversation(byID conversationID: String) async throws -> Result { + guard session != nil, + let accessToken = session?.accessToken else { + return .failure(ATRequestPrepareError.missingActiveSession) + } + + guard let sessionURL = session?.pdsURL, + let requestURL = URL(string: "\(sessionURL)/xrpc/app.bsky.graph.getList") else { + return .failure(ATRequestPrepareError.invalidRequestURL) + } + + var queryItems = [(String, String)]() + + queryItems.append(("convoId", conversationID)) + + let queryURL: URL + + do { + queryURL = try APIClientService.setQueryItems( + for: requestURL, + with: queryItems + ) + + let request = APIClientService.createRequest(forRequest: queryURL, + andMethod: .get, + acceptValue: "application/json", + contentTypeValue: nil, + authorizationValue: "Bearer \(accessToken)") + let response = try await APIClientService.sendRequest(request, + decodeTo: ChatBskyLexicon.Conversation.GetConversationOutput.self) + + return .success(response) + } catch { + return .failure(error) + } + + } +} diff --git a/Sources/ATProtoKit/Networking/ChatAPI/ChatGetConvoForMembers.swift b/Sources/ATProtoKit/Networking/ChatAPI/ChatGetConvoForMembers.swift new file mode 100644 index 0000000000..d157f3f170 --- /dev/null +++ b/Sources/ATProtoKit/Networking/ChatAPI/ChatGetConvoForMembers.swift @@ -0,0 +1,60 @@ +// +// ChatGetConvoForMembers.swift +// +// +// Created by Christopher Jr Riley on 2024-05-31. +// + +import Foundation + +extension ATProtoBlueskyChat { + + /// Retrieves a conversation based on the list of members. + /// + /// - Note: `members` will only take the first 10 items. Any additional items will be discared. + /// + /// - SeeAlso: This is based on the [`chat.bsky.convo.getConvoForMembers`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/convo/getConvoForMembers.json + /// + /// - Parameter members: An array of members within the conversation. Maximum amount is + /// 10 items. + /// - - Returns: A `Result`, containing either a ``ChatBskyLexicon/Conversation/GetConversationForMembersOutput`` + /// if successful, or an `Error` if not. + public func getConversaionForMembers(_ members: [String]) async throws -> Result { + guard session != nil, + let accessToken = session?.accessToken else { + throw ATRequestPrepareError.missingActiveSession + } + + guard let sessionURL = session?.pdsURL, + let requestURL = URL(string: "\(sessionURL)/xrpc/chat.bsky.convo.getConvoForMembers") else { + return .failure(ATRequestPrepareError.invalidRequestURL) + } + + var queryItems = [(String, String)]() + + queryItems += members.map { ("members", $0) } + + let queryURL: URL + + do { + queryURL = try APIClientService.setQueryItems( + for: requestURL, + with: queryItems + ) + + let request = APIClientService.createRequest(forRequest: queryURL, + andMethod: .get, + acceptValue: "application/json", + contentTypeValue: nil, + authorizationValue: "Bearer \(accessToken)") + let response = try await APIClientService.sendRequest(request, + decodeTo: ChatBskyLexicon.Conversation.GetConversationForMembersOutput.self) + + return .success(response) + } catch { + return .failure(error) + } + } +} diff --git a/Sources/ATProtoKit/Networking/ChatAPI/ChatGetLog.swift b/Sources/ATProtoKit/Networking/ChatAPI/ChatGetLog.swift new file mode 100644 index 0000000000..d28bdd50db --- /dev/null +++ b/Sources/ATProtoKit/Networking/ChatAPI/ChatGetLog.swift @@ -0,0 +1,60 @@ +// +// ChatGetLog.swift +// +// +// Created by Christopher Jr Riley on 2024-05-31. +// + +import Foundation + +extension ATProtoBlueskyChat { + + /// Retrieves logs for messages. + /// + /// - SeeAlso: This is based on the [`chat.bsky.convo.getLog`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/convo/getLog.json + /// + /// - Parameter cursor: The mark used to indicate the starting point for the next set of + /// result. Optional. + /// - Returns: A `Result`, containing either a ``ChatBskyLexicon/Conversation/GetLogOutput`` + /// if successful, or an `Error` if not. + public func getLog(cursor: String? = nil) async throws -> Result { + guard session != nil, + let accessToken = session?.accessToken else { + return .failure(ATRequestPrepareError.missingActiveSession) + } + + guard let sessionURL = session?.pdsURL, + let requestURL = URL(string: "\(sessionURL)/xrpc/chat.bsky.convo.getLog") else { + return .failure(ATRequestPrepareError.invalidRequestURL) + } + + var queryItems = [(String, String)]() + + if let cursor { + queryItems.append(("cursor", cursor)) + } + + let queryURL: URL + + do { + queryURL = try APIClientService.setQueryItems( + for: requestURL, + with: queryItems + ) + + let request = APIClientService.createRequest(forRequest: queryURL, + andMethod: .get, + acceptValue: "application/json", + contentTypeValue: nil, + authorizationValue: "Bearer \(accessToken)") + let response = try await APIClientService.sendRequest(request, + decodeTo: ChatBskyLexicon.Conversation.GetLogOutput.self) + + return .success(response) + } catch { + return .failure(error) + } + } +} diff --git a/Sources/ATProtoKit/Networking/ChatAPI/ChatGetMessageContext.swift b/Sources/ATProtoKit/Networking/ChatAPI/ChatGetMessageContext.swift new file mode 100644 index 0000000000..f423ef17d0 --- /dev/null +++ b/Sources/ATProtoKit/Networking/ChatAPI/ChatGetMessageContext.swift @@ -0,0 +1,83 @@ +// +// ChatGetMessageContext.swift +// +// +// Created by Christopher Jr Riley on 2024-05-31. +// + +import Foundation + +extension ATProtoBlueskyChat { + + /// Retrieves the message context as a moderator. + /// + /// - Important: This is a moderator task and as such, regular users won't be able to access + /// this; if they attempt to do so, an error will occur. + /// + /// - SeeAlso: This is based on the [`chat.bsky.moderation.getMessageContext`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/moderation/getMessageContext.json + /// + /// - Parameters: + /// - conversationID: The ID of the conversation. Optional. + /// - messageID: The ID of the message. + /// - messagesBefore: The number of messages older than the message in `messageID`. Optional. + /// Defaults to `5`. + /// - messagesAfter: The number of messages younger than the message in `messageID`. + /// Optional. Defaults to `5`. + /// - Returns: A `Result`, containing either a ``ChatBskyLexicon/Moderation/GetMessageContextOutput`` + /// if successful, or an `Error` if not. + public func getMessageContext( + from conversationID: String?, + messageID: String, + messagesBefore: Int? = 5, + messagesAfter: Int? = 5 + ) async throws -> Result { + guard session != nil, + let accessToken = session?.accessToken else { + return .failure(ATRequestPrepareError.missingActiveSession) + } + + guard let sessionURL = session?.pdsURL, + let requestURL = URL(string: "\(sessionURL)/xrpc/chat.bsky.moderation.getMessageContext") else { + return .failure(ATRequestPrepareError.invalidRequestURL) + } + + var queryItems = [(String, String)]() + + if let conversationID { + queryItems.append(("convoId", conversationID)) + } + + queryItems.append(("messageId", messageID)) + + if let messagesBefore { + queryItems.append(("before", "\(messagesBefore)")) + } + + if let messagesAfter { + queryItems.append(("after", "\(messagesAfter)")) + } + + let queryURL: URL + + do { + queryURL = try APIClientService.setQueryItems( + for: requestURL, + with: queryItems + ) + + let request = APIClientService.createRequest(forRequest: queryURL, + andMethod: .get, + acceptValue: "application/json", + contentTypeValue: "application/json", + authorizationValue: "Bearer \(accessToken)") + let response = try await APIClientService.sendRequest(request, + decodeTo: ChatBskyLexicon.Moderation.GetMessageContextOutput.self) + + return .success(response) + } catch { + return .failure(error) + } + } +} diff --git a/Sources/ATProtoKit/Networking/ChatAPI/ChatGetMessages.swift b/Sources/ATProtoKit/Networking/ChatAPI/ChatGetMessages.swift new file mode 100644 index 0000000000..a0a4a9deab --- /dev/null +++ b/Sources/ATProtoKit/Networking/ChatAPI/ChatGetMessages.swift @@ -0,0 +1,67 @@ +// +// ChatGetMessages.swift +// +// +// Created by Christopher Jr Riley on 2024-05-31. +// + +import Foundation + +extension ATProtoBlueskyChat { + + /// Retrieves messages from a conversation. + /// + /// - SeeAlso: This is based on the [`chat.bsky.convo.getMessages`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/convo/getMessages.json + /// + /// - Parameters: + /// - conversationID: The ID of the conversation. + /// - limit: The number of items that can be in the list. Optional. Defaults to `50`. + /// - Returns: A `Result`, containing either a ``ChatBskyLexicon/Conversation/GetMessagesOutput`` + /// if successful, or an `Error` if not. + public func getMessages( + from conversationID: String, + limit: Int? = 50 + ) async throws -> Result { + guard session != nil, + let accessToken = session?.accessToken else { + return .failure(ATRequestPrepareError.missingActiveSession) + } + + guard let sessionURL = session?.pdsURL, + let requestURL = URL(string: "\(sessionURL)/xrpc/chat.bsky.convo.getMessages") else { + return .failure(ATRequestPrepareError.invalidRequestURL) + } + + var queryItems = [(String, String)]() + + queryItems.append(("convoId", conversationID)) + + if let limit { + let finalLimit = max(1, min(limit, 100)) + queryItems.append(("limit", "\(finalLimit)")) + } + + let queryURL: URL + + do { + queryURL = try APIClientService.setQueryItems( + for: requestURL, + with: queryItems + ) + + let request = APIClientService.createRequest(forRequest: queryURL, + andMethod: .get, + acceptValue: "application/json", + contentTypeValue: nil, + authorizationValue: "Bearer \(accessToken)") + let response = try await APIClientService.sendRequest(request, + decodeTo: ChatBskyLexicon.Conversation.GetMessagesOutput.self) + + return .success(response) + } catch { + return .failure(error) + } + } +} diff --git a/Sources/ATProtoKit/Networking/ChatAPI/ChatLeaveConvo.swift b/Sources/ATProtoKit/Networking/ChatAPI/ChatLeaveConvo.swift new file mode 100644 index 0000000000..afbdfbbe52 --- /dev/null +++ b/Sources/ATProtoKit/Networking/ChatAPI/ChatLeaveConvo.swift @@ -0,0 +1,51 @@ +// +// ChatLeaveConvo.swift +// +// +// Created by Christopher Jr Riley on 2024-05-31. +// + +import Foundation + +extension ATProtoBlueskyChat { + + /// Removes the user account from the conversation. + /// + /// - SeeAlso: This is based on the [`chat.bsky.convo.leaveConvo`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/convo/leaveConvo.json + /// + /// - Parameter conversationID: The ID of the conversation. + /// - Returns: A `Result`, containing either a ``ChatBskyLexicon/Conversation/LeaveConversationOutput`` + /// if successful, or an `Error` if not. + public func leaveConversation(from conversationID: String) async throws -> Result { + guard session != nil, + let accessToken = session?.accessToken else { + throw ATRequestPrepareError.missingActiveSession + } + + guard let sessionURL = session?.pdsURL, + let requestURL = URL(string: "\(sessionURL)/xrpc/chat.bsky.convo.leaveConvo") else { + return .failure(ATRequestPrepareError.invalidRequestURL) + } + + let requestBody = ChatBskyLexicon.Conversation.LeaveConversationRequestBody( + conversationID: conversationID + ) + + do { + let request = APIClientService.createRequest(forRequest: requestURL, + andMethod: .post, + acceptValue: "application/json", + contentTypeValue: "application/json", + authorizationValue: "Bearer \(accessToken)") + let response = try await APIClientService.sendRequest(request, + withEncodingBody: requestBody, + decodeTo: ChatBskyLexicon.Conversation.LeaveConversationOutput.self) + + return .success(response) + } catch { + throw error + } + } +} diff --git a/Sources/ATProtoKit/Networking/ChatAPI/ChatListConvos.swift b/Sources/ATProtoKit/Networking/ChatAPI/ChatListConvos.swift new file mode 100644 index 0000000000..b3992cad05 --- /dev/null +++ b/Sources/ATProtoKit/Networking/ChatAPI/ChatListConvos.swift @@ -0,0 +1,70 @@ +// +// ChatListConvos.swift +// +// +// Created by Christopher Jr Riley on 2024-05-31. +// + +import Foundation + +extension ATProtoBlueskyChat { + + /// Lists various conversations the user account is participating in. + /// + /// - SeeAlso: This is based on the [`chat.bsky.convo.listConvos`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/convo/listConvos.json + /// + /// - Parameters: + /// - limit: The number of items that can be in the list. Optional. Defaults to `50`. + /// - cursor: The mark used to indicate the starting point for the next set of + /// result. Optional. + /// - Returns: A `Result`, containing either a ``ChatBskyLexicon/Conversation/ListConversationsOutput`` + /// if successful, or an `Error` if not. + public func listConversations( + limit: Int? = 50, + cursor: String? = nil + ) async throws -> Result { + guard session != nil, + let accessToken = session?.accessToken else { + return .failure(ATRequestPrepareError.missingActiveSession) + } + + guard let sessionURL = session?.pdsURL, + let requestURL = URL(string: "\(sessionURL)/xrpc/chat.bsky.convo.listConvos") else { + return .failure(ATRequestPrepareError.invalidRequestURL) + } + + var queryItems = [(String, String)]() + + if let limit { + let finalLimit = max(1, min(limit, 100)) + queryItems.append(("limit", "\(finalLimit)")) + } + + if let cursor { + queryItems.append(("cursor", cursor)) + } + + let queryURL: URL + + do { + queryURL = try APIClientService.setQueryItems( + for: requestURL, + with: queryItems + ) + + let request = APIClientService.createRequest(forRequest: queryURL, + andMethod: .get, + acceptValue: "application/json", + contentTypeValue: nil, + authorizationValue: "Bearer \(accessToken)") + let response = try await APIClientService.sendRequest(request, + decodeTo: ChatBskyLexicon.Conversation.ListConversationsOutput.self) + + return .success(response) + } catch { + return .failure(error) + } + } +} diff --git a/Sources/ATProtoKit/Networking/ChatAPI/ChatMuteConvo.swift b/Sources/ATProtoKit/Networking/ChatAPI/ChatMuteConvo.swift new file mode 100644 index 0000000000..14885daa49 --- /dev/null +++ b/Sources/ATProtoKit/Networking/ChatAPI/ChatMuteConvo.swift @@ -0,0 +1,51 @@ +// +// ChatMuteConvo.swift +// +// +// Created by Christopher Jr Riley on 2024-05-31. +// + +import Foundation + +extension ATProtoBlueskyChat { + + /// Mutes a conversation the user account is participating in. + /// + /// - SeeAlso: This is based on the [`chat.bsky.convo.muteConvo`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/convo/muteConvo.json + /// + /// - Parameter conversationID: The ID of the conversation. + /// - Returns: A `Result`, containing either a ``ChatBskyLexicon/Conversation/MuteConversationOutput`` + /// if successful, or an `Error` if not. + public func muteConversation(from conversationID: String) async throws -> Result { + guard session != nil, + let accessToken = session?.accessToken else { + return .failure(ATRequestPrepareError.missingActiveSession) + } + + guard let sessionURL = session?.pdsURL, + let requestURL = URL(string: "\(sessionURL)/xrpc/chat.bsky.convo.muteConvo") else { + return .failure(ATRequestPrepareError.invalidRequestURL) + } + + let requestBody = ChatBskyLexicon.Conversation.MuteConversationRequestBody( + conversationID: conversationID + ) + + do { + let request = APIClientService.createRequest(forRequest: requestURL, + andMethod: .get, + acceptValue: "application/json", + contentTypeValue: "application/json", + authorizationValue: "Bearer \(accessToken)") + let response = try await APIClientService.sendRequest(request, + withEncodingBody: requestBody, + decodeTo: ChatBskyLexicon.Conversation.MuteConversationOutput.self) + + return .success(response) + } catch { + return .failure(error) + } + } +} diff --git a/Sources/ATProtoKit/Networking/ChatAPI/ChatSendMessage.swift b/Sources/ATProtoKit/Networking/ChatAPI/ChatSendMessage.swift new file mode 100644 index 0000000000..9e46cffcec --- /dev/null +++ b/Sources/ATProtoKit/Networking/ChatAPI/ChatSendMessage.swift @@ -0,0 +1,59 @@ +// +// ChatSendMessage.swift +// +// +// Created by Christopher Jr Riley on 2024-05-31. +// + +import Foundation + +extension ATProtoBlueskyChat { + + /// Sends a message to a conversation. + /// + /// Due to current limitations, there is no way to add images to the messages. + /// + /// - SeeAlso: This is based on the [`chat.bsky.convo.sendMessage`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/convo/sendMessage.json + /// + /// - Parameters: + /// - conversationID: The ID of the conversation. + /// - message: The message to be sent. + /// - Returns: A `Result`, containing either a ``ChatBskyLexicon/Conversation/MessageViewDefinition`` + /// if successful, or an `Error` if not. + public func sendMessage( + conversationID: String, + message: ChatBskyLexicon.Conversation.MessageInputDefinition + ) async throws -> Result { + guard session != nil, + let accessToken = session?.accessToken else { + return .failure(ATRequestPrepareError.missingActiveSession) + } + + guard let sessionURL = session?.pdsURL, + let requestURL = URL(string: "\(sessionURL)/xrpc/chat.bsky.convo.sendMessage") else { + return .failure(ATRequestPrepareError.invalidRequestURL) + } + + let requestBody = ChatBskyLexicon.Conversation.SendMessageRequestBody( + conversationID: conversationID, + message: message + ) + + do { + let request = APIClientService.createRequest(forRequest: requestURL, + andMethod: .get, + acceptValue: "application/json", + contentTypeValue: "application/json", + authorizationValue: "Bearer \(accessToken)") + let response = try await APIClientService.sendRequest(request, + withEncodingBody: requestBody, + decodeTo: ChatBskyLexicon.Conversation.MessageViewDefinition.self) + + return .success(response) + } catch { + return .failure(error) + } + } +} diff --git a/Sources/ATProtoKit/Networking/ChatAPI/ChatSendMessageBatch.swift b/Sources/ATProtoKit/Networking/ChatAPI/ChatSendMessageBatch.swift new file mode 100644 index 0000000000..e1c254fc48 --- /dev/null +++ b/Sources/ATProtoKit/Networking/ChatAPI/ChatSendMessageBatch.swift @@ -0,0 +1,53 @@ +// +// ChatSendMessageBatch.swift +// +// +// Created by Christopher Jr Riley on 2024-05-31. +// + +import Foundation + +extension ATProtoBlueskyChat { + + /// Sends a batch of messages to the conversation. + /// + /// Due to Bluesky limitations, you are unable to send images at this time. + /// + /// - SeeAlso: This is based on the [`chat.bsky.convo.sendMessageBatch`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/convo/sendMessageBatch.json + /// + /// - Parameter messages: A array of messages. Maximum number is 100 items. + /// - Returns: A `Result`, containing either a ``ChatBskyLexicon/Conversation/SendMessageBatchOutput`` + /// if successful, or an `Error` if not. + public func sendMessageBatch(messages: [ChatBskyLexicon.Conversation.SendMessageBatch.MessageBatchItem]) async throws -> Result { + guard session != nil, + let accessToken = session?.accessToken else { + return .failure(ATRequestPrepareError.missingActiveSession) + } + + guard let sessionURL = session?.pdsURL, + let requestURL = URL(string: "\(sessionURL)/xrpc/chat.bsky.convo.sendMessageBatch") else { + return .failure(ATRequestPrepareError.invalidRequestURL) + } + + let requestBody = ChatBskyLexicon.Conversation.SendMessageBatchRequestBody( + items: messages + ) + + do { + let request = APIClientService.createRequest(forRequest: requestURL, + andMethod: .get, + acceptValue: "application/json", + contentTypeValue: "application/json", + authorizationValue: "Bearer \(accessToken)") + let response = try await APIClientService.sendRequest(request, + withEncodingBody: requestBody, + decodeTo: ChatBskyLexicon.Conversation.SendMessageBatchOutput.self) + + return .success(response) + } catch { + return .failure(error) + } + } +} diff --git a/Sources/ATProtoKit/Networking/ChatAPI/ChatUnmuteConvo.swift b/Sources/ATProtoKit/Networking/ChatAPI/ChatUnmuteConvo.swift new file mode 100644 index 0000000000..f2f119b02c --- /dev/null +++ b/Sources/ATProtoKit/Networking/ChatAPI/ChatUnmuteConvo.swift @@ -0,0 +1,51 @@ +// +// ChatUnmuteConvo.swift +// +// +// Created by Christopher Jr Riley on 2024-05-31. +// + +import Foundation + +extension ATProtoBlueskyChat { + + /// Unmutes a conversation the user account is participating in. + /// + /// - SeeAlso: This is based on the [`chat.bsky.convo.unmuteConvo`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/convo/unmuteConvo.json + /// + /// - Parameter conversationID: The ID of the conversation. + /// - Returns: A `Result`, containing either a ``ChatBskyLexicon/Conversation/UnmuteConversationOutput`` + /// if successful, or an `Error` if not. + public func unmuteConversation(from conversationID: String) async throws -> Result { + guard session != nil, + let accessToken = session?.accessToken else { + return .failure(ATRequestPrepareError.missingActiveSession) + } + + guard let sessionURL = session?.pdsURL, + let requestURL = URL(string: "\(sessionURL)/xrpc/chat.bsky.convo.unmuteConvo") else { + return .failure(ATRequestPrepareError.invalidRequestURL) + } + + let requestBody = ChatBskyLexicon.Conversation.UnMuteConversationRequestBody( + conversationID: conversationID + ) + + do { + let request = APIClientService.createRequest(forRequest: requestURL, + andMethod: .get, + acceptValue: "application/json", + contentTypeValue: "application/json", + authorizationValue: "Bearer \(accessToken)") + let response = try await APIClientService.sendRequest(request, + withEncodingBody: requestBody, + decodeTo: ChatBskyLexicon.Conversation.UnmuteConversationOutput.self) + + return .success(response) + } catch { + return .failure(error) + } + } +} diff --git a/Sources/ATProtoKit/Networking/ChatAPI/ChatUpdateActorAccess.swift b/Sources/ATProtoKit/Networking/ChatAPI/ChatUpdateActorAccess.swift new file mode 100644 index 0000000000..95bedf0409 --- /dev/null +++ b/Sources/ATProtoKit/Networking/ChatAPI/ChatUpdateActorAccess.swift @@ -0,0 +1,59 @@ +// +// ChatUpdateActorAccess.swift +// +// +// Created by Christopher Jr Riley on 2024-05-31. +// + +import Foundation + +extension ATProtoBlueskyChat { + + /// Updates the user account's access to direct messages as an administrator. + /// + /// - Important: This is an administrator task and as such, regular users won't be able to access + /// this; if they attempt to do so, an error will occur. + /// + /// - SeeAlso: This is based on the [`chat.bsky.moderation.updateActorAccess`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/moderation/updateActorAccess.json + /// + /// - Parameters: + /// - actorDID: The decentralized identifier (DID) of the user account. + /// - doesAllowAccess: Indicates whether the user account can acess direct messages. + /// - reference: A reference. Optional. + public func updateActorAccess( + actorDID: String, + doesAllowAccess: Bool, + reference: String? + ) async throws { + guard session != nil, + let accessToken = session?.accessToken else { + throw ATRequestPrepareError.missingActiveSession + } + + guard let sessionURL = session?.pdsURL, + let requestURL = URL(string: "\(sessionURL)/xrpc/chat.bsky.moderation.updateActorAccess") else { + throw ATRequestPrepareError.invalidRequestURL + } + + let requestBody = ChatBskyLexicon.Moderation.UpdateActorAccessRequestBody( + actorDID: actorDID, + doesAllowAccess: doesAllowAccess, + reference: reference + ) + + do { + let request = APIClientService.createRequest(forRequest: requestURL, + andMethod: .get, + acceptValue: nil, + contentTypeValue: "application/json", + authorizationValue: "Bearer \(accessToken)") + + try await APIClientService.sendRequest(request, + withEncodingBody: requestBody) + } catch { + throw error + } + } +} diff --git a/Sources/ATProtoKit/Networking/ChatAPI/ChatUpdateRead.swift b/Sources/ATProtoKit/Networking/ChatAPI/ChatUpdateRead.swift new file mode 100644 index 0000000000..fd55f977f0 --- /dev/null +++ b/Sources/ATProtoKit/Networking/ChatAPI/ChatUpdateRead.swift @@ -0,0 +1,57 @@ +// +// ChatUpdateRead.swift +// +// +// Created by Christopher Jr Riley on 2024-05-31. +// + +import Foundation + +extension ATProtoBlueskyChat { + + /// Updates the conversation to be marked as read. + /// + /// - SeeAlso: This is based on the [`chat.bsky.convo.updateRead`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/chat/bsky/convo/updateRead.json + /// + /// - Parameters: + /// - conversationID: The ID of the conversation. + /// - messageID: The ID of the message. Optional. + /// - Returns: A `Result`, containing either a ``ChatBskyLexicon/Conversation/UpdateReadOutput`` + /// if successful, or an `Error` if not. + public func updateRead( + from conversationID: String, + upTo messageID: String? = nil + ) async throws -> Result { + guard session != nil, + let accessToken = session?.accessToken else { + return .failure(ATRequestPrepareError.missingActiveSession) + } + + guard let sessionURL = session?.pdsURL, + let requestURL = URL(string: "\(sessionURL)/xrpc/chat.bsky.convo.updateRead") else { + return .failure(ATRequestPrepareError.invalidRequestURL) + } + + let requestBody = ChatBskyLexicon.Conversation.UpdateReadRequestBody( + conversationID: conversationID, + messageID: messageID + ) + + do { + let request = APIClientService.createRequest(forRequest: requestURL, + andMethod: .get, + acceptValue: "application/json", + contentTypeValue: "application/json", + authorizationValue: "Bearer \(accessToken)") + let response = try await APIClientService.sendRequest(request, + withEncodingBody: requestBody, + decodeTo: ChatBskyLexicon.Conversation.UpdateReadOutput.self) + + return .success(response) + } catch { + return .failure(error) + } + } +} diff --git a/Sources/ATProtoKit/Networking/CoreAPI/ApplyWrites.swift b/Sources/ATProtoKit/Networking/CoreAPI/ApplyWrites.swift index 4cac9b7c92..daeeb388c1 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/ApplyWrites.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/ApplyWrites.swift @@ -23,7 +23,12 @@ extension ATProtoKit { /// - shouldValidate: Indicates whether the operation should be validated. Optional. Defaults to `true`. /// - writes: The write operation itself. /// - swapCommit: Swaps out an operation based on the CID. Optional. - public func applyWrites(_ repositoryDID: String, shouldValidate: Bool? = true, writes: [ApplyWritesUnion], swapCommit: String?) async throws { + public func applyWrites( + _ repositoryDID: String, + shouldValidate: Bool? = true, + writes: [ATUnion.ApplyWritesUnion], + swapCommit: String? + ) async throws { guard session != nil, let accessToken = session?.accessToken else { throw ATRequestPrepareError.missingActiveSession @@ -34,7 +39,7 @@ extension ATProtoKit { throw ATRequestPrepareError.invalidRequestURL } - let requestBody = RepoApplyWrites( + let requestBody = ComAtprotoLexicon.Repository.ApplyWritesRequestBody( repositoryDID: repositoryDID, shouldValidate: shouldValidate, writes: writes, diff --git a/Sources/ATProtoKit/Networking/CoreAPI/CheckAccountStatus.swift b/Sources/ATProtoKit/Networking/CoreAPI/CheckAccountStatus.swift index f0e6a05de8..f9d86b2315 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/CheckAccountStatus.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/CheckAccountStatus.swift @@ -19,9 +19,9 @@ extension ATProtoKit { /// /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/checkAccountStatus.json /// - /// - Returns: A `Result`, containing either ``ServerCheckAccountStatusOutput`` + /// - Returns: A `Result`, containing either ``ComAtprotoLexicon/Server/CheckAccountStatusOutput`` /// if successful, or an `Error` if not. - public func checkAccountStatus() async throws -> Result { + public func checkAccountStatus() async throws -> Result { guard let sessionURL = session?.pdsURL, let requestURL = URL(string: "\(sessionURL)/xrpc/com.atproto.server.checkAccountStatus") else { return .failure(ATRequestPrepareError.invalidRequestURL) @@ -33,7 +33,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: nil) let response = try await APIClientService.sendRequest(request, - decodeTo: ServerCheckAccountStatusOutput.self) + decodeTo: ComAtprotoLexicon.Server.CheckAccountStatusOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/CoreAPI/CheckSignupQueue.swift b/Sources/ATProtoKit/Networking/CoreAPI/CheckSignupQueue.swift index 8f6e3f920a..87c77b1318 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/CheckSignupQueue.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/CheckSignupQueue.swift @@ -21,9 +21,9 @@ extension ATProtoKit { /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/temp/checkSignupQueue.json /// /// - Parameter query: The string used to search for the username. - /// - Returns: A `Result`, containing either a ``TempCheckSignupQueueOutput`` + /// - Returns: A `Result`, containing either a ``ComAtprotoLexicon/Temp/CheckSignupQueueOutput`` /// if successful, ot an `Error` if not. - public func checkSignupQueue(for query: String) async throws -> Result { + public func checkSignupQueue(for query: String) async throws -> Result { guard let sessionURL = session?.pdsURL, let requestURL = URL(string: "\(sessionURL)/xrpc/com.atproto.temp.checkSignupQueue") else { return .failure(ATRequestPrepareError.invalidRequestURL) @@ -47,7 +47,7 @@ extension ATProtoKit { contentTypeValue: "application/json", authorizationValue: nil) let response = try await APIClientService.sendRequest(request, - decodeTo: TempCheckSignupQueueOutput.self) + decodeTo: ComAtprotoLexicon.Temp.CheckSignupQueueOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/CoreAPI/ConfirmEmail.swift b/Sources/ATProtoKit/Networking/CoreAPI/ConfirmEmail.swift index b6d6d5f423..5dae2e0dd5 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/ConfirmEmail.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/ConfirmEmail.swift @@ -28,7 +28,10 @@ extension ATProtoKit { /// - Parameters: /// - email: The email address to confirm. /// - token: The token used to confirm the email address. - public func confirmEmail(_ email: String, token: String) async throws { + public func confirmEmail( + _ email: String, + token: String + ) async throws { guard session != nil, let accessToken = session?.accessToken else { throw ATRequestPrepareError.missingActiveSession @@ -39,7 +42,7 @@ extension ATProtoKit { throw ATRequestPrepareError.invalidRequestURL } - let requestBody = ServerConfirmEmail( + let requestBody = ComAtprotoLexicon.Server.ConfirmEmailRequestBody( email: email, token: token ) diff --git a/Sources/ATProtoKit/Networking/CoreAPI/CreateAppPassword.swift b/Sources/ATProtoKit/Networking/CoreAPI/CreateAppPassword.swift index b17e5ae8ce..c062a4b0f3 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/CreateAppPassword.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/CreateAppPassword.swift @@ -23,9 +23,9 @@ extension ATProtoKit { /// /// - Parameter passwordName: The name given to the App Password to help distingush it /// from others. - /// - Returns: A `Result`, either containing a ``ServerCreateAppPasswordOutput`` + /// - Returns: A `Result`, either containing a ``ComAtprotoLexicon/Server/CreateAppPasswordOutput`` /// if successful, or an `Error` if not. - public func createAppPassword(named passwordName: String) async throws -> Result { + public func createAppPassword(named passwordName: String) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -36,7 +36,7 @@ extension ATProtoKit { return .failure(ATRequestPrepareError.invalidRequestURL) } - let requestBody = ServerCreateAppPassword( + let requestBody = ComAtprotoLexicon.Server.CreateAppPasswordRequestBody( name: passwordName ) @@ -48,7 +48,7 @@ extension ATProtoKit { authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, withEncodingBody: requestBody, - decodeTo: ServerCreateAppPasswordOutput.self) + decodeTo: ComAtprotoLexicon.Server.CreateAppPasswordOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/CoreAPI/CreateInviteCode.swift b/Sources/ATProtoKit/Networking/CoreAPI/CreateInviteCode.swift index d86fa1de05..40c5c82900 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/CreateInviteCode.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/CreateInviteCode.swift @@ -24,9 +24,12 @@ extension ATProtoKit { /// - codeCount: The number of invite codes to be created. Defaults to 1. /// - forAccount: The decentralized identifier (DIDs) of the user that can use the /// invite code. Optional. - /// - Returns: A `Result`, containing either a ``ServerCreateInviteCodeOutput`` + /// - Returns: A `Result`, containing either a ``ComAtprotoLexicon/Server/CreateInviteCodeOutput`` /// if successful, or an `Error` if not. - public func createInviteCode(_ codeCount: Int = 1, for account: [String]) async throws -> Result { + public func createInviteCode( + _ codeCount: Int = 1, + for account: [String] + ) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -38,7 +41,7 @@ extension ATProtoKit { } // Make sure the number isn't lower than one. - let requestBody = ServerCreateInviteCode( + let requestBody = ComAtprotoLexicon.Server.CreateInviteCodeRequestBody( useCount: codeCount > 0 ? codeCount : 1, forAccount: account ) @@ -51,7 +54,7 @@ extension ATProtoKit { authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, withEncodingBody: requestBody, - decodeTo: ServerCreateInviteCodeOutput.self) + decodeTo: ComAtprotoLexicon.Server.CreateInviteCodeOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/CoreAPI/CreateInviteCodes.swift b/Sources/ATProtoKit/Networking/CoreAPI/CreateInviteCodes.swift index 95610c7785..2fe7e622ec 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/CreateInviteCodes.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/CreateInviteCodes.swift @@ -21,9 +21,12 @@ extension ATProtoKit { /// - codeCount: The number of invite codes to be created. Defaults to `1`. /// - forAccounts: An array of decentralized identifiers (DIDs) that can use the /// invite codes. - /// - Returns: A `Result`, containing either a ``ServerCreateInviteCodesOutput`` + /// - Returns: A `Result`, containing either a ``ComAtprotoLexicon/Server/CreateInviteCodesOutput`` /// if successful, or an `Error` if not. - public func createInviteCodes(_ codeCount: Int = 1, for accounts: [String]) async throws -> Result { + public func createInviteCodes( + _ codeCount: Int = 1, + for accounts: [String] + ) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -35,7 +38,7 @@ extension ATProtoKit { } // Make sure the number isn't lower than one. - let requestBody = ServerCreateInviteCodes( + let requestBody = ComAtprotoLexicon.Server.CreateInviteCodesRequestBody( useCount: codeCount > 0 ? codeCount : 1, forAccounts: accounts ) @@ -48,7 +51,7 @@ extension ATProtoKit { authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, withEncodingBody: requestBody, - decodeTo: ServerCreateInviteCodesOutput.self) + decodeTo: ComAtprotoLexicon.Server.CreateInviteCodesOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/CoreAPI/CreateRecord.swift b/Sources/ATProtoKit/Networking/CoreAPI/CreateRecord.swift index 2dbd291788..d6f93687f3 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/CreateRecord.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/CreateRecord.swift @@ -29,10 +29,16 @@ extension ATProtoKit { /// - shouldValidate: ndicates whether the record should be validated. Optional. Defaults to `true`. /// - record: The record itself. /// - swapCommit: Swaps out an operation based on the CID. Optional. - /// - Returns: A `Result`, containing either a ``StrongReference`` + /// - Returns: A `Result`, containing either a ``ComAtprotoLexicon/Repository/StrongReference`` /// if successful, and an `Error` if not. - public func createRecord(repositoryDID: String, collection: String, recordKey: String? = nil, shouldValidate: Bool? = true, record: UnknownType, - swapCommit: String? = nil) async -> Result { + public func createRecord( + repositoryDID: String, + collection: String, + recordKey: String? = nil, + shouldValidate: Bool? = true, + record: UnknownType, + swapCommit: String? = nil + ) async -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -43,7 +49,7 @@ extension ATProtoKit { return .failure(ATRequestPrepareError.invalidRequestURL) } - let requestBody = RepoCreateRecord( + let requestBody = ComAtprotoLexicon.Repository.CreateRecordRequestBody( repositoryDID: repositoryDID, collection: collection, recordKey: recordKey, @@ -60,7 +66,7 @@ extension ATProtoKit { authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, withEncodingBody: requestBody, - decodeTo: StrongReference.self) + decodeTo: ComAtprotoLexicon.Repository.StrongReference.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/CoreAPI/CreateReport.swift b/Sources/ATProtoKit/Networking/CoreAPI/CreateReport.swift index efccfbee2e..f1c3332a32 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/CreateReport.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/CreateReport.swift @@ -23,10 +23,13 @@ extension ATProtoAdmin { /// - reasonType: The reason for the report. /// - reason: Any additional context accompanying the report. Optional. /// - subject: The responsible party being reported. - /// - Returns: A `Result`, containing either ``ModerationCreateReportOutput`` + /// - Returns: A `Result`, containing either ``ComAtprotoLexicon/Moderation/CreateReportOutput`` /// if successful, or an `Error` if not. - public func createReport(with reasonType: ModerationReasonType, withContextof reason: String?, - subject: RepositoryReferencesUnion) async throws -> Result { + public func createReport( + with reasonType: ComAtprotoLexicon.Moderation.ReasonTypeDefinition, + withContextof reason: String?, + subject: ATUnion.CreateReportSubjectUnion + ) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -37,7 +40,7 @@ extension ATProtoAdmin { return .failure(ATRequestPrepareError.invalidRequestURL) } - let requestBody = ModerationCreateReport( + let requestBody = ComAtprotoLexicon.Moderation.CreateReportRequestBody( reasonType: reasonType, reason: reason, subject: subject @@ -51,7 +54,7 @@ extension ATProtoAdmin { authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, withEncodingBody: requestBody, - decodeTo: ModerationCreateReportOutput.self) + decodeTo: ComAtprotoLexicon.Moderation.CreateReportOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/CoreAPI/DeactivateAccount.swift b/Sources/ATProtoKit/Networking/CoreAPI/DeactivateAccount.swift index 5327490751..9e7d87165e 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/DeactivateAccount.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/DeactivateAccount.swift @@ -35,7 +35,7 @@ extension ATProtoKit { throw ATRequestPrepareError.invalidRequestURL } - let requestBody = ServerDeactivateAccount( + let requestBody = ComAtprotoLexicon.Server.DeactivateAccountRequestBody( deleteAfter: date ) diff --git a/Sources/ATProtoKit/Networking/CoreAPI/DeleteAccount.swift b/Sources/ATProtoKit/Networking/CoreAPI/DeleteAccount.swift index 861a41fc44..0e5f2458ea 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/DeleteAccount.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/DeleteAccount.swift @@ -18,13 +18,17 @@ extension ATProtoKit { /// /// - SeeAlso: This is based on the [`com.atproto.server.deleteAccount`][github] lexicon. /// - /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/admin/deleteAccount.json + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/deleteAccount.json /// /// - Parameters: /// - accountDID: The decentralized identifier (DID) of the user account to be deleted. /// - password: The password of the user account. /// - token: A token to confirm the deletion of the account. - public func deleteAccount(_ accountDID: String, password: String, token: String) async throws { + public func deleteAccount( + _ accountDID: String, + password: String, + token: String + ) async throws { guard session != nil, let accessToken = session?.accessToken else { throw ATRequestPrepareError.missingActiveSession @@ -35,7 +39,7 @@ extension ATProtoKit { throw ATRequestPrepareError.invalidRequestURL } - let requestBody = ServerDeleteAccount( + let requestBody = ComAtprotoLexicon.Server.DeleteAccountRequestBody( accountDID: accountDID, accountPassword: password, token: token diff --git a/Sources/ATProtoKit/Networking/CoreAPI/DeleteRecord.swift b/Sources/ATProtoKit/Networking/CoreAPI/DeleteRecord.swift index 418c84bcb0..df9a339f8e 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/DeleteRecord.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/DeleteRecord.swift @@ -26,7 +26,13 @@ extension ATProtoKit { /// of the record on the server. /// - swapCommit: Swap the commit on the server with this current commit based on the CID /// of the commit on the server. - public func deleteRecord(repositoryDID: String, collection: String, recordKey: String, swapRecord: String? = nil, swapCommit: String? = nil) async throws { + public func deleteRecord( + repositoryDID: String, + collection: String, + recordKey: String, + swapRecord: String? = nil, + swapCommit: String? = nil + ) async throws { guard session != nil, let accessToken = session?.accessToken else { throw ATRequestPrepareError.missingActiveSession @@ -37,7 +43,7 @@ extension ATProtoKit { throw ATRequestPrepareError.invalidRequestURL } - let requestBody = RepoDeleteRecord( + let requestBody = ComAtprotoLexicon.Repository.DeleteRecordRequestBody( repositoryDID: repositoryDID, collection: collection, recordKey: recordKey, diff --git a/Sources/ATProtoKit/Networking/CoreAPI/DescribeRepository.swift b/Sources/ATProtoKit/Networking/CoreAPI/DescribeRepository.swift index 663073ac85..567901ea1e 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/DescribeRepository.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/DescribeRepository.swift @@ -19,10 +19,12 @@ extension ATProtoKit { /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/repo/describeRepo.json /// /// - Parameter repositoryDID: The decentralized identifier (DID) or handle of the repository. - /// - Returns: A `Result`, containing either a ``RepoDescribeRepoOutput`` + /// - Returns: A `Result`, containing either a ``ComAtprotoLexicon/Repository/DescribeRepositoryOutput`` /// if successful, ot an `Error` if not. - public func describeRepository(_ repositoryDID: String, - pdsURL: String? = nil) async throws -> Result { + public func describeRepository( + _ repositoryDID: String, + pdsURL: String? = nil + ) async throws -> Result { guard let sessionURL = pdsURL != nil ? pdsURL : session?.pdsURL, let requestURL = URL(string: "\(sessionURL)/xrpc/com.atproto.repo.describeRepo") else { return .failure(ATRequestPrepareError.invalidRequestURL) @@ -46,7 +48,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: nil) let response = try await APIClientService.sendRequest(request, - decodeTo: RepoDescribeRepoOutput.self) + decodeTo: ComAtprotoLexicon.Repository.DescribeRepositoryOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/CoreAPI/DescribeServer.swift b/Sources/ATProtoKit/Networking/CoreAPI/DescribeServer.swift index ea8efe189e..1da30c513b 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/DescribeServer.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/DescribeServer.swift @@ -19,9 +19,9 @@ extension ATProtoKit { /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/describeServer.json /// /// - Parameter pdsURL: The URL of the Personal Data Server (PDS). Defaults to `nil`. - /// - Returns: A `Result`, containing either a ``ServerDescribeServerOutput`` + /// - Returns: A `Result`, containing either a ``ComAtprotoLexicon/Server/DescribeServerOutput`` /// if successful, or an `Error` if not. - public func describeServer(_ pdsURL: String? = nil) async throws -> Result { + public func describeServer(_ pdsURL: String? = nil) async throws -> Result { guard let sessionURL = pdsURL != nil ? pdsURL : session?.pdsURL, let requestURL = URL(string: "\(sessionURL)/xrpc/com.atproto.server.describeServer") else { return .failure(ATRequestPrepareError.invalidRequestURL) @@ -34,7 +34,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: nil) let response = try await APIClientService.sendRequest(request, - decodeTo: ServerDescribeServerOutput.self) + decodeTo: ComAtprotoLexicon.Server.DescribeServerOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/CoreAPI/GetAccountInviteCodes.swift b/Sources/ATProtoKit/Networking/CoreAPI/GetAccountInviteCodes.swift index e025d214d4..5b3273e7f7 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/GetAccountInviteCodes.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/GetAccountInviteCodes.swift @@ -23,10 +23,12 @@ extension ATProtoKit { /// be included in the list. Optional. Defaults to `true`. /// - areEarnedCodesIncluded: Indicates whether the invite codes that the user earned should /// be included in the list. Optional. Defaults to `true`. - /// - Returns: A `Result`, containing either ``ServerGetAccountInviteCodesOutput`` + /// - Returns: A `Result`, containing either ``ComAtprotoLexicon/Server/GetAccountInviteCodesOutput`` /// if successful, and an `Error` if not. - public func getAccountInviteCodes(_ areUsedCodesIncluded: Bool = true, - areEarnedCodesIncluded: Bool = true) async throws -> Result { + public func getAccountInviteCodes( + _ areUsedCodesIncluded: Bool = true, + areEarnedCodesIncluded: Bool = true + ) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -56,7 +58,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, - decodeTo: ServerGetAccountInviteCodesOutput.self) + decodeTo: ComAtprotoLexicon.Server.GetAccountInviteCodesOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/CoreAPI/GetBlob.swift b/Sources/ATProtoKit/Networking/CoreAPI/GetBlob.swift index d51fcbd392..b075aa73d9 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/GetBlob.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/GetBlob.swift @@ -10,26 +10,32 @@ import Foundation extension ATProtoKit { /// Retrieves a blob from a given record. - /// + /// /// - Note: According to the AT Protocol specifications: "Get a blob associated with a given /// account. Returns the full blob as originally uploaded. Does not require auth; implemented /// by PDS." - /// + /// /// - SeeAlso: This is based on the [`com.atproto.sync.getBlob`][github] lexicon. - /// + /// /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/sync/getBlob.json /// - /// - Parameter blobQuery: An object containing the `accountDID` and `cidHash` of the blob. + /// - Parameter accountDID: The decentralized identifier (DID) of the account. + /// - Parameter cidHash: The CID hash of the blob. + /// - Parameter pdsURL: The URL of the Personal Data Server (PDS). Defaults to `https://bsky.social`. /// - Returns: A `Result` containing `Data` on success or `Error` on failure. - public static func getBlob(from blobQuery: BlobQuery, pdsURL: String? = "https://bsky.social") async -> Result { + public static func getBlob( + from accountDID: String, + cidHash: String, + pdsURL: String? = "https://bsky.social" + ) async -> Result { guard let sessionURL = pdsURL, let requestURL = URL(string: "\(sessionURL)/xrpc/com.atproto.sync.getBlob") else { return .failure(ATRequestPrepareError.invalidRequestURL) } let queryItems = [ - ("did", blobQuery.accountDID), - ("cid", blobQuery.cidHash) + ("did", accountDID), + ("cid", cidHash) ] let queryURL: URL diff --git a/Sources/ATProtoKit/Networking/CoreAPI/GetLatestCommit.swift b/Sources/ATProtoKit/Networking/CoreAPI/GetLatestCommit.swift index 37d3be73f1..19196e97f0 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/GetLatestCommit.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/GetLatestCommit.swift @@ -21,9 +21,12 @@ extension ATProtoKit { /// - Parameters: /// - repositoryDID: The decentralized identifier (DID) of the repository. /// - pdsURL: The URL of the Personal Data Server (PDS). Defaults to `nil`. - /// - Returns: A `Result`, containing either a ``SyncGetBlocksOutput`` + /// - Returns: A `Result`, containing either a ``ComAtprotoLexicon/Sync/GetLatestCommitOutput`` /// if successful, or an `Error` if not. - public func getLatestCommit(from repositoryDID: String, pdsURL: String? = nil) async throws -> Result { + public func getLatestCommit( + from repositoryDID: String, + pdsURL: String? = nil + ) async throws -> Result { guard let sessionURL = pdsURL != nil ? pdsURL : session?.pdsURL, let requestURL = URL(string: "\(sessionURL)/xrpc/com.atproto.sync.getLatestCommit") else { return .failure(ATRequestPrepareError.invalidRequestURL) @@ -47,7 +50,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: nil) let response = try await APIClientService.sendRequest(request, - decodeTo: SyncGetLatestCommitOutput.self) + decodeTo: ComAtprotoLexicon.Sync.GetLatestCommitOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/CoreAPI/GetRecommendedDidCredentials.swift b/Sources/ATProtoKit/Networking/CoreAPI/GetRecommendedDidCredentials.swift index a8ffca3fa5..2752943225 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/GetRecommendedDidCredentials.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/GetRecommendedDidCredentials.swift @@ -19,9 +19,9 @@ extension ATProtoKit { /// /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/identity/getRecommendedDidCredentials.json /// - /// - Returns: A `Result`, containing either an ``IdentityGetRecommendedDidCredentialsOutput`` + /// - Returns: A `Result`, containing either an ``ComAtprotoLexicon/Identity/GetRecommendedDidCredentialsOutput`` /// if successful, or an `Error` if not. - public func getRecommendedDIDCredentials() async throws -> Result { + public func getRecommendedDIDCredentials() async throws -> Result { guard let sessionURL = session?.pdsURL, let requestURL = URL(string: "\(sessionURL)/xrpc/com.atproto.identity.getRecommendedDidCredentials") else { return .failure(ATRequestPrepareError.invalidRequestURL) @@ -34,7 +34,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: nil) let response = try await APIClientService.sendRequest(request, decodeTo: - IdentityGetRecommendedDidCredentialsOutput.self) + ComAtprotoLexicon.Identity.GetRecommendedDidCredentialsOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/CoreAPI/GetRepoRecord.swift b/Sources/ATProtoKit/Networking/CoreAPI/GetRepoRecord.swift index 91fe0f33f3..8f619b2880 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/GetRepoRecord.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/GetRepoRecord.swift @@ -10,33 +10,42 @@ import Foundation extension ATProtoKit { /// Searches for and validates a record from the repository. - /// + /// /// - Note: According to the AT Protocol specifications: "Get a single record from a /// repository. Does not require auth." - /// + /// /// - SeeAlso: This is based on the [`com.atproto.repo.getRecord`][github] lexicon. - /// + /// /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/repo/getRecord.json - /// + /// /// - Parameters: - /// - recordQuery: The record object. + /// - repository: The repository that owns the record. + /// - collection: The Namespaced Identifier (NSID) of the record. + /// - recordKey: The record key of the record. + /// - recordCID: The CID hash of the record. Optional. /// - pdsURL: The URL of the Personal Data Server (PDS). - /// - Returns: A `Result`, which either contains a ``RecordOutput`` + /// - Returns: A `Result`, which either contains a ``ComAtprotoLexicon/Repository/GetRecordOutput`` /// if successful, and an `Error` if not. - public func getRepositoryRecord(from recordQuery: RecordQuery, pdsURL: String? = nil) async throws -> Result { + public func getRepositoryRecord( + from repository: String, + collection: String, + recordKey: String, + recordCID: String? = nil, + pdsURL: String? = nil + ) async throws -> Result { guard let sessionURL = pdsURL != nil ? pdsURL : session?.pdsURL, let requestURL = URL(string: "\(sessionURL)/xrpc/com.atproto.repo.getRecord") else { return .failure(ATRequestPrepareError.invalidRequestURL) } var queryItems = [ - ("repo", recordQuery.repo), - ("collection", recordQuery.collection), - ("rkey", recordQuery.recordKey) + ("repo", repository), + ("collection", collection), + ("rkey", recordKey) ] - if let cid = recordQuery.recordCID { - queryItems.append(("cid", cid)) + if let recordCID { + queryItems.append(("cid", recordCID)) } let queryURL: URL @@ -51,7 +60,7 @@ extension ATProtoKit { andMethod: .get, authorizationValue: nil) let response = try await APIClientService.sendRequest(request, - decodeTo: RecordOutput.self) + decodeTo: ComAtprotoLexicon.Repository.GetRecordOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/CoreAPI/GetRepository.swift b/Sources/ATProtoKit/Networking/CoreAPI/GetRepository.swift index 61382ae333..658313790d 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/GetRepository.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/GetRepository.swift @@ -25,8 +25,11 @@ extension ATProtoKit { /// - pdsURL: The URL of the Personal Data Server (PDS). Defaults to `nil`. /// - Returns: A `Result`, containing either a `Data` object /// if successful, or an `Error` if not. - public func getRepository(_ repositoryDID: String, sinceRevision: String? = nil, - pdsURL: String? = nil) async throws -> Result { + public func getRepository( + _ repositoryDID: String, + sinceRevision: String? = nil, + pdsURL: String? = nil + ) async throws -> Result { guard let sessionURL = pdsURL != nil ? pdsURL : session?.pdsURL, let requestURL = URL(string: "\(sessionURL)/xrpc/com.atproto.sync.getRepo") else { return .failure(ATRequestPrepareError.invalidRequestURL) diff --git a/Sources/ATProtoKit/Networking/CoreAPI/GetRepositoryStatus.swift b/Sources/ATProtoKit/Networking/CoreAPI/GetRepositoryStatus.swift new file mode 100644 index 0000000000..65e4cd77bd --- /dev/null +++ b/Sources/ATProtoKit/Networking/CoreAPI/GetRepositoryStatus.swift @@ -0,0 +1,60 @@ +// +// GetRepositoryStatus.swift +// +// +// Created by Christopher Jr Riley on 2024-05-31. +// + +import Foundation + +extension ATProtoKit { + + /// Retrieves the status for a repository in the Personal Data Server (PDS). + /// + /// - Note: According to the AT Protocol specifications: "Get the hosting status for a + /// repository, on this server. Expected to be implemented by PDS and Relay." + /// + /// - SeeAlso: This is based on the [`com.atproto.sync.getRepoStatus`][github] lexicon. + /// + /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/sync/getRepoStatus.json + /// + /// - Parameter actorDID: The decentralized identifier (DID) of the user account. + /// - Returns: A `Result`, containing either a ``ComAtprotoLexicon/Sync/GetRepositoryStatusOutput`` + /// if successful, or an `Error` if not. + public func getRepositoryStatus(from actorDID: String) async throws -> Result { + guard session != nil, + let accessToken = session?.accessToken else { + return .failure(ATRequestPrepareError.missingActiveSession) + } + + guard let sessionURL = session?.pdsURL, + let requestURL = URL(string: "\(sessionURL)/xrpc/com.atproto.sync.getRepoStatus") else { + return .failure(ATRequestPrepareError.invalidRequestURL) + } + + var queryItems = [(String, String)]() + + queryItems.append(("did", actorDID)) + + let queryURL: URL + + do { + queryURL = try APIClientService.setQueryItems( + for: requestURL, + with: queryItems + ) + + let request = APIClientService.createRequest(forRequest: queryURL, + andMethod: .get, + acceptValue: "application/json", + contentTypeValue: nil, + authorizationValue: "Bearer \(accessToken)") + let response = try await APIClientService.sendRequest(request, + decodeTo: ComAtprotoLexicon.Sync.GetRepositoryStatusOutput.self) + + return .success(response) + } catch { + return .failure(error) + } + } +} diff --git a/Sources/ATProtoKit/Networking/CoreAPI/GetServiceAuthentication.swift b/Sources/ATProtoKit/Networking/CoreAPI/GetServiceAuthentication.swift index d83f4e6e70..9acb1e2343 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/GetServiceAuthentication.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/GetServiceAuthentication.swift @@ -19,9 +19,9 @@ extension ATProtoKit { /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/getServiceAuth.json /// /// - Parameter serviceDID: The decentralized identifier (DID) of the service. - /// - Returns: A `Result`, containing either a ``ServerGetServiceAuthOutput`` + /// - Returns: A `Result`, containing either a ``ComAtprotoLexicon/Server/GetServiceAuthOutput`` /// if successful, or an `Error`if not. - public func getServiceAuthentication(from serviceDID: String) async throws -> Result { + public func getServiceAuthentication(from serviceDID: String) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -50,7 +50,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, - decodeTo: ServerGetServiceAuthOutput.self) + decodeTo: ComAtprotoLexicon.Server.GetServiceAuthOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/CoreAPI/GetSyncBlocks.swift b/Sources/ATProtoKit/Networking/CoreAPI/GetSyncBlocks.swift index 2ceffce250..3fd5128d64 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/GetSyncBlocks.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/GetSyncBlocks.swift @@ -29,18 +29,17 @@ extension ATProtoKit { /// - pdsURL: The URL of the Personal Data Server (PDS). Defaults to `nil`. /// - Returns: A `Result`, containing either `Data` /// if successful, or `Error` if not. - public func getSyncBlocks(from repositoryDID: String, by repositoryCIDHashes: [String], - pdsURL: String? = nil) async throws -> Result { + public func getSyncBlocks( + from repositoryDID: String, + by repositoryCIDHashes: [String], + pdsURL: String? = nil + ) async throws -> Result { guard let sessionURL = pdsURL != nil ? pdsURL : session?.pdsURL, let requestURL = URL(string: "\(sessionURL)/xrpc/com.atproto.sync.getBlocks") else { return .failure(ATRequestPrepareError.invalidRequestURL) } var queryItems = [(String, String)]() -// let queryItems = [ -// ("did", blobQuery.accountDID), -// ("cid", blobQuery.cidHash) -// ] queryItems.append(("did", repositoryDID)) queryItems += repositoryCIDHashes.map { ("cids", $0) } diff --git a/Sources/ATProtoKit/Networking/CoreAPI/GetSyncRecord.swift b/Sources/ATProtoKit/Networking/CoreAPI/GetSyncRecord.swift index 84cdf0eae6..7cc309a065 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/GetSyncRecord.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/GetSyncRecord.swift @@ -19,23 +19,35 @@ extension ATProtoKit { /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/sync/getRecord.json /// /// - Parameters: - /// - recordQuery: The information required to get a record. + /// - repository: The repository that owns the record. + /// - collection: The Namespaced Identifier (NSID) of the record. + /// - recordKey: The record key of the record. + /// - recordCID: The CID hash of the record. Optional. /// - pdsURL: The URL of the Personal Data Server (PDS). Defaults to `nil`. /// - Returns: A `Result`, containing either a `Data` object /// if successful, or an `Error` if not. - public func getSyncRecord(_ recordQuery: RecordQuery, - pdsURL: String? = nil) async throws -> Result { + public func getSyncRecord( + from repository: String, + collection: String, + recordKey: String, + recordCID: String? = nil, + pdsURL: String? = nil + ) async throws -> Result { guard let sessionURL = pdsURL != nil ? pdsURL : session?.pdsURL, let requestURL = URL(string: "\(sessionURL)/xrpc/com.atproto.sync.getRecord") else { return .failure(ATRequestPrepareError.invalidRequestURL) } - let queryItems = [ - ("repo", recordQuery.repo), - ("collection", recordQuery.collection), - ("rkey", recordQuery.recordKey) + var queryItems = [ + ("repo", repository), + ("collection", collection), + ("rkey", recordKey) ] + if let recordCID { + queryItems.append(("cid", recordCID)) + } + let queryURL: URL do { diff --git a/Sources/ATProtoKit/Networking/CoreAPI/ImportRepository.swift b/Sources/ATProtoKit/Networking/CoreAPI/ImportRepository.swift index f2018d8de7..0d722b770b 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/ImportRepository.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/ImportRepository.swift @@ -26,13 +26,16 @@ extension ATProtoKit { /// - Parameters: /// - repositoryData: The repository data in the form of a CAR file. /// - pdsURL: The URL of the Personal Data Server (PDS). Defaults to `nil`. - public func importRepository(_ repositoryData: Data, pdsURL: String? = nil) async throws { + public func importRepository( + _ repositoryData: Data, + pdsURL: String? = nil + ) async throws { guard let sessionURL = pdsURL != nil ? pdsURL : session?.pdsURL, let requestURL = URL(string: "\(sessionURL)/xrpc/com.atproto.repo.importRepo") else { throw ATRequestPrepareError.invalidRequestURL } - let requestBody = RepoImportRepo( + let requestBody = ComAtprotoLexicon.Repository.ImportRepositoryRequestBody( repository: repositoryData ) diff --git a/Sources/ATProtoKit/Networking/CoreAPI/ListAppPasswords.swift b/Sources/ATProtoKit/Networking/CoreAPI/ListAppPasswords.swift index 75fcc2b4f8..9c2cd9fdcc 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/ListAppPasswords.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/ListAppPasswords.swift @@ -20,9 +20,9 @@ extension ATProtoKit { /// /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/listAppPasswords.json /// - /// - Returns: A `Result`, containing either a ``ServerListAppPasswordsOutput`` + /// - Returns: A `Result`, containing either a ``ComAtprotoLexicon/Server/ListAppPasswordsOutput`` /// if successful, or an `Error` if not. - public func listAppPasswords() async throws -> Result { + public func listAppPasswords() async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -40,7 +40,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, - decodeTo: ServerListAppPasswordsOutput.self) + decodeTo: ComAtprotoLexicon.Server.ListAppPasswordsOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/CoreAPI/ListBlobs.swift b/Sources/ATProtoKit/Networking/CoreAPI/ListBlobs.swift index 4135ce9e64..8a6e69c067 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/ListBlobs.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/ListBlobs.swift @@ -25,10 +25,15 @@ extension ATProtoKit { /// - cursor: The mark used to indicate the starting point for the next set of /// results. Optional. /// - pdsURL: The URL of the Personal Data Server (PDS). Defaults to `nil`. - /// - Returns: A `Result`, containing either a ``SyncListBlobsOutput`` + /// - Returns: A `Result`, containing either a ``ComAtprotoLexicon/Sync/ListBlobsOutput`` /// if successful, or an `Error` if not. - public func listBlobs(from repositoryDID: String, sinceRevision: String?, limit: Int? = 500, cursor: String? = nil, - pdsURL: String? = nil) async throws -> Result { + public func listBlobs( + from repositoryDID: String, + sinceRevision: String?, + limit: Int? = 500, + cursor: String? = nil, + pdsURL: String? = nil + ) async throws -> Result { guard let sessionURL = pdsURL != nil ? pdsURL : session?.pdsURL, let requestURL = URL(string: "\(sessionURL)/xrpc/com.atproto.sync.listBlobs") else { return .failure(ATRequestPrepareError.invalidRequestURL) @@ -65,7 +70,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: nil) let response = try await APIClientService.sendRequest(request, - decodeTo: SyncListBlobsOutput.self) + decodeTo: ComAtprotoLexicon.Sync.ListBlobsOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/CoreAPI/ListMissingBlobs.swift b/Sources/ATProtoKit/Networking/CoreAPI/ListMissingBlobs.swift index 71e3db6a9b..dfe0518917 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/ListMissingBlobs.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/ListMissingBlobs.swift @@ -22,9 +22,12 @@ extension ATProtoKit { /// - limit: The number of items that can be in the list. Optional. Defaults to `500`. /// - cursor: The mark used to indicate the starting point for the next set of /// result. Optional. - /// - Returns: A `Result`, containing either a ``RepoListMissingBlobsOutput`` + /// - Returns: A `Result`, containing either a ``ComAtprotoLexicon/Repository/ListMissingBlobsOutput`` /// if successful, or an `Error` if not. - public func listMissingBlobs(limit: Int? = 500, cursor: String? = nil) async throws -> Result { + public func listMissingBlobs( + limit: Int? = 500, + cursor: String? = nil + ) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -60,7 +63,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, - decodeTo: RepoListMissingBlobsOutput.self) + decodeTo: ComAtprotoLexicon.Repository.ListMissingBlobsOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/CoreAPI/ListRecords.swift b/Sources/ATProtoKit/Networking/CoreAPI/ListRecords.swift index c97dc28ef1..4e6f347d22 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/ListRecords.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/ListRecords.swift @@ -26,10 +26,16 @@ extension ATProtoKit { /// result. Optional. /// - isArrayReverse: Indicates whether the list of records is listed in reverse. Optional. /// - pdsURL: The URL of the Personal Data Server (PDS). Defaults to `nil`. - /// - Returns: A `Result`, containing ``RepoListRecordsOutput`` + /// - Returns: A `Result`, containing ``ComAtprotoLexicon/Repository/ListRecordsOutput`` /// if successful, or an `Error` if not. - public func listRecords(from repositoryDID: String, collection: String, limit: Int? = 50, cursor: String? = nil, isArrayReverse: Bool? = nil, - pdsURL: String? = nil) async throws -> Result { + public func listRecords( + from repositoryDID: String, + collection: String, + limit: Int? = 50, + cursor: String? = nil, + isArrayReverse: Bool? = nil, + pdsURL: String? = nil + ) async throws -> Result { guard let sessionURL = pdsURL != nil ? pdsURL : session?.pdsURL, let requestURL = URL(string: "\(sessionURL)/xrpc/com.atproto.repo.listRecords") else { return .failure(ATRequestPrepareError.invalidRequestURL) @@ -68,7 +74,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: nil) let response = try await APIClientService.sendRequest(request, - decodeTo: RepoListRecordsOutput.self) + decodeTo: ComAtprotoLexicon.Repository.ListRecordsOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/CoreAPI/ListRepositories.swift b/Sources/ATProtoKit/Networking/CoreAPI/ListRepositories.swift index 1db6f61ed0..7577ae3713 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/ListRepositories.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/ListRepositories.swift @@ -25,10 +25,13 @@ extension ATProtoKit { /// - cursor: The mark used to indicate the starting point for the next set of /// results. Optional. /// - pdsURL: The URL of the Personal Data Server (PDS). Defaults to `nil`. - /// - Returns: A `Result`, containing either a ``SyncListReposOutput`` + /// - Returns: A `Result`, containing either a ``ComAtprotoLexicon/Sync/ListRepositoriesOutput`` /// if successful, or an `Error` if not. - public func listRepositories(limit: Int? = 500, cursor: String? = nil, - pdsURL: String? = nil) async throws -> Result { + public func listRepositories( + limit: Int? = 500, + cursor: String? = nil, + pdsURL: String? = nil + ) async throws -> Result { guard let sessionURL = pdsURL != nil ? pdsURL : session?.pdsURL, let requestURL = URL(string: "\(sessionURL)/xrpc/com.atproto.sync.getRepos") else { return .failure(ATRequestPrepareError.invalidRequestURL) @@ -59,7 +62,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: nil) let response = try await APIClientService.sendRequest(request, - decodeTo: SyncListReposOutput.self) + decodeTo: ComAtprotoLexicon.Sync.ListRepositoriesOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/CoreAPI/NotifyOfUpdate.swift b/Sources/ATProtoKit/Networking/CoreAPI/NotifyOfUpdate.swift index c461f1fca9..96a35f533a 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/NotifyOfUpdate.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/NotifyOfUpdate.swift @@ -26,8 +26,10 @@ extension ATProtoKit { /// - Parameters: /// - crawlingHostname: The hostname that the crawling service resides in. Optional. /// - pdsURL: The URL of the Personal Data Server (PDS). Defaults to `nil`. - public func notifyOfUpdate(in crawlingHostname: String? = nil, - pdsURL: String? = nil) async throws { + public func notifyOfUpdate( + in crawlingHostname: String? = nil, + pdsURL: String? = nil + ) async throws { guard let sessionURL = pdsURL != nil ? pdsURL : session?.pdsURL, let requestURL = URL(string: "\(sessionURL)/xrpc/app.bsky.graph.notifyOfUpdate") else { throw ATRequestPrepareError.invalidRequestURL @@ -39,7 +41,7 @@ extension ATProtoKit { throw ATRequestPrepareError.invalidHostnameURL } - let requestBody = SyncCrawler( + let requestBody = ComAtprotoLexicon.Sync.Crawler( crawlingHostname: finalhostnameURL ) diff --git a/Sources/ATProtoKit/Networking/CoreAPI/PutRecord.swift b/Sources/ATProtoKit/Networking/CoreAPI/PutRecord.swift index 41616fc5c2..2a0ec1878d 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/PutRecord.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/PutRecord.swift @@ -27,10 +27,17 @@ extension ATProtoKit { /// - record: The record itself. /// - swapRecord: Swaps the record in the server with the record contained in here. Optional. /// - swapCommit: Swaps the commit in the server with the commit contained in here. Optional. - /// - Returns: A `Result`, containing either a ``StrongReference`` + /// - Returns: A `Result`, containing either a ``ComAtprotoLexicon/Repository/StrongReference`` /// if successful, or an `Error` if not. - public func putRecord(_ repositoryDID: String, collection: String, recordKey: String, shouldValidate: Bool? = true, record: UnknownType, - swapRecord: String? = nil, swapCommit: String? = nil) async throws -> Result { + public func putRecord( + _ repositoryDID: String, + collection: String, + recordKey: String, + shouldValidate: Bool? = true, + record: UnknownType, + swapRecord: String? = nil, + swapCommit: String? = nil + ) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -41,7 +48,7 @@ extension ATProtoKit { return .failure(ATRequestPrepareError.invalidRequestURL) } - let requestBody = RepoPutRecord( + let requestBody = ComAtprotoLexicon.Repository.PutRecordRequestBody( repositoryDID: repositoryDID, collection: collection, recordKey: recordKey, @@ -59,7 +66,7 @@ extension ATProtoKit { authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, withEncodingBody: requestBody, - decodeTo: StrongReference.self) + decodeTo: ComAtprotoLexicon.Repository.StrongReference.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/CoreAPI/QueryLabels.swift b/Sources/ATProtoKit/Networking/CoreAPI/QueryLabels.swift index a46bc61e3d..844bba0be7 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/QueryLabels.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/QueryLabels.swift @@ -32,11 +32,16 @@ extension ATProtoKit { /// - pdsURL: The URL of the Personal Data Server (PDS). Defaults to `nil`. /// - shouldAuthenticate: Indicates whether the method will use the access token when /// sending the request. Defaults to `false`. - /// - Returns: A `Result`, containing either a ``LabelQueryLabelsOutput`` + /// - Returns: A `Result`, containing either a ``ComAtprotoLexicon/Label/QueryLabelsOutput`` /// if successful, or an `Error` if not. - public func queryLabels(uriPatterns: [String], sources: [String]?, limit: Int? = 50, cursor: String? = nil, - pdsURL: String? = nil, - shouldAuthenticate: Bool = false) async throws -> Result { + public func queryLabels( + uriPatterns: [String], + sources: [String]?, + limit: Int? = 50, + cursor: String? = nil, + pdsURL: String? = nil, + shouldAuthenticate: Bool = false + ) async throws -> Result { let authorizationValue = prepareAuthorizationValue( methodPDSURL: pdsURL, shouldAuthenticate: shouldAuthenticate, @@ -79,7 +84,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: authorizationValue) let response = try await APIClientService.sendRequest(request, - decodeTo: LabelQueryLabelsOutput.self) + decodeTo: ComAtprotoLexicon.Label.QueryLabelsOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/CoreAPI/RequestCrawl.swift b/Sources/ATProtoKit/Networking/CoreAPI/RequestCrawl.swift index b4be90bc7a..86abdedf85 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/RequestCrawl.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/RequestCrawl.swift @@ -23,8 +23,10 @@ extension ATProtoKit { /// - Parameters: /// - crawlingHostname: The hostname that the crawling service resides in. Optional. /// - pdsURL: The URL of the Personal Data Server (PDS). Defaults to `nil`. - public func requestCrawl(in crawlingHostname: String? = nil, - pdsURL: String? = nil) async throws { + public func requestCrawl( + in crawlingHostname: String? = nil, + pdsURL: String? = nil + ) async throws { guard let sessionURL = pdsURL != nil ? pdsURL : session?.pdsURL, let requestURL = URL(string: "\(sessionURL)/xrpc/com.atproto.sync.notifyOfUpdate") else { throw ATRequestPrepareError.invalidRequestURL @@ -36,7 +38,7 @@ extension ATProtoKit { throw ATRequestPrepareError.invalidHostnameURL } - let requestBody = SyncCrawler( + let requestBody = ComAtprotoLexicon.Sync.Crawler( crawlingHostname: finalhostnameURL ) diff --git a/Sources/ATProtoKit/Networking/CoreAPI/RequestEmailUpdate.swift b/Sources/ATProtoKit/Networking/CoreAPI/RequestEmailUpdate.swift index 1b36082b4e..60690541d1 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/RequestEmailUpdate.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/RequestEmailUpdate.swift @@ -18,9 +18,9 @@ extension ATProtoKit { /// /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/requestEmailUpdate.json /// - /// - Returns: A `Result`, containing either a ``RequestEmailUpdateOutput`` + /// - Returns: A `Result`, containing either a ``ComAtprotoLexicon/Server/RequestEmailUpdateOutput`` /// if successful, or an `Error` if not. - public func requestEmailUpdate() async throws -> Result { + public func requestEmailUpdate() async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -38,7 +38,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, - decodeTo: RequestEmailUpdateOutput.self) + decodeTo: ComAtprotoLexicon.Server.RequestEmailUpdateOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/CoreAPI/RequestPasswordReset.swift b/Sources/ATProtoKit/Networking/CoreAPI/RequestPasswordReset.swift index 5c9d00740a..9a8c6c9461 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/RequestPasswordReset.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/RequestPasswordReset.swift @@ -23,14 +23,16 @@ extension ATProtoKit { /// - Parameters: /// - email: The email associated with the user's account. /// - pdsURL: The URL of the Personal Data Server (PDS). Defaults to `nil`. - public func requestPasswordReset(_ email: String, - pdsURL: String? = nil) async throws { + public func requestPasswordReset( + _ email: String, + pdsURL: String? = nil + ) async throws { guard let sessionURL = pdsURL != nil ? pdsURL : session?.pdsURL, let requestURL = URL(string: "\(sessionURL)/xrpc/com.atproto.server.requestPasswordReset") else { throw ATRequestPrepareError.invalidRequestURL } - let requestBody = ServerRequestPasswordReset( + let requestBody = ComAtprotoLexicon.Server.RequestPasswordResetRequestBody( email: email ) diff --git a/Sources/ATProtoKit/Networking/CoreAPI/RequestPhoneVerification.swift b/Sources/ATProtoKit/Networking/CoreAPI/RequestPhoneVerification.swift index b8cd94a439..a94a8fd85c 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/RequestPhoneVerification.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/RequestPhoneVerification.swift @@ -31,7 +31,7 @@ extension ATProtoKit { throw ATRequestPrepareError.invalidRequestURL } - let requestBody = TempRequestPhoneVerification( + let requestBody = ComAtprotoLexicon.Temp.RequestPhoneVerificationRequestBody( phoneNumber: phoneNumber ) diff --git a/Sources/ATProtoKit/Networking/CoreAPI/ReserveSigningKey.swift b/Sources/ATProtoKit/Networking/CoreAPI/ReserveSigningKey.swift index b58d56f9b2..6ad2464b1a 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/ReserveSigningKey.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/ReserveSigningKey.swift @@ -23,15 +23,18 @@ extension ATProtoKit { /// - Parameters: /// - repositoryDID: The decentalized identifier (DID) of the repository. /// - pdsURL: The URL of the Personal Data Server (PDS). Defaults to `nil`. - /// - Returns: A `Result`, containing either a ``ServerReserveSigningKeyOutput`` + /// - Returns: A `Result`, containing either a ``ComAtprotoLexicon/Server/ReserveSigningKeyOutput`` /// if successful, or an `Error` if not. - public func reserveSigningKey(_ repositoryDID: String, pdsURL: String? = nil) async throws -> Result { + public func reserveSigningKey( + _ repositoryDID: String, + pdsURL: String? = nil + ) async throws -> Result { guard let sessionURL = pdsURL != nil ? pdsURL : determinePDSURL(customPDSURL: pdsURL), let requestURL = URL(string: "\(sessionURL)/xrpc/com.atproto.server.reserveSigningKey") else { return .failure(ATRequestPrepareError.invalidRequestURL) } - let requestBody = ServerReserveSigningKey( + let requestBody = ComAtprotoLexicon.Server.ReserveSigningKeyRequestBody( repositoryDID: repositoryDID ) @@ -43,7 +46,7 @@ extension ATProtoKit { authorizationValue: nil) let response = try await APIClientService.sendRequest(request, withEncodingBody: requestBody, - decodeTo: ServerReserveSigningKeyOutput.self) + decodeTo: ComAtprotoLexicon.Server.ReserveSigningKeyOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/CoreAPI/ResetPassword.swift b/Sources/ATProtoKit/Networking/CoreAPI/ResetPassword.swift index ebe13710e8..394d3ee62a 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/ResetPassword.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/ResetPassword.swift @@ -24,14 +24,17 @@ extension ATProtoKit { /// - token: The token used to reset the password. /// - newPassword: The new password for the user's account. /// - pdsURL: The URL of the Personal Data Server (PDS). Defaults to `nil`. - public func resetPassword(using token: String, newPassword: String, - pdsURL: String? = nil) async throws { + public func resetPassword( + using token: String, + newPassword: String, + pdsURL: String? = nil + ) async throws { guard let sessionURL = pdsURL != nil ? pdsURL : session?.pdsURL, let requestURL = URL(string: "\(sessionURL)/xrpc/com.atproto.server.resetPassword") else { throw ATRequestPrepareError.invalidRequestURL } - let requestBody = ServerResetPassword( + let requestBody = ComAtprotoLexicon.Server.ResetPasswordRequestBody( token: token, newPassword: newPassword ) diff --git a/Sources/ATProtoKit/Networking/CoreAPI/ResolveHandle.swift b/Sources/ATProtoKit/Networking/CoreAPI/ResolveHandle.swift index da505a6a5d..c61914c05d 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/ResolveHandle.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/ResolveHandle.swift @@ -22,9 +22,12 @@ extension ATProtoKit { /// - Parameters: /// - handle: The handle to resolve into a decentralized identifier (DID). /// - pdsURL: The URL of the Personal Data Server (PDS). Defaults to `nil`. - /// - Returns: A `Result`, containing either a ``ResolveHandleOutput`` + /// - Returns: A `Result`, containing either a ``ComAtprotoLexicon/Identity/ResolveHandleOutput`` /// if successful, or an `Error` if not. - public func resolveHandle(from handle: String, pdsURL: String? = nil) async throws -> Result { + public func resolveHandle( + from handle: String, + pdsURL: String? = nil + ) async throws -> Result { guard let sessionURL = pdsURL != nil ? pdsURL : session?.pdsURL, let requestURL = URL(string: "\(sessionURL)/xrpc/com.atproto.identity.resolveHandle") else { return .failure(ATRequestPrepareError.invalidRequestURL) @@ -48,7 +51,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: nil) let response = try await APIClientService.sendRequest(request, - decodeTo: ResolveHandleOutput.self) + decodeTo: ComAtprotoLexicon.Identity.ResolveHandleOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/CoreAPI/RevokeAppPassword.swift b/Sources/ATProtoKit/Networking/CoreAPI/RevokeAppPassword.swift index d6cf1d5cfa..1dca71255b 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/RevokeAppPassword.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/RevokeAppPassword.swift @@ -30,7 +30,7 @@ extension ATProtoKit { throw ATRequestPrepareError.invalidRequestURL } - let requestBody = ServerRevokeAppPassword( + let requestBody = ComAtprotoLexicon.Server.RevokeAppPasswordRequestBody( appPasswordName: appPasswordName ) diff --git a/Sources/ATProtoKit/Networking/CoreAPI/SignPLCOperation.swift b/Sources/ATProtoKit/Networking/CoreAPI/SignPLCOperation.swift index 62db477cf4..5d3f4ae704 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/SignPLCOperation.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/SignPLCOperation.swift @@ -27,10 +27,15 @@ extension ATProtoKit { /// - verificationMethods: A verification method recommeneded to be added in the /// DID document. Optional. /// - service: The service endpoint recommended in the DID document. Optional. - /// - Returns: A `Result`, containing either an ``IdentitySignPLCOperationOutput`` + /// - Returns: A `Result`, containing either an ``ComAtprotoLexicon/Identity/SignPLCOperationOutput`` /// if successful, ot an `Error` if not. - public func signPLCOperation(token: String, rotationKeys: [String]?, alsoKnownAs: [String]?, verificationMethods: VerificationMethod?, - service: ATService?) async throws -> Result { + public func signPLCOperation( + token: String, + rotationKeys: [String]?, + alsoKnownAs: [String]?, + verificationMethods: VerificationMethod?, + service: ATService? + ) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -41,7 +46,7 @@ extension ATProtoKit { return .failure(ATRequestPrepareError.invalidRequestURL) } - let requestBody = IdentitySignPLCOperation( + let requestBody = ComAtprotoLexicon.Identity.SignPLCOperationRequestBody( token: token, rotationKeys: rotationKeys, alsoKnownAs: alsoKnownAs, @@ -57,7 +62,7 @@ extension ATProtoKit { authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, withEncodingBody: requestBody, - decodeTo: IdentitySignPLCOperationOutput.self) + decodeTo: ComAtprotoLexicon.Identity.SignPLCOperationOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/CoreAPI/SubmitPLCOperation.swift b/Sources/ATProtoKit/Networking/CoreAPI/SubmitPLCOperation.swift index b6ee4ada70..00a9b0dd5e 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/SubmitPLCOperation.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/SubmitPLCOperation.swift @@ -20,15 +20,13 @@ extension ATProtoKit { /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/identity/submitPlcOperation.json /// /// - Parameter operation: - /// - Returns: A `Result`, containing either an ``IdentitySignPLCOperationOutput`` - /// if successful, or an `Error` if not. - public func submitPLCOperation(_ operation: UnknownType) async throws -> Result { + public func submitPLCOperation(_ operation: UnknownType) async throws { guard let sessionURL = session?.pdsURL, let requestURL = URL(string: "\(sessionURL)/xrpc/com.atproto.identity.identitySubmitPLCOperation") else { - return .failure(ATRequestPrepareError.invalidRequestURL) + throw ATRequestPrepareError.invalidRequestURL } - let requestBody = IdentitySignPLCOperationOutput( + let requestBody = ComAtprotoLexicon.Identity.SubmitPLCOperationRequestBody( operation: operation ) @@ -38,13 +36,10 @@ extension ATProtoKit { acceptValue: "application/json", contentTypeValue: nil, authorizationValue: nil) - let response = try await APIClientService.sendRequest(request, - withEncodingBody: requestBody, - decodeTo: IdentitySignPLCOperation.self) - - return .success(response) + try await APIClientService.sendRequest(request, + withEncodingBody: requestBody) } catch { - return .failure(error) + throw error } } } diff --git a/Sources/ATProtoKit/Networking/CoreAPI/UpdateEmail.swift b/Sources/ATProtoKit/Networking/CoreAPI/UpdateEmail.swift index a55189d138..98b77bd6ad 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/UpdateEmail.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/UpdateEmail.swift @@ -26,7 +26,11 @@ extension ATProtoKit { /// - isEmailAuthenticationFactorEnabled: Indicates whether /// Two-Factor Authentication (via email) is enabled. Optional. /// - token: The token used to confirm the change. Optional. - public func updateEmail(_ email: String, isEmailAuthenticationFactorEnabled: Bool? = nil, token: String? = nil) async throws { + public func updateEmail( + _ email: String, + isEmailAuthenticationFactorEnabled: Bool? = nil, + token: String? = nil + ) async throws { guard session != nil, let accessToken = session?.accessToken else { throw ATRequestPrepareError.missingActiveSession @@ -36,7 +40,7 @@ extension ATProtoKit { throw ATRequestPrepareError.invalidRequestURL } - let requestBody = ServerUpdateEmail( + let requestBody = ComAtprotoLexicon.Server.UpdateEmailRequestBody( email: email, isEmailAuthenticationFactorEnabled: isEmailAuthenticationFactorEnabled, token: token diff --git a/Sources/ATProtoKit/Networking/CoreAPI/UpdateHandle.swift b/Sources/ATProtoKit/Networking/CoreAPI/UpdateHandle.swift index f80ad3a689..07c36f3d0a 100644 --- a/Sources/ATProtoKit/Networking/CoreAPI/UpdateHandle.swift +++ b/Sources/ATProtoKit/Networking/CoreAPI/UpdateHandle.swift @@ -20,7 +20,7 @@ extension ATProtoKit { /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/identity/updateHandle.json /// /// - Parameter handle: The object which conains the user's new handle. - public func updateHandle(_ handle: UpdateHandleQuery) async throws { + public func updateHandle(_ handle: String) async throws { guard session != nil, let accessToken = session?.accessToken else { throw ATRequestPrepareError.missingActiveSession @@ -31,13 +31,17 @@ extension ATProtoKit { throw ATRequestPrepareError.invalidRequestURL } + let requestBody = ComAtprotoLexicon.Identity.UpdateHandleRequestBody( + handle: handle + ) + do { let request = APIClientService.createRequest(forRequest: requestURL, andMethod: .post, authorizationValue: "Bearer \(accessToken)") try await APIClientService.sendRequest(request, - withEncodingBody: handle) + withEncodingBody: requestBody) } catch { throw error } diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/CreateLike.swift b/Sources/ATProtoKit/Networking/PlatformAPI/CreateLike.swift index 192ac6a5a6..2d6c012a36 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/CreateLike.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/CreateLike.swift @@ -18,16 +18,14 @@ extension ATProtoKit { /// Defaults to `true`. /// - Returns: A `Result`, containing either a ``StrongReference`` /// if it's successful, or an `Error` if it's not. - public func createLikeRecord(_ strongReference: StrongReference, createdAt: Date = Date.now, - shouldValidate: Bool? = true) async throws -> Result { -// guard let sessionURL = session.pdsURL, -// let requestURL = URL(string: "\(sessionURL)/xrpc/com.atproto.repo.createRecord") else { -// throw NSError(domain: "", code: -1, userInfo: [NSLocalizedDescriptionKey: "Invalid URL"]) -// } - + public func createLikeRecord( + _ strongReference: ComAtprotoLexicon.Repository.StrongReference, + createdAt: Date = Date.now, + shouldValidate: Bool? = true + ) async throws -> Result { guard let session else { return .failure(ATRequestPrepareError.missingActiveSession) } - let likeRecord = FeedLike( + let likeRecord = AppBskyLexicon.Feed.LikeRecord( subject: strongReference, createdAt: createdAt ) @@ -49,6 +47,6 @@ extension ATProtoKit { /// - Warning: The value must not change. let collection: String = "app.bsky.feed.like" /// The like record itself. - let record: FeedLike + let record: AppBskyLexicon.Feed.LikeRecord } } diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/CreatePost.swift b/Sources/ATProtoKit/Networking/PlatformAPI/CreatePost.swift index 76e854d2e9..6ccd7f0c49 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/CreatePost.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/CreatePost.swift @@ -26,9 +26,18 @@ extension ATProtoKit { /// Defaults to `true`. /// - swapCommit: Swaps out an operation based on the CID. Optional. /// - Returns: A strong reference, which contains the newly-created record's URI and CID hash. - public func createPostRecord(text: String, locales: [Locale] = [], replyTo: String? = nil, embed: EmbedIdentifier? = nil, - labels: FeedLabelUnion? = nil, tags: [String]? = nil, creationDate: Date = Date.now, recordKey: String? = nil, - shouldValidate: Bool? = true, swapCommit: String? = nil) async -> Result { + public func createPostRecord( + text: String, + locales: [Locale] = [], + replyTo: String? = nil, + embed: EmbedIdentifier? = nil, + labels: ATUnion.PostSelfLabelsUnion? = nil, + tags: [String]? = nil, + creationDate: Date = Date.now, + recordKey: String? = nil, + shouldValidate: Bool? = true, + swapCommit: String? = nil + ) async -> Result { guard let session else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -38,7 +47,7 @@ extension ATProtoKit { return .failure(ATRequestPrepareError.invalidPDS) } // Replies - var resolvedReplyTo: ReplyReference? = nil + var resolvedReplyTo: AppBskyLexicon.Feed.PostRecord.ReplyReference? = nil if let replyURI = replyTo { do { resolvedReplyTo = try await ATProtoTools().resolveReplyReferences(parentURI: replyURI) @@ -51,7 +60,7 @@ extension ATProtoKit { let localeIdentifiers = locales.isEmpty ? nil : locales.map { $0.identifier } // Embed - var resolvedEmbed: EmbedUnion? = nil + var resolvedEmbed: ATUnion.PostEmbedUnion? = nil if let embedUnion = embed { do { switch embedUnion { @@ -71,7 +80,7 @@ extension ATProtoKit { } // Compiling all parts of the post into one. - let postRecord = FeedPost( + let postRecord = AppBskyLexicon.Feed.PostRecord( text: text, facets: await ATFacetParser.parseFacets(from: text, pdsURL: session.accessToken), reply: resolvedReplyTo, @@ -101,8 +110,9 @@ extension ATProtoKit { /// use in a record. /// /// - Important: Each image can only be 1 MB in size. - public func uploadImages(_ images: [ImageQuery], pdsURL: String = "https://bsky.social", accessToken: String) async throws -> EmbedUnion { - var embedImages = [EmbedImage]() + public func uploadImages(_ images: [ComAtprotoLexicon.Repository.ImageQuery], pdsURL: String = "https://bsky.social", + accessToken: String) async throws -> ATUnion.PostEmbedUnion { + var embedImages = [AppBskyLexicon.Embed.ImagesDefinition.Image]() for image in images { // Check if the image is too large. @@ -114,11 +124,11 @@ extension ATProtoKit { let blobReference = try await APIClientService.uploadBlob(pdsURL: pdsURL, accessToken: accessToken, filename: image.fileName, imageData: image.imageData) - let embedImage = EmbedImage(image: blobReference.blob, altText: image.altText ?? "", aspectRatio: nil) + let embedImage = AppBskyLexicon.Embed.ImagesDefinition.Image(image: blobReference.blob, altText: image.altText ?? "", aspectRatio: nil) embedImages.append(embedImage) } - return .images(EmbedImages(images: embedImages)) + return .images(AppBskyLexicon.Embed.ImagesDefinition(images: embedImages)) } /// Scraps the website for the required information in order to attach to a record's embed at a @@ -126,7 +136,7 @@ extension ATProtoKit { /// - Parameter url: The URL of the website /// - Returns: An ``EmbedUnion`` which contains an ``EmbedExternal`` for use /// in a record. - public func buildExternalEmbed(from url: URL) async throws -> EmbedUnion? { + public func buildExternalEmbed(from url: URL) async throws -> ATUnion.PostEmbedUnion? { // Temporary comment until it's time to work on this part of the library. // let external = EmbedExternal(external: External(embedURI: "", title: "", description: "", thumbnailImage: UploadBlobOutput(type: <#T##String?#>, reference: <#T##BlobReference#>, mimeType: <#T##String#>, size: <#T##Int#>))) @@ -139,10 +149,10 @@ extension ATProtoKit { /// the `cidHash` (CID) . /// - Returns: A strong reference, which contains a record's `recordURI` (URI) and the /// `cidHash` (CID) . - public func addQuotePostToEmbed(_ strongReference: StrongReference) async throws -> EmbedUnion { + public func addQuotePostToEmbed(_ strongReference: ComAtprotoLexicon.Repository.StrongReference) async throws -> ATUnion.PostEmbedUnion { let record = try await ATProtoTools().fetchRecordForURI(strongReference.recordURI) - let reference = StrongReference(recordURI: record.recordURI, cidHash: record.recordCID) - let embedRecord = EmbedRecord(record: reference) + let reference = ComAtprotoLexicon.Repository.StrongReference(recordURI: record.recordURI, cidHash: record.recordCID) + let embedRecord = AppBskyLexicon.Embed.RecordDefinition(record: reference) return .record(embedRecord) } @@ -165,7 +175,7 @@ extension ATProtoKit { /// Represents a set of images to be embedded in the post. /// - Parameter images: An array of `ImageQuery` objects, each containing the image data, /// metadata, and filenames of the image. - case images(images: [ImageQuery]) + case images(images: [ComAtprotoLexicon.Repository.ImageQuery]) /// Represents an external link to be embedded in the post. /// - Parameter url: A `URL` pointing to the external content. @@ -174,12 +184,12 @@ extension ATProtoKit { /// Represents another post record that is to be embedded within the current post. /// - Parameter strongReference: A `StrongReference` to the post record to be embedded, /// which contains a record's `recordURI` (URI) and the `cidHash` (CID) . - case record(strongReference: StrongReference) + case record(strongReference: ComAtprotoLexicon.Repository.StrongReference) /// Represents a post record accompanied by media, to be embedded within the current post. /// - Parameters: /// - record: An `EmbedRecord`, representing the post to be embedded. /// - media: A `MediaUnion`, representing the media content associated with the post. - case recordWithMedia(record: EmbedRecord, media: MediaUnion) + case recordWithMedia(record: AppBskyLexicon.Embed.RecordDefinition, media: ATUnion.RecordWithMediaUnion) } } diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/DeleteLike.swift b/Sources/ATProtoKit/Networking/PlatformAPI/DeleteLike.swift index 2c55a038c9..0e5f6a026d 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/DeleteLike.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/DeleteLike.swift @@ -24,12 +24,12 @@ extension ATProtoKit { throw ATRequestPrepareError.invalidRequestURL } - var likeRecord: RecordQuery? = nil + var likeRecord: ATProtoTools.RecordQuery? = nil try await resolveRecordIdentifierToQuery(record, sessionURL, &likeRecord) let requestBody = likeRecord - guard let repositoryDID = requestBody?.repo, + guard let repositoryDID = requestBody?.repository, let likeCollection = requestBody?.collection, let likeRecordKey = requestBody?.recordKey else { throw ATRequestPrepareError.invalidRecord @@ -39,15 +39,16 @@ extension ATProtoKit { } fileprivate func resolveRecordIdentifierToQuery(_ record: RecordIdentifier, _ sessionURL: String, - _ likeRecord: inout RecordQuery?) async throws { + _ likeRecord: inout ATProtoTools.RecordQuery?) async throws { switch record { case .recordQuery(let recordQuery): // Perform the fetch and validation based on recordQuery. - let output = try await ATProtoKit().getRepositoryRecord(from: recordQuery, pdsURL: sessionURL) + let output = try await self.getRepositoryRecord(from: recordQuery.repository, collection: recordQuery.collection, + recordKey: recordQuery.recordKey, recordCID: recordQuery.recordCID, pdsURL: sessionURL) switch output { case .success(let result): - let recordURI = "at://\(recordQuery.repo)/\(recordQuery.collection)/\(recordQuery.recordKey)" + let recordURI = "at://\(recordQuery.repository)/\(recordQuery.collection)/\(recordQuery.recordKey)" guard result.recordURI == recordURI else { throw ATRequestPrepareError.invalidRecord } @@ -60,7 +61,8 @@ extension ATProtoKit { case .recordURI(let recordURI): // Perform the fetch and validation based on the parsed URI. let parsedURI = try ATProtoTools().parseURI(recordURI) - let output = try await ATProtoKit().getRepositoryRecord(from: parsedURI, pdsURL: sessionURL) + let output = try await self.getRepositoryRecord(from: parsedURI.repository, collection: parsedURI.collection, + recordKey: parsedURI.recordKey, recordCID: parsedURI.recordCID, pdsURL: sessionURL) switch output { case .success(let result): @@ -83,7 +85,7 @@ extension ATProtoKit { public enum RecordIdentifier { /// The record object itself. /// - Parameter recordQuery: the record object. - case recordQuery(recordQuery: RecordQuery) + case recordQuery(recordQuery: ATProtoTools.RecordQuery) /// The URI of the record. case recordURI(atURI: String) } diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/DescribeFeedGenerator.swift b/Sources/ATProtoKit/Networking/PlatformAPI/DescribeFeedGenerator.swift index 00b09b65e7..a847d58f3a 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/DescribeFeedGenerator.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/DescribeFeedGenerator.swift @@ -19,9 +19,9 @@ extension ATProtoKit { /// /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/describeFeedGenerator.json /// - /// - Returns: A `Result`, containing either a ``FeedDescribeFeedGeneratorOutput`` + /// - Returns: A `Result`, containing either a ``AppBskyLexicon/Feed/DescribeFeedGeneratorOutput`` /// if successful, or an `Error` if not. - public func describeFeedGenerator(pdsURL: String? = nil) async throws -> Result { + public func describeFeedGenerator(pdsURL: String? = nil) async throws -> Result { guard let sessionURL = pdsURL != nil ? pdsURL : session?.pdsURL, let requestURL = URL(string: "\(sessionURL)/app.bsky.feed.describeFeedGenerator") else { return .failure(ATRequestPrepareError.invalidRequestURL) @@ -34,7 +34,7 @@ extension ATProtoKit { contentTypeValue: "application/json", authorizationValue: nil) let response = try await APIClientService.sendRequest(request, - decodeTo: FeedDescribeFeedGeneratorOutput.self) + decodeTo: AppBskyLexicon.Feed.DescribeFeedGeneratorOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/GetActorFeeds.swift b/Sources/ATProtoKit/Networking/PlatformAPI/GetActorFeeds.swift index e03d54eea9..1c45c7c0f2 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/GetActorFeeds.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/GetActorFeeds.swift @@ -23,9 +23,13 @@ extension ATProtoKit { /// - limit: The number of items that can be in the list. Optional. Defaults to `50`. /// - cursor: The mark used to indicate the starting point for the next set of /// result. Optional. - /// - Returns: A `Result`, containing either a ``FeedGetActorFeedsOutput`` + /// - Returns: A `Result`, containing either a ``AppBskyLexicon/Feed/GetActorFeedsOutput`` /// if successful, or an `Error` if not. - public func getActorFeeds(by actorDID: String, limit: Int? = 50, cursor: String? = nil) async throws -> Result { + public func getActorFeeds( + by actorDID: String, + limit: Int? = 50, + cursor: String? = nil + ) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -63,7 +67,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, - decodeTo: FeedGetActorFeedsOutput.self) + decodeTo: AppBskyLexicon.Feed.GetActorFeedsOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/GetActorLikes.swift b/Sources/ATProtoKit/Networking/PlatformAPI/GetActorLikes.swift index 880562314e..087c13c776 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/GetActorLikes.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/GetActorLikes.swift @@ -34,9 +34,13 @@ extension ATProtoKit { /// - limit: The number of items the list will hold. Optional. Defaults to `50`. /// - cursor: The mark used to indicate the starting point for the next set of /// result. Optional. - /// - Returns: A `Result`, containing either a ``FeedGetActorLikesOutput`` + /// - Returns: A `Result`, containing either a ``AppBskyLexicon/Feed/GetActorLikesOutput`` /// if successful, or an `Error` if not. - public func getActorLikes(by actorDID: String, limit: Int? = 50, cursor: String? = nil) async throws -> Result { + public func getActorLikes( + by actorDID: String, + limit: Int? = 50, + cursor: String? = nil + ) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -74,7 +78,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, - decodeTo: FeedGetActorLikesOutput.self) + decodeTo: AppBskyLexicon.Feed.GetActorLikesOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/GetAuthorFeed.swift b/Sources/ATProtoKit/Networking/PlatformAPI/GetAuthorFeed.swift index 8916d392bd..d2f212a800 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/GetAuthorFeed.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/GetAuthorFeed.swift @@ -29,10 +29,14 @@ extension ATProtoKit { /// - limit: The number of items the list will hold. Optional. Defaults to `50`. /// - cursor: The mark used to indicate the starting point for the next set of /// result. Optional. - /// - Returns: A `Result`, containing either a ``FeedGetAuthorFeedOutput`` + /// - Returns: A `Result`, containing either a ``AppBskyLexicon/Feed/GetAuthorFeedOutput`` /// if successful, or an `Error` if not. - public func getAuthorFeed(by actorDID: String, limit: Int? = 50, cursor: String? = nil, postFilter: - FeedGetAuthorFeedFilter? = .postsWithReplies) async throws -> Result { + public func getAuthorFeed( + by actorDID: String, + limit: Int? = 50, + cursor: String? = nil, + postFilter: AppBskyLexicon.Feed.GetAuthorFeed.Filter? = .postsWithReplies + ) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -74,7 +78,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, - decodeTo: FeedGetAuthorFeedOutput.self) + decodeTo: AppBskyLexicon.Feed.GetAuthorFeedOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/GetFeed.swift b/Sources/ATProtoKit/Networking/PlatformAPI/GetFeed.swift index de47a5d181..ca99b18062 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/GetFeed.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/GetFeed.swift @@ -23,9 +23,13 @@ extension ATProtoKit { /// - limit: The number of items the list will hold. Optional. Defaults to `50`. /// - cursor: The mark used to indicate the starting point for the next set of /// result. Optional. - /// - Returns: A `Result`, containing either a ``FeedGetFeedOutput`` + /// - Returns: A `Result`, containing either a ``AppBskyLexicon/Feed/GetFeedOutput`` /// if successful, or an `Error` if not. - public func getFeed(_ feedURI: String, limit: Int? = 50, cursor: String? = nil) async throws -> Result { + public func getFeed( + _ feedURI: String, + limit: Int? = 50, + cursor: String? = nil + ) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -63,7 +67,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, - decodeTo: FeedGetFeedOutput.self) + decodeTo: AppBskyLexicon.Feed.GetFeedOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/GetFeedGenerator.swift b/Sources/ATProtoKit/Networking/PlatformAPI/GetFeedGenerator.swift index 8db9807be0..25dfc84078 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/GetFeedGenerator.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/GetFeedGenerator.swift @@ -22,9 +22,9 @@ extension ATProtoKit { /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/getFeedGenerator.json /// /// - Parameter feedURI: The URI of the feed generator. - /// - Returns: A `Result`, containing either a ``FeedGetFeedGeneratorOutput`` + /// - Returns: A `Result`, containing either a ``AppBskyLexicon/Feed/GetFeedGeneratorOutput`` /// if successful, or an `Error` if not. - public func getFeedGenerator(_ feedURI: String) async throws -> Result { + public func getFeedGenerator(_ feedURI: String) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -53,7 +53,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, - decodeTo: FeedGetFeedGeneratorOutput.self) + decodeTo: AppBskyLexicon.Feed.GetFeedGeneratorOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/GetFeedGenerators.swift b/Sources/ATProtoKit/Networking/PlatformAPI/GetFeedGenerators.swift index 6e20ab2486..b89aa92fcc 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/GetFeedGenerators.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/GetFeedGenerators.swift @@ -22,9 +22,9 @@ extension ATProtoKit { /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/getFeedGenerators.json /// /// - Parameter feedURIs: An array of URIs for feed generators. - /// - Returns: A `Result`, containing either a ``FeedGetFeedGeneratorOutput`` + /// - Returns: A `Result`, containing either a ``AppBskyLexicon/Feed/GetFeedGeneratorsOutput`` /// if successful, or an `Error` if not. - public func getFeedGenerators(_ feedURIs: [String]) async throws -> Result { + public func getFeedGenerators(_ feedURIs: [String]) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -53,7 +53,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, - decodeTo: FeedGetFeedGeneratorsOutput.self) + decodeTo: AppBskyLexicon.Feed.GetFeedGeneratorsOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/GetFeedSkeleton.swift b/Sources/ATProtoKit/Networking/PlatformAPI/GetFeedSkeleton.swift index e397fba5ae..37b4c80d8b 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/GetFeedSkeleton.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/GetFeedSkeleton.swift @@ -29,10 +29,14 @@ extension ATProtoKit { /// result. Optional. /// - accessToken: The token used to authenticate the user. Optional. /// - pdsURL: The URL of the Personal Data Server (PDS). - /// - Returns: A `Result`, containing either a ``FeedGetFeedSkeletonOutput`` + /// - Returns: A `Result`, containing either a ``AppBskyLexicon/Feed/GetFeedSkeletonOutput`` /// if successful, or an `Error` if not. - public static func getFeedSkeleton(_ feedURI: String, limit: Int? = 50, cursor: String? = nil, - pdsURL: String) async throws -> Result { + public static func getFeedSkeleton( + _ feedURI: String, + limit: Int? = 50, + cursor: String? = nil, + pdsURL: String + ) async throws -> Result { guard let requestURL = URL(string: "\(pdsURL)/xrpc/app.bsky.feed.getFeedSkeleton") else { return .failure(ATRequestPrepareError.invalidRequestURL) } @@ -40,6 +44,7 @@ extension ATProtoKit { if pdsURL == "https://bsky.social" { return .failure(ATRequestPrepareError.invalidPDS) } + var queryItems = [(String, String)]() queryItems.append(("feed", feedURI)) @@ -58,7 +63,7 @@ extension ATProtoKit { contentTypeValue: "application/json", authorizationValue: nil) let response = try await APIClientService.sendRequest(request, - decodeTo: FeedGetFeedSkeletonOutput.self) + decodeTo: AppBskyLexicon.Feed.GetFeedSkeletonOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/GetFollowers.swift b/Sources/ATProtoKit/Networking/PlatformAPI/GetFollowers.swift index 7eb3e8430e..71e1beec9e 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/GetFollowers.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/GetFollowers.swift @@ -23,9 +23,13 @@ extension ATProtoKit { /// their followers. /// - limit: The number of items the list will hold. Optional. Defaults to `50`. /// - cursor: The mark used to indicate the starting point for the next set of result. Optional. - /// - Returns: A `Result`, containing either a ``GraphGetFollowersOutput`` + /// - Returns: A `Result`, containing either a ``AppBskyLexicon/Graph/GetFollowersOutput`` /// if successful, or an `Error` if not. - public func getFollowers(by actorDID: String, limit: Int? = 50, cursor: String? = nil) async throws -> Result { + public func getFollowers( + by actorDID: String, + limit: Int? = 50, + cursor: String? = nil + ) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -63,7 +67,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, - decodeTo: GraphGetFollowersOutput.self) + decodeTo: AppBskyLexicon.Graph.GetFollowersOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/GetFollows.swift b/Sources/ATProtoKit/Networking/PlatformAPI/GetFollows.swift index 1483a55f42..22e4454f0c 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/GetFollows.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/GetFollows.swift @@ -24,9 +24,13 @@ extension ATProtoKit { /// - limit: The number of items the list will hold. Optional. Defaults to `50`. /// - cursor: The mark used to indicate the starting point for the next set of /// result. Optional. - /// - Returns: A `Result`, containing either a ``GraphFollowsOutput`` + /// - Returns: A `Result`, containing either a ``AppBskyLexicon/Graph/GetFollowsOutput`` /// if successful, or an `Error` if not. - public func getFollows(from actorDID: String, limit: Int? = 50, cursor: String? = nil) async throws -> Result { + public func getFollows( + from actorDID: String, + limit: Int? = 50, + cursor: String? = nil + ) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -64,7 +68,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, - decodeTo: GraphFollowsOutput.self) + decodeTo: AppBskyLexicon.Graph.GetFollowsOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/GetGraphBlocks.swift b/Sources/ATProtoKit/Networking/PlatformAPI/GetGraphBlocks.swift index b43c013712..8c82f2d473 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/GetGraphBlocks.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/GetGraphBlocks.swift @@ -22,9 +22,12 @@ extension ATProtoKit { /// - limit: The number of items the list will hold. Optional. Defaults to `50`. /// - cursor: The mark used to indicate the starting point for the next set of /// result. Optional. - /// - Returns: A `Result`, containing either a ``GraphGetBlocksOutput`` + /// - Returns: A `Result`, containing either a ``AppBskyLexicon/Graph/GetBlocksOutput`` /// if successful, or an `Error` if not. - public func getGraphBlocks(limit: Int? = 50, cursor: String? = nil) async throws -> Result { + public func getGraphBlocks( + limit: Int? = 50, + cursor: String? = nil + ) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -60,7 +63,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, - decodeTo: GraphGetBlocksOutput.self) + decodeTo: AppBskyLexicon.Graph.GetBlocksOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/GetLabelerServices.swift b/Sources/ATProtoKit/Networking/PlatformAPI/GetLabelerServices.swift index 55d19e7cb8..0a463beb5d 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/GetLabelerServices.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/GetLabelerServices.swift @@ -22,10 +22,13 @@ extension ATProtoKit { /// - labelerDIDs: An array of decentralized identifiers (DIDs) of labeler services. /// - isDetailed: Indicates whether the information is detailed. Optional. /// - pdsURL: The URL of the Personal Data Server (PDS). Defaults to `nil`. - /// - Returns: A `Result`, containing either a ``LabelerGetServicesOutput`` + /// - Returns: A `Result`, containing either a ``AppBskyLexicon/Labeler/GetServicesOutput`` /// if successful, or an `Error` if not. - public func getLabelerServices(labelerDIDs: [String], isDetailed: Bool? = nil, - pdsURL: String? = nil) async throws -> Result { + public func getLabelerServices( + labelerDIDs: [String], + isDetailed: Bool? = nil, + pdsURL: String? = nil + ) async throws -> Result { guard let sessionURL = pdsURL != nil ? pdsURL : session?.pdsURL, let requestURL = URL(string: "\(sessionURL)/xrpc/app.bsky.labeler.getServices") else { return .failure(ATRequestPrepareError.invalidFormat) @@ -49,7 +52,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: nil) let response = try await APIClientService.sendRequest(request, decodeTo: - LabelerGetServicesOutput.self) + AppBskyLexicon.Labeler.GetServicesOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/GetLikes.swift b/Sources/ATProtoKit/Networking/PlatformAPI/GetLikes.swift index 9886bf98b9..b17b9afb23 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/GetLikes.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/GetLikes.swift @@ -24,10 +24,14 @@ extension ATProtoKit { /// - limit: The number of items that can be in the list. Optional. Defaults to `50`. /// - cursor: The mark used to indicate the starting point for the next set of /// result. Optional. - /// - Returns: A `Result`, containing either a ``FeedGetLikesOutput`` + /// - Returns: A `Result`, containing either a ``AppBskyLexicon/Feed/GetLikesOutput`` /// if successful, or an `Error` if not. - public func getLikes(from recordURI: String, recordCID: String? = nil, limit: Int? = 50, - cursor: String? = nil) async throws -> Result { + public func getLikes( + from recordURI: String, + recordCID: String? = nil, + limit: Int? = 50, + cursor: String? = nil + ) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -69,7 +73,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, - decodeTo: FeedGetLikesOutput.self) + decodeTo: AppBskyLexicon.Feed.GetLikesOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/GetList.swift b/Sources/ATProtoKit/Networking/PlatformAPI/GetList.swift index f05dc7e420..acf76d4b9d 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/GetList.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/GetList.swift @@ -23,9 +23,13 @@ extension ATProtoKit { /// - limit: The number of items that can be in the list. Optional. Defaults to `50`. /// - cursor: The mark used to indicate the starting point for the next set of /// result. Optional. - /// - Returns: A `Result`, containing either a ``GraphGetListOutput`` + /// - Returns: A `Result`, containing either a ``AppBskyLexicon/Graph/GetListOutput`` /// if successful, or an `Error` if not. - public func getList(from listURI: String, limit: Int? = 50, cursor: String? = nil) async throws -> Result { + public func getList( + from listURI: String, + limit: Int? = 50, + cursor: String? = nil + ) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -63,7 +67,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, - decodeTo: GraphGetListOutput.self) + decodeTo: AppBskyLexicon.Graph.GetListOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/GetListBlocks.swift b/Sources/ATProtoKit/Networking/PlatformAPI/GetListBlocks.swift index 236040e4de..a2699659c2 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/GetListBlocks.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/GetListBlocks.swift @@ -22,9 +22,12 @@ extension ATProtoKit { /// - limit: The number of items that can be in the list. Optional. Defaults to `50`. /// - cursor: The mark used to indicate the starting point for the next set of /// result. Optional. - /// - Returns: A `Result`, containing either a ``GraphGetBlocksOutput`` + /// - Returns: A `Result`, containing either a ``AppBskyLexicon/Graph/GetBlocksOutput`` /// if successful, or an `Error` if not. - public func getListBlocks(limit: Int? = 50, cursor: String? = nil) async throws -> Result { + public func getListBlocks( + limit: Int? = 50, + cursor: String? = nil + ) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -60,7 +63,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, - decodeTo: GraphGetBlocksOutput.self) + decodeTo: AppBskyLexicon.Graph.GetBlocksOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/GetListFeed.swift b/Sources/ATProtoKit/Networking/PlatformAPI/GetListFeed.swift index 796a793e66..ee8ea8724b 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/GetListFeed.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/GetListFeed.swift @@ -25,11 +25,15 @@ extension ATProtoKit { /// - cursor: The mark used to indicate the starting point for the next set of results. Optional. /// - accessToken: The access token of the user. Optional. /// - pdsURL: The URL of the Personal Data Server (PDS). Defaults to `nil`. - /// - Returns: A `Result`, containing either an ``FeedGetListFeedOutput`` + /// - Returns: A `Result`, containing either an ``AppBskyLexicon/Feed/GetListFeedOutput`` /// if succesful, or an `Error` if it's not. - public func getListFeed(from listURI: String, limit: Int? = 50, cursor: String? = nil, - accessToken: String? = nil, - pdsURL: String? = nil) async throws -> Result { + public func getListFeed( + from listURI: String, + limit: Int? = 50, + cursor: String? = nil, + accessToken: String? = nil, + pdsURL: String? = nil + ) async throws -> Result { guard let sessionURL = pdsURL != nil ? pdsURL : session?.pdsURL, let requestURL = URL(string: "\(sessionURL)/xrpc/app.bsky.feed.getListFeed") else { return .failure(ATRequestPrepareError.invalidRequestURL) @@ -62,7 +66,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: nil) let response = try await APIClientService.sendRequest(request, - decodeTo: FeedGetListFeedOutput.self) + decodeTo: AppBskyLexicon.Feed.GetListFeedOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/GetListMutes.swift b/Sources/ATProtoKit/Networking/PlatformAPI/GetListMutes.swift index cd848affdb..bc2981af3d 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/GetListMutes.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/GetListMutes.swift @@ -22,9 +22,12 @@ extension ATProtoKit { /// - limit: The number of items that can be in the list. Optional. Defaults to `50`. /// - cursor: The mark used to indicate the starting point for the next set of /// result. Optional. - /// - Returns: A `Result`, containing either a ``GraphGetListMutesOutput`` + /// - Returns: A `Result`, containing either a ``AppBskyLexicon/Graph/GetListMutesOutput`` /// if successful, or an `Error` if not. - public func getListMutes(limit: Int? = 50, cursor: String? = nil) async throws -> Result { + public func getListMutes( + limit: Int? = 50, + cursor: String? = nil + ) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -60,7 +63,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, - decodeTo: GraphGetListMutesOutput.self) + decodeTo: AppBskyLexicon.Graph.GetListMutesOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/GetLists.swift b/Sources/ATProtoKit/Networking/PlatformAPI/GetLists.swift index 5181a27282..5f26342fa5 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/GetLists.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/GetLists.swift @@ -23,9 +23,13 @@ extension ATProtoKit { /// - limit: The number of items that can be in the list. Optional. Defaults to `50`. /// - cursor: The mark used to indicate the starting point for the next set of /// result. Optional. - /// - Returns: A `Result`, containing either a ``GraphGetListsOutput`` + /// - Returns: A `Result`, containing either a ``AppBskyLexicon/Graph/GetListsOutput`` /// if successful, or an `Error` if not. - public func getLists(from actorDID: String, limit: Int? = 50, cursor: String? = nil) async throws -> Result { + public func getLists( + from actorDID: String, + limit: Int? = 50, + cursor: String? = nil + ) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -63,7 +67,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, - decodeTo: GraphGetListsOutput.self) + decodeTo: AppBskyLexicon.Graph.GetListsOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/GetMutes.swift b/Sources/ATProtoKit/Networking/PlatformAPI/GetMutes.swift index 52bcaec1f7..213af61ed5 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/GetMutes.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/GetMutes.swift @@ -22,9 +22,12 @@ extension ATProtoKit { /// - limit: The number of items that can be in the list. Optional. Defaults to `50`. /// - cursor: The mark used to indicate the starting point for the next set of /// result. Optional. - /// - Returns: A `Result`, containing either a ``GraphGetMutesOutput`` + /// - Returns: A `Result`, containing either a ``AppBskyLexicon/Graph/GetMutesOutput`` /// if successful, or an `Error` if not. - public func getMutes(limit: Int? = 50, cursor: String? = nil) async throws -> Result { + public func getMutes( + limit: Int? = 50, + cursor: String? = nil + ) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -60,7 +63,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, - decodeTo: GraphGetMutesOutput.self) + decodeTo: AppBskyLexicon.Graph.GetMutesOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/GetPopularFeedGenerators.swift b/Sources/ATProtoKit/Networking/PlatformAPI/GetPopularFeedGenerators.swift index e8d9977d6c..d8c894abaf 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/GetPopularFeedGenerators.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/GetPopularFeedGenerators.swift @@ -26,10 +26,13 @@ extension ATProtoKit { /// - limit: The number of items that can be in the list. Optional. Defaults to `50`. /// - cursor: The mark used to indicate the starting point for the next set of /// result. Optional. - /// - Returns: A `Result`, containing either an ``UnspeccedGetPopularFeedGeneratorsOutput`` + /// - Returns: A `Result`, containing either an ``AppBskyLexicon/Unspecced/GetPopularFeedGeneratorsOutput`` /// if successful, or an `Error` if not. - public func getPopularFeedGenerators(_ query: String?, limit: Int? = 50, - cursor: String? = nil) async throws -> Result { + public func getPopularFeedGenerators( + _ query: String?, + limit: Int? = 50, + cursor: String? = nil + ) async throws -> Result { guard let sessionURL = session?.pdsURL, let requestURL = URL(string: "\(sessionURL)/xrpc/app.bsky.unspecced.getPopularFeedGenerators") else { return .failure(ATRequestPrepareError.invalidRequestURL) @@ -64,7 +67,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: nil) let response = try await APIClientService.sendRequest(request, - decodeTo: UnspeccedGetPopularFeedGeneratorsOutput.self) + decodeTo: AppBskyLexicon.Unspecced.GetPopularFeedGeneratorsOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/GetPostThread.swift b/Sources/ATProtoKit/Networking/PlatformAPI/GetPostThread.swift index 7581537099..50da6781a3 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/GetPostThread.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/GetPostThread.swift @@ -26,11 +26,15 @@ extension ATProtoKit { /// Optional. Defaults to `80`. Can be between `0` and `1000`. /// - accessToken: The token used to authenticate the user. Optional. /// - pdsURL: The URL of the Personal Data Server (PDS). Defaults to `nil`. - /// - Returns: A `Result`, containing either a ``FeedGetPostThreadOutput`` + /// - Returns: A `Result`, containing either a ``AppBskyLexicon/Feed/GetPostThreadOutput`` /// if successful, or an `Error` if not. - public func getPostThread(from postURI: String, depth: Int? = 6, parentHeight: Int? = 80, - pdsURL: String? = nil, - shouldAuthenticate: Bool = false) async throws -> Result { + public func getPostThread( + from postURI: String, + depth: Int? = 6, + parentHeight: Int? = 80, + pdsURL: String? = nil, + shouldAuthenticate: Bool = false + ) async throws -> Result { let authorizationValue = prepareAuthorizationValue( methodPDSURL: pdsURL, shouldAuthenticate: shouldAuthenticate, @@ -70,7 +74,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: authorizationValue) let response = try await APIClientService.sendRequest(request, - decodeTo: FeedGetPostThreadOutput.self) + decodeTo: AppBskyLexicon.Feed.GetPostThreadOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/GetPosts.swift b/Sources/ATProtoKit/Networking/PlatformAPI/GetPosts.swift index 8e1ff0b027..e1a29ad77c 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/GetPosts.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/GetPosts.swift @@ -25,9 +25,9 @@ extension ATProtoKit { /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/getPosts.json /// /// - Parameter postURIs: An array of URIs of post records. - /// - Returns: A `Result`, containing either a ``FeedGetPostsOutput`` + /// - Returns: A `Result`, containing either a ``AppBskyLexicon/Feed/GetPostsOutput`` /// if successful, or an `Error` if not. - public func getPosts(_ postURIs: [String]) async throws -> Result { + public func getPosts(_ postURIs: [String]) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -58,7 +58,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, - decodeTo: FeedGetPostsOutput.self) + decodeTo: AppBskyLexicon.Feed.GetPostsOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/GetPreferences.swift b/Sources/ATProtoKit/Networking/PlatformAPI/GetPreferences.swift index 00d18df861..c1a7e5b515 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/GetPreferences.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/GetPreferences.swift @@ -19,8 +19,8 @@ extension ATProtoKit { /// /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/actor/getPreferences.json /// - /// - Returns: A `Result`, containing either ``ActorPreferences`` if successful, or `Error` if not. - public func getPreferences() async throws -> Result { + /// - Returns: A `Result`, containing either ``AppBskyLexicon/Actor/GetPreferencesOutput`` if successful, or `Error` if not. + public func getPreferences() async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -38,7 +38,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, - decodeTo: ActorPreferences.self) + decodeTo: AppBskyLexicon.Actor.GetPreferencesOutput.self) return .success(response) } catch(let error) { diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/GetProfile.swift b/Sources/ATProtoKit/Networking/PlatformAPI/GetProfile.swift index 3525704f27..b44eb83149 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/GetProfile.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/GetProfile.swift @@ -33,11 +33,13 @@ extension ATProtoKit { /// - pdsURL: The URL of the Personal Data Server (PDS). Defaults to `nil`. /// - shouldAuthenticate: Indicates whether the method will use the access token when /// sending the request. Defaults to `false`. - /// - Returns: A `Result`, containing ``ActorGetProfileOutput`` + /// - Returns: A `Result`, containing ``AppBskyLexicon/Actor/GetProfileOutput`` /// if successful, or an `Error` if not. - public func getProfile(_ actor: String, - pdsURL: String? = nil, - shouldAuthenticate: Bool = false) async throws -> Result { + public func getProfile( + _ actor: String, + pdsURL: String? = nil, + shouldAuthenticate: Bool = false + ) async throws -> Result { let authorizationValue = prepareAuthorizationValue( methodPDSURL: pdsURL, shouldAuthenticate: shouldAuthenticate, @@ -66,9 +68,8 @@ extension ATProtoKit { andMethod: .get, contentTypeValue: nil, authorizationValue: authorizationValue) - let actorProfileViewDetailedResult = try await APIClientService.sendRequest(request, - decodeTo: ActorProfileViewDetailed.self) - let result = ActorGetProfileOutput(actorProfileView: actorProfileViewDetailedResult) + let result = try await APIClientService.sendRequest(request, + decodeTo: AppBskyLexicon.Actor.GetProfileOutput.self) return .success(result) } catch { diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/GetProfiles.swift b/Sources/ATProtoKit/Networking/PlatformAPI/GetProfiles.swift index 4287c517ea..70d9abfc74 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/GetProfiles.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/GetProfiles.swift @@ -35,11 +35,13 @@ extension ATProtoKit { /// - pdsURL: The URL of the Personal Data Server (PDS). Defaults to `nil`. /// - shouldAuthenticate: Indicates whether the method will use the access token when /// sending the request. Defaults to `false`. - /// - Returns: A `Result`, containing ``ActorGetProfileOutput`` + /// - Returns: A `Result`, containing ``AppBskyLexicon/Actor/GetProfilesOutput`` /// if successful, or an `Error` if not. - public func getProfiles(_ actors: [String], - pdsURL: String? = nil, - shouldAuthenticate: Bool = false) async throws -> Result { + public func getProfiles( + _ actors: [String], + pdsURL: String? = nil, + shouldAuthenticate: Bool = false + ) async throws -> Result { let authorizationValue = prepareAuthorizationValue( methodPDSURL: pdsURL, shouldAuthenticate: shouldAuthenticate, @@ -69,10 +71,10 @@ extension ATProtoKit { andMethod: .get, contentTypeValue: nil, authorizationValue: authorizationValue) - let actorProfileViewsDetailedResult = try await APIClientService.sendRequest(request, - decodeTo: ActorGetProfilesOutput.self) + let result = try await APIClientService.sendRequest(request, + decodeTo: AppBskyLexicon.Actor.GetProfilesOutput.self) - return .success(actorProfileViewsDetailedResult) + return .success(result) } catch { return .failure(error) } diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/GetRelationships.swift b/Sources/ATProtoKit/Networking/PlatformAPI/GetRelationships.swift index b8d17445ef..4e1173c3df 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/GetRelationships.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/GetRelationships.swift @@ -23,10 +23,14 @@ extension ATProtoKit { /// - otherDIDs: An array of decentralized identifiers (DIDs) for the other user accounts /// that the primary user account may be related to. Optional. Current maximum item length /// is `30`. - /// - Returns: A `Result`, containing either a ``GraphGetRelationships`` + /// - Returns: A `Result`, containing either a ``AppBskyLexicon/Graph/GetRelationshipsOutput`` /// if successful, or an `Error` if not. - public func getRelationships(between actorDID: String, and otherDIDs: [String]? = nil, maxLength: Int? = 50, - pdsURL: String? = nil) async throws -> Result { + public func getRelationships( + between actorDID: String, + and otherDIDs: [String]? = nil, + maxLength: Int? = 50, + pdsURL: String? = nil + ) async throws -> Result { guard let sessionURL = pdsURL != nil ? pdsURL : session?.pdsURL, let requestURL = URL(string: "\(sessionURL)/xrpc/app.bsky.graph.getRelationships") else { return .failure(ATRequestPrepareError.invalidRequestURL) @@ -55,7 +59,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: nil) let response = try await APIClientService.sendRequest(request, - decodeTo: GraphGetRelationships.self) + decodeTo: AppBskyLexicon.Graph.GetRelationshipsOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/GetRepostedBy.swift b/Sources/ATProtoKit/Networking/PlatformAPI/GetRepostedBy.swift index debbd51ec9..243123db54 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/GetRepostedBy.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/GetRepostedBy.swift @@ -24,10 +24,14 @@ extension ATProtoKit { /// - limit: The number of items that can be in the list. Optional. Defaults to `50`. /// - cursor: The mark used to indicate the starting point for the next set of /// result. Optional. - /// - Returns: A `Result`, containing either a ``FeedGetRepostedBy`` + /// - Returns: A `Result`, containing either a ``AppBskyLexicon/Feed/GetRepostedByOutput`` /// if successful, or an `Error` if not. - public func getRepostedBy(_ postURI: String, postCID: String? = nil, limit: Int? = 50, - cursor: String? = nil) async throws -> Result { + public func getRepostedBy( + _ postURI: String, + postCID: String? = nil, + limit: Int? = 50, + cursor: String? = nil + ) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -69,7 +73,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, - decodeTo: FeedGetRepostedBy.self) + decodeTo: AppBskyLexicon.Feed.GetRepostedByOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/GetSuggestedFeeds.swift b/Sources/ATProtoKit/Networking/PlatformAPI/GetSuggestedFeeds.swift index 2ca8e93494..0f199351c7 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/GetSuggestedFeeds.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/GetSuggestedFeeds.swift @@ -22,9 +22,12 @@ extension ATProtoKit { /// - limit: The number of items the list will hold. Optional. Defaults to `50`. /// - cursor: The mark used to indicate the starting point for the next set of /// result. Optional. - /// - Returns: A `Result`, containing either a ``FeedGetSuggestedFeedsOutput`` + /// - Returns: A `Result`, containing either a ``AppBskyLexicon/Feed/GetSuggestedFeedsOutput`` /// if successful, or an `Error` if not. - public func getSuggestedFeeds(limit: Int? = 50, cursor: String? = nil) async throws -> Result { + public func getSuggestedFeeds( + limit: Int? = 50, + cursor: String? = nil + ) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -60,7 +63,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, - decodeTo: FeedGetSuggestedFeedsOutput.self) + decodeTo: AppBskyLexicon.Feed.GetSuggestedFeedsOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/GetSuggestedFollowsByActor.swift b/Sources/ATProtoKit/Networking/PlatformAPI/GetSuggestedFollowsByActor.swift index f6e20bb32e..4b08e2cc05 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/GetSuggestedFollowsByActor.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/GetSuggestedFollowsByActor.swift @@ -21,9 +21,9 @@ extension ATProtoKit { /// /// - Parameter actorDID: The decentralized identifier (DID) or handle of the user account /// that the suggestions are based on. - /// - Returns: A `Result`, containing either a ``GraphGetSuggestedFollowsByActorOutput`` + /// - Returns: A `Result`, containing either a ``AppBskyLexicon/Graph/GetSuggestedFollowsByActorOutput`` /// if successful, or an `Error` if not. - public func getSuggestedFollowsByActor(_ actorDID: String) async throws -> Result { + public func getSuggestedFollowsByActor(_ actorDID: String) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -53,7 +53,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, - decodeTo: GraphGetSuggestedFollowsByActorOutput.self) + decodeTo: AppBskyLexicon.Graph.GetSuggestedFollowsByActorOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/GetSuggestions.swift b/Sources/ATProtoKit/Networking/PlatformAPI/GetSuggestions.swift index ffddcbd86a..c6acdb13c9 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/GetSuggestions.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/GetSuggestions.swift @@ -23,9 +23,12 @@ extension ATProtoKit { /// Can only choose between 1 and 100. /// - cursor: The mark used to indicate the starting point for the next set of /// results. Optional. - /// - Returns: A `Result`, containing either an ``ActorGetSuggestionsOutput`` + /// - Returns: A `Result`, containing either an ``AppBskyLexicon/Actor/GetSuggestionsOutput`` /// if succesful, or an `Error` if it's not. - public func getSuggestions(limit: Int? = 50, cursor: String? = nil) async throws -> Result { + public func getSuggestions( + limit: Int? = 50, + cursor: String? = nil + ) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -58,7 +61,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, - decodeTo: ActorGetSuggestionsOutput.self) + decodeTo: AppBskyLexicon.Actor.GetSuggestionsOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/GetSuggestionsSkeleton.swift b/Sources/ATProtoKit/Networking/PlatformAPI/GetSuggestionsSkeleton.swift index aa96ab2e00..a5de2ceda7 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/GetSuggestionsSkeleton.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/GetSuggestionsSkeleton.swift @@ -26,9 +26,12 @@ extension ATProtoKit { /// - viewerDID: The decentralized identifier (DID) of the requesting account. Optional. /// - limit: - limit: The number of items the list will hold. Optional. Defaults to `50`. Can /// only be between `1` and `100`. - /// - Returns: A `Result`, containing either an ``UnspeccedGetSuggestionsSkeletonOutput`` + /// - Returns: A `Result`, containing either an ``AppBskyLexicon/Unspecced/GetSuggestionsSkeletonOutput`` /// if successful, or an `Error` if not. - public func getSuggestionsSkeleton(viewerDID: String?, limit: Int? = 50) async throws -> Result { + public func getSuggestionsSkeleton( + viewerDID: String?, + limit: Int? = 50 + ) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -64,7 +67,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, - decodeTo: UnspeccedGetSuggestionsSkeletonOutput.self) + decodeTo: AppBskyLexicon.Unspecced.GetSuggestionsSkeletonOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/GetTaggedSuggestions.swift b/Sources/ATProtoKit/Networking/PlatformAPI/GetTaggedSuggestions.swift index 414039afac..a16e09deca 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/GetTaggedSuggestions.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/GetTaggedSuggestions.swift @@ -21,9 +21,9 @@ extension ATProtoKit { /// /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/unspecced/getTaggedSuggestions.json /// - /// - Returns: A `Result`, containing either an ``UnspeccedGetTaggedSuggestionsOutput`` + /// - Returns: A `Result`, containing either an ``AppBskyLexicon/Unspecced/GetTaggedSuggestionsOutput`` /// if successful, or an `Error` if not. - public func getTaggedSuggestions(pdsURL: String? = nil) async throws -> Result { + public func getTaggedSuggestions(pdsURL: String? = nil) async throws -> Result { guard let sessionURL = pdsURL != nil ? pdsURL : session?.pdsURL, let requestURL = URL(string: "\(sessionURL)/xrpc/app.bsky.unspecced.getTaggedSuggestions") else { return .failure(ATRequestPrepareError.invalidRequestURL) @@ -36,7 +36,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: nil) let response = try await APIClientService.sendRequest(request, - decodeTo: UnspeccedGetTaggedSuggestionsOutput.self) + decodeTo: AppBskyLexicon.Unspecced.GetTaggedSuggestionsOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/GetTimeline.swift b/Sources/ATProtoKit/Networking/PlatformAPI/GetTimeline.swift index eadccfccc2..e1e956abe7 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/GetTimeline.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/GetTimeline.swift @@ -29,9 +29,13 @@ extension ATProtoKit { /// - limit: The number of items the list will hold. Optional. Defaults to `50`. Can only be /// between `1` and `100`. /// - cursor: The mark used to indicate the starting point for the next set of result. Optional. - /// - Returns: A `Result`, containing either a ``FeedGetTimelineOutput`` + /// - Returns: A `Result`, containing either a ``AppBskyLexicon/Feed/GetTimelineOutput`` /// if successful, or an `Error` if not. - public func getTimeline(using algorithm: String? = nil, limit: Int? = 50, cursor: String? = nil) async throws -> Result { + public func getTimeline( + using algorithm: String? = nil, + limit: Int? = 50, + cursor: String? = nil + ) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -70,7 +74,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, - decodeTo: FeedGetTimelineOutput.self) + decodeTo: AppBskyLexicon.Feed.GetTimelineOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/GetUnreadCount.swift b/Sources/ATProtoKit/Networking/PlatformAPI/GetUnreadCount.swift index ea1a2c8bb1..48097b905d 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/GetUnreadCount.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/GetUnreadCount.swift @@ -20,9 +20,11 @@ extension ATProtoKit { /// /// - Parameter seenAt: The date and time the notifications were seen. Defaults to the date and /// time the request was sent. - /// - Returns: A `Result`, containing either a ``NotificationGetUnreadCountOutput`` + /// - Returns: A `Result`, containing either a ``AppBskyLexicon/Notification/GetUnreadCountOutput`` /// if successful, or an `Error` if not. - public func getUnreadCount(seenAt: Date = Date.now) async throws -> Result { + public func getUnreadCount( + seenAt: Date = Date.now + ) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -53,7 +55,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, - decodeTo: NotificationGetUnreadCountOutput.self) + decodeTo: AppBskyLexicon.Notification.GetUnreadCountOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/ListNotifications.swift b/Sources/ATProtoKit/Networking/PlatformAPI/ListNotifications.swift index bbea46f410..768e8ae37f 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/ListNotifications.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/ListNotifications.swift @@ -24,10 +24,13 @@ extension ATProtoKit { /// results. Optional. /// - seenAt: The date and time the notification was seen. Defaults to the date and time the /// request was sent. - /// - Returns: A `Result`, containing either a ``NotificationListNotificationsOutput`` + /// - Returns: A `Result`, containing either a ``AppBskyLexicon/Notification/ListNotificationsOutput`` /// if successful, or an `Error` if not. - public func listNotifications(withLimitOf limit: Int? = 50, cursor: String? = nil, - seenAt: Date = Date.now) async throws -> Result { + public func listNotifications( + withLimitOf limit: Int? = 50, + cursor: String? = nil, + seenAt: Date = Date.now + ) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -69,7 +72,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, - decodeTo: NotificationListNotificationsOutput.self) + decodeTo: AppBskyLexicon.Notification.ListNotificationsOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/MuteActor.swift b/Sources/ATProtoKit/Networking/PlatformAPI/MuteActor.swift index 9502522565..0fa93064ea 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/MuteActor.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/MuteActor.swift @@ -30,7 +30,7 @@ extension ATProtoKit { throw ATRequestPrepareError.invalidRequestURL } - let requestBody = GraphMuteActor( + let requestBody = AppBskyLexicon.Graph.MuteActorRequestBody( actorDID: actorDID ) diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/MuteActorList.swift b/Sources/ATProtoKit/Networking/PlatformAPI/MuteActorList.swift index 4eb923f027..4bdb543821 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/MuteActorList.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/MuteActorList.swift @@ -30,7 +30,7 @@ extension ATProtoKit { throw ATRequestPrepareError.invalidRequestURL } - let requestBody = GraphMuteActorList( + let requestBody = AppBskyLexicon.Graph.MuteActorListRequestBody( listURI: listURI ) diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/PutPreferences.swift b/Sources/ATProtoKit/Networking/PlatformAPI/PutPreferences.swift index eb616b9b45..18650e37e9 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/PutPreferences.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/PutPreferences.swift @@ -19,7 +19,7 @@ extension ATProtoKit { /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/actor/putPreferences.json /// /// - Parameter preferences: An array of preferences the user wants to change. - public func putPreferences(preferences: ActorPreferences) async throws { + public func putPreferences(preferences: AppBskyLexicon.Actor.PreferencesDefinition) async throws { guard session != nil, let accessToken = session?.accessToken else { throw ATRequestPrepareError.missingActiveSession @@ -30,7 +30,7 @@ extension ATProtoKit { throw ATRequestPrepareError.invalidRequestURL } - let requestBody = ActorPutPreferences( + let requestBody = AppBskyLexicon.Actor.PutPreferencesRequestBody( preferences: preferences.preferences ) diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/RegisterPush.swift b/Sources/ATProtoKit/Networking/PlatformAPI/RegisterPush.swift index e4f9425ac0..66c51b3ae6 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/RegisterPush.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/RegisterPush.swift @@ -23,7 +23,12 @@ extension ATProtoKit { /// - token: The token of the service. /// - platform: The platform of the client. /// - appID: The identifier of the client. - public func registerPush(serviceDID: String, token: String, platform: RegisterPushRequest.Platform, appID: String) async throws { + public func registerPush( + serviceDID: String, + token: String, + platform: AppBskyLexicon.Notification.RegisterPush.Platform, + appID: String + ) async throws { guard session != nil, let accessToken = session?.accessToken else { throw ATRequestPrepareError.missingActiveSession @@ -34,7 +39,7 @@ extension ATProtoKit { throw ATRequestPrepareError.invalidRequestURL } - let requestBody = RegisterPushRequest( + let requestBody = AppBskyLexicon.Notification.RegisterPushRequestBody( serviceDID: serviceDID, token: token, platform: platform, diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/SearchActorsSkeleton.swift b/Sources/ATProtoKit/Networking/PlatformAPI/SearchActorsSkeleton.swift index af77212494..0aafc8f346 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/SearchActorsSkeleton.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/SearchActorsSkeleton.swift @@ -28,10 +28,16 @@ extension ATProtoKit { /// - limit: The number of items that can be in the list. Optional. Defaults to `25`. /// - cursor: The mark used to indicate the starting point for the next set of /// result. Optional. - /// - Returns: A `Result`, containing either an ``UnspeccedSearchActorsSkeletonOutput`` + /// - Returns: A `Result`, containing either an ``AppBskyLexicon/Unspecced/SearchActorsSkeletonOutput`` /// if successful, or an `Error` if not. - public func searchActorsSkeleton(_ query: String, viewerDID: String? = nil, canTypeAhead: Bool?, limit: Int? = 25, cursor: String? = nil, - pdsURL: String? = nil) async throws -> Result { + public func searchActorsSkeleton( + _ query: String, + viewerDID: String? = nil, + canTypeAhead: Bool?, + limit: Int? = 25, + cursor: String? = nil, + pdsURL: String? = nil + ) async throws -> Result { guard let sessionURL = pdsURL != nil ? pdsURL : session?.pdsURL, let requestURL = URL(string: "\(sessionURL)/xrpc/app.bsky.unspecced.searchActorsSkeleton") else { return .failure(ATRequestPrepareError.invalidRequestURL) @@ -72,7 +78,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: nil) let response = try await APIClientService.sendRequest(request, - decodeTo: UnspeccedSearchActorsSkeletonOutput.self) + decodeTo: AppBskyLexicon.Unspecced.SearchActorsSkeletonOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/SearchPosts.swift b/Sources/ATProtoKit/Networking/PlatformAPI/SearchPosts.swift index 857ba40292..a25d438b2e 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/SearchPosts.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/SearchPosts.swift @@ -39,11 +39,22 @@ extension ATProtoKit { /// Can only choose between `1` and `100`. /// - cursor: The mark used to indicate the starting point for the next set of /// results. Optional. - /// - Returns: A `Result`, containing either an ``FeedSearchPostsOutput`` + /// - Returns: A `Result`, containing either an ``AppBskyLexicon/Feed/SearchPostsOutput`` /// if succesful, or an `Error` if it's not. - public func searchPosts(with searchQuery: String, sortRanking: FeedSearchPostsSortRanking? = .latest, sinceDate: Date?, untilDate: Date?, - mentionIdentifier: String? = nil, author: String? = nil, language: Locale?, domain: String?, url: String?, tags: [String]?, - limit: Int? = 25, cursor: String? = nil) async throws -> Result { + public func searchPosts( + with searchQuery: String, + sortRanking: AppBskyLexicon.Feed.SearchPosts.SortRanking? = .latest, + sinceDate: Date?, + untilDate: Date?, + mentionIdentifier: String? = nil, + author: String? = nil, + language: Locale?, + domain: String?, + url: String?, + tags: [String]?, + limit: Int? = 25, + cursor: String? = nil + ) async throws -> Result { guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -117,7 +128,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, - decodeTo: FeedSearchPostsOutput.self) + decodeTo: AppBskyLexicon.Feed.SearchPostsOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/SearchPostsSkeleton.swift b/Sources/ATProtoKit/Networking/PlatformAPI/SearchPostsSkeleton.swift index 131b3f1118..140dac4dcd 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/SearchPostsSkeleton.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/SearchPostsSkeleton.swift @@ -42,12 +42,23 @@ extension ATProtoKit { /// to `25`. /// - cursor: The mark used to indicate the starting point for the next set of /// result. Optional. - /// - Returns: A `Result`, containing either an ``UnspeccedSearchPostsSkeletonOutput`` + /// - Returns: A `Result`, containing either an ``AppBskyLexicon/Unspecced/SearchPostsSkeletonOutput`` /// if successful, or an `Error` if not. - public func searchPostsSkeleton(with searchQuery: String, sortRanking: UnspeccedSearchPostsSortRanking? = .latest, sinceDate: Date?, untilDate: Date?, - mentionIdentifier: String? = nil, author: String? = nil, language: Locale?, domain: String?, url: String?, - tags: [String]?, limit: Int? = 25, cursor: String? = nil, - pdsURL: String? = nil) async throws -> Result { + public func searchPostsSkeleton( + with searchQuery: String, + sortRanking: AppBskyLexicon.Unspecced.SearchPostsSkeleton.Sort? = .latest, + sinceDate: Date?, + untilDate: Date?, + mentionIdentifier: String? = nil, + author: String? = nil, + language: Locale?, + domain: String?, + url: String?, + tags: [String]?, + limit: Int? = 25, + cursor: String? = nil, + pdsURL: String? = nil + ) async throws -> Result { guard let sessionURL = pdsURL != nil ? pdsURL : session?.pdsURL, let requestURL = URL(string: "\(sessionURL)/xrpc/app.bsky.unspecced.searchPostsSkeleton") else { return .failure(ATRequestPrepareError.invalidRequestURL) @@ -116,7 +127,7 @@ extension ATProtoKit { contentTypeValue: nil, authorizationValue: nil) let response = try await APIClientService.sendRequest(request, - decodeTo: UnspeccedSearchPostsSkeletonOutput.self) + decodeTo: AppBskyLexicon.Unspecced.SearchPostsSkeletonOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/SearchUsers.swift b/Sources/ATProtoKit/Networking/PlatformAPI/SearchUsers.swift index cb62c68798..238285245d 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/SearchUsers.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/SearchUsers.swift @@ -38,11 +38,15 @@ extension ATProtoKit { /// - pdsURL: The URL of the Personal Data Server (PDS). Defaults to `nil`. /// - shouldAuthenticate: Indicates whether the method will use the access token /// when sending the request. Defaults to `false`. - /// - Returns: A `Result`, containing either ``ActorSearchActorsOutput`` + /// - Returns: A `Result`, containing either ``AppBskyLexicon/Actor/SearchActorsOutput`` /// if successful, and an `Error` if not. - public func searchUsers(by query: String, limit: Int? = 25, cursor: String? = nil, - pdsURL: String? = nil, - shouldAuthenticate: Bool = false) async throws -> Result { + public func searchUsers( + by query: String, + limit: Int? = 25, + cursor: String? = nil, + pdsURL: String? = nil, + shouldAuthenticate: Bool = false + ) async throws -> Result { let authorizationValue = prepareAuthorizationValue( methodPDSURL: pdsURL, shouldAuthenticate: shouldAuthenticate, @@ -80,7 +84,7 @@ extension ATProtoKit { acceptValue: "application/json", authorizationValue: authorizationValue) let response = try await APIClientService.sendRequest(request, - decodeTo: ActorSearchActorsOutput.self) + decodeTo: AppBskyLexicon.Actor.SearchActorsOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/SearchUsersTypeahead.swift b/Sources/ATProtoKit/Networking/PlatformAPI/SearchUsersTypeahead.swift index 3f4981fd99..aba76ca9fc 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/SearchUsersTypeahead.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/SearchUsersTypeahead.swift @@ -37,11 +37,14 @@ extension ATProtoKit { /// - pdsURL: The URL of the Personal Data Server (PDS). Defaults to `nil`. /// - shouldAuthenticate: Indicates whether the method will use the access token when /// sending the request. Defaults to `false`. - /// - Returns: A `Result`, containing either ``ActorSearchActorsOutput`` + /// - Returns: A `Result`, containing either ``AppBskyLexicon/Actor/SearchActorsTypeaheadOutput`` /// if successful, and an `Error` if not. - public func searchUsersTypeahead(by query: String, limit: Int? = 10, - pdsURL: String? = nil, - shouldAuthenticate: Bool = false) async throws -> Result { + public func searchUsersTypeahead( + by query: String, + limit: Int? = 10, + pdsURL: String? = nil, + shouldAuthenticate: Bool = false + ) async throws -> Result { let authorizationValue = prepareAuthorizationValue( methodPDSURL: pdsURL, shouldAuthenticate: shouldAuthenticate, @@ -76,7 +79,7 @@ extension ATProtoKit { acceptValue: "application/json", authorizationValue: authorizationValue) let response = try await APIClientService.sendRequest(request, - decodeTo: ActorSearchActorsTypeaheadOutput.self) + decodeTo: AppBskyLexicon.Actor.SearchActorsTypeaheadOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/SendInteractions.swift b/Sources/ATProtoKit/Networking/PlatformAPI/SendInteractions.swift index 135366e69a..bef2274a05 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/SendInteractions.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/SendInteractions.swift @@ -22,9 +22,11 @@ extension ATProtoKit { /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/feed/sendInteractions.json /// /// - Parameter interactions: An array of interactions. - /// - Returns: A `Result`, containing either a ``FeedSendInteractionsOutput`` + /// - Returns: A `Result`, containing either a ``AppBskyLexicon/Feed/SendInteractionsOutput`` /// if sucessful, or an `Error` if not. - public func sendInteractions(_ interactions: [FeedInteraction]) async throws -> Result{ + public func sendInteractions( + _ interactions: [AppBskyLexicon.Feed.InteractionDefinition] + ) async throws -> Result{ guard session != nil, let accessToken = session?.accessToken else { return .failure(ATRequestPrepareError.missingActiveSession) @@ -35,7 +37,7 @@ extension ATProtoKit { return .failure(ATRequestPrepareError.invalidRequestURL) } - let requestBody = FeedSendInteractions( + let requestBody = AppBskyLexicon.Feed.SendInteractionsRequestBody( interactions: interactions ) @@ -47,7 +49,7 @@ extension ATProtoKit { authorizationValue: "Bearer \(accessToken)") let response = try await APIClientService.sendRequest(request, withEncodingBody: requestBody, - decodeTo: FeedSendInteractionsOutput.self) + decodeTo: AppBskyLexicon.Feed.SendInteractionsOutput.self) return .success(response) } catch { diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/UnmuteActor.swift b/Sources/ATProtoKit/Networking/PlatformAPI/UnmuteActor.swift index c7ecc70370..5fd069b3a4 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/UnmuteActor.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/UnmuteActor.swift @@ -31,7 +31,7 @@ extension ATProtoKit { throw ATRequestPrepareError.invalidRequestURL } - let requestBody = GraphUnmuteActor( + let requestBody = AppBskyLexicon.Graph.UnmuteActorRequestBody( actorDID: actorDID ) diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/UnmuteActorList.swift b/Sources/ATProtoKit/Networking/PlatformAPI/UnmuteActorList.swift index 6a9a56d62b..c1349a4de3 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/UnmuteActorList.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/UnmuteActorList.swift @@ -30,7 +30,7 @@ extension ATProtoKit { throw ATRequestPrepareError.invalidRequestURL } - let requestBody = GraphUnmuteActorList( + let requestBody = AppBskyLexicon.Graph.UnmuteActorListRequestBody( listURI: listURI ) diff --git a/Sources/ATProtoKit/Networking/PlatformAPI/UpdateSeen.swift b/Sources/ATProtoKit/Networking/PlatformAPI/UpdateSeen.swift index 58671c70df..284e42f6c3 100644 --- a/Sources/ATProtoKit/Networking/PlatformAPI/UpdateSeen.swift +++ b/Sources/ATProtoKit/Networking/PlatformAPI/UpdateSeen.swift @@ -31,7 +31,7 @@ extension ATProtoKit { throw ATRequestPrepareError.invalidRequestURL } - let requestBody = NotificationUpdateSeen( + let requestBody = AppBskyLexicon.Notification.UpdateSeenRequestBody( seenAt: seenAt ) diff --git a/Sources/ATProtoKit/Networking/SessionManager/ATProtocolConfiguration.swift b/Sources/ATProtoKit/Networking/SessionManager/ATProtocolConfiguration.swift index 04806f168b..240e581ea6 100644 --- a/Sources/ATProtoKit/Networking/SessionManager/ATProtocolConfiguration.swift +++ b/Sources/ATProtoKit/Networking/SessionManager/ATProtocolConfiguration.swift @@ -49,8 +49,13 @@ public class ATProtocolConfiguration: ProtocolConfiguration { /// be in. Optional. Defaults to `ATProtoKit`. /// - logLevel: Specifies the highest level of logs that will be outputted. Optional. /// Defaults to `.info`. - public init(handle: String, appPassword: String, pdsURL: String = "https://bsky.social", logIdentifier: String? = nil, logCategory: String? = nil, - logLevel: Logger.Level? = .info) { + public init( + handle: String, + appPassword: String, + pdsURL: String = "https://bsky.social", + logIdentifier: String? = nil, + logCategory: String? = nil, + logLevel: Logger.Level? = .info) { self.handle = handle self.appPassword = appPassword self.pdsURL = !pdsURL.isEmpty ? pdsURL : "https://bsky.social" @@ -82,6 +87,7 @@ public class ATProtocolConfiguration: ProtocolConfiguration { /// - SeeAlso: This is based on the [`com.atproto.server.createSession`][github] lexicon. /// /// [github]: https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/server/createSession.json + /// /// - Parameter authenticationFactorToken: A token used for /// Two-Factor Authentication. Optional. /// - Returns: A `Result` containing ``UserSession`` on success or an `Error` on failure. @@ -92,7 +98,7 @@ public class ATProtocolConfiguration: ProtocolConfiguration { return .failure(ATRequestPrepareError.invalidRequestURL) } - let credentials = SessionCredentials( + let credentials = ComAtprotoLexicon.Server.CreateSessionRequestBody( identifier: handle, password: appPassword, authenticationFactorToken: authenticationFactorToken @@ -148,14 +154,22 @@ public class ATProtocolConfiguration: ProtocolConfiguration { /// account to this instance. Optional. /// - Returns: A `Result`, containing either a ``UserSession`` /// if successful, or an `Error` if not. - public func createAccount(email: String? = nil, handle: String, existingDID: String? = nil, inviteCode: String? = nil, - verificationCode: String? = nil, verificationPhone: String? = nil, password: String? = nil, recoveryKey: String? = nil, - plcOp: UnknownType? = nil) async throws -> Result { + public func createAccount( + email: String? = nil, + handle: String, + existingDID: String? = nil, + inviteCode: String? = nil, + verificationCode: String? = nil, + verificationPhone: String? = nil, + password: String? = nil, + recoveryKey: String? = nil, + plcOp: UnknownType? = nil + ) async throws -> Result { guard let requestURL = URL(string: "\(self.pdsURL)/xrpc/com.atproto.server.createAccount") else { return .failure(ATRequestPrepareError.invalidRequestURL) } - let requestBody = ServerCreateAccount( + let requestBody = ComAtprotoLexicon.Server.CreateAccountRequestBody( email: email, handle: handle, existingDID: existingDID, @@ -202,8 +216,10 @@ public class ATProtocolConfiguration: ProtocolConfiguration { /// - pdsURL: The URL of the Personal Data Server (PDS). Defaults to `nil`. /// - Returns: Returns: A `Result` containing either ``SessionResponse`` /// if successful, or an `Error` if not. - public func getSession(by accessToken: String, - pdsURL: String? = nil) async throws -> Result { + public func getSession( + by accessToken: String, + pdsURL: String? = nil + ) async throws -> Result { guard let sessionURL = pdsURL != nil ? pdsURL : self.pdsURL, let requestURL = URL(string: "\(sessionURL)/xrpc/com.atproto.server.getSession") else { return .failure(ATRequestPrepareError.invalidRequestURL) @@ -236,8 +252,10 @@ public class ATProtocolConfiguration: ProtocolConfiguration { /// - pdsURL: The URL of the Personal Data Server (PDS). Defaults to `nil`. /// - Returns: A `Result`, containing either a ``UserSession`` /// if successful, or an `Error` if not. - public func refreshSession(using refreshToken: String, - pdsURL: String? = nil) async throws -> Result { + public func refreshSession( + using refreshToken: String, + pdsURL: String? = nil + ) async throws -> Result { guard let sessionURL = pdsURL != nil ? pdsURL : self.pdsURL, let requestURL = URL(string: "\(sessionURL)/xrpc/com.atproto.server.refreshSession") else { return .failure(ATRequestPrepareError.invalidRequestURL) @@ -273,8 +291,10 @@ public class ATProtocolConfiguration: ProtocolConfiguration { /// - Parameters: /// - accessToken: The access token for the session. /// - pdsURL: The URL of the Personal Data Server (PDS). Defaults to `nil`. - public func deleteSession(using accessToken: String, - pdsURL: String? = nil) async throws { + public func deleteSession( + using accessToken: String, + pdsURL: String? = nil + ) async throws { guard let sessionURL = pdsURL != nil ? pdsURL : self.pdsURL, let requestURL = URL(string: "\(sessionURL)/xrpc/com.atproto.server.deleteSession") else { throw ATRequestPrepareError.invalidRequestURL diff --git a/Sources/ATProtoKit/Utilities/APIClientService.swift b/Sources/ATProtoKit/Utilities/APIClientService.swift index 560ffe4957..c84b8641d2 100644 --- a/Sources/ATProtoKit/Utilities/APIClientService.swift +++ b/Sources/ATProtoKit/Utilities/APIClientService.swift @@ -134,7 +134,7 @@ public class APIClientService { /// - imageData: The data of the blob to upload. /// - Returns: A `BlobContainer` instance with the upload result. public static func uploadBlob(pdsURL: String = "https://bsky.social", accessToken: String, filename: String, - imageData: Data) async throws -> BlobContainer { + imageData: Data) async throws -> ComAtprotoLexicon.Repository.BlobContainer { guard let requestURL = URL(string: "\(pdsURL)/xrpc/com.atproto.repo.uploadBlob") else { throw ATRequestPrepareError.invalidRequestURL } @@ -150,7 +150,7 @@ public class APIClientService { request.httpBody = imageData let response = try await sendRequest(request, - decodeTo: BlobContainer.self) + decodeTo: ComAtprotoLexicon.Repository.BlobContainer.self) return response } catch { diff --git a/Sources/ATProtoKit/Utilities/ATFacetParser.swift b/Sources/ATProtoKit/Utilities/ATFacetParser.swift index 1b1cecf1d8..72804b54f1 100644 --- a/Sources/ATProtoKit/Utilities/ATFacetParser.swift +++ b/Sources/ATProtoKit/Utilities/ATFacetParser.swift @@ -10,15 +10,15 @@ import Foundation /// A utility class designed for parsing various elements like mentions, URLs, and hashtags from text. public class ATFacetParser { - /// Manages a collection of ``Facet`` objects, providing thread-safe append operations. + /// Manages a collection of ``AppBskyLexicon/RichText/Facet`` objects, providing thread-safe append operations. actor FacetsActor { - /// The collection of ``Facet`` objects. - var facets = [Facet]() - - /// Appends a new ``Facet`` to the collection in a thread-safe manner. - /// - Parameter facet: Parameter facet: The ``Facet`` to append. - func append(_ facet: Facet) { + /// The collection of ``AppBskyLexicon/RichText/Facet`` objects. + var facets = [AppBskyLexicon.RichText.Facet]() + + /// Appends a new ``AppBskyLexicon/RichText/Facet`` to the collection in a thread-safe manner. + /// - Parameter facet: Parameter facet: The ``AppBskyLexicon/RichText/Facet`` to append. + func append(_ facet: AppBskyLexicon.RichText.Facet) { facets.append(facet) } } @@ -136,13 +136,13 @@ public class ATFacetParser { } /// Processes text to find mentions, URLs, and hashtags, converting these elements into - /// ``Facet`` objects. + /// ``AppBskyLexicon/RichText/Facet`` objects. /// - Parameters: /// - text: The text to be processed. /// - pdsURL: The URL of the Personal Data Server, defaulting to "https://bsky.social". - /// - Returns: An array of ``Facet`` objects representing the structured data elements found + /// - Returns: An array of ``AppBskyLexicon/RichText/Facet`` objects representing the structured data elements found /// in the text. - public static func parseFacets(from text: String, pdsURL: String = "https://bsky.social") async -> [Facet] { + public static func parseFacets(from text: String, pdsURL: String = "https://bsky.social") async -> [AppBskyLexicon.RichText.Facet] { let facets = FacetsActor() await withTaskGroup(of: Void.self) { group in @@ -174,9 +174,9 @@ public class ATFacetParser { case .success(let resolveHandleOutput): guard let start = mention["start"] as? Int, let end = mention["end"] as? Int else { return } - let mentionFacet = Facet( - index: ByteSlice(byteStart: start, byteEnd: end), - features: [.mention(Mention(did: resolveHandleOutput.handleDID))]) + let mentionFacet = AppBskyLexicon.RichText.Facet( + index: AppBskyLexicon.RichText.Facet.ByteSlice(byteStart: start, byteEnd: end), + features: [.mention(AppBskyLexicon.RichText.Facet.Mention(did: resolveHandleOutput.handleDID))]) await facets.append(mentionFacet) case .failure(let error): @@ -197,9 +197,9 @@ public class ATFacetParser { if let start = link["start"] as? Int, let end = link["end"] as? Int { - let linkFacet = Facet( - index: ByteSlice(byteStart: start, byteEnd: end), - features: [.link(Link(uri: url))] + let linkFacet = AppBskyLexicon.RichText.Facet( + index: AppBskyLexicon.RichText.Facet.ByteSlice(byteStart: start, byteEnd: end), + features: [.link(AppBskyLexicon.RichText.Facet.Link(uri: url))] ) await facets.append(linkFacet) @@ -216,9 +216,9 @@ public class ATFacetParser { if let start = hashtag["start"] as? Int, let end = hashtag["end"] as? Int { - let hashTagFacet = Facet( - index: ByteSlice(byteStart: start, byteEnd: end), - features: [.tag(Tag(tag: tag))] + let hashTagFacet = AppBskyLexicon.RichText.Facet( + index: AppBskyLexicon.RichText.Facet.ByteSlice(byteStart: start, byteEnd: end), + features: [.tag(AppBskyLexicon.RichText.Facet.Tag(tag: tag))] ) await facets.append(hashTagFacet) diff --git a/Sources/ATProtoKit/Utilities/ATImageProcessing.swift b/Sources/ATProtoKit/Utilities/ATImageProcessing.swift index 29a36d4056..63f321937d 100644 --- a/Sources/ATProtoKit/Utilities/ATImageProcessing.swift +++ b/Sources/ATProtoKit/Utilities/ATImageProcessing.swift @@ -107,7 +107,7 @@ public protocol ATImageProcessable { /// - targetFileSize: The size (in bytes) the file needs to be. /// - Returns: An ``ImageQuery``, which combines the image itself in a `Data` format and /// the alt text. - func convertToImageQuery(imagePath: String, altText: String?, targetFileSize: Int) -> ImageQuery? + func convertToImageQuery(imagePath: String, altText: String?, targetFileSize: Int) -> ComAtprotoLexicon.Repository.ImageQuery? /// Removes all EXIF and GPS metadata from the image. /// @@ -118,7 +118,7 @@ public protocol ATImageProcessable { } public extension ATImageProcessable { - func convertToImageQuery(imagePath: String, altText: String?, targetFileSize: Int = 1_000_000) -> ImageQuery? { + func convertToImageQuery(imagePath: String, altText: String?, targetFileSize: Int = 1_000_000) -> ComAtprotoLexicon.Repository.ImageQuery? { guard let image = NSImage(contentsOfFile: imagePath) else { print("Image could not be loaded.") return nil @@ -166,7 +166,7 @@ public extension ATImageProcessable { } if let imageData { - return ImageQuery(imageData: imageData, fileName: filename, altText: altText) + return ComAtprotoLexicon.Repository.ImageQuery(imageData: imageData, fileName: filename, altText: altText) } return nil diff --git a/Sources/ATProtoKit/Utilities/ATProtoTools.swift b/Sources/ATProtoKit/Utilities/ATProtoTools.swift index 0d01bb0d92..3d8372cfa7 100644 --- a/Sources/ATProtoKit/Utilities/ATProtoTools.swift +++ b/Sources/ATProtoKit/Utilities/ATProtoTools.swift @@ -19,34 +19,67 @@ import Foundation /// - Important: The rule where the method becomes deprecated will be active either /// when version 1.0 is launched or `ATProtoTools` is stabilized, whichever comes first. /// Until then, if a method is better suited elsewhere, it will be immediately moved. -class ATProtoTools { +public class ATProtoTools { /// Resolves the reply references to prepare them for a later post record request. /// /// - Parameter parentURI: The URI of the post record the current one is directly replying to. /// - Returns: A ``ReplyReference``. - public func resolveReplyReferences(parentURI: String) async throws -> ReplyReference { - let parentRecord = try await fetchRecordForURI(parentURI) + public func resolveReplyReferences(parentURI: String) async throws -> AppBskyLexicon.Feed.PostRecord.ReplyReference { + let threadRecords = try await fetchRecordForURI(parentURI) - guard let replyReference = parentRecord.value?.reply else { - // The parent record is a top-level post, so it is also the root - return createReplyReference(from: parentRecord) + guard let parentRecord = threadRecords.value else { + return createReplyReference(from: threadRecords) } + var replyReference: AppBskyLexicon.Feed.PostRecord.ReplyReference? + + switch parentRecord { + case .unknown(let unknown): + replyReference = try decodeReplyReference(from: unknown) + default: + break + } + + if let replyReference = replyReference { + return try await getReplyReferenceWithRoot(replyReference) + } + + return createReplyReference(from: threadRecords) + } + + private func decodeReplyReference(from unknown: [String: Any]) throws -> AppBskyLexicon.Feed.PostRecord.ReplyReference? { + if let replyData = unknown["reply"] as? [String: Any] { + let jsonData = try JSONSerialization.data(withJSONObject: replyData, options: []) + let decoder = JSONDecoder() + return try decoder.decode(AppBskyLexicon.Feed.PostRecord.ReplyReference.self, from: jsonData) + } + return nil + } + + private func getReplyReferenceWithRoot( + _ replyReference: AppBskyLexicon.Feed.PostRecord.ReplyReference) async throws -> AppBskyLexicon.Feed.PostRecord.ReplyReference { let rootRecord = try await fetchRecordForURI(replyReference.root.recordURI) - let rootReference = rootRecord.value?.reply?.root ?? replyReference.root - return ReplyReference(root: rootReference, parent: replyReference.parent) + if let rootReferenceValue = rootRecord.value { + switch rootReferenceValue { + case .unknown: + return AppBskyLexicon.Feed.PostRecord.ReplyReference(root: replyReference.root, parent: replyReference.parent) + default: + return AppBskyLexicon.Feed.PostRecord.ReplyReference(root: replyReference.root, parent: replyReference.parent) + } + } + return AppBskyLexicon.Feed.PostRecord.ReplyReference(root: replyReference.root, parent: replyReference.parent) } /// Gets a record from the user's repository. /// /// - Parameter uri: The URI of the record. /// - Returns: A ``RecordOutput`` - public func fetchRecordForURI(_ uri: String) async throws -> RecordOutput { + public func fetchRecordForURI(_ uri: String) async throws -> ComAtprotoLexicon.Repository.GetRecordOutput { let query = try parseURI(uri) - let record = try await ATProtoKit().getRepositoryRecord(from: query, pdsURL: nil) + let record = try await ATProtoKit().getRepositoryRecord(from: query.repository, collection: query.collection, recordKey: query.recordKey, pdsURL: nil) switch record { case .success(let result): @@ -60,9 +93,10 @@ class ATProtoTools { /// /// - Parameter record: The record to convert. /// - Returns: A ``ReplyReference``. - private func createReplyReference(from record: RecordOutput) -> ReplyReference { - let reference = StrongReference(recordURI: record.recordURI, cidHash: record.recordCID) - return ReplyReference(root: reference, parent: reference) + private func createReplyReference(from record: ComAtprotoLexicon.Repository.GetRecordOutput) -> AppBskyLexicon.Feed.PostRecord.ReplyReference { + let reference = ComAtprotoLexicon.Repository.StrongReference(recordURI: record.recordURI, cidHash: record.recordCID) + + return AppBskyLexicon.Feed.PostRecord.ReplyReference(root: reference, parent: reference) } /// Parses the URI in order to get a ``RecordQuery``. @@ -82,11 +116,12 @@ class ATProtoTools { let components = uri.split(separator: "/").map(String.init) guard components.count >= 4 else { throw ATRequestPrepareError.invalidFormat } - return RecordQuery(repo: components[1], collection: components[2], recordKey: components[3]) + return ATProtoTools.RecordQuery(repository: components[1], collection: components[2], recordKey: components[3]) } else if uri.hasPrefix("\(pdsURL)/") { let components = uri.split(separator: "/").map(String.init) guard components.count >= 6 else { - throw ATRequestPrepareError.invalidFormat } + throw ATRequestPrepareError.invalidFormat + } let record = components[3] let recordKey = components[5] @@ -103,9 +138,47 @@ class ATProtoTools { throw ATRequestPrepareError.invalidFormat } - return RecordQuery(repo: record, collection: collection, recordKey: recordKey) + return RecordQuery(repository: record, collection: collection, recordKey: recordKey) } else { throw ATRequestPrepareError.invalidFormat } } + + /// A structure for a record. + public struct RecordQuery: Codable { + + /// The handle or decentralized identifier (DID) of the repo." + /// + /// - Note: According to the AT Protocol specifications: "The handle or DID of the repo." + public let repository: String + + /// The NSID of the record. + /// + /// - Note: According to the AT Protocol specifications: "The NSID of the record collection." + public let collection: String + + /// The record's key. + /// + //// - Note: According to the AT Protocol specifications: "The Record Key." + public let recordKey: String + + /// The CID of the version of the record. Optional. Defaults to `nil`. + /// + /// - Note: According to the AT Protocol specifications: "The CID of the version of the record. + /// If not specified, then return the most recent version." + public let recordCID: String? = nil + + public init(repository: String, collection: String, recordKey: String) { + self.repository = repository + self.collection = collection + self.recordKey = recordKey + } + + enum CodingKeys: String, CodingKey { + case repository = "repo" + case collection = "collection" + case recordKey = "rkey" + case recordCID = "cid" + } + } } diff --git a/Sources/ATProtoKit/Utilities/ATRecordProtocol.swift b/Sources/ATProtoKit/Utilities/ATRecordProtocol.swift index d069d3efb5..2e7077ad62 100644 --- a/Sources/ATProtoKit/Utilities/ATRecordProtocol.swift +++ b/Sources/ATProtoKit/Utilities/ATRecordProtocol.swift @@ -91,7 +91,14 @@ public struct ATRecordTypeRegistry { /// `struct` that was found if there's a match. public static var recordRegistry = [String: ATRecordProtocol.Type]() + /// Indicates whether any Bluesky-related `ATRecordProtocol`-conforming `struct`s have been + /// added to ``recordRegistry``. Defaults to `false`. + /// + /// - Warning: Don't touch this property; this should only be used for ``ATProtoKit``. + public static var areBlueskyRecordsRegistered = false + /// Initializes the registry with an array of record types. + /// /// - Parameter types: An array of ``ATRecordProtocol``-conforming `struct`s. public init(types: [ATRecordProtocol.Type]) { for type in types { diff --git a/Sources/ATProtoKit/Utilities/ExtensionHelpers.swift b/Sources/ATProtoKit/Utilities/ExtensionHelpers.swift index fe7c2161b6..161a1387a9 100644 --- a/Sources/ATProtoKit/Utilities/ExtensionHelpers.swift +++ b/Sources/ATProtoKit/Utilities/ExtensionHelpers.swift @@ -19,7 +19,7 @@ extension String: Truncatable { /// - Parameter length: The maximum number of characters that the `String` can have /// before it truncates. /// - Returns: A new `String` that contains the maximum number of characters or less. - func truncated(toLength length: Int) -> String { + public func truncated(toLength length: Int) -> String { return String(self.prefix(length)) } @@ -29,7 +29,7 @@ extension String: Truncatable { /// Any uppercased characters will be lowercased. Any characters that could be interpreted as /// hypens will be converted into standard hyphens. Any additional characters will /// be discarded. - func transformToLowerASCIIAndHyphen() -> String { + public func transformToLowerASCIIAndHyphen() -> String { // Trim trailing spaces. let trimmedString = self.trimmingCharacters(in: .whitespacesAndNewlines) @@ -86,7 +86,7 @@ extension Array: Truncatable { /// - Parameter length: The maximum number of items that an `Array` can /// have before it truncates. /// - Returns: A new `Array` that contains the maximum number of items or less. - func truncated(toLength length: Int) -> Array { + public func truncated(toLength length: Int) -> Array { return Array(self.prefix(length)) } } @@ -97,7 +97,7 @@ extension Encodable { /// Converts an object into a JSON object. /// /// - Returns: A JSON object. - func toJsonData() throws -> Data? { + public func toJsonData() throws -> Data? { return try JSONEncoder().encode(self) } } @@ -112,7 +112,7 @@ extension UInt64 { /// the characters `234567abcdefghijklmnopqrstuvwxyz` and is 13 characters in length. /// /// - Returns: A `String` that's encoded in a Base32-sortable format. - func toBase32Sortable() -> String { + public func toBase32Sortable() -> String { let base32Characters = "234567abcdefghijklmnopqrstuvwxyz" var number = self var encoded = "" @@ -132,7 +132,7 @@ extension UInt64 { extension Data { /// Returns an array of `UInt8` objects. - var bytes: [UInt8] { + public var bytes: [UInt8] { return [UInt8](self) } }