diff --git a/apps/sylo-ios/SyloKit/Sources/SyloKit/Access/ModeratorView.swift b/apps/sylo-ios/SyloKit/Sources/SyloKit/Access/ModeratorView.swift new file mode 100644 index 00000000..7dd0c8d5 --- /dev/null +++ b/apps/sylo-ios/SyloKit/Sources/SyloKit/Access/ModeratorView.swift @@ -0,0 +1,177 @@ +import Foundation + +// The focused moderator view (Sylo 5.3, `moderator-view` in `GET /api/mobile/info`). A person whose level in a +// server is Inbox lands on the inbox and sees only the moderation tools their level allows, instead of the full +// app with its settings locked. View keeps the full read-only app (observers need the whole picture) and Edit is +// unchanged. An Inbox person can choose "Show everything" to get the full, still locked, app back. Nothing changes +// on the server: the level is `access` of each server in `GET /api/v2/guilds`, and the server enforces it on every +// route. The rules here follow the web dashboard's (web-v2/src/overviewModel.js, `navModel` with `focused`): +// the inboxes whose module is on (Tickets, Appeals, Applications, Suggestions), the Moderation hub and Member +// data. The audit log, the leaderboard, the insights, the module settings and the server settings are not in it. +// A server that does not announce `moderator-view` (Sylo 5.2 and older, self-hosted ones) keeps the full app. + +extension ServerFeature { + /// The web dashboard's focused view for Inbox-level people; the app follows the same rules. + public static let moderatorView = ServerFeature(rawValue: "moderator-view") +} + +public enum ModeratorView { + /// The device's choice to see everything instead of the focused view (one choice for the device, as the + /// web keeps one for the browser). + public static let showEverythingKey = "moderatorView.showEverything" + + /// What a server screen shows the signed-in person. + public enum Mode: Equatable, Sendable { + /// The whole app (Edit, View, an unknown level, Inbox who chose "Show everything", or a server that + /// has no focused view). + case full + /// Only the moderation tools. + case focused + /// An Inbox person on a server whose features are not known yet: wait before drawing the app, so it + /// does not show the full app and then narrow it. + case undecided + } + + /// - Parameters: + /// - access: The person's level in the server; nil from a server without levels (that is Edit). + /// - supports: Whether the server announces ``ServerFeature/moderatorView``; nil while that is not known. + /// - showEverything: The person's choice to see everything. + public static func mode(access: DashboardAccess?, supports: Bool?, showEverything: Bool) -> Mode { + guard access == DashboardAccess.inbox else { return .full } + switch supports { + case .some(true): return showEverything ? .full : .focused + case .some(false): return .full + case .none: return .undecided + } + } + + /// How long an Inbox person waits for the server's features before the app draws as it would without them. + public static let featureWait: Duration = .seconds(3) + + /// Whether the server announces ``ServerFeature/moderatorView``; nil only while that is really not known. An + /// Inbox person on a server that does not announce it (Sylo 5.2, self-hosted) never waits: the sign-in's own + /// read of the server already says so (`serverInfoKnown`), a finished read of the features says so + /// (`featuresRead`, whether it worked or not), and after ``featureWait`` the app stops waiting. + public static func supports(hasFeature: Bool, featuresRead: Bool, serverInfoKnown: Bool, waited: Bool) -> Bool? { + if hasFeature { return true } + if featuresRead || serverInfoKnown || waited { return false } + return nil + } + + /// Whether the person may switch between the focused and the full app (an Inbox person on a server that + /// has the focused view): the switch is shown only then. + public static func canChoose(access: DashboardAccess?, supports: Bool?) -> Bool { + access == DashboardAccess.inbox && supports == true + } + + // MARK: - What the focused view lists + + /// The tabs of a server screen in the focused view, in the order they are shown. + public enum Tab: Hashable, Sendable { + /// The ticket conversations (when the Tickets module is on). + case tickets + /// The rest of the queues (applications, suggestions) and Member data. + case tools + /// The Moderation hub: infractions, and ban appeals when that module is on. + case moderation + } + + /// The pages the Tools tab lists. + public enum Tool: Hashable, Sendable { + case applications + case suggestions + case memberData + } + + /// Where a server opens for an Inbox person: the first inbox that is switched on, in the order of the web + /// dashboard (tickets, appeals, applications, suggestions), else the Moderation hub. + public enum Landing: Hashable, Sendable { + case tickets + /// The Moderation tab, on its Appeals part. + case appeals + case applications + case moderationHub + + /// The tab this lands on. + public var tab: Tab { + switch self { + case .tickets: .tickets + case .appeals, .moderationHub: .moderation + case .applications: .tools + } + } + } + + /// Whether a module is on. A card the overview does not list counts as on (as on the web), and so does every + /// module while the overview is not known. + public static func isModuleOn(_ id: String, in overview: ServerOverview?) -> Bool { + guard let card = overview?.groups.lazy.flatMap(\.cards).first(where: { $0.id == id }) else { return true } + return !(card.hasToggle && card.isEnabled != true) + } + + public static func tabs(overview: ServerOverview?) -> [Tab] { + var tabs: [Tab] = [] + if isModuleOn("tickets", in: overview) { tabs.append(.tickets) } + tabs.append(.tools) + tabs.append(.moderation) + return tabs + } + + public static func tools(overview: ServerOverview?) -> [Tool] { + var tools: [Tool] = [] + if isModuleOn("applications", in: overview) { tools.append(.applications) } + if isModuleOn("suggestions", in: overview) { tools.append(.suggestions) } + tools.append(.memberData) + return tools + } + + /// Whether the Moderation tab offers the Appeals part. + public static func showsAppeals(overview: ServerOverview?) -> Bool { + isModuleOn("appeals", in: overview) + } + + public static func landing(overview: ServerOverview?) -> Landing { + if isModuleOn("tickets", in: overview) { return .tickets } + if isModuleOn("appeals", in: overview) { return .appeals } + if isModuleOn("applications", in: overview) || isModuleOn("suggestions", in: overview) { + return .applications + } + return .moderationHub + } + + /// Which part of the Moderation tab opens first in the focused view. + public enum ModerationStart: Hashable, Sendable { + case infractions + case appeals + } + + /// The Moderation tab opens on Appeals when that is where the server lands (Tickets off, Appeals on). The + /// view applies it again when the overview arrives, so it holds also when the first draw had no overview. + public static func moderationStart(overview: ServerOverview?) -> ModerationStart { + landing(overview: overview) == .appeals ? .appeals : .infractions + } + + /// The pages the search offers in the focused view (not the settings, the audit log or the insights). + public static func searchPages(overview: ServerOverview?) -> [SearchPage] { + var pages: [SearchPage] = [] + if isModuleOn("tickets", in: overview) { pages.append(.tickets) } + if showsAppeals(overview: overview) { pages.append(.appeals) } + pages.append(.moderation) + pages.append(.memberData) + return pages + } + + /// The overview the search sees in the focused view: only the two queues that are modules (the + /// applications and the suggestions), so module settings and the rest are not offered. + public static func searchOverview(_ overview: ServerOverview?) -> ServerOverview? { + guard let overview else { return nil } + let queues: Set = ["applications", "suggestions"] + let groups = overview.groups.compactMap { group -> OverviewGroup? in + let cards = group.cards.filter { queues.contains($0.id) } + return cards.isEmpty ? nil : OverviewGroup(title: group.title, cards: cards) + } + return ServerOverview( + server: overview.server, openTickets: overview.openTickets, openAppeals: overview.openAppeals, + groups: groups, attention: nil) + } +} diff --git a/apps/sylo-ios/SyloKit/Sources/SyloKit/Health/HealthModels.swift b/apps/sylo-ios/SyloKit/Sources/SyloKit/Health/HealthModels.swift index b923118d..7863fed3 100644 --- a/apps/sylo-ios/SyloKit/Sources/SyloKit/Health/HealthModels.swift +++ b/apps/sylo-ios/SyloKit/Sources/SyloKit/Health/HealthModels.swift @@ -32,10 +32,16 @@ public struct HealthReport: Decodable, Sendable, Equatable { public let backupsKept: Int? /// Where off-site copies go ("WebDAV"), or nil when there are none. public let offsite: String? + /// Rights of the Postgres role Sylo connects as that are more than it needs ("SUPERUSER", ...); empty when + /// the role is fine or the database is SQLite. nil when the server did not send the list (Sylo 5.2 and + /// older), which is also how the app tells that a restore must not be sent a ``RestoreConfirmation``. + public let roleRisks: [String]? + /// The docs on setting up a role with few rights, when the server sent them. + public let roleDocsURL: URL? public init( size: String? = nil, wal: String? = nil, isPostgres: Bool = false, backupIntervalHours: Double? = nil, - backupsKept: Int? = nil, offsite: String? = nil + backupsKept: Int? = nil, offsite: String? = nil, roleRisks: [String]? = nil, roleDocsURL: URL? = nil ) { self.size = size self.wal = wal @@ -43,9 +49,13 @@ public struct HealthReport: Decodable, Sendable, Equatable { self.backupIntervalHours = backupIntervalHours self.backupsKept = backupsKept self.offsite = offsite + self.roleRisks = roleRisks + self.roleDocsURL = roleDocsURL } - private enum CodingKeys: String, CodingKey { case size, wal, postgres, intervalHours, retention, offsite } + private enum CodingKeys: String, CodingKey { + case size, wal, postgres, intervalHours, retention, offsite, roleRisks, roleDocsUrl + } public init(from decoder: any Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) @@ -55,6 +65,9 @@ public struct HealthReport: Decodable, Sendable, Equatable { backupIntervalHours = try c.decodeIfPresent(Double.self, forKey: .intervalHours) backupsKept = try c.decodeIfPresent(Int.self, forKey: .retention) offsite = try c.decodeIfPresent(String.self, forKey: .offsite) + // `try?`: a list of an odd shape reads as not sent. + roleRisks = (try? c.decodeIfPresent([String].self, forKey: .roleRisks)) ?? nil + roleDocsURL = ServerMarkdown.openable((try? c.decodeURLIfPresent(forKey: .roleDocsUrl)) ?? nil) } } diff --git a/apps/sylo-ios/SyloKit/Sources/SyloKit/Operator/Backups.swift b/apps/sylo-ios/SyloKit/Sources/SyloKit/Operator/Backups.swift index d82591d7..4d35ef00 100644 --- a/apps/sylo-ios/SyloKit/Sources/SyloKit/Operator/Backups.swift +++ b/apps/sylo-ios/SyloKit/Sources/SyloKit/Operator/Backups.swift @@ -42,13 +42,20 @@ extension Endpoints { } /// `POST /api/v2/health/backups/:name/restore`: replaces the live database with the backup and - /// restarts the bot (the server answers first, then exits). + /// restarts the bot (the server answers first, then exits). A Sylo 5.3 server wants the snapshot's name + /// as `confirm`, and `acknowledgeSql` for an uploaded Postgres dump (see ``RestorePlan``); an older server + /// takes no body, and gets none. public struct RestoreBackup: APIEndpoint { public typealias Response = OKResponse public let name: String - public init(name: String) { self.name = name } + public let confirmation: RestoreConfirmation? + public init(name: String, confirmation: RestoreConfirmation? = nil) { + self.name = name + self.confirmation = confirmation + } public var path: String { "/api/v2/health/backups/\(name.encodedPathSegment)/restore" } public var method: HTTPMethod { .post } + public var body: (any Encodable & Sendable)? { confirmation } } /// `POST /api/v2/health/backups/import`: a raw body, sent as `application/octet-stream` and streamed @@ -76,6 +83,61 @@ extension Endpoints { } } +/// What a restore request says besides the snapshot in its address (Sylo 5.3, src/db/backup.js +/// `restoreConfirmationError`). `confirm` is the snapshot's name. `acknowledgeSql` is `true` for a Postgres dump +/// that was uploaded (its name starts with `sylo-imported-`): restoring it runs the SQL in the file with the rights +/// of the database role Sylo connects as, and the server refuses it (400) unless the request says the person knows. +/// A key that is not set is not sent. +public struct RestoreConfirmation: Encodable, Sendable, Equatable { + public let confirm: String + public let acknowledgeSql: Bool? + + public init(confirm: String, acknowledgeSql: Bool? = nil) { + self.confirm = confirm + self.acknowledgeSql = acknowledgeSql + } +} + +/// What the app asks and sends for a restore of one snapshot. +public struct RestorePlan: Sendable, Equatable { + /// The snapshot is an uploaded Postgres dump: restoring it runs the SQL in the file. The app explains that and + /// wants the person to say they know, whatever the server's version. + public let isUploadedSqlDump: Bool + /// The body to send; nil for a server that did not say it wants one (Sylo 5.2 and older, which take none). + public let confirmation: RestoreConfirmation? + + public init(isUploadedSqlDump: Bool, confirmation: RestoreConfirmation?) { + self.isUploadedSqlDump = isUploadedSqlDump + self.confirmation = confirmation + } + + /// The name an uploaded snapshot is stored under (`sylo-imported-...`). + public static func isImported(_ name: String) -> Bool { name.hasPrefix("sylo-imported-") } + + /// The plan for `name` on a server whose health report has this `database`. The 5.3 server sends `roleRisks` + /// (an empty list when the role is fine); a server without it is not sent the new keys. + public static func make(name: String, database: HealthReport.Database?) -> RestorePlan { + let sql = database?.isPostgres == true && isImported(name) + let wantsConfirmation = database?.roleRisks != nil + return RestorePlan( + isUploadedSqlDump: sql, + confirmation: wantsConfirmation ? RestoreConfirmation(confirm: name, acknowledgeSql: sql ? true : nil) : nil) + } +} + +/// What the app says before it restores an uploaded Postgres dump, in the dashboard's words. +public enum UploadedDumpNotice { + public static let title = "This file was uploaded" + public static let message = "A Postgres dump holds SQL, and restoring it runs that SQL with the rights of the database role Sylo connects as. Inside Sylo's own database that adds nothing an operator cannot already do, because a restore replaces the whole database. A role with more rights can also reach the database server's own system. Restore only a file you made or trust." + public static let acknowledgement = "I made this file or I trust it" + + /// The role's extra rights as a sentence, nil when there are none. + public static func roleSentence(_ risks: [String]?) -> String? { + guard let risks, !risks.isEmpty else { return nil } + return "The database role Sylo connects as has more rights than it needs: \(risks.joined(separator: ", ")). A restored dump runs its SQL with those rights." + } +} + /// The Backups screen: the list, and creating, deleting and restoring. @MainActor @Observable @@ -162,13 +224,19 @@ public final class BackupsModel { /// it had), which the session handles like any other 401. /// - Returns: Whether the server took the restore. @discardableResult - public func restore(_ name: String, typed: String) async -> Bool { + public func restore(_ name: String, typed: String, acknowledgedSql: Bool = false) async -> Bool { guard confirmed(.restore(backup: name), typed) else { return false } + // An uploaded Postgres dump runs its SQL with the database role's rights: the person has to say they know. + let plan = RestorePlan.make(name: name, database: report?.database) + if plan.isUploadedSqlDump, !acknowledgedSql { + actionError = "Confirm that you made this file or trust it before it is restored." + return false + } // Where the old process stands, to tell it from a restarted one afterwards. let before = await uptimeBeforeRestore() let logBaseline = await newestErrorID() let started = await change { generation in - _ = try await self.session.send(Endpoints.RestoreBackup(name: name)) + _ = try await self.session.send(Endpoints.RestoreBackup(name: name, confirmation: plan.confirmation)) guard self.session.generation == generation else { return } self.restoring = name } diff --git a/apps/sylo-ios/SyloKit/Sources/SyloKit/PublicLook/PublicPageLook.swift b/apps/sylo-ios/SyloKit/Sources/SyloKit/PublicLook/PublicPageLook.swift new file mode 100644 index 00000000..87e5d624 --- /dev/null +++ b/apps/sylo-ios/SyloKit/Sources/SyloKit/PublicLook/PublicPageLook.swift @@ -0,0 +1,656 @@ +import Foundation +import Observation + +// The server's look on its public member pages (Sylo 5.3, `public-page-look` in `GET /api/mobile/info`; +// src/web/routes/v2PublicLook.js, Server settings -> Public pages). The pages members open without the dashboard +// (the application form and the web shop, the ban appeal, the quote page and the leaderboards) can take the +// server's accent colour and a background, and nothing else: the layout, the type, the light and dark themes and the +// "Powered by Sylo" link stay Sylo's, and the dashboard and the app are never restyled. Edit level only, the read +// too. A server that does not announce `public-page-look` has none of these routes, so the app shows nothing. + +extension ServerFeature { + /// `GET` and `POST /api/v2/guilds/:id/public-page-look`, the background upload and the invite-background check. + public static let publicPageLook = ServerFeature(rawValue: "public-page-look") +} + +/// What a server may choose for the background of its public pages. +public enum PublicPageBackground: Hashable, Sendable, RawRepresentable, Codable { + case noBackground + /// A picture the server uploaded. + case upload + /// A copy of the server's invite background (Discord and Fluxer both have one, and a server may not have set it). + case discordSplash + /// A value a newer Sylo adds. The app does not offer it, and reads it as it is sent. + case other(String) + + public init(rawValue: String) { + switch rawValue { + case "none": self = .noBackground + case "upload": self = .upload + case "discord-splash": self = .discordSplash + default: self = .other(rawValue) + } + } + + public var rawValue: String { + switch self { + case .noBackground: "none" + case .upload: "upload" + case .discordSplash: "discord-splash" + case .other(let raw): raw + } + } + + public init(from decoder: any Decoder) throws { + self.init(rawValue: try decoder.singleValueContainer().decode(String.self)) + } + + public func encode(to encoder: any Encoder) throws { + var c = encoder.singleValueContainer() + try c.encode(rawValue) + } +} + +/// A value for each of Sylo's two themes. +public struct ThemePair: Decodable, Sendable, Equatable { + public let dark: Value + public let light: Value + + public init(dark: Value, light: Value) { + self.dark = dark + self.light = light + } +} + +/// `GET /api/v2/guilds/:id/public-page-look`, and the answer of every other call here. +public struct PublicPageLook: Decodable, Sendable, Equatable { + public struct Upload: Decodable, Sendable, Equatable { + public let bytes: Int + /// A path on the Sylo server (`/look/..webp`); the app loads it through the session. + public let url: String + + public init(bytes: Int, url: String) { + self.bytes = bytes + self.url = url + } + + private enum CodingKeys: String, CodingKey { case bytes, url } + + public init(from decoder: any Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + bytes = (try? c.decodeIfPresent(Int.self, forKey: .bytes)) ?? 0 + url = try c.decode(String.self, forKey: .url) + } + } + + public struct Splash: Decodable, Sendable, Equatable { + /// The server has an invite background on its platform. + public let isAvailable: Bool + /// The path of Sylo's own copy, nil until it was downloaded. + public let copiedURL: String? + + public init(isAvailable: Bool = false, copiedURL: String? = nil) { + self.isAvailable = isAvailable + self.copiedURL = copiedURL + } + + private enum CodingKeys: String, CodingKey { case available, copied } + private struct Copy: Decodable { let url: String? } + + public init(from decoder: any Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + isAvailable = (try? c.decodeIfPresent(Bool.self, forKey: .available)) ?? false + let copy = (try? c.decodeIfPresent(Copy.self, forKey: .copied)) ?? nil + copiedURL = copy?.url + } + } + + /// What the choice comes to on the pages. + public struct Effective: Decodable, Sendable, Equatable { + /// The accent used for fills and borders, per theme. + public let accent: ThemePair? + /// The colour used for text, per theme. + public let accentText: ThemePair? + /// The themes where the accent is too hard to read and Sylo's own colour is used instead. + public let fallback: [String] + /// The sentence to show when ``fallback`` is not empty. + public let note: String? + /// The path of the picture of the chosen background. + public let backgroundURL: String? + + public init( + accent: ThemePair? = nil, accentText: ThemePair? = nil, fallback: [String] = [], + note: String? = nil, backgroundURL: String? = nil + ) { + self.accent = accent + self.accentText = accentText + self.fallback = fallback + self.note = note + self.backgroundURL = backgroundURL + } + + private enum CodingKeys: String, CodingKey { case accent, accentText, fallback, note, backgroundUrl } + + public init(from decoder: any Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + accent = (try? c.decodeIfPresent(ThemePair.self, forKey: .accent)) ?? nil + accentText = (try? c.decodeIfPresent(ThemePair.self, forKey: .accentText)) ?? nil + fallback = (try? c.decodeIfPresent([String].self, forKey: .fallback)) ?? [] + note = (try? c.decodeIfPresent(String.self, forKey: .note)) ?? nil + backgroundURL = (try? c.decodeIfPresent(String.self, forKey: .backgroundUrl)) ?? nil + } + } + + /// What the server holds an upload to. + public struct Limits: Decodable, Sendable, Equatable { + public let maxBytes: Int + public let maxSide: Int + + public init(maxBytes: Int = 2 * 1024 * 1024, maxSide: Int = 1920) { + self.maxBytes = maxBytes + self.maxSide = maxSide + } + + private enum CodingKeys: String, CodingKey { case maxBytes, maxSide } + + public init(from decoder: any Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + maxBytes = (try? c.decodeIfPresent(Int.self, forKey: .maxBytes)) ?? 2 * 1024 * 1024 + maxSide = (try? c.decodeIfPresent(Int.self, forKey: .maxSide)) ?? 1920 + } + } + + /// The saved accent as `#rrggbb`, or empty for Sylo's own. + public let accent: String + public let background: PublicPageBackground + /// The values the server takes for ``background``; the three known ones when it did not say. + public let backgrounds: [PublicPageBackground] + public let platform: Platform? + public let upload: Upload? + public let splash: Splash + public let effective: Effective + /// Sylo's own accent per theme, for the preview when there is no accent of the server's. + public let syloAccent: ThemePair? + public let limits: Limits + + public init( + accent: String = "", background: PublicPageBackground = .noBackground, + backgrounds: [PublicPageBackground] = PublicPageLook.knownBackgrounds, platform: Platform? = nil, + upload: Upload? = nil, splash: Splash = Splash(), effective: Effective = Effective(), + syloAccent: ThemePair? = nil, limits: Limits = Limits() + ) { + self.accent = accent + self.background = background + self.backgrounds = backgrounds + self.platform = platform + self.upload = upload + self.splash = splash + self.effective = effective + self.syloAccent = syloAccent + self.limits = limits + } + + public static let knownBackgrounds: [PublicPageBackground] = [.noBackground, .upload, .discordSplash] + + private enum CodingKeys: String, CodingKey { + case accent, background, backgrounds, platform, upload, splash, effective, sylo, limits + } + + private struct SyloBlock: Decodable { let accent: ThemePair? } + + public init(from decoder: any Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + accent = (try? c.decodeIfPresent(String.self, forKey: .accent)) ?? "" + background = (try? c.decodeIfPresent(PublicPageBackground.self, forKey: .background)) ?? .noBackground + let listed = (try? c.decodeIfPresent([PublicPageBackground].self, forKey: .backgrounds)) ?? nil + backgrounds = listed.flatMap { $0.isEmpty ? nil : $0 } ?? Self.knownBackgrounds + platform = (try? c.decodeIfPresent(Platform.self, forKey: .platform)) ?? nil + upload = (try? c.decodeIfPresent(Upload.self, forKey: .upload)) ?? nil + splash = (try? c.decodeIfPresent(Splash.self, forKey: .splash)) ?? Splash() + effective = (try? c.decodeIfPresent(Effective.self, forKey: .effective)) ?? Effective() + syloAccent = ((try? c.decodeIfPresent(SyloBlock.self, forKey: .sylo)) ?? nil)?.accent + limits = (try? c.decodeIfPresent(Limits.self, forKey: .limits)) ?? Limits() + } + + /// The picture a background choice shows, as a path on the server; nil for none or a picture not there yet. + public func imagePath(for background: PublicPageBackground) -> String? { + switch background { + case .upload: upload?.url + case .discordSplash: splash.copiedURL + case .noBackground, .other: nil + } + } + + /// The backgrounds the picker offers: what the server takes, and only the invite background when this server has + /// one (or has chosen it already, so the choice never silently vanishes). A value the app does not know is not + /// offered. + public func offeredBackgrounds(chosen: PublicPageBackground) -> [PublicPageBackground] { + backgrounds.filter { value in + switch value { + case .noBackground, .upload: true + case .discordSplash: splash.isAvailable || chosen == .discordSplash + case .other: false + } + } + } +} + +/// What `POST .../public-page-look` takes. Both keys, as the dashboard sends them. +public struct PublicPageLookChoice: Encodable, Sendable, Equatable { + /// `#rrggbb`, or empty for Sylo's own colour. + public let accent: String + public let background: PublicPageBackground + + public init(accent: String, background: PublicPageBackground) { + self.accent = accent + self.background = background + } +} + +// MARK: - The accent colour + +/// The accent colour rules of the server (src/lib/publicLook.js), for a preview before saving: what is a colour, +/// whether it reads on the card in each theme, and the sentence when it does not. The server decides on save; this +/// only shows the same answer sooner. +public enum AccentColour { + /// The card the form sits on, per theme (`--bg-surface` of the public pages). + public static let card = ThemePair(dark: "#161618", light: "#ffffff") + /// Sylo's own accent per theme. + public static let syloAccent = ThemePair(dark: "#38c8f0", light: "#076787") + /// The page colour behind the card, per theme. + public static let page = ThemePair(dark: "#0b0b0d", light: "#f5f5f7") + /// The least contrast an accent needs against the card to be used at all (WCAG for interface elements). + public static let minimumContrast = 3.0 + /// The least contrast of accent text (WCAG AA). + public static let minimumTextContrast = 4.5 + + /// The colour as `#rrggbb` in lower case, empty for none, or nil when it is not a colour. Accepts `#rgb`, + /// `#rrggbb` and the same without the `#`. + public static func normalise(_ text: String) -> String? { + let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) + if trimmed.isEmpty { return "" } + var digits = Substring(trimmed) + if digits.hasPrefix("#") { digits = digits.dropFirst() } + guard digits.count == 3 || digits.count == 6, digits.allSatisfy({ $0.isASCII && $0.isHexDigit }) else { + return nil + } + var hex = digits.lowercased() + if hex.count == 3 { hex = hex.map { "\($0)\($0)" }.joined() } + return "#" + hex + } + + /// A colour picker's red, green and blue (0 to 1, clamped) as `#rrggbb`. + public static func hex(red: Double, green: Double, blue: Double) -> String { + func byte(_ value: Double) -> Int { Int((min(max(value, 0), 1) * 255).rounded()) } + let packed = (byte(red) << 16) | (byte(green) << 8) | byte(blue) + let digits = String(packed, radix: 16) + return "#" + String(repeating: "0", count: 6 - digits.count) + digits + } + + /// The red, green and blue of a `#rrggbb` colour, 0 to 255; nil when it is not one. + public static func components(_ hex: String) -> (red: Int, green: Int, blue: Int)? { + guard hex.count == 7, hex.hasPrefix("#"), let value = Int(hex.dropFirst(), radix: 16) else { return nil } + return ((value >> 16) & 255, (value >> 8) & 255, value & 255) + } + + /// The relative luminance of a `#rrggbb` colour (WCAG 2). + public static func luminance(_ hex: String) -> Double { + guard let rgb = components(hex) else { return 0 } + func channel(_ value: Int) -> Double { + let v = Double(value) / 255 + return v <= 0.03928 ? v / 12.92 : pow((v + 0.055) / 1.055, 2.4) + } + return 0.2126 * channel(rgb.red) + 0.7152 * channel(rgb.green) + 0.0722 * channel(rgb.blue) + } + + /// The contrast ratio of two `#rrggbb` colours, 1 to 21. + public static func contrast(_ a: String, _ b: String) -> Double { + let first = luminance(a) + let second = luminance(b) + return (max(first, second) + 0.05) / (min(first, second) + 0.05) + } + + /// The ratio of an accent to the card in a theme, rounded to two places as the server does. + public static func ratio(of accent: String, dark: Bool) -> Double { + let value = contrast(accent, dark ? card.dark : card.light) + return (value * 100).rounded() / 100 + } + + /// The themes where the accent is too hard to read on the card, so Sylo's own colour is used (`dark`, `light`). + /// Empty for no accent. + public static func fallbackThemes(_ accent: String) -> [String] { + guard !accent.isEmpty, components(accent) != nil else { return [] } + var themes: [String] = [] + // The raw ratio decides, as on the server; the rounded one is only for showing. + if contrast(accent, card.dark) < minimumContrast { themes.append("dark") } + if contrast(accent, card.light) < minimumContrast { themes.append("light") } + return themes + } + + /// The sentence that says Sylo's accent is used, or nil when the colour is fine everywhere. + public static func fallbackNote(_ accent: String) -> String? { + let themes = fallbackThemes(accent) + guard !themes.isEmpty else { return nil } + let place = themes.count == 2 ? "both the light and the dark theme" : "the \(themes[0]) theme" + return "This colour is too hard to read on the card in \(place), so public pages use Sylo's own colour there. Pick a darker or lighter shade." + } + + /// The colour of the text on a button of this accent: black or white, whichever reads better. + public static func onAccent(_ accent: String) -> String { + contrast(accent, "#ffffff") >= contrast(accent, "#000000") ? "#ffffff" : "#000000" + } + + /// The accent really used for fills in a theme: the chosen one where it is readable, else Sylo's own. + public static func effective(_ accent: String, dark: Bool) -> String { + let fallback = dark ? syloAccent.dark : syloAccent.light + guard !accent.isEmpty, components(accent) != nil else { return fallback } + return contrast(accent, dark ? card.dark : card.light) >= minimumContrast ? accent : fallback + } + + /// The colour `t` (0 to 1) of the way from `a` to `b`, both `#rrggbb`. + public static func mix(_ a: String, _ b: String, _ t: Double) -> String { + guard let x = components(a), let y = components(b) else { return a } + func channel(_ from: Int, _ to: Int) -> Int { + let value = min(255, max(0, Double(from) + (Double(to) - Double(from)) * t)) + // Like JavaScript's Math.round: halves go up. + return Int((value + 0.5).rounded(.down)) + } + let packed = (channel(x.red, y.red) << 16) | (channel(x.green, y.green) << 8) | channel(x.blue, y.blue) + let digits = String(packed, radix: 16) + return "#" + String(repeating: "0", count: 6 - digits.count) + digits + } + + /// The accent as a text colour in a theme (links, labels): the accent itself when it reaches 4.5:1 against the + /// card, the page and both tinted with the accent, else the same hue mixed toward white (dark theme) or black + /// (light theme) in small steps until it does. The same steps as the server (`accentText`). + public static func accentText(_ accent: String, dark: Bool) -> String { + guard components(accent) != nil else { return accent } + let card = dark ? Self.card.dark : Self.card.light + let page = dark ? Self.page.dark : Self.page.light + let backs = [card, page, mix(card, accent, 0.14), mix(page, accent, 0.14)] + func reads(_ colour: String) -> Bool { backs.allSatisfy { contrast(colour, $0) >= minimumTextContrast } } + if reads(accent) { return accent } + let target = dark ? "#ffffff" : "#000000" + var t = 0.02 + while t < 1 { + let candidate = mix(accent, target, t) + if reads(candidate) { return candidate } + t += 0.02 + } + return target + } + + /// The text colour really used in a theme: ``accentText(_:dark:)`` where the accent is used, else Sylo's own. + public static func effectiveText(_ accent: String, dark: Bool) -> String { + let fallback = dark ? syloAccent.dark : syloAccent.light + guard !accent.isEmpty, components(accent) != nil else { return fallback } + let fits = contrast(accent, dark ? card.dark : card.light) >= minimumContrast + return fits ? accentText(accent, dark: dark) : fallback + } +} + +// MARK: - Calls + +extension Endpoints { + static func publicLookPath(_ server: ServerID, _ tail: String = "") -> String { + "/api/v2/guilds/\(server.pathComponent)/public-page-look\(tail)" + } + + /// `GET .../public-page-look`: the choice and what it comes to. Edit level. + public struct LoadPublicLook: APIEndpoint { + public typealias Response = PublicPageLook + public let server: ServerID + public init(server: ServerID) { self.server = server } + public var path: String { Endpoints.publicLookPath(server) } + } + + /// `POST .../public-page-look` with `{accent, background}`; answers like the `GET`. 400 for a colour that is not + /// `#rgb` or `#rrggbb`, for `upload` with no picture and for `discord-splash` when the server has none; 502 + /// when the invite background could not be downloaded. + public struct SavePublicLook: APIEndpoint { + public typealias Response = PublicPageLook + public let server: ServerID + public let choice: PublicPageLookChoice + public init(server: ServerID, choice: PublicPageLookChoice) { + self.server = server + self.choice = choice + } + public var path: String { Endpoints.publicLookPath(server) } + public var method: HTTPMethod { .post } + public var body: (any Encodable & Sendable)? { choice } + } + + /// `POST .../public-page-look/image`: a multipart upload (the field `file`: PNG, JPEG or WebP, at most 2 MB, at + /// most 16 megapixels). It does not change the choice: save `"background": "upload"` after it. Never retried. + public struct UploadPublicLookImage: APIEndpoint { + public typealias Response = PublicPageLook + public let server: ServerID + public let form: MultipartForm + + public init(server: ServerID, picture: PreparedPicture, boundary: String? = nil) { + self.server = server + var form = boundary.map { MultipartForm(boundary: $0) } ?? MultipartForm() + form.addFile(name: "file", filename: picture.filename, mimeType: picture.mimeType, data: picture.data) + self.form = form + } + + public var path: String { Endpoints.publicLookPath(server, "/image") } + public var method: HTTPMethod { .post } + public var rawBody: RawBody? { form.rawBody } + } + + /// `POST .../public-page-look/image/delete`: deletes the uploaded picture (a choice of `upload` falls back to + /// `none` on the server). + public struct DeletePublicLookImage: APIEndpoint { + public typealias Response = PublicPageLook + public let server: ServerID + public init(server: ServerID) { self.server = server } + public var path: String { Endpoints.publicLookPath(server, "/image/delete") } + public var method: HTTPMethod { .post } + } + + /// `POST .../public-page-look/splash/refresh`: checks the invite background against the platform now. Six a + /// minute. + public struct RefreshPublicLookSplash: APIEndpoint { + public typealias Response = PublicPageLook + public let server: ServerID + public init(server: ServerID) { self.server = server } + public var path: String { Endpoints.publicLookPath(server, "/splash/refresh") } + public var method: HTTPMethod { .post } + } +} + +// MARK: - The model + +/// The Public pages screen: what is saved, what the person has changed, and the calls that save it. +@MainActor +@Observable +public final class PublicLookModel { + public let server: ServerID + public private(set) var look: PublicPageLook? + public private(set) var isLoading = false + public private(set) var isSaving = false + /// A picture upload, a removal or an invite-background check is on its way. + public private(set) var isWorking = false + /// Why the screen could not be loaded. + public var errorMessage: String? + /// Why the last save, upload or removal did not go through. + public var actionError: String? + /// Bumped after every save, for the success feedback. + public private(set) var saveCount = 0 + + /// What was typed in the colour field, nil while it shows the saved colour. + private var accentDraft: String? + private var backgroundDraft: PublicPageBackground? + + private let session: AppSession + + public init(server: ServerID, session: AppSession) { + self.server = server + self.session = session + } + + // MARK: Draft + + /// The text of the colour field. + public var accentText: String { + get { accentDraft ?? look?.accent ?? "" } + set { accentDraft = newValue } + } + + /// The chosen background. + public var background: PublicPageBackground { + get { backgroundDraft ?? look?.background ?? .noBackground } + set { backgroundDraft = newValue } + } + + /// The colour as `#rrggbb` (empty for Sylo's own), or nil while the field does not hold a colour. + public var accent: String? { AccentColour.normalise(accentText) } + + public var accentIsValid: Bool { accent != nil } + + /// The sentence about the colour: the server's while the colour is the saved one, else the same rule worked + /// out here. Nil when the colour is fine in both themes. + public var accentNote: String? { + guard let accent else { return nil } + if accent == look?.accent { return look?.effective.note } + return AccentColour.fallbackNote(accent) + } + + /// The picture the chosen background shows, as a path on the server. + public var previewImagePath: String? { look?.imagePath(for: background) } + + /// Whether the invite background was chosen but Sylo has no copy yet (it is downloaded when saved). + public var waitsForSplash: Bool { background == .discordSplash && look?.splash.copiedURL == nil } + + public var hasChanges: Bool { + guard let look, let accent else { return false } + return accent != look.accent || background != look.background + } + + public var canSave: Bool { hasChanges && !isSaving && !isWorking } + + /// The backgrounds to offer. + public var offeredBackgrounds: [PublicPageBackground] { + look?.offeredBackgrounds(chosen: background) ?? PublicPageLook.knownBackgrounds + } + + public func discardChanges() { + accentDraft = nil + backgroundDraft = nil + } + + // MARK: Calls + + public func load() async { + isLoading = true + defer { isLoading = false } + let generation = session.generation + do { + let loaded = try await session.send(Endpoints.LoadPublicLook(server: server)) + guard session.generation == generation else { return } + look = loaded + errorMessage = nil + } catch { + guard session.generation == generation else { return } + if let text = describe(error) { errorMessage = text } + } + } + + /// Saves the colour and the background. Nothing is sent while the colour is not one. + @discardableResult + public func save() async -> Bool { + guard canSave, let accent else { return false } + isSaving = true + defer { isSaving = false } + actionError = nil + let generation = session.generation + do { + let saved = try await session.send( + Endpoints.SavePublicLook(server: server, choice: PublicPageLookChoice(accent: accent, background: background))) + guard session.generation == generation else { return false } + look = saved + discardChanges() + saveCount += 1 + return true + } catch { + guard session.generation == generation else { return false } + actionError = describe(error) + return false + } + } + + /// Uploads the picture as the server's own background, and chooses it (still to be saved). + @discardableResult + public func upload(_ picture: PreparedPicture) async -> Bool { + guard !isWorking, !isSaving else { return false } + isWorking = true + defer { isWorking = false } + actionError = nil + let generation = session.generation + do { + let answer = try await session.upload(Endpoints.UploadPublicLookImage(server: server, picture: picture)) + guard session.generation == generation else { return false } + look = answer + backgroundDraft = .upload + return true + } catch { + guard session.generation == generation else { return false } + actionError = describe(error) + return false + } + } + + /// Deletes the uploaded picture. A choice of it that was not saved yet goes back to none. + @discardableResult + public func removePicture() async -> Bool { + guard !isWorking, !isSaving else { return false } + isWorking = true + defer { isWorking = false } + actionError = nil + let generation = session.generation + do { + let answer = try await session.send(Endpoints.DeletePublicLookImage(server: server)) + guard session.generation == generation else { return false } + look = answer + // A picture that is gone cannot stay chosen; whatever else was changed stays. + if background == .upload { backgroundDraft = nil } + return true + } catch { + guard session.generation == generation else { return false } + actionError = describe(error) + return false + } + } + + /// Checks the invite background against the platform now. + @discardableResult + public func refreshSplash() async -> Bool { + guard !isWorking, !isSaving else { return false } + isWorking = true + defer { isWorking = false } + actionError = nil + let generation = session.generation + do { + let answer = try await session.send(Endpoints.RefreshPublicLookSplash(server: server)) + guard session.generation == generation else { return false } + look = answer + return true + } catch { + guard session.generation == generation else { return false } + actionError = describe(error) + return false + } + } + + /// The sentence for a failure; nil for a cancelled call or a sign-out (which the session handles). + private func describe(_ error: any Error) -> String? { + let error = NetworkError(error) + switch error { + case .cancelled, .unauthorized: return nil + case .tooLarge: return "The picture is larger than the server takes (\(look?.limits.maxBytes ?? 2 * 1024 * 1024) bytes). Choose a smaller one." + case .forbidden: return "Only people with Edit access can change how the public pages look." + default: return error.userMessage + } + } +} diff --git a/apps/sylo-ios/SyloKit/Sources/SyloKit/Update/UpdateNotice.swift b/apps/sylo-ios/SyloKit/Sources/SyloKit/Update/UpdateNotice.swift new file mode 100644 index 00000000..211df07b --- /dev/null +++ b/apps/sylo-ios/SyloKit/Sources/SyloKit/Update/UpdateNotice.swift @@ -0,0 +1,631 @@ +import Foundation +import Observation + +// The operators' update notice (Sylo 5.3, `update-notice` in `GET /api/mobile/info`; src/web/routes/v2Update.js): +// whether a newer Sylo release is out, what is in it and the command to update by hand, and, when the instance runs +// Wise Wren, "Update now" with the progress of the run. Everything here is for operators only: the server answers +// anyone else 403, and the app shows it only to an operator. Sylo restarts during an update, so the requests fail +// for a while; the app keeps asking until the run is finished or Sylo reports another version. + +extension ServerFeature { + /// `GET /api/v2/update`, and with Wise Wren set up `POST /api/v2/update/wren/approve` and + /// `GET /api/v2/update/wren/runs/:id`. Operators only. + public static let updateNotice = ServerFeature(rawValue: "update-notice") +} + +/// What `GET /api/v2/update` answers. Every field has a default, so a server of another version still reads. +public struct UpdateStatus: Decodable, Sendable, Equatable { + /// False when the instance runs with `UPDATE_CHECK=off`: there is nothing else to show then. + public let isEnabled: Bool + /// The version that runs, for example `5.2.0`. + public let current: String + /// The newest release, nil when it was never read. + public let latest: String? + /// Whether `latest` is newer than `current`. + public let isAvailable: Bool + /// The last look at GitHub failed (`latest` then holds an earlier answer, if there was one). + public let checkFailed: Bool + public let releaseURL: URL? + /// The release notes, only while an update is available. Shown as text, never as HTML. + public let notes: ChangelogRelease? + /// Release notes that are not in the usual format, as plain text. + public let notesText: String? + /// What to run by hand. + public let command: String + /// Wise Wren, nil when it is not set up. + public let wren: WrenStatus? + + public static let defaultCommand = "docker compose pull && docker compose up -d" + + public init( + isEnabled: Bool = true, current: String = "", latest: String? = nil, isAvailable: Bool = false, + checkFailed: Bool = false, releaseURL: URL? = nil, notes: ChangelogRelease? = nil, notesText: String? = nil, + command: String = UpdateStatus.defaultCommand, wren: WrenStatus? = nil + ) { + self.isEnabled = isEnabled + self.current = current + self.latest = latest + self.isAvailable = isAvailable + self.checkFailed = checkFailed + self.releaseURL = releaseURL + self.notes = notes + self.notesText = notesText + self.command = command + self.wren = wren + } + + private enum CodingKeys: String, CodingKey { + case enabled, current, latest, available, checkFailed, releaseUrl, notes, notesText, command, wren + } + + public init(from decoder: any Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + isEnabled = (try? c.decodeIfPresent(Bool.self, forKey: .enabled)) ?? true + current = (try? c.decodeIfPresent(String.self, forKey: .current)) ?? "" + latest = (try? c.decodeIfPresent(String.self, forKey: .latest)) ?? nil + isAvailable = (try? c.decodeIfPresent(Bool.self, forKey: .available)) ?? false + checkFailed = (try? c.decodeIfPresent(Bool.self, forKey: .checkFailed)) ?? false + releaseURL = ServerMarkdown.openable((try? c.decodeURLIfPresent(forKey: .releaseUrl)) ?? nil) + // `try?`: notes of an odd shape must never lose the notice. + notes = (try? c.decodeIfPresent(ChangelogRelease.self, forKey: .notes)) ?? nil + notesText = (try? c.decodeIfPresent(String.self, forKey: .notesText)) ?? nil + let sent = (try? c.decodeIfPresent(String.self, forKey: .command)) ?? nil + command = (sent?.isEmpty == false ? sent : nil) ?? Self.defaultCommand + wren = (try? c.decodeIfPresent(WrenStatus.self, forKey: .wren)) ?? nil + } + + /// The sentence at the top of the notice. + public var headline: String { + if !isEnabled { return "Sylo \(current). The update check is off." } + if isAvailable, let latest { return "Sylo \(latest) is available. This Sylo runs \(current)." } + if checkFailed, latest == nil { return "Sylo \(current). The latest release could not be checked." } + return "Sylo \(current) is up to date." + } + + /// A short line for a list row. + public var summary: String { + if !isEnabled { return "Check is off" } + if isAvailable, let latest { return "\(latest) is available" } + if checkFailed, latest == nil { return "Couldn't check" } + return "Up to date" + } + + /// Whether the person should be told: a newer release, or an update that Wise Wren is running. + public var needsAttention: Bool { + if isAvailable { return true } + if let run = wren?.latestRun { return !run.isFinished } + return false + } + + /// Whether to offer "Update now": Wise Wren is set up and answers, and there is an update to approve. Whether + /// it can be pressed is the server's call (``WrenStatus/canApprove``, with the reason in ``WrenStatus/whyNot``). + public var offersUpdateNow: Bool { + guard let wren, wren.error == nil else { return false } + return isAvailable || wren.updateSeen + } +} + +/// What Wise Wren says about Sylo's target. It never holds Wise Wren's address or Sylo's token. +public struct WrenStatus: Decodable, Sendable, Equatable { + /// Wise Wren could not be asked, or does not accept Sylo's token. + public struct Problem: Decodable, Sendable, Equatable { + public let code: String + public let message: String + + public init(code: String, message: String) { + self.code = code + self.message = message + } + + private enum CodingKeys: String, CodingKey { case code, message } + + public init(from decoder: any Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + code = (try? c.decodeIfPresent(String.self, forKey: .code)) ?? "" + message = (try? c.decodeIfPresent(String.self, forKey: .message)) ?? "" + } + } + + public struct Target: Decodable, Sendable, Equatable { + public let name: String + public let status: String? + public let installedVersion: String? + public let latestVersion: String? + public let mode: String? + + public init( + name: String, status: String? = nil, installedVersion: String? = nil, latestVersion: String? = nil, + mode: String? = nil + ) { + self.name = name + self.status = status + self.installedVersion = installedVersion + self.latestVersion = latestVersion + self.mode = mode + } + + private enum CodingKeys: String, CodingKey { case name, status, installedVersion, latestVersion, mode } + + public init(from decoder: any Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + name = (try? c.decodeIfPresent(String.self, forKey: .name)) ?? "" + status = (try? c.decodeIfPresent(String.self, forKey: .status)) ?? nil + installedVersion = (try? c.decodeIfPresent(String.self, forKey: .installedVersion)) ?? nil + latestVersion = (try? c.decodeIfPresent(String.self, forKey: .latestVersion)) ?? nil + mode = (try? c.decodeIfPresent(String.self, forKey: .mode)) ?? nil + } + } + + public let error: Problem? + /// The dashboard has no login, so Update now is off unless the operator allowed it. + public let isOpenMode: Bool + public let target: Target? + /// Wise Wren sees an update, whatever the GitHub check says (they can differ for a while). + public let updateSeen: Bool + public let canApprove: Bool + /// The reason Update now is off, in words. + public let whyNot: String? + /// The run Sylo last approved. While it is not finished, Update now is off and the run is followed. + public let latestRun: WrenRun? + + public init( + error: Problem? = nil, isOpenMode: Bool = false, target: Target? = nil, updateSeen: Bool = false, + canApprove: Bool = false, whyNot: String? = nil, latestRun: WrenRun? = nil + ) { + self.error = error + self.isOpenMode = isOpenMode + self.target = target + self.updateSeen = updateSeen + self.canApprove = canApprove + self.whyNot = whyNot + self.latestRun = latestRun + } + + private enum CodingKeys: String, CodingKey { + case error, openMode, target, updateSeen, canApprove, whyNot, latestRun + } + + public init(from decoder: any Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + error = (try? c.decodeIfPresent(Problem.self, forKey: .error)) ?? nil + isOpenMode = (try? c.decodeIfPresent(Bool.self, forKey: .openMode)) ?? false + target = (try? c.decodeIfPresent(Target.self, forKey: .target)) ?? nil + updateSeen = (try? c.decodeIfPresent(Bool.self, forKey: .updateSeen)) ?? false + canApprove = (try? c.decodeIfPresent(Bool.self, forKey: .canApprove)) ?? false + whyNot = (try? c.decodeIfPresent(String.self, forKey: .whyNot)) ?? nil + latestRun = (try? c.decodeIfPresent(WrenRun.self, forKey: .latestRun)) ?? nil + } +} + +/// A Wise Wren run as the server shapes it (no step logs). +public struct WrenRun: Decodable, Sendable, Equatable { + public struct Step: Decodable, Sendable, Equatable { + public let step: String + public let status: String + + public init(step: String, status: String) { + self.step = step + self.status = status + } + + private enum CodingKeys: String, CodingKey { case step, status } + + public init(from decoder: any Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + step = (try? c.decodeIfPresent(String.self, forKey: .step)) ?? "" + status = (try? c.decodeIfPresent(String.self, forKey: .status)) ?? "" + } + } + + public let id: Int + /// `queued`, `running`, `succeeded`, `rolled_back`, `failed`, `rollback_failed`, `refused`, `cancelled`, + /// `lapsed`, or a state a newer Wise Wren adds. + public let status: String + public let isFinished: Bool + public let detail: String? + public let steps: [Step] + + /// The states in which Wise Wren is done with a run (all but `queued` and `running`). + static let finishedStatuses: Set = [ + "succeeded", "rolled_back", "failed", "rollback_failed", "refused", "cancelled", "lapsed", + ] + + public init(id: Int, status: String, isFinished: Bool? = nil, detail: String? = nil, steps: [Step] = []) { + self.id = id + self.status = status + self.isFinished = isFinished ?? Self.finishedStatuses.contains(status) + self.detail = detail + self.steps = steps + } + + private enum CodingKeys: String, CodingKey { case id, status, finished, detail, steps } + + public init(from decoder: any Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + id = try c.decode(Int.self, forKey: .id) + let status = (try? c.decodeIfPresent(String.self, forKey: .status)) ?? "queued" + self.status = status + // `finished` is the server's word; without it the status decides. + isFinished = (try? c.decodeIfPresent(Bool.self, forKey: .finished)) ?? Self.finishedStatuses.contains(status) + detail = (try? c.decodeIfPresent(String.self, forKey: .detail)) ?? nil + steps = try c.decodeLossyArray(of: Step.self, forKey: .steps) + } + + public enum Tone: Sendable, Equatable { + case working, success, failure + } + + /// What to tell the operator about the run. + public struct Description: Sendable, Equatable { + public let tone: Tone + public let text: String + /// The step it is on, while it works. + public let step: String? + } + + /// Wise Wren's step names, in words. A step it adds later shows as it is named. + public static func stepLabel(_ step: String) -> String { + switch step { + case "preflight": "Pulling the new version" + case "maintenance": "Opening the maintenance window" + case "stop": "Stopping Sylo" + case "snapshot": "Taking a snapshot of the data" + case "update": "Starting the new version" + case "health": "Checking that Sylo is healthy" + case "rollback": "Rolling back" + case "close": "Cleaning up" + default: step + } + } + + public var described: Description { + switch status { + case "queued": + return Description( + tone: .working, text: "Approved. Waiting for the Wise Wren agent to pick the update up.", step: nil) + case "running": + let current = steps.last(where: { $0.status == "running" }) ?? steps.last + let label: String? = current.flatMap { $0.step.isEmpty ? nil : Self.stepLabel($0.step) } + return Description( + tone: .working, + text: "Wise Wren is updating Sylo. Sylo restarts during this and the app reconnects by itself.", + step: label) + case "succeeded": + return Description(tone: .success, text: "Wise Wren finished the update.", step: nil) + case "rolled_back": + return Description( + tone: .failure, + text: "The new version did not come up healthy, so Wise Wren rolled back. Sylo runs the old version again.", + step: nil) + case "failed": + return Description( + tone: .failure, text: "The update failed before anything was changed. Sylo still runs the old version.", + step: nil) + case "rollback_failed": + return Description( + tone: .failure, text: "The update failed and the rollback failed too. Look at Sylo in Wise Wren now.", + step: nil) + case "refused": + return Description( + tone: .failure, + text: "The Wise Wren agent refused the update: its own settings do not allow updating Sylo.", step: nil) + case "cancelled": + return Description(tone: .failure, text: "The update was cancelled in Wise Wren.", step: nil) + case "lapsed": + return Description( + tone: .failure, text: "A newer version appeared before the update started, so it was dropped. Try again.", + step: nil) + default: + return Description(tone: .working, text: "Wise Wren is working on the update.", step: nil) + } + } +} + +/// `POST /api/v2/update/wren/approve`: the run that started, and the version it started from. +public struct UpdateStarted: Decodable, Sendable, Equatable { + public let runID: Int + public let status: String + public let from: String + + public init(runID: Int, status: String = "queued", from: String) { + self.runID = runID + self.status = status + self.from = from + } + + private enum CodingKeys: String, CodingKey { case runId, status, from } + + public init(from decoder: any Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + runID = try c.decode(Int.self, forKey: .runId) + status = (try? c.decodeIfPresent(String.self, forKey: .status)) ?? "queued" + from = (try? c.decodeIfPresent(String.self, forKey: .from)) ?? "" + } +} + +/// `GET /api/v2/update/wren/runs/:id`. +public struct UpdateRunAnswer: Decodable, Sendable, Equatable { + public let run: WrenRun + + public init(run: WrenRun) { self.run = run } +} + +extension Endpoints { + /// `GET /api/v2/update[?refresh=1]`: the update notice. Operators only. `refresh` asks GitHub again now + /// (a few times a minute at most). + public struct LoadUpdate: APIEndpoint { + public typealias Response = UpdateStatus + public let refresh: Bool + public init(refresh: Bool = false) { self.refresh = refresh } + public var path: String { "/api/v2/update" } + public var query: [URLQueryItem] { refresh ? [URLQueryItem(name: "refresh", value: "1")] : [] } + } + + /// `POST /api/v2/update/wren/approve` (no body): asks Wise Wren to update Sylo now, to exactly the version + /// Wise Wren shows. 404 when Wise Wren is not set up; 409 when there is nothing to approve, Wise Wren refuses + /// or the dashboard has no login; 502 when Wise Wren cannot be reached. Never retried. + public struct ApproveUpdate: APIEndpoint { + public typealias Response = UpdateStarted + public init() {} + public var path: String { "/api/v2/update/wren/approve" } + public var method: HTTPMethod { .post } + } + + /// `GET /api/v2/update/wren/runs/:id`: a run's progress. Up to 60 a minute. + public struct LoadUpdateRun: APIEndpoint { + public typealias Response = UpdateRunAnswer + public let id: Int + public init(id: Int) { self.id = id } + public var path: String { "/api/v2/update/wren/runs/\(id)" } + } +} + +// MARK: - The model + +/// Where the update of Sylo stands while the app follows a run. +public struct UpdateProgress: Sendable, Equatable { + public let runID: Int + /// The version the update started from. + public let from: String + public var run: WrenRun? + /// Sylo is not answering (it is restarting). + public var isSyloDown = false + /// Wise Wren answered with an error, or the progress could not be read. + public var problem: String? + /// Sylo answers again and runs another version than `from`: the update worked. + public var newVersion: String? + /// Sylo did not come back in time: somebody has to look. + public var timedOut = false + /// The model stopped asking. + public var isDone = false + + public init(runID: Int, from: String) { + self.runID = runID + self.from = from + } + + private var shownRun: WrenRun { run ?? WrenRun(id: runID, status: "queued") } + + /// What to tell the operator now. + public var text: String { + if let newVersion { return "Sylo is now on \(newVersion)." } + if isSyloDown { return "Sylo is restarting. The app keeps trying and shows the result as soon as Sylo is back." } + return shownRun.described.text + } + + public var step: String? { + guard newVersion == nil, !isSyloDown else { return nil } + return shownRun.described.step + } + + public var tone: WrenRun.Tone { + if newVersion != nil { return .success } + if isSyloDown { return .working } + return shownRun.described.tone + } +} + +/// The update notice screen: the status, "Check again", "Update now" and the progress of the run. +@MainActor +@Observable +public final class UpdateModel { + public private(set) var status: UpdateStatus? + public private(set) var isLoading = false + /// The server said this account is not an operator (403): nothing is shown. + public private(set) var isRefused = false + /// Why the status could not be read. + public var errorMessage: String? + /// "Update now" is on its way to the server. + public private(set) var isApproving = false + /// Why the last "Update now" did not start, in the server's words. + public var actionError: String? + /// The run being followed, nil when none. It stays after the run is done, until ``closeProgress()``. + public private(set) var progress: UpdateProgress? + + /// The model is asking for the progress of a run now. + public var isFollowing: Bool { following != nil } + + private let session: AppSession + private let pollEvery: Duration + private let giveUpAfter: Duration + private var following: Task? + /// Counts the runs followed, so a stopped poll never clears the reference of a newer one. + private var followCount = 0 + + /// - Parameters: + /// - pollEvery: The time between two reads of the run (the server allows 60 a minute). + /// - giveUpAfter: How long to wait for an update that has not come back before saying so. + public init(session: AppSession, pollEvery: Duration = .seconds(3), giveUpAfter: Duration = .seconds(30 * 60)) { + self.session = session + self.pollEvery = pollEvery + self.giveUpAfter = giveUpAfter + } + + /// Reads the notice. A run that is already going (started here earlier, or in Wise Wren) is followed too, also + /// when this read fails: Sylo is down while it restarts, and the person who looked away comes back to that. + /// - Parameter followsRun: False for a row that only shows the status, so nothing keeps asking for a screen + /// that is not there. + public func load(refresh: Bool = false, followsRun: Bool = true) async { + isLoading = true + let generation = session.generation + defer { + isLoading = false + if followsRun, session.generation == generation { resumeOpenRun() } + } + do { + let loaded = try await session.send(Endpoints.LoadUpdate(refresh: refresh)) + guard session.generation == generation else { return } + status = loaded + isRefused = false + errorMessage = nil + if followsRun, following == nil, progress?.isDone != true, let run = loaded.wren?.latestRun, !run.isFinished { + follow(runID: run.id, from: loaded.current) + } + } catch { + guard session.generation == generation else { return } + let error = NetworkError(error) + if OperatorOnly.isRefusal(error) { + isRefused = true + status = nil + } else if error != .cancelled, error != .unauthorized { + errorMessage = error.userMessage + } + } + } + + /// Asks Wise Wren to update Sylo now, then follows the run. The caller has asked the person first. + @discardableResult + public func approve() async -> Bool { + guard !isApproving, following == nil, status?.offersUpdateNow == true else { return false } + isApproving = true + defer { isApproving = false } + actionError = nil + let generation = session.generation + do { + let started = try await session.send(Endpoints.ApproveUpdate()) + guard session.generation == generation else { return false } + follow(runID: started.runID, from: started.from.isEmpty ? (status?.current ?? "") : started.from) + return true + } catch { + guard session.generation == generation else { return false } + let error = NetworkError(error) + if error != .cancelled, error != .unauthorized { actionError = error.userMessage } + return false + } + } + + /// Stops following and clears the progress (the person closed it). + public func closeProgress() { + followCount += 1 + following?.cancel() + following = nil + progress = nil + } + + /// Leaves the screen: stops asking, keeps what was read. + public func stop() { + followCount += 1 + following?.cancel() + following = nil + } + + /// Asks again for a run that was being followed and is not done (the person left the screen). + private func resumeOpenRun() { + guard following == nil, let open = progress, !open.isDone else { return } + follow(runID: open.runID, from: open.from) + } + + /// Starts following a run. A second call while one is followed is ignored. The last state of the same run is + /// kept, so the screen does not fall back to "approved" when it is picked up again. + public func follow(runID: Int, from: String) { + guard following == nil else { return } + if progress?.runID != runID || progress?.isDone == true { + progress = UpdateProgress(runID: runID, from: from) + } + followCount += 1 + let mine = followCount + following = Task { [weak self] in + await self?.poll(runID: runID, from: from, followID: mine) + } + } + + /// Whether a failed read means Sylo itself is not answering (it restarts during the update, or a proxy has + /// no upstream), as opposed to Sylo answering with a Wise Wren error. + public nonisolated static func syloIsDown(_ error: NetworkError) -> Bool { + switch error { + case .offline, .unreachable, .timeout, .notASyloServer, .secureConnectionFailed, .transport: + return true + case .server(let status): + // Wise Wren's refusals come as JSON with the words; a proxy's 502 or 503 has none. + return status.message == nil + case .notFound: + // A reverse proxy without an upstream answers "404 page not found" as plain text while Sylo restarts; + // Sylo's own 404s (a run that is not Sylo's, Wise Wren not set up) carry their words. + return error.serverMessage == nil + default: + return false + } + } + + /// Whether a failed read will fail the same way next time, so asking on is no use: the account is no longer an + /// operator, or the run or Wise Wren is not there. + public nonisolated static func isPermanent(_ error: NetworkError) -> Bool { + switch error { + case .forbidden: true + case .notFound: error.serverMessage != nil + default: false + } + } + + private func poll(runID: Int, from: String, followID: Int) async { + let clock = ContinuousClock() + let started = clock.now + var wasDown = false + let generation = session.generation + while !Task.isCancelled { + var finished = false + var down = false + var problem: String? + var permanent = false + var run: WrenRun? + do { + let answer = try await session.send(Endpoints.LoadUpdateRun(id: runID)) + run = answer.run + finished = answer.run.isFinished + } catch { + let error = NetworkError(error) + if error == .cancelled || error == .unauthorized || session.generation != generation { break } + if Self.syloIsDown(error) { + down = true + wasDown = true + } else { + problem = error.userMessage + permanent = Self.isPermanent(error) + } + } + var newVersion: String? + // Back after a restart, or finished: Sylo's own version tells whether it worked. + if !down, wasDown || finished { + if let fresh = try? await session.send(Endpoints.LoadUpdate()), session.generation == generation { + status = fresh + // Sylo answered: the restart is over, so the version is read again only when the run ends. + wasDown = false + if !fresh.current.isEmpty, fresh.current != from { newVersion = fresh.current } + } + } + guard !Task.isCancelled, session.generation == generation else { break } + var next = progress ?? UpdateProgress(runID: runID, from: from) + if let run { next.run = run } + next.isSyloDown = down + next.problem = problem + if let newVersion { next.newVersion = newVersion } + let timedOut = newVersion == nil && !finished && clock.now - started > giveUpAfter + next.timedOut = timedOut + next.isDone = newVersion != nil || finished || timedOut || permanent + progress = next + if next.isDone { break } + try? await Task.sleep(for: pollEvery) + } + if followCount == followID { following = nil } + } +} diff --git a/apps/sylo-ios/SyloKit/Tests/SyloKitTests/Account/NoDashboardLinkSourceTests.swift b/apps/sylo-ios/SyloKit/Tests/SyloKitTests/Account/NoDashboardLinkSourceTests.swift index 7d8abbe9..c1a0a32b 100644 --- a/apps/sylo-ios/SyloKit/Tests/SyloKitTests/Account/NoDashboardLinkSourceTests.swift +++ b/apps/sylo-ios/SyloKit/Tests/SyloKitTests/Account/NoDashboardLinkSourceTests.swift @@ -103,6 +103,11 @@ struct NoDashboardLinkSourceTests { "sylo-ios/Views/Server/Tickets/TicketThreadView.swift": 1, // A reference in a release note (an issue or a pull request). "sylo-ios/Views/Settings/ChangelogView.swift": 1, + // The operators' update notice: the new release on GitHub, and the Wise Wren project page. + "sylo-ios/Views/Settings/UpdateView.swift": 2, + // The docs on a Postgres role with few rights (the restore of an uploaded dump), in the Backups list and in + // the restore sheet. + "sylo-ios/Views/Operator/BackupsView.swift": 2, // "Open Dashboard" for anyone who wants it, the platform's add-to-server pages, the public // What's New page for a Sylo that does not send its changelog, the privacy policy, the // terms, and the system settings of the app. diff --git a/apps/sylo-ios/SyloKit/Tests/SyloKitTests/Servers/ServerEnvironmentSourceTests.swift b/apps/sylo-ios/SyloKit/Tests/SyloKitTests/Servers/ServerEnvironmentSourceTests.swift index a4cee854..e74ff3f4 100644 --- a/apps/sylo-ios/SyloKit/Tests/SyloKitTests/Servers/ServerEnvironmentSourceTests.swift +++ b/apps/sylo-ios/SyloKit/Tests/SyloKitTests/Servers/ServerEnvironmentSourceTests.swift @@ -93,8 +93,10 @@ struct ServerEnvironmentSourceTests { // `navigationDestination(isPresented:)` resolve in the stack's context instead, so each one in the app is listed. // Value-based links: the server screen's own routes (`ModuleRoute`, `ServerPageRoute`, `TicketRoute`, which // `ServerView` wraps in `scoped`) and the search results (whose sheet sets the values above its stack). + // `FocusedToolsView` (the focused moderator view's Tools tab) pushes `ModuleRoute` for applications and + // suggestions, which `ServerView` handles through `scoped`. #expect(Self.counts(of: "NavigationLink(value:") - == ["ServerSearchView.swift": 1, "TicketListView.swift": 2, "OverviewView.swift": 5]) + == ["ServerSearchView.swift": 1, "TicketListView.swift": 2, "OverviewView.swift": 5, "FocusedToolsView.swift": 2]) // The one `isPresented` destination is Settings' Health page, which reads none of the server's values. #expect(Self.counts(of: ".navigationDestination(isPresented:") == ["SettingsView.swift": 1]) #expect(Self.counts(of: ".navigationDestination(item:").isEmpty, "a navigationDestination(item:) needs the server's environment") diff --git a/apps/sylo-ios/SyloKit/Tests/SyloKitTests/Sylo53/ModeratorViewTests.swift b/apps/sylo-ios/SyloKit/Tests/SyloKitTests/Sylo53/ModeratorViewTests.swift new file mode 100644 index 00000000..cf90f63e --- /dev/null +++ b/apps/sylo-ios/SyloKit/Tests/SyloKitTests/Sylo53/ModeratorViewTests.swift @@ -0,0 +1,274 @@ +import Foundation +import Testing +@testable import SyloKit + +// The focused moderator view (Sylo 5.3, `moderator-view`): who gets it, what it lists, where a server opens. The app +// also talks to servers on 5.2 and older and self-hosted ones, which do not announce the feature: they keep the full +// app for everyone, so each rule is checked against both shapes. + +private func card(_ id: String, on: Bool? = true, toggle: Bool = true) -> OverviewCard { + OverviewCard( + kind: .module, id: id, name: id.capitalized, hasToggle: toggle, isEnabled: toggle ? on : nil, + status: on == true ? .on : .off) +} + +private func overview( + tickets: Bool? = true, appeals: Bool? = true, applications: Bool? = true, suggestions: Bool? = true, + omit: Set = [] +) -> ServerOverview { + let cards = [ + ("tickets", tickets), ("appeals", appeals), ("applications", applications), ("suggestions", suggestions), + ("leveling", true), ("welcome", false), + ] + .filter { !omit.contains($0.0) } + .map { card($0.0, on: $0.1) } + return ServerOverview( + server: OverviewServer(id: "1", name: "HQ"), + groups: [OverviewGroup(title: "Everything", cards: cards)]) +} + +@Suite("Moderator view: who gets it") +struct ModeratorViewModeTests { + @Test("Inbox on a 5.3 server gets the focused view, unless they chose to see everything") + func inboxFocused() { + #expect(ModeratorView.mode(access: .inbox, supports: true, showEverything: false) == .focused) + #expect(ModeratorView.mode(access: .inbox, supports: true, showEverything: true) == .full) + } + + @Test("View and Edit keep the full app, and so does a server without levels") + func othersFull() { + for access in [DashboardAccess.view, .edit, .other("manager")] { + #expect(ModeratorView.mode(access: access, supports: true, showEverything: false) == .full) + #expect(ModeratorView.mode(access: access, supports: nil, showEverything: false) == .full) + } + #expect(ModeratorView.mode(access: nil, supports: true, showEverything: false) == .full) + #expect(ModeratorView.mode(access: nil, supports: nil, showEverything: false) == .full) + } + + @Test("A server that does not announce the feature (5.2, self-hosted) keeps the full app, also for Inbox") + func olderServer() { + #expect(ModeratorView.mode(access: .inbox, supports: false, showEverything: false) == .full) + #expect(ModeratorView.mode(access: .inbox, supports: false, showEverything: true) == .full) + } + + @Test("An Inbox person waits while the features are not known, so the full app never flashes") + func undecided() { + #expect(ModeratorView.mode(access: .inbox, supports: nil, showEverything: false) == .undecided) + // Nobody else waits for anything. + #expect(ModeratorView.mode(access: .edit, supports: nil, showEverything: false) == .full) + } + + @Test("Only an Inbox person on a 5.3 server may switch views") + func canChoose() { + #expect(ModeratorView.canChoose(access: .inbox, supports: true)) + #expect(!ModeratorView.canChoose(access: .inbox, supports: false)) + #expect(!ModeratorView.canChoose(access: .inbox, supports: nil)) + #expect(!ModeratorView.canChoose(access: .view, supports: true)) + #expect(!ModeratorView.canChoose(access: .edit, supports: true)) + #expect(!ModeratorView.canChoose(access: nil, supports: true)) + } + + @Test("The feature string is `moderator-view`") + func featureString() { + #expect(ServerFeature.moderatorView.rawValue == "moderator-view") + #expect(ModeratorView.showEverythingKey == "moderatorView.showEverything") + } + + @Test("A 5.3 info lists the feature, a 5.2 info does not, and both decode") + func infoShapes() throws { + let info53 = try JSONDecoder().decode( + ServerInfo.self, + from: Data(#"{"name":"Sylo","version":"5.3.0","apiVersion":1,"login":true,"loginProviders":["discord"],"platforms":["discord"],"features":["app-login","access-levels","moderator-view","update-notice","public-page-look","some-future-feature"]}"#.utf8)) + #expect(info53.supports(.moderatorView)) + #expect(info53.supports(.updateNotice)) + #expect(info53.supports(.publicPageLook)) + let info52 = try JSONDecoder().decode( + ServerInfo.self, + from: Data(#"{"name":"Sylo","version":"5.2.0","apiVersion":1,"login":true,"loginProviders":["discord"],"platforms":["discord"],"features":["app-login","access-levels","message-move"]}"#.utf8)) + #expect(!info52.supports(.moderatorView)) + #expect(!info52.supports(.updateNotice)) + #expect(!info52.supports(.publicPageLook)) + } + + @Test("The level of a server comes from the server list; a 5.2 list without one reads as Edit") + func levelFromList() throws { + let list = try JSONDecoder().decode( + ServerList.self, + from: Data(#"{"guilds":[{"id":"1","name":"Mod","access":"inbox"},{"id":"2","name":"Old"}]}"#.utf8)) + #expect(list.servers[0].access == .inbox) + #expect(list.servers[1].access == nil) + #expect(list.servers[1].effectiveAccess == .edit) + #expect(ModeratorView.mode(access: list.servers[0].access, supports: true, showEverything: false) == .focused) + #expect(ModeratorView.mode(access: list.servers[1].access, supports: true, showEverything: false) == .full) + } +} + +@Suite("Moderator view: what it lists") +struct ModeratorViewContentTests { + @Test("With every inbox on: Tickets, Tools and Moderation, in that order") + func allOn() { + #expect(ModeratorView.tabs(overview: overview()) == [.tickets, .tools, .moderation]) + #expect(ModeratorView.tools(overview: overview()) == [.applications, .suggestions, .memberData]) + #expect(ModeratorView.showsAppeals(overview: overview())) + } + + @Test("A switched-off module leaves the view; Member data and the Moderation hub always stay") + func someOff() { + let quiet = overview(tickets: false, appeals: false, applications: false, suggestions: false) + #expect(ModeratorView.tabs(overview: quiet) == [.tools, .moderation]) + #expect(ModeratorView.tools(overview: quiet) == [.memberData]) + #expect(!ModeratorView.showsAppeals(overview: quiet)) + let some = overview(applications: false) + #expect(ModeratorView.tools(overview: some) == [.suggestions, .memberData]) + } + + @Test("A card the overview does not list counts as on, and so does everything before the overview is known") + func unknownIsOn() { + let missing = overview(omit: ["tickets", "suggestions"]) + #expect(ModeratorView.tabs(overview: missing).contains(.tickets)) + #expect(ModeratorView.tools(overview: missing).contains(.suggestions)) + #expect(ModeratorView.tabs(overview: nil) == [.tickets, .tools, .moderation]) + #expect(ModeratorView.tools(overview: nil) == [.applications, .suggestions, .memberData]) + #expect(ModeratorView.landing(overview: nil) == .tickets) + // A switch that is on but not reported as enabled is off, as on the web. + let blank = ServerOverview( + server: OverviewServer(id: "1", name: "HQ"), + groups: [OverviewGroup(title: "G", cards: [card("tickets", on: nil)])]) + #expect(!ModeratorView.isModuleOn("tickets", in: blank)) + } + + @Test("A server opens on the first inbox that is on: tickets, appeals, applications or suggestions, else the hub") + func landing() { + #expect(ModeratorView.landing(overview: overview()) == .tickets) + #expect(ModeratorView.landing(overview: overview(tickets: false)) == .appeals) + #expect(ModeratorView.landing(overview: overview(tickets: false, appeals: false)) == .applications) + #expect( + ModeratorView.landing(overview: overview(tickets: false, appeals: false, applications: false)) + == .applications) + #expect( + ModeratorView.landing( + overview: overview(tickets: false, appeals: false, applications: false, suggestions: false)) + == .moderationHub) + } + + @Test("Each landing opens its own tab") + func landingTabs() { + #expect(ModeratorView.Landing.tickets.tab == .tickets) + #expect(ModeratorView.Landing.appeals.tab == .moderation) + #expect(ModeratorView.Landing.applications.tab == .tools) + #expect(ModeratorView.Landing.moderationHub.tab == .moderation) + } + + @Test("The search lists the moderation pages only, never settings, audit log, insights or module settings") + func search() { + let pages = ModeratorView.searchPages(overview: overview()) + #expect(pages == [.tickets, .appeals, .moderation, .memberData]) + for forbidden in [SearchPage.settings, .auditLog, .insights, .leaderboard, .commands, .messages] { + #expect(!pages.contains(forbidden)) + } + #expect(ModeratorView.searchPages(overview: overview(tickets: false, appeals: false)) == [.moderation, .memberData]) + + let scoped = ModeratorView.searchOverview(overview()) + #expect(scoped?.groups.flatMap(\.cards).map(\.id) == ["applications", "suggestions"]) + #expect(ModeratorView.searchOverview(nil) == nil) + // No module of the server's settings is searchable. + let items = SearchIndex.items(overview: scoped, pages: pages) + #expect(!items.contains { $0.id == "module:leveling" || $0.id == "module:welcome" }) + #expect(items.contains { $0.id == "module:applications" }) + } +} + +@Suite("Moderator view: round two") +struct ModeratorViewRoundTwoTests { + @Test("An Inbox person waits only while nothing says whether the server has the feature") + func supportsTable() { + // The feature is announced: true, whatever else is known. + #expect(ModeratorView.supports(hasFeature: true, featuresRead: false, serverInfoKnown: false, waited: false) == true) + // Nothing is known yet: wait. + #expect(ModeratorView.supports(hasFeature: false, featuresRead: false, serverInfoKnown: false, waited: false) == nil) + // A 5.2 server whose info the sign-in read already: no spinner at all. + #expect(ModeratorView.supports(hasFeature: false, featuresRead: false, serverInfoKnown: true, waited: false) == false) + // The read of the features finished (it worked, or it failed): decided. + #expect(ModeratorView.supports(hasFeature: false, featuresRead: true, serverInfoKnown: false, waited: false) == false) + // The short wait is over: the app draws as it does without the feature. + #expect(ModeratorView.supports(hasFeature: false, featuresRead: false, serverInfoKnown: false, waited: true) == false) + } + + @Test("The wait is short, and an Inbox person on a server without the feature gets the full app at once") + func boundedWait() { + #expect(ModeratorView.featureWait <= .seconds(5)) + let known52 = ModeratorView.supports(hasFeature: false, featuresRead: false, serverInfoKnown: true, waited: false) + #expect(ModeratorView.mode(access: .inbox, supports: known52, showEverything: false) == .full) + let waiting = ModeratorView.supports(hasFeature: false, featuresRead: false, serverInfoKnown: false, waited: false) + #expect(ModeratorView.mode(access: .inbox, supports: waiting, showEverything: false) == .undecided) + let expired = ModeratorView.supports(hasFeature: false, featuresRead: false, serverInfoKnown: false, waited: true) + #expect(ModeratorView.mode(access: .inbox, supports: expired, showEverything: false) == .full) + // Nobody below Inbox ever waits. + #expect(ModeratorView.mode(access: .edit, supports: waiting, showEverything: false) == .full) + } + + @Test("The Moderation tab opens on Appeals when that is where the server lands, and on Infractions otherwise") + func moderationStart() { + func cards(tickets: Bool, appeals: Bool) -> ServerOverview { + func card(_ id: String, _ on: Bool) -> OverviewCard { + OverviewCard(kind: .module, id: id, name: id, hasToggle: true, isEnabled: on, status: on ? .on : .off) + } + return ServerOverview( + server: OverviewServer(id: "1", name: "HQ"), + groups: [OverviewGroup(title: "G", cards: [card("tickets", tickets), card("appeals", appeals)])]) + } + // Before the overview is known the server lands on tickets, so Infractions. + #expect(ModeratorView.moderationStart(overview: nil) == .infractions) + #expect(ModeratorView.moderationStart(overview: cards(tickets: true, appeals: true)) == .infractions) + #expect(ModeratorView.moderationStart(overview: cards(tickets: false, appeals: true)) == .appeals) + // Appeals off as well: the hub, on Infractions. + #expect(ModeratorView.moderationStart(overview: cards(tickets: false, appeals: false)) == .infractions) + // The start changes when the overview arrives: that change is what the Moderation tab applies again. + #expect( + ModeratorView.moderationStart(overview: nil) != ModeratorView.moderationStart(overview: cards(tickets: false, appeals: true))) + // Appeals as a landing only lands on the Moderation tab, which is where the start applies. + #expect(ModeratorView.landing(overview: cards(tickets: false, appeals: true)).tab == .moderation) + } +} + +@Suite("Public pages: round two") +struct AccentColourRoundTwoTests { + @Test("The raw ratio decides, as on the server: 2.995:1 falls back although it shows as 3:1") + func rawRatio() { + // #959595 on the white card is 2.9953:1, which rounds to 3.00 for display. + #expect(AccentColour.ratio(of: "#959595", dark: false) == 3.0) + #expect(AccentColour.fallbackThemes("#959595") == ["light"]) + #expect(AccentColour.effective("#959595", dark: false) == AccentColour.syloAccent.light) + #expect(AccentColour.fallbackNote("#959595")?.contains("the light theme") == true) + // The dark card is fine with it. + #expect(AccentColour.effective("#959595", dark: true) == "#959595") + } + + @Test("Mixing two colours rounds halves up, like the server") + func mix() { + #expect(AccentColour.mix("#000000", "#ffffff", 0.5) == "#808080") + #expect(AccentColour.mix("#000000", "#ffffff", 0) == "#000000") + #expect(AccentColour.mix("#102030", "#ffffff", 1) == "#ffffff") + #expect(AccentColour.mix("nope", "#ffffff", 0.5) == "nope") + } + + @Test("Text in the accent is the accent lightened or darkened until it reads, as on the pages") + func accentText() { + // Values worked out with the server's algorithm (src/lib/publicLook.js accentText). + #expect(AccentColour.accentText("#5865f2", dark: true) == "#737ef4") + #expect(AccentColour.accentText("#5865f2", dark: false) == "#4c57d0") + #expect(AccentColour.accentText("#ff0000", dark: true) == "#ff3333") + #expect(AccentColour.accentText("#ff0000", dark: false) == "#c20000") + // An accent that already reads stays as it is. + #expect(AccentColour.accentText("#00aa00", dark: true) == "#00aa00") + #expect(AccentColour.accentText("#00aa00", dark: false) == "#007700") + } + + @Test("The text colour really used is Sylo's own where the accent is not used") + func effectiveText() { + #expect(AccentColour.effectiveText("", dark: true) == AccentColour.syloAccent.dark) + #expect(AccentColour.effectiveText("#ffff00", dark: false) == AccentColour.syloAccent.light) + #expect(AccentColour.effectiveText("#5865f2", dark: true) == "#737ef4") + #expect(AccentColour.effectiveText("not a colour", dark: true) == AccentColour.syloAccent.dark) + } +} diff --git a/apps/sylo-ios/SyloKit/Tests/SyloKitTests/Sylo53/PublicLookTests.swift b/apps/sylo-ios/SyloKit/Tests/SyloKitTests/Sylo53/PublicLookTests.swift new file mode 100644 index 00000000..6d926d29 --- /dev/null +++ b/apps/sylo-ios/SyloKit/Tests/SyloKitTests/Sylo53/PublicLookTests.swift @@ -0,0 +1,412 @@ +import Foundation +import Testing +@testable import SyloKit + +// The server's look on its public pages (Sylo 5.3, `public-page-look`): what the server answers, what the app posts, +// and the accent colour rules it mirrors for the preview. A server without the feature has none of these routes. + +private func decode(_ type: T.Type, _ json: String) throws -> T { + try JSONDecoder().decode(type, from: Data(json.utf8)) +} + +/// The JSON a request body encodes to. +private func bodyJSON(_ body: (any Encodable & Sendable)?) throws -> [String: Any] { + struct Box: Encodable { + let value: any Encodable + func encode(to encoder: any Encoder) throws { try value.encode(to: encoder) } + } + let value = try #require(body) + let data = try JSONEncoder().encode(Box(value: value)) + return try #require(try JSONSerialization.jsonObject(with: data) as? [String: Any]) +} + +/// `GET .../public-page-look` of a Discord server that chose its own picture and a colour that reads in one theme. +let publicLookJSON = #""" +{ + "platform": "discord", "accent": "#5865f2", "background": "upload", + "backgrounds": ["none", "upload", "discord-splash"], + "upload": {"bytes": 123456, "url": "/look/900000000000000201.0123456789abcdef.webp", "updatedAt": 1763640000000}, + "splash": {"available": true, "copied": {"url": "/look/900000000000000201.fedcba9876543210.webp", "checkedAt": 1763640000000, "updatedAt": 1763640000000}}, + "limits": {"maxBytes": 2097152, "types": ["PNG", "JPEG", "WebP"], "maxSide": 1920}, + "sylo": {"accent": {"dark": "#38c8f0", "light": "#076787"}}, + "effective": { + "accent": {"dark": "#5865f2", "light": "#5865f2"}, + "accentText": {"dark": "#737ef4", "light": "#5865f2"}, + "contrast": {"dark": {"ratio": 3.92, "ok": true}, "light": {"ratio": 4.61, "ok": true}}, + "fallback": [], "note": null, + "backgroundUrl": "/look/900000000000000201.0123456789abcdef.webp", + "css": "/look/900000000000000201.aaaaaaaaaaaaaaaa.css" + } +} +"""# + +@Suite("Public pages: decoding") +struct PublicLookDecodingTests { + @Test("A full answer reads: choice, picture, invite background, limits and what it comes to") + func full() throws { + let look = try decode(PublicPageLook.self, publicLookJSON) + #expect(look.accent == "#5865f2") + #expect(look.background == .upload) + #expect(look.platform == .discord) + #expect(look.backgrounds == [.noBackground, .upload, .discordSplash]) + #expect(look.upload?.bytes == 123_456) + #expect(look.upload?.url == "/look/900000000000000201.0123456789abcdef.webp") + #expect(look.splash.isAvailable) + #expect(look.splash.copiedURL == "/look/900000000000000201.fedcba9876543210.webp") + #expect(look.limits.maxBytes == 2_097_152) + #expect(look.limits.maxSide == 1920) + #expect(look.effective.accent?.dark == "#5865f2") + #expect(look.effective.accentText?.dark == "#737ef4") + #expect(look.effective.fallback.isEmpty) + #expect(look.effective.note == nil) + #expect(look.effective.backgroundURL == "/look/900000000000000201.0123456789abcdef.webp") + #expect(look.syloAccent?.light == "#076787") + #expect(look.imagePath(for: .upload) == look.upload?.url) + #expect(look.imagePath(for: .discordSplash) == look.splash.copiedURL) + #expect(look.imagePath(for: .noBackground) == nil) + } + + @Test("An empty answer, null parts and wrong types still read, with the defaults") + func lenient() throws { + let empty = try decode(PublicPageLook.self, "{}") + #expect(empty.accent == "") + #expect(empty.background == .noBackground) + #expect(empty.backgrounds == PublicPageLook.knownBackgrounds) + #expect(empty.upload == nil) + #expect(!empty.splash.isAvailable) + #expect(empty.effective.note == nil) + #expect(empty.limits.maxBytes == 2 * 1024 * 1024) + + let odd = try decode( + PublicPageLook.self, + #"{"accent":7,"background":"hologram","backgrounds":[],"upload":{"bytes":"x"},"splash":null,"effective":[1],"limits":"big","platform":null,"unknownKey":true}"#) + #expect(odd.accent == "") + #expect(odd.background == .other("hologram")) + #expect(odd.backgrounds == PublicPageLook.knownBackgrounds) + #expect(odd.upload == nil) + #expect(odd.effective.fallback.isEmpty) + // A value the app does not know is never offered, but it is not lost either. + #expect(odd.offeredBackgrounds(chosen: odd.background).allSatisfy { $0 != .other("hologram") }) + #expect(odd.imagePath(for: .other("hologram")) == nil) + } + + @Test("The server's note and fallback themes read when the colour is too faint") + func fallback() throws { + let look = try decode( + PublicPageLook.self, + ##"{"accent":"#ffff00","background":"none","effective":{"accent":{"dark":"#ffff00","light":"#076787"},"fallback":["light"],"note":"This colour is too hard to read on the card in the light theme, so public pages use Sylo's own colour there. Pick a darker or lighter shade."}}"##) + #expect(look.effective.fallback == ["light"]) + #expect(look.effective.note?.hasPrefix("This colour is too hard to read") == true) + #expect(look.effective.accent?.light == "#076787") + } + + @Test("Fluxer without an invite background is offered an upload or none only") + func offered() throws { + let fluxer = try decode( + PublicPageLook.self, + #"{"platform":"fluxer","accent":"","background":"none","backgrounds":["none","upload","discord-splash"],"splash":{"available":false,"copied":null}}"#) + #expect(fluxer.offeredBackgrounds(chosen: .noBackground) == [.noBackground, .upload]) + // A server that already chose the invite background keeps seeing it. + #expect(fluxer.offeredBackgrounds(chosen: .discordSplash) == [.noBackground, .upload, .discordSplash]) + let discord = try decode(PublicPageLook.self, publicLookJSON) + #expect(discord.offeredBackgrounds(chosen: .upload) == [.noBackground, .upload, .discordSplash]) + // The server lists what it takes; the app offers no more. + let narrow = try decode(PublicPageLook.self, #"{"backgrounds":["none","upload"],"splash":{"available":true}}"#) + #expect(narrow.offeredBackgrounds(chosen: .noBackground) == [.noBackground, .upload]) + } + + @Test("The values the app posts for a background") + func backgroundValues() { + #expect(PublicPageBackground.noBackground.rawValue == "none") + #expect(PublicPageBackground.upload.rawValue == "upload") + #expect(PublicPageBackground.discordSplash.rawValue == "discord-splash") + #expect(PublicPageBackground(rawValue: "discord-splash") == .discordSplash) + #expect(ServerFeature.publicPageLook.rawValue == "public-page-look") + } +} + +@Suite("Public pages: the accent colour") +struct AccentColourTests { + @Test("A colour is #rgb or #rrggbb, with or without the #; empty is none; anything else is not a colour") + func normalise() { + #expect(AccentColour.normalise("#5865F2") == "#5865f2") + #expect(AccentColour.normalise("5865f2") == "#5865f2") + #expect(AccentColour.normalise(" #abc ") == "#aabbcc") + #expect(AccentColour.normalise("fff") == "#ffffff") + #expect(AccentColour.normalise("") == "") + #expect(AccentColour.normalise(" ") == "") + for bad in ["#12", "#12345", "#1234567", "#gggggg", "red", "#5865f2ff", "rgb(1,2,3)", "#58 65f2"] { + #expect(AccentColour.normalise(bad) == nil, "\(bad)") + } + } + + @Test("A picker's colour becomes #rrggbb") + func hex() { + #expect(AccentColour.hex(red: 0.345, green: 0.396, blue: 0.949) == "#5865f2") + #expect(AccentColour.hex(red: 0, green: 0, blue: 0) == "#000000") + #expect(AccentColour.hex(red: 1, green: 1, blue: 1) == "#ffffff") + #expect(AccentColour.hex(red: 0, green: 0, blue: 0.02) == "#000005") + #expect(AccentColour.hex(red: -1, green: 2, blue: 0.5) == "#00ff80") + #expect(AccentColour.components("#5865f2")?.red == 0x58) + #expect(AccentColour.components("5865f2") == nil) + } + + @Test("Contrast against the card is the server's rule: 3:1 or Sylo's own colour is used") + func contrast() { + // Mid-tones such as Discord's blurple read in both themes. + #expect(AccentColour.fallbackThemes("#5865f2").isEmpty) + #expect(AccentColour.fallbackNote("#5865f2") == nil) + #expect(abs(AccentColour.ratio(of: "#5865f2", dark: true) - 3.92) < 0.011) + #expect(abs(AccentColour.ratio(of: "#5865f2", dark: false) - 4.61) < 0.011) + // Yellow vanishes on a white card, black on a dark one. + #expect(AccentColour.fallbackThemes("#ffff00") == ["light"]) + #expect(AccentColour.fallbackThemes("#000000") == ["dark"]) + #expect(AccentColour.fallbackThemes("#ffffff") == ["light"]) + #expect(AccentColour.fallbackThemes("") == []) + #expect(AccentColour.fallbackNote("#ffff00")?.contains("the light theme") == true) + #expect(AccentColour.fallbackNote("#ffff00")?.hasSuffix("Pick a darker or lighter shade.") == true) + } + + @Test("The colour really used is the chosen one where it reads, else Sylo's own") + func effective() { + #expect(AccentColour.effective("#5865f2", dark: true) == "#5865f2") + #expect(AccentColour.effective("#ffff00", dark: false) == AccentColour.syloAccent.light) + #expect(AccentColour.effective("#ffff00", dark: true) == "#ffff00") + #expect(AccentColour.effective("", dark: true) == AccentColour.syloAccent.dark) + #expect(AccentColour.effective("not a colour", dark: false) == AccentColour.syloAccent.light) + } + + @Test("The text on a button is black or white, whichever reads better") + func onAccent() { + #expect(AccentColour.onAccent("#5865f2") == "#ffffff") + #expect(AccentColour.onAccent("#ffff00") == "#000000") + #expect(AccentColour.onAccent("#000000") == "#ffffff") + } +} + +@Suite("Public pages: the calls") +struct PublicLookCallTests { + @Test("The routes are the server's, one per call") + func routes() throws { + #expect(Endpoints.LoadPublicLook(server: "1").path == "/api/v2/guilds/1/public-page-look") + #expect(Endpoints.LoadPublicLook(server: "1").method == .get) + let save = Endpoints.SavePublicLook(server: "fluxer:7", choice: PublicPageLookChoice(accent: "#5865f2", background: .upload)) + #expect(save.path == "/api/v2/guilds/fluxer%3A7/public-page-look") + #expect(save.method == .post) + #expect(Endpoints.DeletePublicLookImage(server: "1").path == "/api/v2/guilds/1/public-page-look/image/delete") + #expect(Endpoints.DeletePublicLookImage(server: "1").method == .post) + #expect(Endpoints.RefreshPublicLookSplash(server: "1").path == "/api/v2/guilds/1/public-page-look/splash/refresh") + #expect(Endpoints.RefreshPublicLookSplash(server: "1").method == .post) + let picture = PreparedPicture(data: Data([1, 2, 3]), mimeType: "image/jpeg", filename: "picture.jpg", width: 1, height: 1) + let upload = Endpoints.UploadPublicLookImage(server: "1", picture: picture, boundary: "B") + #expect(upload.path == "/api/v2/guilds/1/public-page-look/image") + #expect(upload.method == .post) + #expect(upload.body == nil) + let raw = try #require(upload.rawBody) + #expect(raw.contentType == "multipart/form-data; boundary=B") + let text = String(decoding: raw.data, as: UTF8.self) + #expect(text.contains(#"name="file"; filename="picture.jpg""#)) + #expect(text.contains("Content-Type: image/jpeg")) + } + + @Test("A save posts both keys: the colour and the background") + func saveBody() throws { + let save = Endpoints.SavePublicLook(server: "1", choice: PublicPageLookChoice(accent: "#5865f2", background: .discordSplash)) + let json = try bodyJSON(save.body) + #expect(Set(json.keys) == ["accent", "background"]) + #expect(json["accent"] as? String == "#5865f2") + #expect(json["background"] as? String == "discord-splash") + let none = try bodyJSON(Endpoints.SavePublicLook(server: "1", choice: PublicPageLookChoice(accent: "", background: .noBackground)).body) + #expect(none["accent"] as? String == "") + #expect(none["background"] as? String == "none") + } +} + +@MainActor +@Suite("Public pages: the model") +struct PublicLookModelTests { + nonisolated static func look( + accent: String = "#5865f2", background: PublicPageBackground = .upload, hasUpload: Bool = true, + note: String? = nil + ) -> PublicPageLook { + PublicPageLook( + accent: accent, background: background, platform: .discord, + upload: hasUpload ? PublicPageLook.Upload(bytes: 10, url: "/look/1.aaaaaaaaaaaaaaaa.webp") : nil, + splash: PublicPageLook.Splash(isAvailable: true, copiedURL: nil), + effective: PublicPageLook.Effective(note: note)) + } + + private func makeModel(_ clients: StubClients) -> PublicLookModel { + PublicLookModel(server: "1", session: makeSignedInSession(clients: clients)) + } + + private static let picture = PreparedPicture( + data: Data([1, 2, 3]), mimeType: "image/jpeg", filename: "picture.jpg", width: 10, height: 10) + + @Test("Loading shows the saved choice, and an unchanged page has nothing to save") + func loads() async { + let model = makeModel(StubClients { _ in Self.look() }) + await model.load() + #expect(model.accentText == "#5865f2") + #expect(model.background == .upload) + #expect(!model.hasChanges) + #expect(!model.canSave) + #expect(model.previewImagePath == "/look/1.aaaaaaaaaaaaaaaa.webp") + } + + @Test("A typed colour is a change; one that is not a colour cannot be saved") + func typing() async { + let model = makeModel(StubClients { _ in Self.look() }) + await model.load() + model.accentText = "#ff0000" + #expect(model.hasChanges) + #expect(model.canSave) + model.accentText = "#ff00" + #expect(!model.accentIsValid) + #expect(!model.hasChanges) + #expect(!model.canSave) + model.accentText = "F00" + #expect(model.accent == "#ff0000") + model.discardChanges() + #expect(model.accentText == "#5865f2") + #expect(!model.hasChanges) + } + + @Test("The note is the server's for the saved colour and worked out here for a typed one") + func note() async { + let model = makeModel(StubClients { _ in Self.look(accent: "#ffff00", note: "The server's sentence.") }) + await model.load() + #expect(model.accentNote == "The server's sentence.") + model.accentText = "#ffffff" + #expect(model.accentNote?.contains("the light theme") == true) + model.accentText = "#5865f2" + #expect(model.accentNote == nil) + model.accentText = "nope" + #expect(model.accentNote == nil) + } + + @Test("Saving posts the colour and the background, then shows what the server answers") + func saves() async { + let clients = StubClients { endpoint in + if let save = endpoint as? Endpoints.SavePublicLook { + return Self.look(accent: save.choice.accent, background: save.choice.background) + } + return Self.look() + } + let model = makeModel(clients) + await model.load() + model.accentText = "00F" + model.background = .noBackground + #expect(await model.save()) + let sent = clients.calls.compactMap { $0.endpoint as? Endpoints.SavePublicLook } + #expect(sent.count == 1) + #expect(sent.first?.choice.accent == "#0000ff") + #expect(sent.first?.choice.background == .noBackground) + #expect(model.look?.accent == "#0000ff") + #expect(!model.hasChanges) + #expect(model.saveCount == 1) + } + + @Test("Nothing is sent when nothing changed or the colour is not one") + func noSave() async { + let clients = StubClients { _ in Self.look() } + let model = makeModel(clients) + await model.load() + #expect(await model.save() == false) + model.accentText = "xyz" + #expect(await model.save() == false) + #expect(!clients.calls.contains { $0.endpoint is Endpoints.SavePublicLook }) + } + + @Test("A save the server refuses shows its words and keeps the changes") + func refusedSave() async { + let clients = StubClients { endpoint in + if endpoint is Endpoints.SavePublicLook { + throw NetworkError.badRequest(message: "This server has no invite background. Set one in the server settings, or choose another.") + } + return Self.look() + } + let model = makeModel(clients) + await model.load() + model.background = .discordSplash + #expect(await model.save() == false) + #expect(model.actionError == "This server has no invite background. Set one in the server settings, or choose another.") + #expect(model.hasChanges) + } + + @Test("An uploaded picture is chosen at once and saved with the rest") + func uploads() async { + let clients = StubClients { endpoint in + if endpoint is Endpoints.UploadPublicLookImage { + return Self.look(accent: "#5865f2", background: .noBackground, hasUpload: true) + } + return Self.look(background: .noBackground, hasUpload: false) + } + let model = makeModel(clients) + await model.load() + #expect(model.look?.upload == nil) + #expect(await model.upload(Self.picture)) + #expect(model.look?.upload != nil) + #expect(model.background == .upload) + #expect(model.hasChanges) + #expect(clients.calls.contains { $0.endpoint is Endpoints.UploadPublicLookImage }) + // The upload alone does not save the choice. + #expect(!clients.calls.contains { $0.endpoint is Endpoints.SavePublicLook }) + } + + @Test("A picture the server refuses shows why, and the choice stays") + func refusedUpload() async { + let clients = StubClients { endpoint in + if endpoint is Endpoints.UploadPublicLookImage { throw NetworkError.tooLarge } + return Self.look(background: .noBackground, hasUpload: false) + } + let model = makeModel(clients) + await model.load() + #expect(await model.upload(Self.picture) == false) + #expect(model.actionError?.contains("larger than the server takes") == true) + #expect(model.background == .noBackground) + #expect(!model.hasChanges) + } + + @Test("Removing the picture takes a not yet saved choice of it back") + func removes() async { + let clients = StubClients { endpoint in + if endpoint is Endpoints.DeletePublicLookImage { return Self.look(background: .noBackground, hasUpload: false) } + return Self.look(background: .noBackground, hasUpload: true) + } + let model = makeModel(clients) + await model.load() + model.background = .upload + #expect(model.hasChanges) + #expect(await model.removePicture()) + #expect(model.look?.upload == nil) + #expect(model.background == .noBackground) + #expect(!model.hasChanges) + } + + @Test("The invite background is checked on request, and a missing copy is said to wait for the save") + func splash() async { + let clients = StubClients { endpoint in + if endpoint is Endpoints.RefreshPublicLookSplash { + return PublicPageLook( + background: .discordSplash, splash: PublicPageLook.Splash(isAvailable: true, copiedURL: "/look/1.bbbbbbbbbbbbbbbb.webp")) + } + return PublicPageLook(background: .noBackground, splash: PublicPageLook.Splash(isAvailable: true, copiedURL: nil)) + } + let model = makeModel(clients) + await model.load() + model.background = .discordSplash + #expect(model.waitsForSplash) + #expect(await model.refreshSplash()) + #expect(!model.waitsForSplash) + #expect(model.previewImagePath == "/look/1.bbbbbbbbbbbbbbbb.webp") + } + + @Test("A person below Edit gets the server's refusal in words") + func forbidden() async { + let model = makeModel(StubClients { _ in throw NetworkError.forbidden }) + await model.load() + #expect(model.look == nil) + #expect(model.errorMessage?.contains("Edit access") == true) + } +} diff --git a/apps/sylo-ios/SyloKit/Tests/SyloKitTests/Sylo53/RestoreTests.swift b/apps/sylo-ios/SyloKit/Tests/SyloKitTests/Sylo53/RestoreTests.swift new file mode 100644 index 00000000..5c63a80b --- /dev/null +++ b/apps/sylo-ios/SyloKit/Tests/SyloKitTests/Sylo53/RestoreTests.swift @@ -0,0 +1,300 @@ +import Foundation +#if canImport(FoundationNetworking) +import FoundationNetworking +#endif +import Testing +@testable import SyloKit + +// Restoring a backup (Sylo 5.3, src/db/backup.js `restoreConfirmationError`): a 5.3 server wants the snapshot's name as +// `confirm`, and `acknowledgeSql: true` for an uploaded Postgres dump (its SQL runs with the rights of the database +// role); without them an uploaded dump gets a 400. A server before 5.3 takes no body, and the app sends it none: the +// new keys go out only to a server that says it knows them (it sends `roleRisks` in the health report). + +private func decode(_ type: T.Type, _ json: String) throws -> T { + try JSONDecoder().decode(type, from: Data(json.utf8)) +} + +private func bodyJSON(_ body: (any Encodable & Sendable)?) throws -> [String: Any] { + struct Box: Encodable { + let value: any Encodable + func encode(to encoder: any Encoder) throws { try value.encode(to: encoder) } + } + let value = try #require(body) + let data = try JSONEncoder().encode(Box(value: value)) + return try #require(try JSONSerialization.jsonObject(with: data) as? [String: Any]) +} + +/// A count a @Sendable stub can bump. +private final class Asks: @unchecked Sendable { + private let lock = NSLock() + private var count = 0 + func next() -> Int { lock.withLock { count += 1; return count } } +} + +private let imported = "sylo-imported-2026-11-20T09-00-00.dump" + +@Suite("Restore: the health report") +struct RestoreHealthTests { + @Test("A 5.3 report lists the role's extra rights (empty when fine) and the docs") + func report53() throws { + let db = try decode( + HealthReport.Database.self, + #"{"size":"12 MB","postgres":true,"intervalHours":24,"retention":7,"roleRisks":["SUPERUSER","pg_read_server_files"],"roleDocsUrl":"https://github.com/Ferdinand99/Sylo/blob/main/docs/postgres.md#least-privilege-database-role"}"#) + #expect(db.isPostgres) + #expect(db.roleRisks == ["SUPERUSER", "pg_read_server_files"]) + #expect(db.roleDocsURL?.host == "github.com") + let fine = try decode(HealthReport.Database.self, #"{"postgres":true,"roleRisks":[]}"#) + #expect(fine.roleRisks == []) + } + + @Test("A 5.2 report has neither, and an odd one reads as not sent") + func report52() throws { + let db = try decode(HealthReport.Database.self, #"{"size":"12 MB","postgres":true,"intervalHours":24}"#) + #expect(db.roleRisks == nil) + #expect(db.roleDocsURL == nil) + let odd = try decode(HealthReport.Database.self, #"{"postgres":true,"roleRisks":"SUPERUSER","roleDocsUrl":"javascript:alert(1)"}"#) + #expect(odd.roleRisks == nil) + #expect(odd.roleDocsURL == nil) + let report = try decode(HealthReport.self, #"{"ready":true,"db":{"postgres":true,"roleRisks":["CREATEDB"]}}"#) + #expect(report.database?.roleRisks == ["CREATEDB"]) + } +} + +@Suite("Restore: what is sent") +struct RestorePlanTests { + private static let db53 = HealthReport.Database(isPostgres: true, roleRisks: []) + private static let db52 = HealthReport.Database(isPostgres: true) + private static let sqlite53 = HealthReport.Database(isPostgres: false, roleRisks: []) + + @Test("Only a snapshot named sylo-imported- is an uploaded one") + func importedName() { + #expect(RestorePlan.isImported(imported)) + #expect(!RestorePlan.isImported("sylo-manual-2026-11-20.dump")) + #expect(!RestorePlan.isImported("my-sylo-imported-1.dump")) + #expect(!RestorePlan.isImported("")) + } + + @Test("An uploaded dump on a 5.3 Postgres is sent the name and the acknowledgement") + func uploadedDump53() throws { + let plan = RestorePlan.make(name: imported, database: Self.db53) + #expect(plan.isUploadedSqlDump) + #expect(plan.confirmation == RestoreConfirmation(confirm: imported, acknowledgeSql: true)) + let json = try bodyJSON(Endpoints.RestoreBackup(name: imported, confirmation: plan.confirmation).body) + #expect(Set(json.keys) == ["confirm", "acknowledgeSql"]) + #expect(json["confirm"] as? String == imported) + #expect(json["acknowledgeSql"] as? Bool == true) + } + + @Test("Any other snapshot on a 5.3 server is sent the name only, never the acknowledgement") + func otherSnapshot53() throws { + let plan = RestorePlan.make(name: "sylo-manual-1.dump", database: Self.db53) + #expect(!plan.isUploadedSqlDump) + let json = try bodyJSON(Endpoints.RestoreBackup(name: "sylo-manual-1.dump", confirmation: plan.confirmation).body) + #expect(Set(json.keys) == ["confirm"]) + // An uploaded file on SQLite runs no SQL: the same. + let sqlite = RestorePlan.make(name: "sylo-imported-1.db", database: Self.sqlite53) + #expect(!sqlite.isUploadedSqlDump) + #expect(sqlite.confirmation == RestoreConfirmation(confirm: "sylo-imported-1.db")) + } + + @Test("A server that did not send roleRisks (5.2 and older) is sent no body at all") + func olderServer() { + let plan = RestorePlan.make(name: imported, database: Self.db52) + // The app still explains the SQL: it is true on every version. + #expect(plan.isUploadedSqlDump) + #expect(plan.confirmation == nil) + #expect(Endpoints.RestoreBackup(name: imported, confirmation: plan.confirmation).body == nil) + #expect(RestorePlan.make(name: "sylo-manual-1.dump", database: Self.db52).confirmation == nil) + #expect(RestorePlan.make(name: "sylo-manual-1.dump", database: nil).confirmation == nil) + } + + @Test("The warning is the dashboard's words, with the role's extra rights when there are some") + func notice() { + #expect(UploadedDumpNotice.title == "This file was uploaded") + #expect(UploadedDumpNotice.message.contains("runs that SQL with the rights of the database role")) + #expect(UploadedDumpNotice.message.contains("Restore only a file you made or trust.")) + #expect(UploadedDumpNotice.roleSentence(nil) == nil) + #expect(UploadedDumpNotice.roleSentence([]) == nil) + #expect(UploadedDumpNotice.roleSentence(["SUPERUSER", "CREATEDB"])?.contains("SUPERUSER, CREATEDB") == true) + } +} + +@MainActor +@Suite("Restore: the model") +struct RestoreModelTests { + nonisolated static func report(roleRisks: [String]?, postgres: Bool = true) -> HealthReport { + HealthReport( + isReady: true, database: HealthReport.Database(isPostgres: postgres, roleRisks: roleRisks), + backups: [ + HealthReport.Backup(name: imported, size: "1 MB", age: "1m ago"), + HealthReport.Backup(name: "sylo-manual-1.dump", size: "1 MB", age: "3h ago"), + ]) + } + + /// A server that restarts after the restore call (two failed asks), like a real one. + nonisolated static func clients(_ report: HealthReport) -> StubClients { + let restored = LockedFlag() + let asks = Asks() + return StubClients { endpoint in + switch endpoint { + case is Endpoints.RestoreBackup: + restored.value = true + return OKResponse() + case is Endpoints.Health: + if restored.value, asks.next() < 3 { throw NetworkError.unreachable } + return report + default: throw NetworkError.notFound + } + } + } + + private func makeModel(_ clients: StubClients) -> BackupsModel { + BackupsModel( + session: makeSignedInSession(clients: clients), firstPoll: .zero, pollEvery: .milliseconds(1), + giveUpAfter: .seconds(5)) + } + + @Test("An uploaded dump is not restored until the person says they know what it runs") + func needsAcknowledgement() async { + let clients = Self.clients(Self.report(roleRisks: [])) + let model = makeModel(clients) + await model.load() + #expect(await model.restore(imported, typed: imported) == false) + #expect(model.actionError == "Confirm that you made this file or trust it before it is restored.") + #expect(!clients.calls.contains { $0.endpoint is Endpoints.RestoreBackup }) + #expect(model.restoring == nil) + } + + @Test("With the acknowledgement and the typed name, a 5.3 server gets confirm and acknowledgeSql") + func restoresUploadedDump() async throws { + let clients = Self.clients(Self.report(roleRisks: ["CREATEDB"])) + let model = makeModel(clients) + await model.load() + #expect(await model.restore(imported, typed: imported, acknowledgedSql: true)) + let sent = try #require(clients.calls.compactMap { $0.endpoint as? Endpoints.RestoreBackup }.first) + #expect(sent.name == imported) + #expect(sent.confirmation == RestoreConfirmation(confirm: imported, acknowledgeSql: true)) + #expect(model.notice == "Restored from \(imported). Sylo is back.") + } + + @Test("Another snapshot needs no acknowledgement, and a 5.3 server gets its name as confirm") + func restoresOrdinarySnapshot() async throws { + let clients = Self.clients(Self.report(roleRisks: [])) + let model = makeModel(clients) + await model.load() + #expect(await model.restore("sylo-manual-1.dump", typed: "sylo-manual-1.dump")) + let sent = try #require(clients.calls.compactMap { $0.endpoint as? Endpoints.RestoreBackup }.first) + #expect(sent.confirmation == RestoreConfirmation(confirm: "sylo-manual-1.dump")) + } + + @Test("A 5.2 server is sent no body, uploaded dump or not") + func olderServerGetsNoBody() async throws { + let clients = Self.clients(Self.report(roleRisks: nil)) + let model = makeModel(clients) + await model.load() + // Even on 5.2 the person is told what the SQL runs with. + #expect(await model.restore(imported, typed: imported) == false) + #expect(await model.restore(imported, typed: imported, acknowledgedSql: true)) + let sent = try #require(clients.calls.compactMap { $0.endpoint as? Endpoints.RestoreBackup }.first) + #expect(sent.confirmation == nil) + #expect(sent.body == nil) + } + + @Test("The typed name is still asked first, whatever else is said") + func typedNameFirst() async { + let clients = Self.clients(Self.report(roleRisks: [])) + let model = makeModel(clients) + await model.load() + #expect(await model.restore(imported, typed: "yes", acknowledgedSql: true) == false) + #expect(model.actionError == "Type \(imported) to confirm.") + #expect(!clients.calls.contains { $0.endpoint is Endpoints.RestoreBackup }) + } +} + +extension APIClientTests { + private func client53() throws -> URLSessionAPIClient { + URLSessionAPIClient( + server: try ServerURL("https://example.com/sylo"), session: MockURLProtocol.session(), + decoder: JSONDecoder(), retryDelays: [.zero, .zero], token: { "sylo_secret" }) + } + + @Test("A 5.3 restore of an uploaded dump posts a JSON body with confirm and acknowledgeSql") + func restoreBodyOnTheWire() async throws { + let mock = MockURLProtocol.state + mock.reset([.json(200, #"{"ok":true}"#)]) + let plan = RestorePlan.make(name: imported, database: HealthReport.Database(isPostgres: true, roleRisks: [])) + _ = try await client53().send(Endpoints.RestoreBackup(name: imported, confirmation: plan.confirmation)) + let request = try #require(mock.requests.first) + #expect(request.url.absoluteString == "https://example.com/sylo/api/v2/health/backups/\(imported)/restore") + #expect(request.method == "POST") + #expect(request.header("Content-Type") == "application/json") + let body = try #require(request.body) + let json = try #require(try JSONSerialization.jsonObject(with: body) as? [String: Any]) + #expect(Set(json.keys) == ["confirm", "acknowledgeSql"]) + #expect(json["confirm"] as? String == imported) + #expect(json["acknowledgeSql"] as? Bool == true) + } + + @Test("A restore on a server that sent no roleRisks posts no body and no content type") + func restoreWithoutBodyOnTheWire() async throws { + let mock = MockURLProtocol.state + mock.reset([.json(200, #"{"ok":true}"#)]) + let plan = RestorePlan.make(name: imported, database: HealthReport.Database(isPostgres: true)) + _ = try await client53().send(Endpoints.RestoreBackup(name: imported, confirmation: plan.confirmation)) + let request = try #require(mock.requests.first) + #expect(request.header("Content-Type") == nil) + #expect(request.body == nil || request.body?.isEmpty == true) + } + + @Test("The public-page look is saved as JSON and a picture goes up as a multipart file") + func publicLookOnTheWire() async throws { + let mock = MockURLProtocol.state + mock.reset([.json(200, publicLookJSON)]) + let saved = try await client53().send( + Endpoints.SavePublicLook(server: "900000000000000201", choice: PublicPageLookChoice(accent: "#5865f2", background: .upload))) + #expect(saved.background == .upload) + var request = try #require(mock.requests.first) + #expect(request.url.absoluteString == "https://example.com/sylo/api/v2/guilds/900000000000000201/public-page-look") + #expect(request.header("Content-Type") == "application/json") + let savedBody = try #require(request.body) + let json = try #require(try JSONSerialization.jsonObject(with: savedBody) as? [String: Any]) + #expect(Set(json.keys) == ["accent", "background"]) + + mock.reset([.json(200, publicLookJSON)]) + let picture = PreparedPicture(data: Data(repeating: 7, count: 32), mimeType: "image/jpeg", filename: "picture.jpg", width: 4, height: 4) + _ = try await client53().send(Endpoints.UploadPublicLookImage(server: "900000000000000201", picture: picture, boundary: "B")) + request = try #require(mock.requests.first) + #expect(request.url.absoluteString == "https://example.com/sylo/api/v2/guilds/900000000000000201/public-page-look/image") + #expect(request.header("Content-Type") == "multipart/form-data; boundary=B") + let uploadBody = try #require(request.body) + let text = String(decoding: uploadBody, as: UTF8.self) + #expect(text.contains(#"name="file""#)) + } + + @Test("Update now posts no body and the run is read from its own route") + func updateOnTheWire() async throws { + let mock = MockURLProtocol.state + mock.reset([.json(200, #"{"runId":42,"status":"queued","from":"5.2.0"}"#)]) + let started = try await client53().send(Endpoints.ApproveUpdate()) + #expect(started.runID == 42) + var request = try #require(mock.requests.first) + #expect(request.url.absoluteString == "https://example.com/sylo/api/v2/update/wren/approve") + #expect(request.method == "POST") + #expect(request.header("Content-Type") == nil) + + mock.reset([.json(200, #"{"run":{"id":42,"status":"running","finished":false,"steps":[{"step":"stop","status":"running","durationMs":null}]}}"#)]) + let answer = try await client53().send(Endpoints.LoadUpdateRun(id: 42)) + #expect(answer.run.described.step == "Stopping Sylo") + request = try #require(mock.requests.first) + #expect(request.url.absoluteString == "https://example.com/sylo/api/v2/update/wren/runs/42") + + // A proxy's answer while Sylo restarts is a server error without words: the app reads it as Sylo being down. + mock.reset([.json(502, "{}"), .json(502, "{}"), .json(502, "{}")]) + do { + _ = try await client53().send(Endpoints.LoadUpdateRun(id: 42)) + Issue.record("a 502 should throw") + } catch { + #expect(UpdateModel.syloIsDown(NetworkError(error))) + } + } +} diff --git a/apps/sylo-ios/SyloKit/Tests/SyloKitTests/Sylo53/UpdateNoticeTests.swift b/apps/sylo-ios/SyloKit/Tests/SyloKitTests/Sylo53/UpdateNoticeTests.swift new file mode 100644 index 00000000..30917205 --- /dev/null +++ b/apps/sylo-ios/SyloKit/Tests/SyloKitTests/Sylo53/UpdateNoticeTests.swift @@ -0,0 +1,591 @@ +import Foundation +import Testing +@testable import SyloKit + +// The operators' update notice (Sylo 5.3, `update-notice`): what `GET /api/v2/update` and the Wise Wren calls answer, +// how a run reads while Sylo restarts, and the model that follows it. The app decodes every payload leniently: a field +// that is missing or of an odd type never loses the notice. + +private func decode(_ type: T.Type, _ json: String) throws -> T { + try JSONDecoder().decode(type, from: Data(json.utf8)) +} + +/// A count a @Sendable stub can bump. +private final class Tally: @unchecked Sendable { + private let lock = NSLock() + private var count = 0 + func next() -> Int { lock.withLock { count += 1; return count } } + var value: Int { lock.withLock { count } } +} + +/// The shape of `GET /api/v2/update` on a 5.3 server with a newer release and Wise Wren set up. +let updateAvailableJSON = #""" +{ + "enabled": true, "current": "5.2.0", "latest": "5.3.0", "available": true, + "checkedAt": "2026-11-20T10:00:00.000Z", "checkFailed": false, + "releaseUrl": "https://github.com/Ferdinand99/Sylo/releases/tag/v5.3.0", "publishedAt": "2026-11-20T09:00:00Z", + "notes": {"version": "5.3.0", "date": "2026-11-20", "url": null, "sections": [ + {"title": "New", "kind": "features", "items": [ + {"scope": "dashboard", "text": "A **focused** view for `Inbox` access", "refs": [{"label": "#365", "url": "https://github.com/Ferdinand99/Sylo/pull/365"}]} + ]} + ]}, + "notesText": null, + "command": "docker compose pull && docker compose up -d", + "wren": { + "configured": true, "error": null, "openMode": false, + "target": {"name": "sylo", "server": "main", "status": "update", "installedVersion": "5.2.0", "latestVersion": "5.3.0", "mode": "approve", "lastCheckedAt": "2026-11-20T09:55:00Z"}, + "updateSeen": true, "canApprove": true, "whyNot": null, "latestRun": null + } +} +"""# + +@Suite("Update notice: decoding") +struct UpdateNoticeDecodingTests { + @Test("A newer release with notes and Wise Wren reads completely") + func available() throws { + let status = try decode(UpdateStatus.self, updateAvailableJSON) + #expect(status.isEnabled) + #expect(status.current == "5.2.0") + #expect(status.latest == "5.3.0") + #expect(status.isAvailable) + #expect(status.releaseURL?.absoluteString == "https://github.com/Ferdinand99/Sylo/releases/tag/v5.3.0") + #expect(status.command == "docker compose pull && docker compose up -d") + let notes = try #require(status.notes) + #expect(notes.version == "5.3.0") + #expect(notes.sections.first?.items.first?.scope == "dashboard") + #expect(notes.sections.first?.items.first?.refs.first?.label == "#365") + let wren = try #require(status.wren) + #expect(wren.target?.name == "sylo") + #expect(wren.target?.installedVersion == "5.2.0") + #expect(wren.updateSeen) + #expect(wren.canApprove) + #expect(wren.latestRun == nil) + #expect(status.offersUpdateNow) + #expect(status.needsAttention) + #expect(status.headline == "Sylo 5.3.0 is available. This Sylo runs 5.2.0.") + #expect(status.summary == "5.3.0 is available") + } + + @Test("Without Wise Wren there is the notice and the command, and no Update now") + func withoutWren() throws { + let status = try decode( + UpdateStatus.self, + #"{"enabled":true,"current":"5.2.0","latest":"5.3.0","available":true,"command":"docker compose pull && docker compose up -d","wren":null}"#) + #expect(status.wren == nil) + #expect(status.isAvailable) + #expect(!status.offersUpdateNow) + #expect(status.needsAttention) + } + + @Test("Up to date, check off and failed check each read in words") + func headlines() throws { + let current = try decode(UpdateStatus.self, #"{"enabled":true,"current":"5.3.0","latest":"5.3.0","available":false}"#) + #expect(current.headline == "Sylo 5.3.0 is up to date.") + #expect(current.summary == "Up to date") + #expect(!current.needsAttention) + let off = try decode(UpdateStatus.self, #"{"enabled":false,"current":"5.3.0","latest":null,"available":false}"#) + #expect(off.headline == "Sylo 5.3.0. The update check is off.") + #expect(off.summary == "Check is off") + let failed = try decode( + UpdateStatus.self, #"{"enabled":true,"current":"5.3.0","latest":null,"available":false,"checkFailed":true}"#) + #expect(failed.headline == "Sylo 5.3.0. The latest release could not be checked.") + #expect(failed.summary == "Couldn't check") + } + + @Test("Missing, null and wrong-typed fields never fail the decode") + func lenient() throws { + let empty = try decode(UpdateStatus.self, "{}") + #expect(empty.isEnabled) + #expect(empty.current == "") + #expect(empty.latest == nil) + #expect(!empty.isAvailable) + #expect(empty.command == UpdateStatus.defaultCommand) + #expect(empty.wren == nil) + + let odd = try decode( + UpdateStatus.self, + #"{"enabled":"yes","current":5,"latest":{"a":1},"available":"true","notes":"text","wren":{"canApprove":"yes","latestRun":{"id":"x"},"target":7},"command":"","someFutureField":[1,2,3]}"#) + #expect(odd.isEnabled) + #expect(odd.current == "") + #expect(odd.notes == nil) + #expect(odd.command == UpdateStatus.defaultCommand) + #expect(odd.wren?.canApprove == false) + #expect(odd.wren?.latestRun == nil) + #expect(odd.wren?.target == nil) + } + + @Test("A release link that is not https is not offered") + func releaseLink() throws { + let status = try decode(UpdateStatus.self, #"{"available":true,"current":"5.2.0","latest":"5.3.0","releaseUrl":"javascript:alert(1)"}"#) + #expect(status.releaseURL == nil) + } + + @Test("Notes that are not in the usual format come as plain text") + func notesText() throws { + let status = try decode( + UpdateStatus.self, + #"{"available":true,"current":"5.2.0","latest":"5.3.0","notes":null,"notesText":"Fixes and improvements."}"#) + #expect(status.notes == nil) + #expect(status.notesText == "Fixes and improvements.") + } + + @Test("Wise Wren's problem, open mode and the reason it cannot update read as sent") + func wrenStates() throws { + let problem = try decode( + UpdateStatus.self, + #"{"available":true,"current":"5.2.0","latest":"5.3.0","wren":{"configured":true,"error":{"code":"wren_unauthorized","message":"Wise Wren did not accept Sylo's token."},"openMode":false,"target":null,"updateSeen":false,"canApprove":false,"whyNot":null,"latestRun":null}}"#) + #expect(problem.wren?.error?.code == "wren_unauthorized") + #expect(problem.wren?.error?.message == "Wise Wren did not accept Sylo's token.") + #expect(!problem.offersUpdateNow) + + let open = try decode( + UpdateStatus.self, + #"{"available":true,"current":"5.2.0","latest":"5.3.0","wren":{"configured":true,"error":null,"openMode":true,"target":{"name":"sylo"},"updateSeen":true,"canApprove":false,"whyNot":"Update now needs a dashboard login.","latestRun":null}}"#) + #expect(open.wren?.isOpenMode == true) + #expect(open.wren?.canApprove == false) + #expect(open.wren?.whyNot == "Update now needs a dashboard login.") + // The button is shown but off; the server says why. + #expect(open.offersUpdateNow) + } + + @Test("A run that is going keeps the notice asking for attention, also with no newer release") + func runningRun() throws { + let status = try decode( + UpdateStatus.self, + #"{"available":false,"current":"5.2.0","latest":"5.2.0","wren":{"configured":true,"canApprove":false,"latestRun":{"id":12,"status":"running","finished":false,"steps":[{"step":"snapshot","status":"done","durationMs":10},{"step":"update","status":"running","durationMs":null}]}}}"#) + #expect(status.needsAttention) + #expect(status.wren?.latestRun?.id == 12) + #expect(status.wren?.latestRun?.isFinished == false) + #expect(status.wren?.latestRun?.described.step == "Starting the new version") + } +} + +@Suite("Update notice: runs") +struct UpdateRunTests { + @Test("Every Wise Wren status has its own sentence and tone") + func described() { + func run(_ status: String, steps: [WrenRun.Step] = []) -> WrenRun.Description { + WrenRun(id: 1, status: status, steps: steps).described + } + #expect(run("queued").tone == .working) + #expect(run("running").tone == .working) + #expect(run("succeeded").tone == .success) + for failure in ["rolled_back", "failed", "rollback_failed", "refused", "cancelled", "lapsed"] { + #expect(run(failure).tone == .failure) + } + #expect(run("rolled_back").text.contains("rolled back")) + #expect(run("rollback_failed").text.contains("rollback failed")) + // A state a newer Wise Wren adds still reads, as work in progress. + #expect(run("hovering").tone == .working) + #expect(run("hovering").text == "Wise Wren is working on the update.") + } + + @Test("A run is finished in every status but queued and running, and the server's word wins") + func finished() throws { + #expect(!WrenRun(id: 1, status: "queued").isFinished) + #expect(!WrenRun(id: 1, status: "running").isFinished) + for status in ["succeeded", "rolled_back", "failed", "rollback_failed", "refused", "cancelled", "lapsed"] { + #expect(WrenRun(id: 1, status: status).isFinished) + } + #expect(try decode(WrenRun.self, #"{"id":3,"status":"failed"}"#).isFinished) + #expect(try decode(WrenRun.self, #"{"id":3,"status":"running","finished":true}"#).isFinished) + #expect(try decode(WrenRun.self, #"{"id":3}"#).status == "queued") + } + + @Test("The step it is on shows in words; a step the app does not know shows as named") + func steps() { + let running = WrenRun( + id: 1, status: "running", + steps: [ + WrenRun.Step(step: "preflight", status: "done"), + WrenRun.Step(step: "snapshot", status: "running"), + ]) + #expect(running.described.step == "Taking a snapshot of the data") + let odd = WrenRun(id: 1, status: "running", steps: [WrenRun.Step(step: "warmup", status: "running")]) + #expect(odd.described.step == "warmup") + #expect(WrenRun(id: 1, status: "running").described.step == nil) + #expect(WrenRun.stepLabel("health") == "Checking that Sylo is healthy") + } + + @Test("A failed read is Sylo restarting when it has no words from Wise Wren") + func syloIsDown() { + for down in [ + NetworkError.offline, .unreachable, .timeout, .notASyloServer, .transport(code: -1), + .server(status: HTTPStatus(502)), .server(status: 503), + // A reverse proxy without an upstream answers a plain-text 404 while Sylo restarts. + .notFound(message: nil), + ] { + #expect(UpdateModel.syloIsDown(down), "\(down)") + } + for answer in [ + NetworkError.server(status: HTTPStatus(502, message: "Wise Wren did not accept Sylo's token.")), + .http(status: HTTPStatus(409, message: "An update of Sylo is already running in Wise Wren.")), + .notFound(message: "Wise Wren does not know this target."), .forbidden, .rateLimited, + .decoding("x"), .badRequest(message: nil), + ] { + #expect(!UpdateModel.syloIsDown(answer), "\(answer)") + } + } + + @Test("The calls go to the update routes, operators only") + func endpoints() throws { + #expect(Endpoints.LoadUpdate().path == "/api/v2/update") + #expect(Endpoints.LoadUpdate().query.isEmpty) + #expect(Endpoints.LoadUpdate(refresh: true).query == [URLQueryItem(name: "refresh", value: "1")]) + #expect(Endpoints.LoadUpdate().method == .get) + let approve = Endpoints.ApproveUpdate() + #expect(approve.path == "/api/v2/update/wren/approve") + #expect(approve.method == .post) + #expect(approve.body == nil) + #expect(approve.rawBody == nil) + #expect(Endpoints.LoadUpdateRun(id: 42).path == "/api/v2/update/wren/runs/42") + let started = try decode(UpdateStarted.self, #"{"runId":42,"status":"queued","from":"5.2.0"}"#) + #expect(started.runID == 42) + #expect(started.from == "5.2.0") + #expect(try decode(UpdateRunAnswer.self, #"{"run":{"id":42,"status":"running","steps":[]}}"#).run.id == 42) + } +} + +@MainActor +@Suite("Update notice: the model") +struct UpdateModelTests { + private func makeModel(_ clients: StubClients, giveUpAfter: Duration = .seconds(10)) -> UpdateModel { + UpdateModel( + session: makeSignedInSession(clients: clients), pollEvery: .milliseconds(1), giveUpAfter: giveUpAfter) + } + + private func waitUntilDone(_ model: UpdateModel) async { + for _ in 0..<2000 where model.progress?.isDone != true { try? await Task.sleep(for: .milliseconds(2)) } + } + + nonisolated private static func availableStatus(current: String = "5.2.0", canApprove: Bool = true) -> UpdateStatus { + UpdateStatus( + current: current, latest: "5.3.0", isAvailable: true, + wren: WrenStatus(target: WrenStatus.Target(name: "sylo"), updateSeen: true, canApprove: canApprove)) + } + + @Test("Loading reads the notice; an account that is not an operator reads nothing") + func loads() async { + let clients = StubClients { endpoint in + guard endpoint is Endpoints.LoadUpdate else { throw NetworkError.notFound } + return Self.availableStatus() + } + let model = makeModel(clients) + await model.load() + #expect(model.status?.latest == "5.3.0") + #expect(model.errorMessage == nil) + #expect(!model.isRefused) + + let refused = makeModel(StubClients { _ in throw NetworkError.forbidden }) + await refused.load() + #expect(refused.isRefused) + #expect(refused.status == nil) + #expect(refused.progress == nil) + } + + @Test("Update now asks Wise Wren, follows the run through Sylo's restart and ends on the new version") + func updatesThroughRestart() async { + let runReads = Tally() + let statusReads = Tally() + let clients = StubClients { endpoint in + switch endpoint { + case is Endpoints.LoadUpdate: + // The first read is the model's own; later ones are after the restart. + return Self.availableStatus(current: statusReads.next() == 1 ? "5.2.0" : "5.3.0") + case is Endpoints.ApproveUpdate: + return UpdateStarted(runID: 7, from: "5.2.0") + case is Endpoints.LoadUpdateRun: + switch runReads.next() { + case 1: return UpdateRunAnswer(run: WrenRun(id: 7, status: "running")) + case 2: throw NetworkError.unreachable + case 3: throw NetworkError.server(status: HTTPStatus(502)) + default: return UpdateRunAnswer(run: WrenRun(id: 7, status: "succeeded")) + } + default: throw NetworkError.notFound + } + } + let model = makeModel(clients) + await model.load() + #expect(await model.approve()) + #expect(model.progress?.runID == 7) + await waitUntilDone(model) + let progress = model.progress + #expect(progress?.isDone == true) + #expect(progress?.newVersion == "5.3.0") + #expect(progress?.text == "Sylo is now on 5.3.0.") + #expect(progress?.tone == .success) + #expect(progress?.timedOut == false) + #expect(runReads.value >= 4) + #expect(clients.calls.filter { $0.endpoint is Endpoints.ApproveUpdate }.count == 1) + model.closeProgress() + #expect(model.progress == nil) + #expect(!model.isFollowing) + } + + @Test("A run that ends in a rollback ends the asking, with the old version still running") + func rollsBack() async { + let clients = StubClients { endpoint in + switch endpoint { + case is Endpoints.LoadUpdate: return Self.availableStatus() + case is Endpoints.ApproveUpdate: return UpdateStarted(runID: 8, from: "5.2.0") + case is Endpoints.LoadUpdateRun: return UpdateRunAnswer(run: WrenRun(id: 8, status: "rolled_back")) + default: throw NetworkError.notFound + } + } + let model = makeModel(clients) + await model.load() + #expect(await model.approve()) + await waitUntilDone(model) + #expect(model.progress?.isDone == true) + #expect(model.progress?.newVersion == nil) + #expect(model.progress?.tone == .failure) + #expect(model.progress?.text.contains("rolled back") == true) + } + + @Test("Wise Wren's refusal is shown in its own words and nothing is followed") + func refused() async { + let clients = StubClients { endpoint in + switch endpoint { + case is Endpoints.LoadUpdate: return Self.availableStatus() + case is Endpoints.ApproveUpdate: + throw NetworkError.http( + status: HTTPStatus(409, message: "An update of Sylo is already running in Wise Wren.")) + default: throw NetworkError.notFound + } + } + let model = makeModel(clients) + await model.load() + #expect(await model.approve() == false) + #expect(model.actionError == "An update of Sylo is already running in Wise Wren.") + #expect(model.progress == nil) + #expect(!model.isFollowing) + } + + @Test("Nothing is asked of Wise Wren when there is no update to approve, or Wise Wren is not set up") + func guarded() async { + let calls = StubClients { endpoint in + if endpoint is Endpoints.LoadUpdate { return UpdateStatus(current: "5.3.0", latest: "5.3.0") } + throw NetworkError.notFound + } + let model = makeModel(calls) + await model.load() + #expect(await model.approve() == false) + #expect(!calls.calls.contains { $0.endpoint is Endpoints.ApproveUpdate }) + + let noWren = StubClients { endpoint in + if endpoint is Endpoints.LoadUpdate { return UpdateStatus(current: "5.2.0", latest: "5.3.0", isAvailable: true) } + throw NetworkError.notFound + } + let plain = makeModel(noWren) + await plain.load() + #expect(await plain.approve() == false) + #expect(!noWren.calls.contains { $0.endpoint is Endpoints.ApproveUpdate }) + } + + @Test("A run that is already going (started elsewhere) is followed when the notice loads") + func followsRunningRun() async { + let reads = Tally() + let clients = StubClients { endpoint in + switch endpoint { + case is Endpoints.LoadUpdate: + return UpdateStatus( + current: "5.2.0", latest: "5.3.0", isAvailable: true, + wren: WrenStatus(latestRun: WrenRun(id: 21, status: "running"))) + case is Endpoints.LoadUpdateRun: + return UpdateRunAnswer(run: WrenRun(id: 21, status: reads.next() < 3 ? "running" : "failed")) + default: throw NetworkError.notFound + } + } + let model = makeModel(clients) + await model.load() + #expect(model.progress?.runID == 21) + await waitUntilDone(model) + #expect(model.progress?.run?.status == "failed") + #expect(model.progress?.tone == .failure) + } + + @Test("An update that never comes back ends with a note after the time is up") + func givesUp() async { + let clients = StubClients { endpoint in + switch endpoint { + case is Endpoints.LoadUpdate: return Self.availableStatus() + case is Endpoints.ApproveUpdate: return UpdateStarted(runID: 9, from: "5.2.0") + case is Endpoints.LoadUpdateRun: throw NetworkError.unreachable + default: throw NetworkError.notFound + } + } + let model = makeModel(clients, giveUpAfter: .milliseconds(40)) + await model.load() + #expect(await model.approve()) + await waitUntilDone(model) + #expect(model.progress?.timedOut == true) + #expect(model.progress?.isDone == true) + #expect(model.progress?.isSyloDown == true) + } +} + +@MainActor +@Suite("Update notice: the model, round two") +struct UpdateModelRoundTwoTests { + private func makeModel(_ clients: StubClients, giveUpAfter: Duration = .seconds(10)) -> UpdateModel { + UpdateModel( + session: makeSignedInSession(clients: clients), pollEvery: .milliseconds(1), giveUpAfter: giveUpAfter) + } + + private func waitUntilDone(_ model: UpdateModel) async { + for _ in 0..<2000 where model.progress?.isDone != true { try? await Task.sleep(for: .milliseconds(2)) } + } + + nonisolated private static func available(current: String = "5.2.0", run: WrenRun? = nil) -> UpdateStatus { + UpdateStatus( + current: current, latest: "5.3.0", isAvailable: true, + wren: WrenStatus(target: WrenStatus.Target(name: "sylo"), updateSeen: true, canApprove: true, latestRun: run)) + } + + @Test("Leaving the screen while Sylo is down and coming back picks the run up again, and it ends on the new version") + func resumesAfterLeaving() async { + let down = LockedFlag() + let reads = Tally() + let clients = StubClients { endpoint in + switch endpoint { + case is Endpoints.LoadUpdate: + if down.value { throw NetworkError.unreachable } + return Self.available(current: reads.next() == 1 ? "5.2.0" : "5.3.0") + case is Endpoints.ApproveUpdate: + return UpdateStarted(runID: 6, from: "5.2.0") + case is Endpoints.LoadUpdateRun: + if down.value { throw NetworkError.unreachable } + return UpdateRunAnswer(run: WrenRun(id: 6, status: "succeeded")) + default: throw NetworkError.notFound + } + } + let model = makeModel(clients) + await model.load() + down.value = true + #expect(await model.approve()) + // The person looks away (the screen disappears) while Sylo restarts. + model.stop() + #expect(!model.isFollowing) + #expect(model.progress?.isDone == false) + // Back on the screen while Sylo is still down: the read of the notice fails, and the run is followed again. + await model.load() + #expect(model.errorMessage != nil) + #expect(model.isFollowing) + #expect(model.progress?.runID == 6) + down.value = false + await waitUntilDone(model) + #expect(model.progress?.newVersion == "5.3.0") + #expect(model.progress?.isDone == true) + #expect(clients.calls.filter { $0.endpoint is Endpoints.ApproveUpdate }.count == 1) + } + + @Test("Following again keeps the last state of the same run") + func keepsLastState() async { + let clients = StubClients { endpoint in + if endpoint is Endpoints.LoadUpdate { return Self.available() } + if endpoint is Endpoints.ApproveUpdate { return UpdateStarted(runID: 9, from: "5.2.0") } + return UpdateRunAnswer(run: WrenRun(id: 9, status: "running", steps: [WrenRun.Step(step: "snapshot", status: "running")])) + } + let model = makeModel(clients) + await model.load() + #expect(await model.approve()) + for _ in 0..<500 where model.progress?.run == nil { try? await Task.sleep(for: .milliseconds(2)) } + model.stop() + #expect(model.progress?.run?.status == "running") + model.follow(runID: 9, from: "5.2.0") + #expect(model.progress?.run?.status == "running") + model.stop() + } + + @Test("A row that only shows the status never follows a run") + func rowDoesNotFollow() async { + let clients = StubClients { endpoint in + if endpoint is Endpoints.LoadUpdate { return Self.available(run: WrenRun(id: 3, status: "running")) } + return UpdateRunAnswer(run: WrenRun(id: 3, status: "running")) + } + let model = makeModel(clients) + await model.load(followsRun: false) + #expect(model.status?.wren?.latestRun?.id == 3) + #expect(!model.isFollowing) + #expect(model.progress == nil) + #expect(!clients.calls.contains { $0.endpoint is Endpoints.LoadUpdateRun }) + // The screen itself follows. + await model.load() + #expect(model.isFollowing) + model.stop() + } + + @Test("After Sylo is back the version is read once, not on every poll until the run ends") + func versionReadOnce() async { + let runReads = Tally() + let statusReads = Tally() + let clients = StubClients { endpoint in + switch endpoint { + case is Endpoints.LoadUpdate: + // 1: the model's own read, 2: Sylo is back (still the old version), 3: the run has ended. + return Self.available(current: statusReads.next() < 3 ? "5.2.0" : "5.3.0") + case is Endpoints.ApproveUpdate: return UpdateStarted(runID: 4, from: "5.2.0") + case is Endpoints.LoadUpdateRun: + switch runReads.next() { + case 1: throw NetworkError.unreachable + case 2, 3, 4, 5, 6: return UpdateRunAnswer(run: WrenRun(id: 4, status: "running")) + default: return UpdateRunAnswer(run: WrenRun(id: 4, status: "succeeded")) + } + default: throw NetworkError.notFound + } + } + let model = makeModel(clients) + await model.load() + #expect(await model.approve()) + await waitUntilDone(model) + #expect(model.progress?.newVersion == "5.3.0") + #expect(runReads.value >= 7) + #expect(clients.calls.filter { $0.endpoint is Endpoints.LoadUpdate }.count == 3) + } + + @Test("An operator who is no longer one, or a run that is not there, ends the asking with the reason") + func permanentErrors() async { + for failure in [NetworkError.forbidden, .notFound(message: "Wise Wren does not know this target.")] { + let clients = StubClients { endpoint in + switch endpoint { + case is Endpoints.LoadUpdate: return Self.available() + case is Endpoints.ApproveUpdate: return UpdateStarted(runID: 8, from: "5.2.0") + case is Endpoints.LoadUpdateRun: throw failure + default: throw NetworkError.notFound + } + } + let model = makeModel(clients) + await model.load() + #expect(await model.approve()) + await waitUntilDone(model) + #expect(model.progress?.isDone == true) + #expect(model.progress?.problem != nil) + #expect(model.progress?.timedOut == false) + #expect(UpdateModel.isPermanent(failure)) + } + #expect(!UpdateModel.isPermanent(.notFound(message: nil))) + #expect(!UpdateModel.isPermanent(.unreachable)) + #expect(!UpdateModel.isPermanent(.server(status: HTTPStatus(502, message: "Wise Wren had an error.")))) + } + + @Test("A plain-text 404 from a proxy during the restart reads as Sylo restarting, with no error shown") + func proxy404() async { + let runReads = Tally() + let clients = StubClients { endpoint in + switch endpoint { + case is Endpoints.LoadUpdate: return Self.available(current: runReads.value >= 3 ? "5.3.0" : "5.2.0") + case is Endpoints.ApproveUpdate: return UpdateStarted(runID: 2, from: "5.2.0") + case is Endpoints.LoadUpdateRun: + if runReads.next() <= 2 { throw NetworkError.notFound(message: nil) } + return UpdateRunAnswer(run: WrenRun(id: 2, status: "succeeded")) + default: throw NetworkError.notFound + } + } + let model = makeModel(clients) + await model.load() + #expect(await model.approve()) + await waitUntilDone(model) + #expect(model.progress?.problem == nil) + #expect(model.progress?.newVersion == "5.3.0") + } +} diff --git a/apps/sylo-ios/sylo-ios.xcodeproj/project.pbxproj b/apps/sylo-ios/sylo-ios.xcodeproj/project.pbxproj index 2e5381d2..b6f1980d 100644 --- a/apps/sylo-ios/sylo-ios.xcodeproj/project.pbxproj +++ b/apps/sylo-ios/sylo-ios.xcodeproj/project.pbxproj @@ -366,7 +366,7 @@ ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; CODE_SIGN_ENTITLEMENTS = "sylo-ios/sylo-ios.entitlements"; CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 9; + CURRENT_PROJECT_VERSION = 10; ENABLE_APP_SANDBOX = YES; ENABLE_PREVIEWS = YES; ENABLE_USER_SELECTED_FILES = readonly; @@ -387,7 +387,7 @@ LD_RUNPATH_SEARCH_PATHS = "@executable_path/Frameworks"; "LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]" = "@executable_path/../Frameworks"; MACOSX_DEPLOYMENT_TARGET = "$(RECOMMENDED_MACOSX_DEPLOYMENT_TARGET)"; - MARKETING_VERSION = 1.2; + MARKETING_VERSION = 1.3; PRODUCT_BUNDLE_IDENTIFIER = net.opland.sylo; PRODUCT_NAME = "$(TARGET_NAME)"; REGISTER_APP_GROUPS = YES; @@ -412,7 +412,7 @@ ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; CODE_SIGN_ENTITLEMENTS = "sylo-ios/sylo-ios.entitlements"; CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 9; + CURRENT_PROJECT_VERSION = 10; ENABLE_APP_SANDBOX = YES; ENABLE_PREVIEWS = YES; ENABLE_USER_SELECTED_FILES = readonly; @@ -433,7 +433,7 @@ LD_RUNPATH_SEARCH_PATHS = "@executable_path/Frameworks"; "LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]" = "@executable_path/../Frameworks"; MACOSX_DEPLOYMENT_TARGET = "$(RECOMMENDED_MACOSX_DEPLOYMENT_TARGET)"; - MARKETING_VERSION = 1.2; + MARKETING_VERSION = 1.3; PRODUCT_BUNDLE_IDENTIFIER = net.opland.sylo; PRODUCT_NAME = "$(TARGET_NAME)"; REGISTER_APP_GROUPS = YES; @@ -457,7 +457,7 @@ APPLICATION_EXTENSION_API_ONLY = YES; CODE_SIGN_ENTITLEMENTS = SyloNotificationService/SyloNotificationService.entitlements; CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 9; + CURRENT_PROJECT_VERSION = 10; GENERATE_INFOPLIST_FILE = YES; INFOPLIST_FILE = SyloNotificationService/Info.plist; INFOPLIST_KEY_CFBundleDisplayName = SyloNotificationService; @@ -468,7 +468,7 @@ "@executable_path/Frameworks", "@executable_path/../../Frameworks", ); - MARKETING_VERSION = 1.2; + MARKETING_VERSION = 1.3; PRODUCT_BUNDLE_IDENTIFIER = "net.opland.sylo.notification-service"; PRODUCT_NAME = "$(TARGET_NAME)"; REGISTER_APP_GROUPS = YES; @@ -493,7 +493,7 @@ APPLICATION_EXTENSION_API_ONLY = YES; CODE_SIGN_ENTITLEMENTS = SyloNotificationService/SyloNotificationService.entitlements; CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 9; + CURRENT_PROJECT_VERSION = 10; GENERATE_INFOPLIST_FILE = YES; INFOPLIST_FILE = SyloNotificationService/Info.plist; INFOPLIST_KEY_CFBundleDisplayName = SyloNotificationService; @@ -504,7 +504,7 @@ "@executable_path/Frameworks", "@executable_path/../../Frameworks", ); - MARKETING_VERSION = 1.2; + MARKETING_VERSION = 1.3; PRODUCT_BUNDLE_IDENTIFIER = "net.opland.sylo.notification-service"; PRODUCT_NAME = "$(TARGET_NAME)"; REGISTER_APP_GROUPS = YES; diff --git a/apps/sylo-ios/sylo-ios/Design/HexColor.swift b/apps/sylo-ios/sylo-ios/Design/HexColor.swift new file mode 100644 index 00000000..7406e458 --- /dev/null +++ b/apps/sylo-ios/sylo-ios/Design/HexColor.swift @@ -0,0 +1,10 @@ +import SwiftUI +import SyloKit + +extension Color { + /// A `#rrggbb` colour (the form the server sends and takes for a server's accent); nil for anything else. + init?(hex: String) { + guard let rgb = AccentColour.components(hex) else { return nil } + self.init(.sRGB, red: Double(rgb.red) / 255, green: Double(rgb.green) / 255, blue: Double(rgb.blue) / 255) + } +} diff --git a/apps/sylo-ios/sylo-ios/Views/Operator/BackupsView.swift b/apps/sylo-ios/sylo-ios/Views/Operator/BackupsView.swift index 836171a8..1386e2f6 100644 --- a/apps/sylo-ios/sylo-ios/Views/Operator/BackupsView.swift +++ b/apps/sylo-ios/sylo-ios/Views/Operator/BackupsView.swift @@ -93,6 +93,13 @@ struct BackupsView: View { } if let kept = database.backupsKept { LabeledContent("Kept", value: kept.formatted()) } LabeledContent("Off-site copies", value: database.offsite ?? "None") + // Sylo 5.3: the role Sylo connects as has rights a restore of an uploaded dump would use. + if database.isPostgres, let sentence = UploadedDumpNotice.roleSentence(database.roleRisks) { + StatusMessage(sentence, kind: .error) + if let docs = database.roleDocsURL { + Link("How to set up a role with few rights", destination: docs) + } + } } } Section { @@ -186,7 +193,11 @@ struct BackupsView: View { } header: { Text("Import") } footer: { - Text("Importing stores the file as a snapshot (up to 128 MB); you then restore it. Restoring replaces the live database and restarts the bot, with a prerestore snapshot taken first.") + if model.report?.database?.isPostgres == true { + Text("Importing stores the file as a snapshot (up to 128 MB); you then restore it. Restoring replaces the live database and restarts the bot, with a prerestore snapshot taken first. A Postgres dump holds SQL, and restoring it runs that SQL with the rights of Sylo's database role, so import only files you made or trust.") + } else { + Text("Importing stores the file as a snapshot (up to 128 MB); you then restore it. Restoring replaces the live database and restarts the bot, with a prerestore snapshot taken first.") + } } } @@ -259,6 +270,74 @@ private struct BackupRow: View { } } +/// The restore of an uploaded Postgres dump (Sylo 5.3): the SQL in the file runs with the rights of the database role +/// Sylo connects as, so the person says they made the file or trust it, and types the snapshot's name, before the +/// server is asked. The server refuses the restore without `acknowledgeSql`. +private struct RestoreDumpSheet: View { + let backup: HealthReport.Backup + let database: HealthReport.Database? + let model: BackupsModel + + @Environment(\.dismiss) private var dismiss + @State private var understood = false + @State private var typed = "" + + private var confirmation: OperatorConfirmation { .restore(backup: backup.name) } + + var body: some View { + NavigationStack { + Form { + Section { + Label { + Text(verbatim: UploadedDumpNotice.title) + .font(.headline) + } icon: { + Image(systemName: "exclamationmark.triangle.fill") + .symbolRenderingMode(.multicolor) + } + Text(verbatim: UploadedDumpNotice.message) + if let sentence = UploadedDumpNotice.roleSentence(database?.roleRisks) { + Text(verbatim: sentence) + .foregroundStyle(.orange) + } + if let docs = database?.roleDocsURL { + Link("How to set up a role with few rights", destination: docs) + } + } + Section { + Toggle(UploadedDumpNotice.acknowledgement, isOn: $understood) + } + Section { + Text(verbatim: confirmation.message) + .font(.footnote) + TextField(backup.name, text: $typed) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + .font(.body.monospaced()) + } header: { + Text("Type the name to confirm") + } footer: { + Text("Type \(backup.name) to confirm.") + } + Section { + Button("Restore and Restart", role: .destructive) { + dismiss() + Task { await model.restore(backup.name, typed: typed, acknowledgedSql: understood) } + } + .disabled(!understood || !confirmation.accepts(typed)) + } + } + .navigationTitle("Restore Uploaded Dump") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button("Cancel") { dismiss() } + } + } + } + } +} + /// What the screen shows from the moment the server takes a restore until Sylo answers again. private struct RestoringView: View { let name: String @@ -290,8 +369,14 @@ private struct BackupDetailView: View { /// The downloaded file while Quick Look shows it. @State private var previewed: DownloadedFile? @State private var isConfirmingRestore = false + @State private var isShowingDumpWarning = false @State private var isConfirmingDelete = false + /// What a restore of this snapshot asks (an uploaded Postgres dump needs its own warning first). + private var restorePlan: RestorePlan { + RestorePlan.make(name: backup.name, database: model.report?.database) + } + init(backup: HealthReport.Backup, model: BackupsModel, session: AppSession) { self.backup = backup self.model = model @@ -314,10 +399,21 @@ private struct BackupDetailView: View { } downloadSection Section { - Button("Restore\u{2026}", role: .destructive) { isConfirmingRestore = true } - .disabled(model.isWorking) + Button("Restore\u{2026}", role: .destructive) { + if restorePlan.isUploadedSqlDump { + isShowingDumpWarning = true + } else { + isConfirmingRestore = true + } + } + .disabled(model.isWorking) } footer: { - Text("Restoring replaces the live database with this backup and restarts the bot. It changes the data of every server at once.") + VStack(alignment: .leading, spacing: 4) { + Text("Restoring replaces the live database with this backup and restarts the bot. It changes the data of every server at once.") + if restorePlan.isUploadedSqlDump { + Text(verbatim: UploadedDumpNotice.title + ". " + UploadedDumpNotice.message) + } + } } Section { Button("Delete Backup\u{2026}", role: .destructive) { isConfirmingDelete = true } @@ -330,6 +426,9 @@ private struct BackupDetailView: View { .typedConfirmation(.restore(backup: backup.name), isPresented: $isConfirmingRestore) { typed in Task { await model.restore(backup.name, typed: typed) } } + .sheet(isPresented: $isShowingDumpWarning) { + RestoreDumpSheet(backup: backup, database: model.report?.database, model: model) + } .typedConfirmation(.deleteBackup(name: backup.name), isPresented: $isConfirmingDelete) { typed in Task { if await model.delete(backup.name, typed: typed) { dismiss() } diff --git a/apps/sylo-ios/sylo-ios/Views/Server/FocusedToolsView.swift b/apps/sylo-ios/sylo-ios/Views/Server/FocusedToolsView.swift new file mode 100644 index 00000000..c673c1c2 --- /dev/null +++ b/apps/sylo-ios/sylo-ios/Views/Server/FocusedToolsView.swift @@ -0,0 +1,82 @@ +import SwiftUI +import SyloKit + +/// The Tools tab of the focused moderator view (an Inbox-level person on a Sylo 5.3 server): the queues that are not +/// tickets or appeals (applications, suggestions) and Member data, and the way back to the full app. The same +/// pages the web dashboard's focused sidebar lists. +struct FocusedToolsView: View { + let model: OverviewModel + /// Whether the person chose to see everything; set to true to leave the focused view. + @Binding var showEverything: Bool + + @Environment(AppSession.self) private var session + + @ScaledMetric(relativeTo: .body) private var iconWidth = 28 + + var body: some View { + let tools = ModeratorView.tools(overview: model.overview) + List { + if let message = model.errorMessage, model.overview == nil { + Section { StatusMessage(message, kind: .error) } + } + Section { + ForEach(tools, id: \.self) { tool in + row(for: tool) + } + } header: { + Text("Moderation tools") + } footer: { + Text("Tickets and ban appeals have their own tabs.") + } + Section { + Button { + showEverything = true + } label: { + Label("Show Everything", systemImage: "square.grid.2x2") + } + } footer: { + Text("You have Inbox access, so Sylo shows the moderation tools only. Show everything brings back the modules and the settings; they stay switched off for your level.") + } + } + .tabBarClearance() + .refreshable { await model.load() } + } + + @ViewBuilder + private func row(for tool: ModeratorView.Tool) -> some View { + switch tool { + case .applications: + NavigationLink(value: ModuleRoute(moduleID: "applications")) { + label("Applications", symbol: "doc.text") + } + case .suggestions: + NavigationLink(value: ModuleRoute(moduleID: "suggestions")) { + label("Suggestions", symbol: "lightbulb") + } + case .memberData: + NavigationLink { + MemberDataView(server: model.server, session: session) + } label: { + label("Member Data", symbol: "person.text.rectangle") + } + } + } + + private func label(_ title: LocalizedStringKey, symbol: String) -> some View { + Label { + Text(title) + } icon: { + Image(systemName: symbol) + .foregroundStyle(.tint) + .frame(width: iconWidth) + } + } +} + +#Preview { + let session = AppSession.preview(.signedIn) + NavigationStack { + FocusedToolsView(model: OverviewModel(server: "1", session: session), showEverything: .constant(false)) + } + .environment(session) +} diff --git a/apps/sylo-ios/sylo-ios/Views/Server/GuildSettingsForm.swift b/apps/sylo-ios/sylo-ios/Views/Server/GuildSettingsForm.swift index fcd71c0d..6cc06e1b 100644 --- a/apps/sylo-ios/sylo-ios/Views/Server/GuildSettingsForm.swift +++ b/apps/sylo-ios/sylo-ios/Views/Server/GuildSettingsForm.swift @@ -71,6 +71,12 @@ struct GuildSettingsForm: View { } .disabled(!access.canEdit) + // The server's look on its public pages exists on a Sylo that announces `public-page-look` (5.3 and + // later), and is Edit work, the read too. + if access.canEdit, session.has(.publicPageLook) { + publicPagesSection + } + serverDataSection } .tabBarClearance() @@ -126,6 +132,19 @@ struct GuildSettingsForm: View { set: { model.accessDraft?[keyPath: keyPath] = $0 }) } + /// The accent colour and background of the pages members open without the dashboard. + private var publicPagesSection: some View { + Section { + NavigationLink { + PublicPagesSettingsView(server: model.server, session: session) + } label: { + Label("Public Pages", systemImage: "globe") + } + } footer: { + Text("Give the application forms, ban appeals, the web shop, the quote page and the leaderboards your server's accent colour and a background.") + } + } + /// What Sylo keeps about this server: its change history, its configuration as a file, and what /// it stores about a member. private var serverDataSection: some View { diff --git a/apps/sylo-ios/sylo-ios/Views/Server/Moderation/ModerationTabView.swift b/apps/sylo-ios/sylo-ios/Views/Server/Moderation/ModerationTabView.swift index 3eb1125e..602fe4af 100644 --- a/apps/sylo-ios/sylo-ios/Views/Server/Moderation/ModerationTabView.swift +++ b/apps/sylo-ios/sylo-ios/Views/Server/Moderation/ModerationTabView.swift @@ -3,37 +3,64 @@ import SyloKit /// The Moderation tab of a server: Infractions (cases, bans, lockdown), Appeals and Commands behind /// a segmented switch. Titles live in ``ServerView``; each part is the same screen the overview's -/// link cards and the module settings open on their own. +/// link cards and the module settings open on their own. In the focused moderator view (Sylo 5.3, an Inbox-level +/// person) it has no Commands part, which is Edit work, and no Appeals part while the Appeals module is off. struct ModerationTabView: View { let server: ServerID let session: AppSession + private let showsAppeals: Bool + private let showsCommands: Bool + private let initialPart: Part /// The open appeals, kept by ``ServerView`` for the tab's badge; the Appeals segment shows it too. @Environment(OpenAppealsModel.self) private var openAppeals: OpenAppealsModel? - @State private var part: Part = .infractions + @State private var part: Part enum Part: Hashable { case infractions, appeals, commands } + init( + server: ServerID, session: AppSession, showsAppeals: Bool = true, showsCommands: Bool = true, + initialPart: Part = .infractions + ) { + self.server = server + self.session = session + self.showsAppeals = showsAppeals + self.showsCommands = showsCommands + self.initialPart = initialPart + _part = State(initialValue: initialPart) + } + /// "Appeals (2)": what the tab's badge counts. private var appealsTitle: LocalizedStringKey { if let count = openAppeals?.count, count > 0 { return "Appeals (\(count))" } return "Appeals" } + /// The part shown: the chosen one, unless it is not offered here. + private var visiblePart: Part { + switch part { + case .appeals where !showsAppeals: .infractions + case .commands where !showsCommands: .infractions + default: part + } + } + var body: some View { VStack(spacing: 0) { - Picker("Section", selection: $part) { - Text("Infractions").tag(Part.infractions) - Text(appealsTitle).tag(Part.appeals) - Text("Commands").tag(Part.commands) + if showsAppeals || showsCommands { + Picker("Section", selection: $part) { + Text("Infractions").tag(Part.infractions) + if showsAppeals { Text(appealsTitle).tag(Part.appeals) } + if showsCommands { Text("Commands").tag(Part.commands) } + } + .pickerStyle(.segmented) + .padding(.horizontal) + .padding(.vertical, 8) } - .pickerStyle(.segmented) - .padding(.horizontal) - .padding(.vertical, 8) - switch part { + switch visiblePart { case .infractions: ModerationView(server: server, session: session) case .appeals: @@ -43,6 +70,9 @@ struct ModerationTabView: View { CommandsView(server: server, session: session, isEmbedded: true).disabledBelow() } } + // The focused view starts on Appeals when that is where the server opens; the overview that decides it may + // arrive after this view was made, so the start is applied again when it changes. + .onChange(of: initialPart) { _, start in part = start } } } diff --git a/apps/sylo-ios/sylo-ios/Views/Server/PublicPagesSettingsView.swift b/apps/sylo-ios/sylo-ios/Views/Server/PublicPagesSettingsView.swift new file mode 100644 index 00000000..00018d93 --- /dev/null +++ b/apps/sylo-ios/sylo-ios/Views/Server/PublicPagesSettingsView.swift @@ -0,0 +1,360 @@ +import PhotosUI +import SwiftUI +import SyloKit +import UIKit + +/// Server settings -> Public pages (Sylo 5.3): the server's own accent colour and background on the pages its +/// members open without the dashboard (application forms and the web shop, ban appeals, the quote page and the +/// leaderboards). Only these two things change; the layout, the type, the light and dark themes and the "Powered by +/// Sylo" link stay Sylo's, and the dashboard and this app are never restyled. Edit level only. Mirrors +/// web-v2/src/components/PublicPagesSettings.jsx. +struct PublicPagesSettingsView: View { + @State private var model: PublicLookModel + + @Environment(\.dashboardAccess) private var access + @Environment(\.serverPlatform) private var platform + @Environment(\.colorScheme) private var colorScheme + @State private var isConfirmingDiscard = false + @State private var isAskingToRemove = false + @State private var selection: PhotosPickerItem? + @State private var isPreparing = false + @State private var prepareError: String? + + init(server: ServerID, session: AppSession) { + _model = State(initialValue: PublicLookModel(server: server, session: session)) + } + + var body: some View { + Group { + if let look = model.look { + form(look) + } else if let message = model.errorMessage { + ContentUnavailableView { + Label("Couldn't Load Public Pages", systemImage: "exclamationmark.triangle") + } description: { + Text(message) + } actions: { + Button("Try Again") { Task { await model.load() } } + } + } else { + ProgressView() + } + } + .navigationTitle("Public Pages") + .navigationBarTitleDisplayMode(.inline) + .navigationBarBackButtonHidden(model.hasChanges) + .tracksUnsavedChanges(model.hasChanges) + .toolbar { + if model.hasChanges { + ToolbarItem(placement: .cancellationAction) { + Button("Discard") { isConfirmingDiscard = true } + .disabled(model.isSaving) + } + } + if model.look != nil { + ToolbarItem(placement: .confirmationAction) { + if model.isSaving { + ProgressView() + } else { + Button("Save") { Task { await model.save() } } + .toolbarSaveStyle() + .disabled(!model.canSave || !access.canEdit) + } + } + } + } + .confirmationDialog("Discard your changes?", isPresented: $isConfirmingDiscard, titleVisibility: .visible) { + Button("Discard Changes", role: .destructive) { model.discardChanges() } + } + .sensoryFeedback(.success, trigger: model.saveCount) + .task { if model.look == nil { await model.load() } } + .lockedBelow() + } + + // MARK: - The form + + private func form(_ look: PublicPageLook) -> some View { + Form { + if let message = model.actionError { + Section { StatusMessage(message, kind: .error) } + } + accentSection + backgroundSection(look) + previewSection(look) + } + .disabled(model.isSaving) + .refreshable { await model.load() } + } + + private var accentSection: some View { + Section { + ColorPicker("Pick the accent colour", selection: pickedColour, supportsOpacity: false) + LabeledContent("Accent colour") { + TextField("Accent colour", text: accentText, prompt: Text(verbatim: AccentColour.syloAccent.dark)) + .multilineTextAlignment(.trailing) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + .font(.body.monospaced()) + .submitLabel(.done) + } + if !model.accentText.isEmpty { + Button("Use Sylo's Colour", systemImage: "arrow.counterclockwise") { + model.accentText = "" + } + } + } header: { + Text("Accent colour") + } footer: { + VStack(alignment: .leading, spacing: 4) { + if !model.accentIsValid { + Text("Use a colour like #5865f2.") + .foregroundStyle(.red) + } else { + Text("Used for buttons, links and highlights. Leave it empty for Sylo's own colour.") + } + if let note = model.accentNote { + Text(verbatim: note) + .foregroundStyle(.orange) + } + } + } + } + + private func backgroundSection(_ look: PublicPageLook) -> some View { + Section { + Picker("Background", selection: backgroundBinding) { + ForEach(model.offeredBackgrounds, id: \.self) { value in + Text(verbatim: title(of: value)).tag(value) + } + } + .pickerStyle(.menu) + PhotosPicker(selection: $selection, matching: .images, photoLibrary: .shared()) { + Label(look.upload == nil ? "Upload a Picture" : "Replace Picture", systemImage: "photo.on.rectangle") + } + .disabled(isPreparing || model.isWorking) + // On one row only: a modifier on the section would be applied to every row of it. + .onChange(of: selection) { _, item in + guard let item else { return } + Task { await prepareAndUpload(item, maxSide: look.limits.maxSide, maxBytes: look.limits.maxBytes) } + } + if isPreparing || model.isWorking { + HStack(spacing: 8) { + ProgressView() + Text(isPreparing ? "Preparing the picture\u{2026}" : "Working\u{2026}").foregroundStyle(.secondary) + } + } + if let prepareError { + StatusMessage(prepareError, kind: .error) + } + if look.upload != nil { + Button("Remove Picture", role: .destructive) { isAskingToRemove = true } + .disabled(model.isWorking) + .confirmationDialog("Remove the picture?", isPresented: $isAskingToRemove, titleVisibility: .visible) { + Button("Remove Picture", role: .destructive) { Task { await model.removePicture() } } + } message: { + Text("A background that uses it goes back to none.") + } + } + if model.background == .discordSplash, look.splash.isAvailable { + Button { + Task { await model.refreshSplash() } + } label: { + Label("Check the Invite Background Now", systemImage: "arrow.clockwise") + } + .disabled(model.isWorking) + } + } header: { + Text("Background") + } footer: { + VStack(alignment: .leading, spacing: 4) { + Text("PNG, JPEG or WebP, at most \(Self.megabytes(look.limits.maxBytes)) MB. The app shrinks a photo to fit. Sylo stores a re-encoded copy without metadata, at most \(look.limits.maxSide) pixels wide, and serves it itself.") + if !look.splash.isAvailable { + Text(verbatim: splashHint(look)) + } else if model.background == .discordSplash { + Text(verbatim: splashHint(look)) + } + if model.waitsForSplash { + Text("The invite background is downloaded when you save.") + } + } + } + } + + private func previewSection(_ look: PublicPageLook) -> some View { + let dark = colorScheme == .dark + let accent = model.accent ?? look.accent + let fill = AccentColour.effective(accent, dark: dark) + return Section { + PublicLookPreview( + accent: Color(hex: fill) ?? .accentColor, + accentText: Color(hex: AccentColour.effectiveText(accent, dark: dark)) ?? .accentColor, + onAccent: Color(hex: AccentColour.onAccent(fill)) ?? .white, + imagePath: model.previewImagePath, isDark: dark) + .listRowInsets(EdgeInsets()) + .listRowBackground(Color.clear) + } header: { + Text("Preview: the application form") + } footer: { + VStack(alignment: .leading, spacing: 4) { + Text("Shown in the \(dark ? "dark" : "light") theme. \(ratios(accent))") + Text("Members see this on the application forms, the web shop, ban appeals, the quote page and the leaderboards. This app and the dashboard keep Sylo's own look.") + } + } + } + + // MARK: - Helpers + + private var accentText: Binding { + Binding(get: { model.accentText }, set: { model.accentText = $0 }) + } + + private var backgroundBinding: Binding { + Binding(get: { model.background }, set: { model.background = $0 }) + } + + /// The system colour picker, as `#rrggbb` in the text field. + private var pickedColour: Binding { + Binding( + get: { + let hex = model.accent.flatMap { $0.isEmpty ? nil : $0 } + ?? (colorScheme == .dark ? AccentColour.syloAccent.dark : AccentColour.syloAccent.light) + return Color(hex: hex) ?? .accentColor + }, + set: { newValue in + let resolved = newValue.resolve(in: EnvironmentValues()) + model.accentText = AccentColour.hex( + red: Double(resolved.red), green: Double(resolved.green), blue: Double(resolved.blue)) + }) + } + + private func title(of background: PublicPageBackground) -> String { + switch background { + case .noBackground: String(localized: "None") + case .upload: String(localized: "My own picture") + case .discordSplash: + platform == .fluxer ? String(localized: "Invite background from Fluxer") : String(localized: "Invite background from Discord") + case .other(let raw): raw + } + } + + private func splashHint(_ look: PublicPageLook) -> String { + let name = (look.platform ?? platform) == .fluxer ? "Fluxer" : "Discord" + if !look.splash.isAvailable { + return String(localized: "This server has no invite background on \(name). Set one there to use it here.") + } + return String(localized: "Sylo keeps its own copy of the server's \(name) invite background and checks it once a day, so visitors never load it from \(name).") + } + + /// "dark 4.6:1, light 2.1:1 (too low)", as the dashboard shows the contrast. + private func ratios(_ accent: String) -> String { + guard !accent.isEmpty else { return "" } + let themes = AccentColour.fallbackThemes(accent) + func part(_ name: String, dark: Bool) -> String { + let ratio = AccentColour.ratio(of: accent, dark: dark) + let low = themes.contains(name) ? " (too low)" : "" + return "\(name) \(ratio.formatted(.number.precision(.fractionLength(0...2)))):1\(low)" + } + return part("dark", dark: true) + ", " + part("light", dark: false) + } + + private static func megabytes(_ bytes: Int) -> Int { max(1, bytes / (1024 * 1024)) } + + /// Reads the photo, shrinks it to what the server takes, and uploads it as the server's own background. + private func prepareAndUpload(_ item: PhotosPickerItem, maxSide: Int, maxBytes: Int) async { + isPreparing = true + prepareError = nil + defer { + isPreparing = false + selection = nil + } + do { + guard let data = try await item.loadTransferable(type: Data.self) else { + throw CollectiblePictureError.unreadable + } + // Decoding and shrinking a 12 MP photo is real work: not on the main actor. + let target = max(1_000_000, maxBytes - 100_000) + let picture = try await Task.detached(priority: .userInitiated) { + try CollectiblePicture.prepare(data, maxSide: maxSide, targetBytes: target) + }.value + isPreparing = false + await model.upload(picture) + } catch is CancellationError { + // The person left the screen. + } catch let error as CollectiblePictureError { + prepareError = error.message + } catch { + prepareError = CollectiblePictureError.unreadable.message + } + } +} + +/// A small picture of an application form page with the chosen accent colour and background: the page, a dim +/// overlay over the picture, the semi-opaque card, one button in the accent colour, and the "Powered by Sylo" link. +private struct PublicLookPreview: View { + let accent: Color + /// The colour of links and labels: the accent lightened or darkened until it reads, as on the pages. + let accentText: Color + let onAccent: Color + let imagePath: String? + let isDark: Bool + + var body: some View { + (isDark ? Color(white: 0.04) : Color(white: 0.96)) + .frame(height: 250) + .overlay { + if let imagePath { + Color.clear + .overlay { AuthenticatedImage(path: imagePath, contentMode: .fill) } + .clipped() + .overlay((isDark ? Color.black : Color.white).opacity(isDark ? 0.55 : 0.4)) + } + } + .overlay { + VStack(spacing: 8) { + card + Text("Powered by Sylo") + .font(.caption2) + .foregroundStyle(.secondary) + } + .padding(16) + } + .clipShape(RoundedRectangle(cornerRadius: 12)) + .accessibilityElement(children: .ignore) + .accessibilityLabel("Preview of an application form page with this accent colour and background") + } + + private var card: some View { + VStack(alignment: .leading, spacing: 8) { + Text("YOUR SERVER") + .font(.caption2.weight(.semibold)) + .foregroundStyle(accentText) + Text("Staff application") + .font(.headline) + (Text("Tell us a little about you. ") + Text("Read the rules first").foregroundStyle(accentText) + Text(".")) + .font(.footnote) + Text("Why do you want to join?") + .font(.footnote) + .foregroundStyle(.secondary) + .padding(8) + .frame(maxWidth: .infinity, alignment: .leading) + .background(.quaternary, in: RoundedRectangle(cornerRadius: 6)) + Text("Submit application") + .font(.footnote.weight(.semibold)) + .foregroundStyle(onAccent) + .padding(.horizontal, 12) + .padding(.vertical, 6) + .background(accent, in: RoundedRectangle(cornerRadius: 6)) + } + .padding(14) + .frame(maxWidth: .infinity, alignment: .leading) + .background((isDark ? Color(white: 0.09) : Color.white).opacity(0.92), in: RoundedRectangle(cornerRadius: 10)) + } +} + +#Preview { + let session = AppSession.preview(.signedIn) + NavigationStack { + PublicPagesSettingsView(server: "1", session: session) + } + .environment(session) +} diff --git a/apps/sylo-ios/sylo-ios/Views/Server/ServerView.swift b/apps/sylo-ios/sylo-ios/Views/Server/ServerView.swift index 828af60f..d63d257a 100644 --- a/apps/sylo-ios/sylo-ios/Views/Server/ServerView.swift +++ b/apps/sylo-ios/sylo-ios/Views/Server/ServerView.swift @@ -1,7 +1,9 @@ import SwiftUI import SyloKit -/// One server, with a tab bar: Modules, Tickets, Moderation and Settings. +/// One server, with a tab bar: Modules, Tickets, Moderation and Settings. A person with Inbox access on a +/// Sylo 5.3 server gets the focused moderator view instead (``ModeratorView``): Tickets, Tools and Moderation, +/// without the modules and the settings, unless they chose "Show everything". /// /// The tab view sits inside the detail column's navigation stack (one stack, never nested), so /// screens pushed from any tab (a module's settings, a ticket) cover the tab bar the way a @@ -26,9 +28,15 @@ struct ServerView: View { /// The setup wizard, shared by the overview's offer, Server settings and the search. @State private var wizard: SetupWizardModel @State private var isSearching = false + /// The Inbox person's choice to see everything (kept on the device). + @AppStorage(ModeratorView.showEverythingKey) private var showEverything = false + /// The read of what this Sylo announces has finished, whether or not it worked. + @State private var featureCheckDone = false + /// The short wait for that read is over: the app draws as it would without the features. + @State private var featureWaitOver = false enum ServerTab: Hashable { - case modules, tickets, moderation, settings + case modules, tickets, tools, moderation, settings } init(summary: ServerSummary, session: AppSession, tab: Binding) { @@ -44,9 +52,70 @@ struct ServerView: View { _wizard = State(initialValue: SetupWizardModel(server: summary.id, session: session)) } - var body: some View { - TabView(selection: $tab) { - OverviewView(summary: summary, model: overview, wizard: wizard, openTab: { tab = $0 }) + // MARK: - The moderator view + + /// Whether this Sylo announces the focused view; nil while that is not known (the read of its features is + /// on its way), so an Inbox person never sees the full app flash before it narrows. + private var supportsModeratorView: Bool? { + ModeratorView.supports( + hasFeature: session.has(.moderatorView), featuresRead: session.featuresKnown || featureCheckDone, + // The sign-in already read this server's info: a Sylo without the feature is known at once. + serverInfoKnown: session.serverInfo != nil, waited: featureWaitOver) + } + + private var mode: ModeratorView.Mode { + ModeratorView.mode(access: summary.access, supports: supportsModeratorView, showEverything: showEverything) + } + + /// Where the Inbox person can switch to the other view: nil for everyone else. + private var moderatorSwitch: Binding? { + ModeratorView.canChoose(access: summary.access, supports: supportsModeratorView) ? $showEverything : nil + } + + private static func focusedTab(_ tab: ServerTab) -> ModeratorView.Tab? { + switch tab { + case .tickets: .tickets + case .tools: .tools + case .moderation: .moderation + case .modules, .settings: nil + } + } + + private static func serverTab(_ tab: ModeratorView.Tab) -> ServerTab { + switch tab { + case .tickets: .tickets + case .tools: .tools + case .moderation: .moderation + } + } + + /// The tab that is shown: the chosen one, or where the server opens when that tab is not in this view (the + /// tab a tapped notification or a new server starts on, or the focused view's own landing). + private var visibleTab: ServerTab { + guard mode == .focused else { return tab == .tools ? .modules : tab } + let current = overview.overview + if let chosen = Self.focusedTab(tab), ModeratorView.tabs(overview: current).contains(chosen) { return tab } + return Self.serverTab(ModeratorView.landing(overview: current).tab) + } + + private var selection: Binding { + Binding(get: { visibleTab }, set: { tab = $0 }) + } + + @ViewBuilder + private var tabs: some View { + switch mode { + case .full: fullTabs + case .focused: focusedTabs + case .undecided: ProgressView("Loading Server") + } + } + + private var fullTabs: some View { + TabView(selection: selection) { + OverviewView( + summary: summary, model: overview, wizard: wizard, openTab: { tab = $0 }, moderatorSwitch: moderatorSwitch + ) .tabItem { Label("Modules", systemImage: "square.grid.2x2") } .tag(ServerTab.modules) TicketListView(model: tickets) @@ -61,6 +130,35 @@ struct ServerView: View { .tabItem { Label("Settings", systemImage: "gearshape") } .tag(ServerTab.settings) } + } + + /// The focused moderator view: the inboxes whose module is on, and the moderation tools. No modules, no + /// settings, no audit log. + private var focusedTabs: some View { + let shown = ModeratorView.tabs(overview: overview.overview) + return TabView(selection: selection) { + if shown.contains(.tickets) { + TicketListView(model: tickets) + .tabItem { Label("Tickets", systemImage: "bubble.left.and.bubble.right") } + .badge(tickets.unreadCount) + .tag(ServerTab.tickets) + } + FocusedToolsView(model: overview, showEverything: $showEverything) + .tabItem { Label("Tools", systemImage: "tray.full") } + .tag(ServerTab.tools) + ModerationTabView( + server: summary.id, session: session, + showsAppeals: ModeratorView.showsAppeals(overview: overview.overview), showsCommands: false, + initialPart: ModeratorView.moderationStart(overview: overview.overview) == .appeals ? .appeals : .infractions + ) + .tabItem { Label("Moderation", systemImage: "shield") } + .badge(openAppeals.count ?? 0) + .tag(ServerTab.moderation) + } + } + + var body: some View { + tabs .navigationTitle(title) .navigationBarTitleDisplayMode(.inline) // Unsaved server settings can't be lost by going back to the server list. @@ -85,7 +183,7 @@ struct ServerView: View { } .sheet(isPresented: $isSearching) { ServerSearchView( - summary: summary, session: session, overview: overview.overview, pages: searchPages, wizard: wizard + summary: summary, session: session, overview: searchOverview, pages: searchPages, wizard: wizard ) { target in tab = target } @@ -126,7 +224,19 @@ struct ServerView: View { .task { await openAppeals.refresh() } .task { await health.load() } // What this Sylo announces (`setup-wizard`, `config-import`, `duplicate`, ...): views show a control only for it. - .task { _ = await session.serverFeatures() } + .task { + _ = await session.serverFeatures() + featureCheckDone = true + } + // An Inbox person waits for that read only a moment; then the app draws as it does without the feature. + .task { + try? await Task.sleep(for: ModeratorView.featureWait) + featureWaitOver = true + } + // The focused view has no Modules tab to load the overview, and its tabs and landing depend on it. + .task(id: mode) { + if mode == .focused, overview.overview == nil { await overview.load() } + } // A read of the features that failed (an offline start) is asked again when the app comes back, so the 5.2 // controls do not stay hidden. .onChange(of: scenePhase) { @@ -150,8 +260,14 @@ struct ServerView: View { .environment(\.dashboardAccess, summary.effectiveAccess) } + /// What the search lists for modules: all of them, or in the focused view only the two queues that are modules. + private var searchOverview: ServerOverview? { + mode == .focused ? ModeratorView.searchOverview(overview.overview) : overview.overview + } + /// The pages the search can open: those of the app, and the wizard and the import where this server has them. private var searchPages: [SearchPage] { + if mode == .focused { return ModeratorView.searchPages(overview: overview.overview) } var pages: [SearchPage] = [.tickets, .moderation, .settings, .auditLog, .memberData, .insights, .leaderboard, .appeals] if ServerPages.hasScreen("commands") { pages.append(.commands) } if ServerPages.hasScreen("messages") { pages.append(.messages) } @@ -163,9 +279,10 @@ struct ServerView: View { } private var title: String { - switch tab { + switch visibleTab { case .modules: summary.name case .tickets: String(localized: "Tickets") + case .tools: String(localized: "Tools") case .moderation: String(localized: "Moderation") case .settings: String(localized: "Server Settings") } @@ -173,7 +290,7 @@ struct ServerView: View { @ToolbarContentBuilder private var settingsToolbar: some ToolbarContent { - if tab == .settings || settings.hasChanges { + if visibleTab == .settings || settings.hasChanges { if settings.hasChanges { ToolbarItem(placement: .cancellationAction) { Button("Discard") { isConfirmingDiscard = true } diff --git a/apps/sylo-ios/sylo-ios/Views/Servers/OverviewView.swift b/apps/sylo-ios/sylo-ios/Views/Servers/OverviewView.swift index 9fb1cd70..e941d931 100644 --- a/apps/sylo-ios/sylo-ios/Views/Servers/OverviewView.swift +++ b/apps/sylo-ios/sylo-ios/Views/Servers/OverviewView.swift @@ -13,6 +13,9 @@ struct OverviewView: View { let wizard: SetupWizardModel /// Moves the server screen to a tab (the Needs attention rows for tickets and appeals). let openTab: (ServerView.ServerTab) -> Void + /// For an Inbox-level person on a Sylo 5.3 server, who chose to see everything: setting it to false goes back + /// to the focused moderator view. nil for everyone else, who has no such choice. + var moderatorSwitch: Binding? @Environment(AppSession.self) private var session @Environment(\.dashboardAccess) private var access @@ -62,6 +65,17 @@ struct OverviewView: View { Section { OverviewHeader(summary: summary, overview: overview) } + if let moderatorSwitch, !isSelecting, !isSearching { + Section { + Button { + moderatorSwitch.wrappedValue = false + } label: { + Label("Show Only Moderation Tools", systemImage: "tray.full") + } + } footer: { + Text("You have Inbox access. The moderation tools alone are easier to work in; the modules below are switched off for your level.") + } + } if !isSelecting, !isSearching { attentionSection(overview) setupOffer(overview) diff --git a/apps/sylo-ios/sylo-ios/Views/Settings/ChangelogView.swift b/apps/sylo-ios/sylo-ios/Views/Settings/ChangelogView.swift index 82a73fda..0a1287a2 100644 --- a/apps/sylo-ios/sylo-ios/Views/Settings/ChangelogView.swift +++ b/apps/sylo-ios/sylo-ios/Views/Settings/ChangelogView.swift @@ -156,7 +156,7 @@ private struct ThisVersionBadge: View { /// A group's label, such as "New" or "Fixes". Breaking changes are red and keep their own symbol, /// so they never stand out by colour alone. -private struct KindLabel: View { +struct KindLabel: View { let section: ChangelogSection var body: some View { @@ -196,7 +196,7 @@ private struct KindLabel: View { /// One change: its scope, the text (inline Markdown: `code`, links, bold) and the issues behind /// it. VoiceOver reads it as one element, with every link it holds as an action. -private struct ChangeRow: View { +struct ChangeRow: View { let scope: String? let text: AttributedString /// "#266, #270", each a link when the server sent an address. @@ -262,7 +262,7 @@ private struct ChangeRow: View { } /// A link in a change, offered to VoiceOver as an action. -private struct ChangeLink: Hashable { +struct ChangeLink: Hashable { let label: String let url: URL } diff --git a/apps/sylo-ios/sylo-ios/Views/Settings/SettingsView.swift b/apps/sylo-ios/sylo-ios/Views/Settings/SettingsView.swift index d48588ce..35144c27 100644 --- a/apps/sylo-ios/sylo-ios/Views/Settings/SettingsView.swift +++ b/apps/sylo-ios/sylo-ios/Views/Settings/SettingsView.swift @@ -304,6 +304,10 @@ struct SettingsView: View { Label(Self.title(feature), systemImage: Self.symbol(feature)) } } + // The update notice exists on a Sylo that announces `update-notice` (5.3 and later). + if serverInfo?.supports(.updateNotice) == true || session.has(.updateNotice) { + UpdatesRow(account: account, session: session) + } } header: { Text("Operator") } footer: { diff --git a/apps/sylo-ios/sylo-ios/Views/Settings/UpdateView.swift b/apps/sylo-ios/sylo-ios/Views/Settings/UpdateView.swift new file mode 100644 index 00000000..7ea89e04 --- /dev/null +++ b/apps/sylo-ios/sylo-ios/Views/Settings/UpdateView.swift @@ -0,0 +1,274 @@ +import SwiftUI +import SyloKit +import UIKit + +/// The operators' update notice (Sylo 5.3): whether a newer Sylo is out, what is in it, the command to update by +/// hand and, when the Sylo runs Wise Wren, "Update now" with its progress. Reached from Settings, for an operator, on +/// a server that announces `update-notice`. +struct UpdateView: View { + let model: UpdateModel + + @State private var isConfirmingUpdate = false + @State private var didCopy = false + + var body: some View { + List { + if let message = model.errorMessage { + Section { StatusMessage(message, kind: .error) } + } + if let status = model.status { + noticeSection(status) + if status.isAvailable { + commandSection(status) + } + wrenSection(status) + } else if model.isLoading { + Section { ProgressView() } + } else if model.isRefused { + Section { OperatorRefusedView() } + } + } + .navigationTitle("Updates") + .navigationBarTitleDisplayMode(.inline) + .task { await model.load() } + .refreshable { await model.load(refresh: true) } + // Leaving the screen stops the asking; coming back reads the run again. + .onDisappear { model.stop() } + .confirmationDialog( + "Update Sylo to \(model.status?.latest ?? "the new version")?", isPresented: $isConfirmingUpdate, + titleVisibility: .visible + ) { + Button("Update Now") { Task { await model.approve() } } + } message: { + Text("Wise Wren stops Sylo for a short while, takes a snapshot, starts the new version and rolls back if it does not come up healthy. The dashboard, the bot and this app are offline meanwhile.") + } + } + + // MARK: - The notice + + private func noticeSection(_ status: UpdateStatus) -> some View { + Section { + Label { + Text(verbatim: status.headline) + } icon: { + Image(systemName: status.isAvailable ? "arrow.down.circle.fill" : "checkmark.circle") + .foregroundStyle(status.isAvailable ? Color.accentColor : Color.secondary) + } + if status.isAvailable, let url = status.releaseURL { + Link(destination: url) { + Label("Release on GitHub", systemImage: "arrow.up.right.square") + } + } + if status.isAvailable { + if let notes = status.notes, !notes.sections.isEmpty { + NavigationLink { + UpdateNotesView(release: notes) + } label: { + Label("What's in This Release", systemImage: "sparkles") + } + } else if let text = status.notesText, !text.isEmpty { + Text(verbatim: text) + .font(.footnote) + .foregroundStyle(.secondary) + } + } + if status.isEnabled, status.checkFailed, status.latest != nil { + Text("The last check failed; this is from an earlier one.") + .font(.footnote) + .foregroundStyle(.secondary) + } + if status.isEnabled { + Button { + Task { await model.load(refresh: true) } + } label: { + Label("Check Again", systemImage: "arrow.clockwise") + } + .disabled(model.isLoading) + } + } footer: { + if status.isEnabled { + Text("Sylo asks GitHub for its newest release at most every 6 hours. A server admin can turn this off with UPDATE_CHECK=off.") + } + } + } + + private func commandSection(_ status: UpdateStatus) -> some View { + Section { + Text(verbatim: status.command) + .font(.footnote.monospaced()) + .textSelection(.enabled) + Button { + UIPasteboard.general.string = status.command + didCopy = true + } label: { + Label(didCopy ? "Copied" : "Copy Command", systemImage: didCopy ? "checkmark" : "doc.on.doc") + } + .sensoryFeedback(.success, trigger: didCopy) + } header: { + Text("Update by hand") + } footer: { + Text("Run this where Sylo's compose file is.") + } + } + + // MARK: - Wise Wren + + @ViewBuilder + private func wrenSection(_ status: UpdateStatus) -> some View { + if let wren = status.wren { + Section { + if let progress = model.progress { + progressRows(progress) + } else if let problem = wren.error { + StatusMessage(problem.message, kind: .error) + } else { + Text(verbatim: wrenLine(wren)) + if let why = wren.whyNot, status.isAvailable || wren.updateSeen { + Text(verbatim: why) + .font(.footnote) + .foregroundStyle(.secondary) + } + } + if let message = model.actionError { + StatusMessage(message, kind: .error) + } + if model.progress == nil, status.offersUpdateNow { + Button { + isConfirmingUpdate = true + } label: { + if model.isApproving { + HStack { + Text("Starting\u{2026}") + Spacer() + ProgressView() + } + } else { + Label("Update Now", systemImage: "arrow.down.circle") + } + } + .disabled(!wren.canApprove || model.isApproving) + } + } header: { + Text("Wise Wren") + } + } else if status.isAvailable { + Section { + Link(destination: Self.wiseWrenURL) { + Label("About Wise Wren", systemImage: "arrow.up.right.square") + } + } header: { + Text("Update from here") + } footer: { + Text("Wise Wren can update Sylo from the app, without a command line. A server admin sets it up with WISE_WREN_URL, WISE_WREN_TOKEN and WISE_WREN_TARGET_ID (see the self-hosting guide).") + } + } + } + + private static let wiseWrenURL = URL(string: "https://github.com/Ferdinand99/Wise-Wren")! + + private func wrenLine(_ wren: WrenStatus) -> String { + guard let target = wren.target else { + return String(localized: "Wise Wren is connected. Its token cannot read the target, so the check above decides.") + } + return wren.updateSeen + ? String(localized: "Wise Wren sees an update for \(target.name).") + : String(localized: "Wise Wren does not see an update for \(target.name) yet.") + } + + @ViewBuilder + private func progressRows(_ progress: UpdateProgress) -> some View { + HStack(alignment: .top, spacing: 12) { + if progress.isDone { + Image(systemName: progress.tone == .failure || progress.timedOut ? "exclamationmark.triangle.fill" : "checkmark.circle.fill") + .foregroundStyle(progress.tone == .failure || progress.timedOut ? Color.orange : Color.green) + } else { + ProgressView() + } + VStack(alignment: .leading, spacing: 4) { + Text(verbatim: progress.text) + if let step = progress.step { + Text(verbatim: step) + .font(.footnote) + .foregroundStyle(.secondary) + } + } + } + .accessibilityElement(children: .combine) + if let problem = progress.problem { + StatusMessage(problem, kind: .error) + } + if progress.timedOut { + StatusMessage( + "Sylo has not come back after 30 minutes. Look at the run in Wise Wren and at Sylo's container.", + kind: .error) + } + if progress.isDone { + Button("Close") { model.closeProgress() } + } + } +} + +/// The release notes of the update that is available, as the What's New screen shows a release. +struct UpdateNotesView: View { + let release: ChangelogRelease + + var body: some View { + List { + ForEach(release.sections.indices, id: \.self) { index in + let section = release.sections[index] + Section { + KindLabel(section: section) + ForEach(section.items.indices, id: \.self) { itemIndex in + ChangeRow(item: section.items[itemIndex]) + } + } + } + } + .navigationTitle("Sylo \(release.version)") + .navigationBarTitleDisplayMode(.inline) + } +} + +/// The Updates row of the Operator section: the status in words, with a dot while there is something to do. It owns +/// the model, so the screen it opens shows what the row already read. +struct UpdatesRow: View { + let account: AccountModel + let session: AppSession + @State private var model: UpdateModel + + init(account: AccountModel, session: AppSession) { + self.account = account + self.session = session + _model = State(initialValue: UpdateModel(session: session)) + } + + var body: some View { + NavigationLink { + OperatorGate(account: account) { UpdateView(model: model) } + } label: { + HStack { + Label { + VStack(alignment: .leading, spacing: 2) { + Text("Updates") + if let status = model.status { + Text(verbatim: status.summary) + .font(.footnote) + .foregroundStyle(.secondary) + } + } + } icon: { + Image(systemName: "arrow.down.circle") + } + if model.status?.needsAttention == true { + Spacer() + Image(systemName: "circle.fill") + .font(.caption2) + .foregroundStyle(.tint) + .accessibilityLabel("Update available") + } + } + } + // Reads the status only: following a run belongs to the screen that shows it. + .task(id: session.generation) { await model.load(followsRun: false) } + } +} diff --git a/docs/mobile-app.md b/docs/mobile-app.md index d03cd0c3..7d65ddca 100644 --- a/docs/mobile-app.md +++ b/docs/mobile-app.md @@ -47,6 +47,27 @@ Settings and only for operator accounts: Health with the database backups Personalizer, the stats cache and the roadmap admin. See [Health and the dev log (operators)](#health-and-the-dev-log-operators). +The app follows the Sylo 5.3 additions where the server announces them (each is +hidden on an older Sylo, and the app never sends a key the server did not send): + +- `moderator-view`: a person whose level in a server is Inbox gets the focused + moderator view, as in the dashboard: the server opens on its first inbox that is + switched on, and the tabs are Tickets, Tools (applications, suggestions and + member data) and Moderation (infractions and appeals, no commands). No modules, + settings, audit log, insights or leaderboard. "Show everything" brings back the + full, still locked, app on that device. View keeps the full read-only app and + Edit is unchanged. Operator screens live in Settings and are not affected. +- `public-page-look`: Server settings, then Public Pages (Edit only), for the + accent colour (with the contrast note of the server) and the background (none, + a picture from the photo library, or the invite background), with a preview. +- `update-notice` (operators): Settings, then Operator, then Updates shows a newer + release with its notes and the command to copy and, when the instance runs Wise + Wren, Update now with the progress of the run while Sylo restarts. +- Restoring an uploaded Postgres dump: Health, then Backups. A server whose health + report has `db.roleRisks` (5.3) is sent `confirm` and, for a dump that was + uploaded, `acknowledgeSql: true`, after the app explains that the SQL runs with + the rights of the database role. An older server is sent no body. + What stays on the web is only what is not an administrator's job: the public pages (the web shop, the application forms, event and quote pages) that members open in a browser. The app can copy or open the address of a public page; it