diff --git a/CHANGELOG.md b/CHANGELOG.md index 9ef02243..1160f046 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,21 @@ All notable changes to SideInstaller are documented here. ## Unreleased +### Added +- **Sources.** A new page under Tools, like SideStore's: add an AltStore-format source (its + https link, an `altstore://` or `sidestore://` source link, or a .json source file) and its apps + are listed with their icons and versions. An app's page has its release notes, its description + and every earlier version, and Install downloads the IPA from the source and goes through the + same "Install from a link?" question as a `sideinstaller://install` link, so it's signed and + installed like a custom .ipa. FrizzleM's source is built in; SideStore, AltStore, LiveContainer + + SideStore and Haven are suggested under Add a source, one tap each. Your sources lists each one + under its developer, with their GitHub picture (or the app's icon when there's none). +- **Updates for the apps from sources.** With LocalDevVPN on, SideInstaller reads which apps are + installed, as Sideloaded apps does, and an app a source has a newer version of gets an Update tag, + with the count on the Sources tile. The sources are checked once when SideInstaller opens, as + SideInstaller checks for its own updates; pull down on Sources, or tap Check for updates, to + check again. + ### Fixed - **The device link finds the pairing port when it isn't 49152.** iOS gives this iPhone's remote pairing listener whatever port is free when it starts, so it isn't always on 49152, and the diff --git a/ios-app/Assets.xcassets/SourcesLogo.imageset/Contents.json b/ios-app/Assets.xcassets/SourcesLogo.imageset/Contents.json new file mode 100644 index 00000000..8a1d14e4 --- /dev/null +++ b/ios-app/Assets.xcassets/SourcesLogo.imageset/Contents.json @@ -0,0 +1,12 @@ +{ + "images" : [ + { + "filename" : "SourcesLogo.png", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/ios-app/Assets.xcassets/SourcesLogo.imageset/SourcesLogo.png b/ios-app/Assets.xcassets/SourcesLogo.imageset/SourcesLogo.png new file mode 100644 index 00000000..de2e4a5b Binary files /dev/null and b/ios-app/Assets.xcassets/SourcesLogo.imageset/SourcesLogo.png differ diff --git a/ios-app/ChineseStrings.swift b/ios-app/ChineseStrings.swift index c23374e6..f6c0b83d 100644 --- a/ios-app/ChineseStrings.swift +++ b/ios-app/ChineseStrings.swift @@ -1278,4 +1278,73 @@ let chineseStrings: [String: String] = [ "Pick the team again?": "重新选择团队?", "Pick Again": "重新选择", "The next sign-in with “%@” asks which developer team signs.": "下次用“%@”登录时,会询问用哪个开发团队签名。", + + // MARK: - Sources + + "Suggested": + "推荐", + + "Paste the link of a SideStore or AltStore source, or of a .json source file. Its apps, their updates and release notes show here.": + "粘贴 SideStore 或 AltStore 源的链接,或 .json 源文件的链接。它的应用、更新和发布说明会显示在这里。", + + "Sources": + "源", + "Add a source": + "添加源", + "Add": + "添加", + "Apps": + "应用", + "Updates": + "更新", + "Update": + "更新", + "Your sources": + "你的源", + "Check for updates": + "检查更新", + "Copy link": + "拷贝链接", + "Source options": + "源选项", + "Loading…": + "正在载入…", + "What's new": + "新功能", + "Version history": + "版本历史", + "This version has no release notes.": + "此版本没有发布说明。", + "%d update": + "%d 个更新", + "%d updates": + "%d 个更新", + "%d source": + "%d 个源", + "%d sources": + "%d 个源", + "Update to %@": + "更新到 %@", + "Install %@ %@?": + "安装 %@ %@?", + "Version %@ · from %@": + "版本 %@ · 来自 %@", + "%@ installed · %@ available": + "已安装 %@ · 可用 %@", + "%@ installed · up to date": + "已安装 %@ · 已是最新", + "That source is already added.": + "该源已添加。", + "The source answered with HTTP %d.": + "源返回了 HTTP %d。", + "Couldn't reach the source: %@": + "无法访问该源:%@", + "That isn't a source link. Paste the whole https:// address of the source.": + "这不是源链接。请粘贴源的完整 https:// 地址。", + "That link didn't return a source. It has to be the source's JSON file itself.": + "该链接未返回源。它必须是源的 JSON 文件本身。", + "Downloads the IPA from the source, then signs it with your Apple ID and installs it, as a custom .ipa would be.": + "从源下载 IPA,然后用你的 Apple 账户签名并安装,与自定义 .ipa 相同。", + "This version is older than the newest one. It's installed over the copy on this iPhone, which may not open data a newer version saved.": + "此版本比最新版本旧。它会覆盖安装在此 iPhone 上的副本,可能无法打开较新版本保存的数据。", ] diff --git a/ios-app/FrenchStrings.swift b/ios-app/FrenchStrings.swift index a184004a..c18c1da8 100644 --- a/ios-app/FrenchStrings.swift +++ b/ios-app/FrenchStrings.swift @@ -1330,4 +1330,73 @@ let frenchStrings: [String: String] = [ "Pick Again": "Choisir à nouveau", "The next sign-in with “%@” asks which developer team signs.": "La prochaine connexion avec « %@ » demandera quelle équipe de développement signe.", + + // MARK: - Sources + + "Suggested": + "Suggestions", + + "Paste the link of a SideStore or AltStore source, or of a .json source file. Its apps, their updates and release notes show here.": + "Collez le lien d'une source SideStore ou AltStore, ou d'un fichier source .json. Ses apps, leurs mises à jour et leurs notes de version s'affichent ici.", + + "Sources": + "Sources", + "Add a source": + "Ajouter une source", + "Add": + "Ajouter", + "Apps": + "Apps", + "Updates": + "Mises à jour", + "Update": + "Mettre à jour", + "Your sources": + "Vos sources", + "Check for updates": + "Rechercher des mises à jour", + "Copy link": + "Copier le lien", + "Source options": + "Options de la source", + "Loading…": + "Chargement…", + "What's new": + "Nouveautés", + "Version history": + "Historique des versions", + "This version has no release notes.": + "Cette version n'a pas de notes de version.", + "%d update": + "%d mise à jour", + "%d updates": + "%d mises à jour", + "%d source": + "%d source", + "%d sources": + "%d sources", + "Update to %@": + "Mettre à jour vers %@", + "Install %@ %@?": + "Installer %@ %@ ?", + "Version %@ · from %@": + "Version %@ · de %@", + "%@ installed · %@ available": + "%@ installée · %@ disponible", + "%@ installed · up to date": + "%@ installée · à jour", + "That source is already added.": + "Cette source est déjà ajoutée.", + "The source answered with HTTP %d.": + "La source a répondu avec HTTP %d.", + "Couldn't reach the source: %@": + "Impossible de joindre la source : %@", + "That isn't a source link. Paste the whole https:// address of the source.": + "Ce n'est pas un lien de source. Collez l'adresse https:// complète de la source.", + "That link didn't return a source. It has to be the source's JSON file itself.": + "Ce lien n'a pas renvoyé de source. Il doit pointer vers le fichier JSON de la source lui-même.", + "Downloads the IPA from the source, then signs it with your Apple ID and installs it, as a custom .ipa would be.": + "Télécharge l'IPA depuis la source, puis la signe avec votre identifiant Apple et l'installe, comme un .ipa personnalisé.", + "This version is older than the newest one. It's installed over the copy on this iPhone, which may not open data a newer version saved.": + "Cette version est plus ancienne que la dernière. Elle est installée par-dessus la copie de cet iPhone, qui risque de ne pas ouvrir les données enregistrées par une version plus récente.", ] diff --git a/ios-app/ItalianStrings.swift b/ios-app/ItalianStrings.swift index 8f017dfc..de7d8067 100644 --- a/ios-app/ItalianStrings.swift +++ b/ios-app/ItalianStrings.swift @@ -1323,4 +1323,73 @@ let italianStrings: [String: String] = [ "Pick Again": "Scegli di nuovo", "The next sign-in with “%@” asks which developer team signs.": "Il prossimo accesso con “%@” chiederà quale team di sviluppo firma.", + + // MARK: - Sources + + "Suggested": + "Suggerite", + + "Paste the link of a SideStore or AltStore source, or of a .json source file. Its apps, their updates and release notes show here.": + "Incolla il link di una sorgente di SideStore o AltStore, o di un file sorgente .json. Qui compaiono le sue app, gli aggiornamenti e le note di rilascio.", + + "Sources": + "Sorgenti", + "Add a source": + "Aggiungi una sorgente", + "Add": + "Aggiungi", + "Apps": + "App", + "Updates": + "Aggiornamenti", + "Update": + "Aggiorna", + "Your sources": + "Le tue sorgenti", + "Check for updates": + "Cerca aggiornamenti", + "Copy link": + "Copia link", + "Source options": + "Opzioni sorgente", + "Loading…": + "Caricamento…", + "What's new": + "Novità", + "Version history": + "Cronologia versioni", + "This version has no release notes.": + "Questa versione non ha note di rilascio.", + "%d update": + "%d aggiornamento", + "%d updates": + "%d aggiornamenti", + "%d source": + "%d sorgente", + "%d sources": + "%d sorgenti", + "Update to %@": + "Aggiorna a %@", + "Install %@ %@?": + "Installare %@ %@?", + "Version %@ · from %@": + "Versione %@ · da %@", + "%@ installed · %@ available": + "%@ installata · %@ disponibile", + "%@ installed · up to date": + "%@ installata · aggiornata", + "That source is already added.": + "Questa sorgente è già stata aggiunta.", + "The source answered with HTTP %d.": + "La sorgente ha risposto con HTTP %d.", + "Couldn't reach the source: %@": + "Impossibile raggiungere la sorgente: %@", + "That isn't a source link. Paste the whole https:// address of the source.": + "Questo non è un link di una sorgente. Incolla l'intero indirizzo https:// della sorgente.", + "That link didn't return a source. It has to be the source's JSON file itself.": + "Quel link non ha restituito una sorgente. Deve essere il file JSON della sorgente.", + "Downloads the IPA from the source, then signs it with your Apple ID and installs it, as a custom .ipa would be.": + "Scarica l'IPA dalla sorgente, poi lo firma con il tuo Apple ID e lo installa, come un .ipa personalizzato.", + "This version is older than the newest one. It's installed over the copy on this iPhone, which may not open data a newer version saved.": + "Questa versione è più vecchia dell'ultima. Viene installata sopra la copia su questo iPhone, che potrebbe non aprire i dati salvati da una versione più recente.", ] diff --git a/ios-app/JapaneseStrings.swift b/ios-app/JapaneseStrings.swift index 46086d6f..257318c6 100644 --- a/ios-app/JapaneseStrings.swift +++ b/ios-app/JapaneseStrings.swift @@ -1289,4 +1289,73 @@ let japaneseStrings: [String: String] = [ "Pick the team again?": "チームを選び直しますか?", "Pick Again": "選び直す", "The next sign-in with “%@” asks which developer team signs.": "次回「%@」でサインインするときに、署名に使う開発者チームを確認します。", + + // MARK: - Sources + + "Suggested": + "おすすめ", + + "Paste the link of a SideStore or AltStore source, or of a .json source file. Its apps, their updates and release notes show here.": + "SideStore または AltStore のソース、または .json ソースファイルのリンクを貼り付けてください。アプリ、アップデート、リリースノートがここに表示されます。", + + "Sources": + "ソース", + "Add a source": + "ソースを追加", + "Add": + "追加", + "Apps": + "アプリ", + "Updates": + "アップデート", + "Update": + "アップデート", + "Your sources": + "追加したソース", + "Check for updates": + "アップデートを確認", + "Copy link": + "リンクをコピー", + "Source options": + "ソースのオプション", + "Loading…": + "読み込み中…", + "What's new": + "新機能", + "Version history": + "バージョン履歴", + "This version has no release notes.": + "このバージョンにはリリースノートがありません。", + "%d update": + "%d 件のアップデート", + "%d updates": + "%d 件のアップデート", + "%d source": + "%d 件のソース", + "%d sources": + "%d 件のソース", + "Update to %@": + "%@ にアップデート", + "Install %@ %@?": + "%@ %@ をインストールしますか?", + "Version %@ · from %@": + "バージョン %@ · %@ から", + "%@ installed · %@ available": + "%@ をインストール済み · %@ が利用可能", + "%@ installed · up to date": + "%@ をインストール済み · 最新", + "That source is already added.": + "そのソースは追加済みです。", + "The source answered with HTTP %d.": + "ソースが HTTP %d を返しました。", + "Couldn't reach the source: %@": + "ソースに接続できませんでした:%@", + "That isn't a source link. Paste the whole https:// address of the source.": + "ソースのリンクではありません。ソースの https:// アドレスを丸ごと貼り付けてください。", + "That link didn't return a source. It has to be the source's JSON file itself.": + "そのリンクはソースを返しませんでした。ソースの JSON ファイルそのものを指定してください。", + "Downloads the IPA from the source, then signs it with your Apple ID and installs it, as a custom .ipa would be.": + "ソースから IPA をダウンロードし、あなたの Apple ID で署名してインストールします。カスタム .ipa と同じです。", + "This version is older than the newest one. It's installed over the copy on this iPhone, which may not open data a newer version saved.": + "このバージョンは最新より古いものです。この iPhone のアプリに上書きでインストールされ、新しいバージョンが保存したデータを開けない場合があります。", ] diff --git a/ios-app/KoreanStrings.swift b/ios-app/KoreanStrings.swift index 263671fe..a2ce4128 100644 --- a/ios-app/KoreanStrings.swift +++ b/ios-app/KoreanStrings.swift @@ -1291,4 +1291,73 @@ let koreanStrings: [String: String] = [ "Pick the team again?": "팀을 다시 고를까요?", "Pick Again": "다시 고르기", "The next sign-in with “%@” asks which developer team signs.": "다음에 “%@”(으)로 로그인할 때 서명할 개발자 팀을 묻습니다.", + + // MARK: - Sources + + "Suggested": + "추천", + + "Paste the link of a SideStore or AltStore source, or of a .json source file. Its apps, their updates and release notes show here.": + "SideStore 또는 AltStore 소스, 또는 .json 소스 파일의 링크를 붙여 넣으세요. 앱, 업데이트, 릴리스 노트가 여기에 표시됩니다.", + + "Sources": + "소스", + "Add a source": + "소스 추가", + "Add": + "추가", + "Apps": + "앱", + "Updates": + "업데이트", + "Update": + "업데이트", + "Your sources": + "내 소스", + "Check for updates": + "업데이트 확인", + "Copy link": + "링크 복사", + "Source options": + "소스 옵션", + "Loading…": + "불러오는 중…", + "What's new": + "새로운 기능", + "Version history": + "버전 기록", + "This version has no release notes.": + "이 버전에는 릴리스 노트가 없습니다.", + "%d update": + "업데이트 %d개", + "%d updates": + "업데이트 %d개", + "%d source": + "소스 %d개", + "%d sources": + "소스 %d개", + "Update to %@": + "%@(으)로 업데이트", + "Install %@ %@?": + "%@ %@을(를) 설치하시겠습니까?", + "Version %@ · from %@": + "버전 %@ · 출처: %@", + "%@ installed · %@ available": + "%@ 설치됨 · %@ 사용 가능", + "%@ installed · up to date": + "%@ 설치됨 · 최신 버전", + "That source is already added.": + "이미 추가된 소스입니다.", + "The source answered with HTTP %d.": + "소스가 HTTP %d(으)로 응답했습니다.", + "Couldn't reach the source: %@": + "소스에 연결할 수 없습니다: %@", + "That isn't a source link. Paste the whole https:// address of the source.": + "소스 링크가 아닙니다. 소스의 https:// 주소 전체를 붙여 넣으세요.", + "That link didn't return a source. It has to be the source's JSON file itself.": + "그 링크는 소스를 반환하지 않았습니다. 소스의 JSON 파일 자체여야 합니다.", + "Downloads the IPA from the source, then signs it with your Apple ID and installs it, as a custom .ipa would be.": + "소스에서 IPA를 다운로드한 다음 사용자의 Apple ID로 서명하고 설치합니다. 사용자 지정 .ipa와 같습니다.", + "This version is older than the newest one. It's installed over the copy on this iPhone, which may not open data a newer version saved.": + "이 버전은 최신 버전보다 오래되었습니다. 이 iPhone의 앱 위에 설치되며, 최신 버전이 저장한 데이터를 열지 못할 수 있습니다.", ] diff --git a/ios-app/PortugueseStrings.swift b/ios-app/PortugueseStrings.swift index fd14dd3a..2b196cbc 100644 --- a/ios-app/PortugueseStrings.swift +++ b/ios-app/PortugueseStrings.swift @@ -1315,4 +1315,73 @@ let portugueseStrings: [String: String] = [ "Pick Again": "Escolher de novo", "The next sign-in with “%@” asks which developer team signs.": "O próximo login com “%@” vai perguntar qual equipe de desenvolvimento assina.", + + // MARK: - Sources + + "Suggested": + "Sugeridas", + + "Paste the link of a SideStore or AltStore source, or of a .json source file. Its apps, their updates and release notes show here.": + "Cole o link de uma fonte do SideStore ou AltStore, ou de um arquivo de fonte .json. Os apps, as atualizações e as notas de versão aparecem aqui.", + + "Sources": + "Fontes", + "Add a source": + "Adicionar uma fonte", + "Add": + "Adicionar", + "Apps": + "Apps", + "Updates": + "Atualizações", + "Update": + "Atualizar", + "Your sources": + "Suas fontes", + "Check for updates": + "Verificar atualizações", + "Copy link": + "Copiar link", + "Source options": + "Opções da fonte", + "Loading…": + "Carregando…", + "What's new": + "Novidades", + "Version history": + "Histórico de versões", + "This version has no release notes.": + "Esta versão não tem notas de versão.", + "%d update": + "%d atualização", + "%d updates": + "%d atualizações", + "%d source": + "%d fonte", + "%d sources": + "%d fontes", + "Update to %@": + "Atualizar para %@", + "Install %@ %@?": + "Instalar %@ %@?", + "Version %@ · from %@": + "Versão %@ · de %@", + "%@ installed · %@ available": + "%@ instalada · %@ disponível", + "%@ installed · up to date": + "%@ instalada · atualizada", + "That source is already added.": + "Essa fonte já foi adicionada.", + "The source answered with HTTP %d.": + "A fonte respondeu com HTTP %d.", + "Couldn't reach the source: %@": + "Não foi possível acessar a fonte: %@", + "That isn't a source link. Paste the whole https:// address of the source.": + "Isso não é um link de fonte. Cole o endereço https:// completo da fonte.", + "That link didn't return a source. It has to be the source's JSON file itself.": + "Esse link não retornou uma fonte. Ele precisa ser o próprio arquivo JSON da fonte.", + "Downloads the IPA from the source, then signs it with your Apple ID and installs it, as a custom .ipa would be.": + "Baixa o IPA da fonte, depois o assina com seu Apple ID e o instala, como um .ipa personalizado.", + "This version is older than the newest one. It's installed over the copy on this iPhone, which may not open data a newer version saved.": + "Esta versão é mais antiga que a mais recente. Ela é instalada sobre a cópia deste iPhone, que pode não abrir dados salvos por uma versão mais nova.", ] diff --git a/ios-app/RootView.swift b/ios-app/RootView.swift index a231ed95..d4beec64 100644 --- a/ios-app/RootView.swift +++ b/ios-app/RootView.swift @@ -63,6 +63,7 @@ struct RootView: View { @StateObject private var entitlementsManager = EntitlementsManager() @StateObject private var appsManager = SideloadedAppsManager() @StateObject private var sideBySideManager = SideBySideManager() + @StateObject private var sourcesManager = SourcesManager() /// What the sign-in sheet showed last, so it keeps its content while it /// slides away after the sign-in clears it. @State private var shownSignInSheet: SignInSheet? @@ -79,7 +80,8 @@ struct RootView: View { locationManager: locationManager, entitlementsManager: entitlementsManager, appsManager: appsManager, - sideBySideManager: sideBySideManager) + sideBySideManager: sideBySideManager, + sourcesManager: sourcesManager) .tabItem { Label(L("Tools"), systemImage: "wrench.and.screwdriver") } .tag(Page.tools) AboutView() @@ -116,6 +118,10 @@ struct RootView: View { entitlementsManager.signOut() sideBySideManager.signOut() } + // The sources are checked for updates once when SideInstaller opens, + // as SideInstallerApp checks SideInstaller itself, so the Sources tile + // can show how many there are. + .task { await sourcesManager.checkAtLaunch(apps: appsManager) } .tint(Theme.accent) .preferredColorScheme(.dark) // A swipe down is a cancel; the sign-in closing it is not. @@ -544,6 +550,7 @@ struct ToolsView: View { @ObservedObject var entitlementsManager: EntitlementsManager @ObservedObject var appsManager: SideloadedAppsManager @ObservedObject var sideBySideManager: SideBySideManager + @ObservedObject var sourcesManager: SourcesManager @State private var showSettings = false @@ -599,6 +606,14 @@ struct ToolsView: View { } .buttonStyle(.plain, sound: .tick) .cascadeItem(rowIndex(5)) + NavigationLink { + SourcesView(manager: sourcesManager, appsManager: appsManager) + } label: { + ToolTile(image: "SourcesLogo", title: L("Sources"), + count: sourcesManager.updateCount(installed: appsManager.entries)) + } + .buttonStyle(.plain, sound: .tick) + .cascadeItem(rowIndex(6)) } } // No bottom padding: the tab bar's inset already clears the last @@ -639,6 +654,8 @@ private struct ToolTile: View { var title: String /// Shows a Beta badge in the top corner. var beta: Bool = false + /// A count in the top corner, such as the updates Sources found. 0 hides it. + var count: Int = 0 var body: some View { let logo = RoundedRectangle(cornerRadius: 16, style: .continuous) @@ -663,6 +680,16 @@ private struct ToolTile: View { BetaBadge() .padding(12) } + if count > 0 { + Text("\(count)") + .font(.footnote.weight(.semibold)) + .foregroundStyle(.white) + .frame(minWidth: 24, minHeight: 24) + .padding(.horizontal, count > 9 ? 4 : 0) + .background(Capsule().fill(Theme.warning)) + .padding(12) + .accessibilityLabel(count == 1 ? L("%d update", count) : L("%d updates", count)) + } } .cardSurface(in: tile) .contentShape(tile) diff --git a/ios-app/SourcesView.swift b/ios-app/SourcesView.swift new file mode 100644 index 00000000..567119a5 --- /dev/null +++ b/ios-app/SourcesView.swift @@ -0,0 +1,1121 @@ +import SwiftUI + +// MARK: - Source format + +/// An app source in the AltStore format, the JSON SideStore and AltStore read: +/// a name, and the apps it offers with their versions and release notes. +/// Decoded leniently: an app the source describes badly is left out rather +/// than failing the whole source. +struct AppSource: Decodable, Equatable { + let name: String + let identifier: String? + let iconURL: URL? + let website: URL? + let apps: [SourceApp] + + private enum CodingKeys: String, CodingKey { + case name, identifier, iconURL, website, apps + } + + /// Who makes the apps: the developer every app names, or the first one's. + var developerName: String? { + apps.lazy.compactMap(\.developerName).first { !$0.isEmpty } + } + + init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + name = (try? c.decode(String.self, forKey: .name)) ?? "" + identifier = try? c.decode(String.self, forKey: .identifier) + iconURL = SourceApp.url(try? c.decode(String.self, forKey: .iconURL)) + website = SourceApp.url(try? c.decode(String.self, forKey: .website)) + let entries = (try? c.decode([Lenient].self, forKey: .apps)) ?? [] + apps = entries.compactMap(\.value) + } + + /// Wraps an element so one that fails to decode becomes nil. + private struct Lenient: Decodable { + let value: T? + init(from decoder: Decoder) throws { value = try? T(from: decoder) } + } +} + +/// One app a source offers. +struct SourceApp: Decodable, Equatable { + let bundleIdentifier: String + let name: String + let developerName: String? + let subtitle: String? + let localizedDescription: String? + let iconURL: URL? + /// Newest first. Built from the app's top-level `version` and + /// `downloadURL` for a source that has no `versions` list. + let versions: [SourceVersion] + + var latest: SourceVersion? { versions.first } + + private enum CodingKeys: String, CodingKey { + case bundleIdentifier, name, developerName, subtitle, localizedDescription, + iconURL, versions, version, versionDate, versionDescription, downloadURL, size + } + + init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + bundleIdentifier = try c.decode(String.self, forKey: .bundleIdentifier) + name = try c.decode(String.self, forKey: .name) + developerName = try? c.decode(String.self, forKey: .developerName) + subtitle = try? c.decode(String.self, forKey: .subtitle) + localizedDescription = try? c.decode(String.self, forKey: .localizedDescription) + iconURL = Self.url(try? c.decode(String.self, forKey: .iconURL)) + + var versions = ((try? c.decode([Lenient].self, forKey: .versions)) ?? []).compactMap(\.value) + if versions.isEmpty, + let version = try? c.decode(String.self, forKey: .version), + let link = Self.url(try? c.decode(String.self, forKey: .downloadURL)) { + versions = [SourceVersion( + version: version, + date: SourceVersion.date(try? c.decode(String.self, forKey: .versionDate)), + notes: try? c.decode(String.self, forKey: .versionDescription), + downloadURL: link, + size: try? c.decode(Int64.self, forKey: .size))] + } + guard !versions.isEmpty else { + throw DecodingError.dataCorruptedError(forKey: .versions, in: c, + debugDescription: "no version to install") + } + self.versions = versions + } + + /// An https link, or nil for anything else. + static func url(_ text: String?) -> URL? { + guard let text, let url = URL(string: text.trimmingCharacters(in: .whitespacesAndNewlines)), + let scheme = url.scheme?.lowercased(), scheme == "https" || scheme == "http" + else { return nil } + return url + } + + private struct Lenient: Decodable { + let value: SourceVersion? + init(from decoder: Decoder) throws { value = try? SourceVersion(from: decoder) } + } +} + +/// One version of a source's app, with its release notes. +struct SourceVersion: Decodable, Equatable, Identifiable { + let version: String + let date: Date? + let notes: String? + let downloadURL: URL + let size: Int64? + + var id: String { version + "|" + downloadURL.absoluteString } + + init(version: String, date: Date?, notes: String?, downloadURL: URL, size: Int64?) { + self.version = version + self.date = date + self.notes = notes + self.downloadURL = downloadURL + self.size = size + } + + private enum CodingKeys: String, CodingKey { + case version, date, localizedDescription, downloadURL, size + } + + init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + version = try c.decode(String.self, forKey: .version) + guard let link = SourceApp.url(try c.decode(String.self, forKey: .downloadURL)) else { + throw DecodingError.dataCorruptedError(forKey: .downloadURL, in: c, + debugDescription: "not an https link") + } + downloadURL = link + date = Self.date(try? c.decode(String.self, forKey: .date)) + notes = try? c.decode(String.self, forKey: .localizedDescription) + size = try? c.decode(Int64.self, forKey: .size) + } + + /// Sources write dates as ISO 8601, with or without the time. + static func date(_ text: String?) -> Date? { + guard let text else { return nil } + let full = ISO8601DateFormatter() + if let date = full.date(from: text) { return date } + full.formatOptions = [.withInternetDateTime, .withFractionalSeconds] + if let date = full.date(from: text) { return date } + let day = DateFormatter() + day.locale = Locale(identifier: "en_US_POSIX") + day.timeZone = TimeZone(identifier: "UTC") + day.dateFormat = "yyyy-MM-dd" + return day.date(from: String(text.prefix(10))) + } +} + +/// An app as the Sources page lists it: the app, the source it came from, and +/// what is installed of it. +struct SourceListing: Identifiable, Equatable { + let app: SourceApp + let sourceURL: URL + let sourceName: String + /// The version on this iPhone, when the device has been read. + let installedVersion: String? + + var id: String { sourceURL.absoluteString + "|" + app.bundleIdentifier } + + /// True when the source has a newer version than the installed one. + var hasUpdate: Bool { + guard let installedVersion, let latest = app.latest?.version else { return false } + return UpdateChecker.isNewer(latest, than: installedVersion) + } +} + +// MARK: - Manager + +/// The sources the user added, what they offer, and which of their apps have +/// updates. Owned by `RootView`, so it survives tab switches. Installs go +/// through the same path as a `sideinstaller://install` link: the link popup +/// asks first, then the Install tab downloads, signs and installs. +@MainActor +final class SourcesManager: ObservableObject { + + /// A source's state after its last fetch. + enum SourceState: Equatable { + case loading + case loaded(AppSource) + case failed(String) + } + + /// The sources, in the order they were added. + @Published private(set) var urls: [URL] = [] + @Published private(set) var states: [URL: SourceState] = [:] + @Published private(set) var isAdding = false + /// Why the last add failed, shown under the field. + @Published var addError: String? + + private static let storeKey = "sources.urls" + + /// Sources every copy of SideInstaller starts with, listed first. They + /// can't be removed: FrizzleM's own, with SideInstaller in it, kept up to + /// date with each release by the update-altsource workflow. + static let builtIn: [URL] = [ + URL(string: "https://raw.githubusercontent.com/FrizzleM/SideInstaller/main/frizzlem.json")!, + ] + + init() { + let saved = (UserDefaults.standard.stringArray(forKey: Self.storeKey) ?? []) + .compactMap(URL.init(string:)) + urls = Self.builtIn + saved.filter { !Self.builtIn.contains($0) } + } + + func isBuiltIn(_ url: URL) -> Bool { Self.builtIn.contains(url) } + + /// A well-known source offered under "Add a source", one tap to add. + struct Suggestion: Identifiable { + let name: String + let developer: String + let url: URL + /// The GitHub account whose picture stands for the developer. + let gitHub: String + + var id: URL { url } + var picture: URL? { URL(string: "https://github.com/\(gitHub).png?size=128") } + } + + /// The official sources of the apps SideInstaller works with, and Haven. + static let suggestions: [Suggestion] = [ + Suggestion(name: "SideStore", developer: "SideStore", + url: URL(string: "https://apps.sidestore.io")!, gitHub: "SideStore"), + Suggestion(name: "AltStore", developer: "AltStore", + url: URL(string: "https://apps.altstore.io")!, gitHub: "altstoreio"), + Suggestion(name: "LiveContainer + SideStore", developer: "LiveContainer", + url: URL(string: "https://github.com/LiveContainer/LiveContainer/releases/download/1.0/apps_ss_lc.json")!, + gitHub: "LiveContainer"), + Suggestion(name: "Haven", developer: "TinusTK", + url: URL(string: "https://tinustk.github.io/Haven/source.json")!, gitHub: "TinusTK"), + ] + + /// The suggestions not added yet. + var openSuggestions: [Suggestion] { + Self.suggestions.filter { !urls.contains($0.url) } + } + + var isRefreshing: Bool { states.values.contains(.loading) } + + /// Every app of every source that loaded, by name. An app two sources + /// both offer is listed under each. + func listings(installed apps: [SideloadedAppStatus]) -> [SourceListing] { + urls.flatMap { url -> [SourceListing] in + guard case .loaded(let source)? = states[url] else { return [] } + return source.apps.map { app in + SourceListing(app: app, sourceURL: url, sourceName: Self.name(of: source, at: url), + installedVersion: Self.installedVersion(of: app, in: apps)) + } + } + .sorted { $0.app.name.localizedCaseInsensitiveCompare($1.app.name) == .orderedAscending } + } + + /// The version of `app` on this iPhone, from what the Sideloaded apps page + /// read. SideInstaller signs an app as `.`, so that + /// counts as the same app. + static func installedVersion(of app: SourceApp, in apps: [SideloadedAppStatus]) -> String? { + apps.first { + ProfileMatcher.installed($0.app.bundleID, isBuiltFrom: app.bundleIdentifier, teamID: nil) + }?.app.version + } + + /// How many apps on this iPhone a source has a newer version of. + func updateCount(installed apps: [SideloadedAppStatus]) -> Int { + listings(installed: apps).filter(\.hasUpdate).count + } + + /// The GitHub account a source is published from, read from where it is + /// hosted (`.github.io`, `raw.githubusercontent.com//…`, + /// `github.com//…`) or from its website. + static func gitHubOwner(of url: URL, website: URL? = nil) -> String? { + if let known = suggestions.first(where: { $0.url == url }) { return known.gitHub } + for link in [url, website].compactMap({ $0 }) { + guard let host = link.host?.lowercased() else { continue } + let parts = link.path.split(separator: "/").map(String.init) + if host.hasSuffix(".github.io") { + return String(host.dropLast(".github.io".count)) + } + if ["raw.githubusercontent.com", "github.com", "www.github.com", + "objects.githubusercontent.com"].contains(host), let owner = parts.first { + return owner + } + } + return nil + } + + /// The picture for a source's row: its developer's GitHub picture when it + /// comes from GitHub, else its first app's icon, else the source's own. + static func picture(of source: AppSource?, at url: URL) -> (primary: URL?, fallback: URL?) { + let appIcon = source?.apps.lazy.compactMap(\.iconURL).first ?? source?.iconURL + if let owner = gitHubOwner(of: url, website: source?.website), + let avatar = URL(string: "https://github.com/\(owner).png?size=128") { + return (avatar, appIcon) + } + return (appIcon, nil) + } + + /// Checks for updates without the page open: fetches the sources and, + /// with LocalDevVPN on, reads which apps are installed. Called once when + /// SideInstaller opens, as `UpdateChecker` checks SideInstaller itself. + func checkAtLaunch(apps: SideloadedAppsManager) async { + guard !urls.isEmpty else { return } + apps.autoLoad() + await refresh() + } + + static func name(of source: AppSource, at url: URL) -> String { + source.name.isEmpty ? (url.host ?? url.absoluteString) : source.name + } + + // MARK: Adding and removing + + /// Adds the source at `text`: an https link to its JSON, or an + /// `altstore://source?url=` / `sidestore://source?url=` link. Fetched first, + /// so only a working source is kept. Returns true once added. + @discardableResult + func add(_ text: String) async -> Bool { + addError = nil + guard let url = Self.sourceLink(text) else { + addError = L("That isn't a source link. Paste the whole https:// address of the source.") + return false + } + guard !urls.contains(url) else { + addError = L("That source is already added.") + return false + } + isAdding = true + defer { isAdding = false } + do { + let source = try await Self.fetch(url) + urls.append(url) + states[url] = .loaded(source) + save() + Engine.shared.log("Sources: added \(url.absoluteString) (\(source.apps.count) apps).") + return true + } catch { + addError = Self.describe(error) + Engine.shared.log("⛔️ Sources: couldn't add \(url.absoluteString): \(addError ?? "")") + return false + } + } + + func remove(_ url: URL) { + guard !isBuiltIn(url) else { return } + urls.removeAll { $0 == url } + states[url] = nil + save() + Engine.shared.log("Sources: removed \(url.absoluteString).") + } + + private func save() { + UserDefaults.standard.set(urls.filter { !isBuiltIn($0) }.map(\.absoluteString), + forKey: Self.storeKey) + } + + /// The source a pasted link points at. + static func sourceLink(_ text: String) -> URL? { + let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) + if let components = URLComponents(string: trimmed), + let scheme = components.scheme?.lowercased(), + ["altstore", "sidestore", "feather"].contains(scheme), + let inner = components.queryItems?.first(where: { $0.name.lowercased() == "url" })?.value { + return Engine.downloadLink(inner) + } + return Engine.downloadLink(trimmed) + } + + // MARK: Fetching + + /// Fetches every source again. Called when the page opens and on pull. + func refresh() async { + let all = urls + guard !all.isEmpty else { return } + for url in all where states[url] == nil { states[url] = .loading } + await withTaskGroup(of: (URL, SourceState).self) { group in + for url in all { + group.addTask { + do { return (url, .loaded(try await Self.fetch(url))) } + catch { return (url, .failed(await Self.describe(error))) } + } + } + for await (url, state) in group where urls.contains(url) { + // A source that fetched before keeps its apps if this fetch fails. + if case .failed = state, case .loaded? = states[url] { continue } + states[url] = state + } + } + } + + /// Fetches the sources not fetched yet, when the page opens. The rest + /// were fetched at launch; pull down or Check for updates fetches them again. + func refreshMissing() async { + guard urls.contains(where: { states[$0] == nil }) else { return } + await refresh() + } + + enum FetchError: Error { + case status(Int) + case notASource + } + + nonisolated static func fetch(_ url: URL) async throws -> AppSource { + var request = URLRequest(url: url) + request.cachePolicy = .reloadIgnoringLocalCacheData + request.timeoutInterval = 30 + request.setValue("SideInstaller", forHTTPHeaderField: "User-Agent") + let (data, response) = try await URLSession.shared.data(for: request) + if let http = response as? HTTPURLResponse, !(200..<300).contains(http.statusCode) { + throw FetchError.status(http.statusCode) + } + guard let source = try? JSONDecoder().decode(AppSource.self, from: data), + !source.apps.isEmpty || !source.name.isEmpty else { + throw FetchError.notASource + } + return source + } + + static func describe(_ error: Error) -> String { + switch error { + case FetchError.status(let code): + return L("The source answered with HTTP %d.", code) + case FetchError.notASource: + return L("That link didn't return a source. It has to be the source's JSON file itself.") + default: + return L("Couldn't reach the source: %@", error.localizedDescription) + } + } + + // MARK: Installing + + /// Puts up the install popup for `version`, as a `sideinstaller://install` + /// link would. On yes, the Install tab downloads, signs and installs it. + func install(_ version: SourceVersion, of app: SourceApp) { + var components = URLComponents() + components.scheme = DeepLink.scheme + components.host = "install" + components.queryItems = [URLQueryItem(name: "url", value: version.downloadURL.absoluteString)] + guard let link = components.url else { return } + Engine.shared.log("Sources: \(app.name) \(version.version) from \(version.downloadURL.absoluteString).") + Engine.shared.receiveLink(link) + } +} + +// MARK: - Sources page + +/// The Sources page: add AltStore-format sources, browse their apps, see which +/// installed ones have updates, and install from them without fetching the +/// IPA by hand. +struct SourcesView: View { + @EnvironmentObject private var loc: Localizer + @ObservedObject var manager: SourcesManager + /// What is installed comes from the Sideloaded apps page's device read. + @ObservedObject var appsManager: SideloadedAppsManager + + @State private var showSettings = false + @State private var newSource = "" + @FocusState private var fieldFocused: Bool + /// The add-a-source field, opened from its button. + @State private var showAdd = false + /// The list of sources, opened from its button. + @State private var showSources = false + + private var listings: [SourceListing] { manager.listings(installed: appsManager.entries) } + + var body: some View { + let all = listings + let updates = all.filter(\.hasUpdate) + ScrollView { + VStack(spacing: 16) { + header(updates: updates.count).cascadeItem(0) + actionButtons.cascadeItem(1) + if showAdd { + addCard.transition(.cardAppear) + } + if !updates.isEmpty { + section(title: L("Updates"), listings: updates) + .transition(.cardAppear) + .cascadeItem(3) + } + if !manager.urls.isEmpty { + sourcesButton.cascadeItem(4) + if showSources { + SourceRowsCard(manager: manager) + .transition(.cardAppear) + } + } + if !all.isEmpty { + section(title: L("Apps"), listings: all) + .cascadeItem(5) + } + } + .padding(20) + .pageColumn() + .animation(.smooth(duration: 0.3), value: manager.states) + .animation(.smooth(duration: 0.3), value: manager.urls) + .animation(.smooth(duration: 0.3), value: appsManager.entries) + .animation(.smooth(duration: 0.3), value: showAdd) + .animation(.smooth(duration: 0.3), value: showSources) + } + .scrollDismissesKeyboard(.interactively) + .background(AppBackground()) + .refreshable { await manager.refresh() } + .toolbar { settingsToolbarItem(isPresented: $showSettings) } + .sheet(isPresented: $showSettings) { SettingsView() } + .task { + appsManager.autoLoad() + await manager.refreshMissing() + } + } + + // MARK: Header + + private func header(updates: Int) -> some View { + BrandHeader(icon: "square.stack.3d.down.right", image: "SourcesLogo", title: L("Sources")) { + if updates > 0 { + StatusDot(text: updates == 1 ? L("%d update", updates) : L("%d updates", updates), + color: Theme.warning) + } else if !manager.urls.isEmpty { + StatusDot(text: manager.urls.count == 1 ? L("%d source", manager.urls.count) + : L("%d sources", manager.urls.count), + color: Theme.positive, idle: manager.isRefreshing) + } + } + } + + // MARK: Add + + private var addCard: some View { + PanelCard { + VStack(alignment: .leading, spacing: 12) { + HStack(spacing: 8) { + TextField(String("https://example.com/source.json"), text: $newSource) + .textFieldStyle(.plain) + .keyboardType(.URL) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + .submitLabel(.done) + .focused($fieldFocused) + .onSubmit(add) + .fieldBackground() + Button(action: add) { + if manager.isAdding { + ProgressView() + } else { + Text(L("Add")) + } + } + .buttonStyle(SecondaryButtonStyle(), sound: .tap) + .disabled(manager.isAdding || newSource.trimmingCharacters(in: .whitespaces).isEmpty) + } + if let error = manager.addError { + Label(error, systemImage: "exclamationmark.triangle") + .font(.caption) + .foregroundStyle(Theme.negative) + .fixedSize(horizontal: false, vertical: true) + .transition(.cardAppear) + } + Text(L("Paste the link of a SideStore or AltStore source, or of a .json source file. Its apps, their updates and release notes show here.")) + .font(.caption) + .foregroundStyle(Theme.muted) + .fixedSize(horizontal: false, vertical: true) + if !manager.openSuggestions.isEmpty { + Divider().overlay(Theme.hairline) + Text(L("Suggested")) + .font(.subheadline.weight(.medium)) + .foregroundStyle(.secondary) + ForEach(manager.openSuggestions) { suggestion in + suggestionRow(suggestion) + .transition(.opacity) + } + } + } + .animation(.smooth(duration: 0.25), value: manager.urls) + .animation(.smooth(duration: 0.25), value: manager.addError) + } + } + + private func suggestionRow(_ suggestion: SourcesManager.Suggestion) -> some View { + HStack(spacing: 12) { + AppIconView(url: suggestion.picture, side: 36, round: true) + VStack(alignment: .leading, spacing: 2) { + Text(suggestion.name) + .font(.subheadline.weight(.medium)) + .lineLimit(1) + Text(suggestion.developer) + .font(.caption) + .foregroundStyle(Theme.muted) + .lineLimit(1) + } + Spacer(minLength: 8) + Button(L("Add")) { + Task { await manager.add(suggestion.url.absoluteString) } + } + .buttonStyle(SecondaryButtonStyle(), sound: .tap) + .controlSize(.small) + .disabled(manager.isAdding) + } + } + + private func add() { + let text = newSource + guard !text.trimmingCharacters(in: .whitespaces).isEmpty else { return } + Task { + if await manager.add(text) { + newSource = "" + fieldFocused = false + showAdd = false + } + } + } + + // MARK: Buttons + + /// "Add a source", which opens the field, and "Check for updates", which + /// reads which apps are on this iPhone (LocalDevVPN on, as Sideloaded apps + /// needs) and fetches every source again. + private var actionButtons: some View { + HStack(spacing: 12) { + Button { + showAdd.toggle() + manager.addError = nil + fieldFocused = showAdd + } label: { + HStack(spacing: 6) { + Image(systemName: showAdd ? "xmark" : "plus") + .contentTransition(.symbolEffect(.replace)) + Text(L("Add a source")) + } + .font(.subheadline.weight(.medium)) + .lineLimit(1) + .minimumScaleFactor(0.7) + .frame(maxWidth: .infinity) + } + .buttonStyle(SecondaryButtonStyle(), sound: .tap) + if !manager.urls.isEmpty { + Button(action: checkForUpdates) { + HStack(spacing: 6) { + if appsManager.isWorking || manager.isRefreshing { + ProgressView().tint(Theme.accent).controlSize(.small) + } else { + Image(systemName: "arrow.clockwise") + } + Text(L("Check for updates")) + } + .font(.subheadline.weight(.medium)) + .lineLimit(1) + .minimumScaleFactor(0.7) + .frame(maxWidth: .infinity) + } + .buttonStyle(SecondaryButtonStyle(), sound: .tap) + .disabled(appsManager.isWorking || manager.isRefreshing) + } + } + } + + private func checkForUpdates() { + appsManager.load() + Task { await manager.refresh() } + } + + // MARK: Apps + + private func section(title: String, listings: [SourceListing]) -> some View { + PanelCard { + VStack(alignment: .leading, spacing: 4) { + Text(title) + .font(.subheadline.weight(.medium)) + .foregroundStyle(.secondary) + .padding(.bottom, 8) + ForEach(Array(listings.enumerated()), id: \.element.id) { index, listing in + if index > 0 { Divider().overlay(Theme.hairline) } + NavigationLink { + SourceAppView(listing: listing, manager: manager) + } label: { + SourceAppRow(listing: listing) + } + .buttonStyle(.plain, sound: .tick) + } + } + } + } + + // MARK: Sources + + /// Opens and closes the list of sources below it, so the apps keep the + /// room until it is wanted. + private var sourcesButton: some View { + Button { showSources.toggle() } label: { + HStack(spacing: 12) { + Image(systemName: "square.stack.3d.up") + .foregroundStyle(Theme.accent) + Text(L("Your sources")) + .font(.body.weight(.medium)) + Spacer(minLength: 8) + Text("\(manager.urls.count)") + .font(.subheadline) + .foregroundStyle(.secondary) + Image(systemName: "chevron.down") + .font(.footnote.weight(.semibold)) + .foregroundStyle(Theme.muted) + .rotationEffect(.degrees(showSources ? 180 : 0)) + } + .padding(.horizontal, 16) + .frame(minHeight: 52) + .cardSurface(in: RoundedRectangle(cornerRadius: Theme.cardRadius, style: .continuous)) + .contentShape(Rectangle()) + } + .buttonStyle(.plain, sound: .tick) + } +} + +/// Every source added, with who publishes it, what it offers and its link; +/// each can be copied or removed. +struct SourceRowsCard: View { + @ObservedObject var manager: SourcesManager + + var body: some View { + PanelCard { + VStack(alignment: .leading, spacing: 4) { + ForEach(Array(manager.urls.enumerated()), id: \.element) { index, url in + if index > 0 { Divider().overlay(Theme.hairline) } + sourceRow(url) + } + } + } + } + + private func sourceRow(_ url: URL) -> some View { + HStack(spacing: 12) { + let picture = SourcesManager.picture(of: loadedSource(url), at: url) + AppIconView(url: picture.primary, fallback: picture.fallback, side: 40, round: true) + VStack(alignment: .leading, spacing: 2) { + Text(loadedSource(url)?.developerName ?? sourceName(url)) + .font(.subheadline.weight(.medium)) + .lineLimit(1) + Group { + switch manager.states[url] { + case .loaded(let source)?: + Text(sourceName(url) + " · " + (source.apps.count == 1 + ? L("%d app", source.apps.count) + : L("%d apps", source.apps.count))) + case .failed(let message)?: + Text(message).foregroundStyle(Theme.negative) + default: + Text(L("Loading…")) + } + } + .font(.caption) + .foregroundStyle(Theme.muted) + .lineLimit(2) + Text(url.absoluteString) + .font(.caption2) + .foregroundStyle(Theme.muted) + .lineLimit(1) + .truncationMode(.middle) + } + Spacer(minLength: 8) + Menu { + Button { UIPasteboard.general.string = url.absoluteString } label: { + Label(L("Copy link"), systemImage: "doc.on.doc") + } + if !manager.isBuiltIn(url) { + Button(role: .destructive) { manager.remove(url) } label: { + Label(L("Remove"), systemImage: "trash") + } + } + } label: { + Image(systemName: "ellipsis.circle") + .font(.title3) + .foregroundStyle(.secondary) + .frame(width: 44, height: 44) + .contentShape(Rectangle()) + } + .accessibilityLabel(L("Source options")) + } + .padding(.vertical, 6) + } + + private func sourceName(_ url: URL) -> String { + if case .loaded(let source)? = manager.states[url] { return SourcesManager.name(of: source, at: url) } + return url.host ?? url.absoluteString + } + + private func loadedSource(_ url: URL) -> AppSource? { + if case .loaded(let source)? = manager.states[url] { return source } + return nil + } +} + +/// One app in a list: its icon, name, developer and version, with an Update +/// tag when the source has a newer one than the iPhone. +private struct SourceAppRow: View { + let listing: SourceListing + + var body: some View { + HStack(spacing: 12) { + AppIconView(url: listing.app.iconURL, side: 48) + VStack(alignment: .leading, spacing: 2) { + Text(listing.app.name) + .font(.body.weight(.medium)) + .lineLimit(1) + Text(listing.app.developerName ?? listing.sourceName) + .font(.caption) + .foregroundStyle(.secondary) + .lineLimit(1) + Text(versionLine) + .font(.caption) + .foregroundStyle(Theme.muted) + .lineLimit(1) + } + Spacer(minLength: 8) + if listing.hasUpdate { + Tag(text: L("Update"), color: Theme.warning) + } else if listing.installedVersion != nil { + Tag(text: L("Installed"), color: Theme.positive) + } + Image(systemName: "chevron.right") + .font(.footnote.weight(.semibold)) + .foregroundStyle(Theme.muted) + } + .padding(.vertical, 8) + .contentShape(Rectangle()) + } + + private var versionLine: String { + let latest = listing.app.latest?.version ?? "" + if let installed = listing.installedVersion, listing.hasUpdate { + return "\(installed) → \(latest)" + } + return latest + } +} + +/// A small outlined tag, like the Beta badge. +private struct Tag: View { + let text: String + let color: Color + + var body: some View { + Text(text) + .font(.caption.weight(.medium)) + .foregroundStyle(color) + .padding(.horizontal, 8) + .padding(.vertical, 3) + .overlay(Capsule().strokeBorder(color.opacity(0.4), lineWidth: 1)) + .fixedSize() + } +} + +/// An app's icon from its source, or a plain tile while it loads or when it +/// has none. With `fallback`, that picture is tried when `url` fails (a +/// developer with no GitHub picture shows their app's icon). `round` draws a +/// person's picture in a circle. +struct AppIconView: View { + let url: URL? + var fallback: URL? = nil + let side: CGFloat + var round = false + + var body: some View { + let shape = RoundedRectangle(cornerRadius: round ? side / 2 : side * 0.225, style: .continuous) + AsyncImage(url: url) { phase in + if let image = phase.image { + image.resizable().scaledToFill() + } else if case .failure = phase, let fallback { + AppIconView(url: fallback, side: side, round: round) + } else { + placeholder + } + } + .frame(width: side, height: side) + .clipShape(shape) + .overlay(shape.strokeBorder(Theme.hairline, lineWidth: 1)) + } + + private var placeholder: some View { + ZStack { + Rectangle().fill(Theme.raised) + Image(systemName: "app.dashed") + .font(.system(size: side * 0.4)) + .foregroundStyle(Theme.muted) + } + } +} + +// MARK: - App page + +/// One source app: install or update it, what's new, its description, and +/// every version with its release notes. +struct SourceAppView: View { + @EnvironmentObject private var loc: Localizer + let listing: SourceListing + @ObservedObject var manager: SourcesManager + + @State private var showSettings = false + @State private var confirm: SourceVersion? + + private var app: SourceApp { listing.app } + + var body: some View { + ScrollView { + VStack(spacing: 16) { + header.cascadeItem(0) + installButton.cascadeItem(1) + if let latest = app.latest { + whatsNew(latest).cascadeItem(2) + } + if let description = app.localizedDescription, !description.isEmpty { + PanelCard { + VStack(alignment: .leading, spacing: 8) { + cardTitle(L("About")) + ReleaseNotesText(text: description) + } + } + .cascadeItem(3) + } + if app.versions.count > 1 { + history.cascadeItem(4) + } + } + .padding(20) + .pageColumn() + } + .background(AppBackground()) + .toolbar { settingsToolbarItem(isPresented: $showSettings) } + .sheet(isPresented: $showSettings) { SettingsView() } + .alert(confirm.map { L("Install %@ %@?", app.name, $0.version) } ?? "", + isPresented: Binding(get: { confirm != nil }, set: { if !$0 { confirm = nil } })) { + Button(L("Install")) { + if let confirm { manager.install(confirm, of: app) } + confirm = nil + } + Button(L("Cancel"), role: .cancel) { confirm = nil } + } message: { + Text(L("This version is older than the newest one. It's installed over the copy on this iPhone, which may not open data a newer version saved.")) + } + } + + private var header: some View { + VStack(spacing: 12) { + AppIconView(url: app.iconURL, side: 96) + VStack(spacing: 4) { + Text(app.name) + .font(.title.weight(.semibold)) + .multilineTextAlignment(.center) + if let developer = app.developerName { + Text(developer) + .font(.subheadline) + .foregroundStyle(.secondary) + } + if let subtitle = app.subtitle, !subtitle.isEmpty { + Text(subtitle) + .font(.footnote) + .foregroundStyle(Theme.muted) + .multilineTextAlignment(.center) + } + } + StatusDot(text: statusText, color: listing.hasUpdate ? Theme.warning : Theme.positive, + idle: listing.installedVersion == nil) + } + .frame(maxWidth: .infinity) + .padding(.top, 8) + } + + private var statusText: String { + let latest = app.latest?.version ?? "" + guard let installed = listing.installedVersion else { + return L("Version %@ · from %@", latest, listing.sourceName) + } + return listing.hasUpdate ? L("%@ installed · %@ available", installed, latest) + : L("%@ installed · up to date", installed) + } + + @ViewBuilder + private var installButton: some View { + if let latest = app.latest { + VStack(spacing: 8) { + Button { manager.install(latest, of: app) } label: { + HStack(spacing: 8) { + Image(systemName: listing.hasUpdate ? "arrow.down.circle" : "square.and.arrow.down") + Text(listing.hasUpdate ? L("Update to %@", latest.version) + : L("Install %@", latest.version)) + } + } + .buttonStyle(PrimaryButtonStyle()) + Text(L("Downloads the IPA from the source, then signs it with your Apple ID and installs it, as a custom .ipa would be.")) + .font(.caption) + .foregroundStyle(Theme.muted) + .multilineTextAlignment(.center) + } + } + } + + private func whatsNew(_ latest: SourceVersion) -> some View { + PanelCard { + VStack(alignment: .leading, spacing: 8) { + HStack(alignment: .firstTextBaseline) { + cardTitle(L("What's new")) + Spacer() + Text(versionMeta(latest)) + .font(.caption) + .foregroundStyle(Theme.muted) + } + if let notes = latest.notes, !notes.isEmpty { + ReleaseNotesText(text: notes) + } else { + Text(L("This version has no release notes.")) + .font(.footnote) + .foregroundStyle(Theme.muted) + } + } + } + } + + private var history: some View { + PanelCard { + VStack(alignment: .leading, spacing: 12) { + cardTitle(L("Version history")) + ForEach(Array(app.versions.dropFirst().enumerated()), id: \.element.id) { index, version in + if index > 0 { Divider().overlay(Theme.hairline) } + VStack(alignment: .leading, spacing: 6) { + HStack(alignment: .firstTextBaseline) { + Text(version.version) + .font(.subheadline.weight(.semibold)) + Text(versionMeta(version)) + .font(.caption) + .foregroundStyle(Theme.muted) + Spacer() + Button(L("Install")) { confirm = version } + .buttonStyle(SecondaryButtonStyle(), sound: .tap) + .controlSize(.small) + } + if let notes = version.notes, !notes.isEmpty { + ReleaseNotesText(text: notes) + } + } + } + } + } + } + + private func cardTitle(_ text: String) -> some View { + Text(text) + .font(.subheadline.weight(.medium)) + .foregroundStyle(.secondary) + } + + /// "16 Nov 2026 · 10.4 MB", with what the source gives. + private func versionMeta(_ version: SourceVersion) -> String { + var parts: [String] = [] + if let date = version.date { + parts.append(date.formatted(Date.FormatStyle(date: .abbreviated, time: .omitted) + .locale(Localizer.locale))) + } + if let size = version.size, size > 0 { + parts.append(ByteCountFormatter.string(fromByteCount: size, countStyle: .file)) + } + return parts.joined(separator: " · ") + } +} + +/// Release notes as sources write them: Markdown headings, bullets and inline +/// bold, italics and links. Anything else shows as plain text. +struct ReleaseNotesText: View { + let text: String + + var body: some View { + VStack(alignment: .leading, spacing: 6) { + ForEach(Array(Self.blocks(text).enumerated()), id: \.offset) { _, block in + switch block { + case .heading(let line): + Text(Self.inline(line)) + .font(.footnote.weight(.semibold)) + .padding(.top, 4) + case .bullet(let line): + HStack(alignment: .firstTextBaseline, spacing: 8) { + Text("•").foregroundStyle(Theme.muted) + Text(Self.inline(line)) + } + .font(.footnote) + case .paragraph(let line): + Text(Self.inline(line)).font(.footnote) + } + } + } + .foregroundStyle(.primary.opacity(0.9)) + .tint(Theme.accent) + .frame(maxWidth: .infinity, alignment: .leading) + .fixedSize(horizontal: false, vertical: true) + .textSelection(.enabled) + } + + enum Block: Equatable { + case heading(String) + case bullet(String) + case paragraph(String) + } + + static func blocks(_ text: String) -> [Block] { + text.replacingOccurrences(of: "\r\n", with: "\n") + .split(separator: "\n", omittingEmptySubsequences: true) + .compactMap { raw -> Block? in + let line = raw.trimmingCharacters(in: .whitespaces) + guard !line.isEmpty else { return nil } + if line.hasPrefix("#") { + return .heading(line.drop { $0 == "#" }.trimmingCharacters(in: .whitespaces)) + } + for marker in ["- ", "* ", "• "] where line.hasPrefix(marker) { + return .bullet(String(line.dropFirst(marker.count))) + } + return .paragraph(line) + } + } + + static func inline(_ line: String) -> AttributedString { + (try? AttributedString(markdown: line, + options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace))) + ?? AttributedString(line) + } +} diff --git a/ios-app/SpanishStrings.swift b/ios-app/SpanishStrings.swift index f974e9b7..cc1d7c25 100644 --- a/ios-app/SpanishStrings.swift +++ b/ios-app/SpanishStrings.swift @@ -1326,4 +1326,73 @@ let spanishStrings: [String: String] = [ "Pick Again": "Elegir de nuevo", "The next sign-in with “%@” asks which developer team signs.": "El próximo inicio de sesión con “%@” preguntará qué equipo de desarrollo firma.", + + // MARK: - Sources + + "Suggested": + "Sugeridas", + + "Paste the link of a SideStore or AltStore source, or of a .json source file. Its apps, their updates and release notes show here.": + "Pega el enlace de una fuente de SideStore o AltStore, o de un archivo de fuente .json. Sus apps, actualizaciones y notas aparecerán aquí.", + + "Sources": + "Fuentes", + "Add a source": + "Añadir una fuente", + "Add": + "Añadir", + "Apps": + "Apps", + "Updates": + "Actualizaciones", + "Update": + "Actualizar", + "Your sources": + "Tus fuentes", + "Check for updates": + "Buscar actualizaciones", + "Copy link": + "Copiar enlace", + "Source options": + "Opciones de la fuente", + "Loading…": + "Cargando…", + "What's new": + "Novedades", + "Version history": + "Historial de versiones", + "This version has no release notes.": + "Esta versión no tiene notas.", + "%d update": + "%d actualización", + "%d updates": + "%d actualizaciones", + "%d source": + "%d fuente", + "%d sources": + "%d fuentes", + "Update to %@": + "Actualizar a %@", + "Install %@ %@?": + "¿Instalar %@ %@?", + "Version %@ · from %@": + "Versión %@ · de %@", + "%@ installed · %@ available": + "%@ instalada · %@ disponible", + "%@ installed · up to date": + "%@ instalada · al día", + "That source is already added.": + "Esa fuente ya está añadida.", + "The source answered with HTTP %d.": + "La fuente respondió con HTTP %d.", + "Couldn't reach the source: %@": + "No se pudo acceder a la fuente: %@", + "That isn't a source link. Paste the whole https:// address of the source.": + "Eso no es un enlace de fuente. Pega la dirección https:// completa de la fuente.", + "That link didn't return a source. It has to be the source's JSON file itself.": + "Ese enlace no devolvió una fuente. Tiene que ser el archivo JSON de la fuente.", + "Downloads the IPA from the source, then signs it with your Apple ID and installs it, as a custom .ipa would be.": + "Descarga el IPA de la fuente y luego lo firma con tu Apple ID y lo instala, como un .ipa personalizado.", + "This version is older than the newest one. It's installed over the copy on this iPhone, which may not open data a newer version saved.": + "Esta versión es más antigua que la más reciente. Se instala sobre la copia de este iPhone, que quizá no abra datos guardados por una versión más nueva.", ] diff --git a/ios-app/TurkishStrings.swift b/ios-app/TurkishStrings.swift index 8ad67c21..1c4131fe 100644 --- a/ios-app/TurkishStrings.swift +++ b/ios-app/TurkishStrings.swift @@ -1185,4 +1185,73 @@ let turkishStrings: [String: String] = [ "Pick Again": "Yeniden seç", "The next sign-in with “%@” asks which developer team signs.": "“%@” ile bir sonraki oturum açmada hangi geliştirici ekibinin imzalayacağı sorulur.", + + // MARK: - Sources + + "Suggested": + "Önerilen", + + "Paste the link of a SideStore or AltStore source, or of a .json source file. Its apps, their updates and release notes show here.": + "Bir SideStore veya AltStore kaynağının ya da bir .json kaynak dosyasının bağlantısını yapıştırın. Uygulamaları, güncellemeleri ve sürüm notları burada görünür.", + + "Sources": + "Kaynaklar", + "Add a source": + "Kaynak ekle", + "Add": + "Ekle", + "Apps": + "Uygulamalar", + "Updates": + "Güncellemeler", + "Update": + "Güncelle", + "Your sources": + "Kaynaklarınız", + "Check for updates": + "Güncellemeleri denetle", + "Copy link": + "Bağlantıyı kopyala", + "Source options": + "Kaynak seçenekleri", + "Loading…": + "Yükleniyor…", + "What's new": + "Yenilikler", + "Version history": + "Sürüm geçmişi", + "This version has no release notes.": + "Bu sürümün sürüm notu yok.", + "%d update": + "%d güncelleme", + "%d updates": + "%d güncelleme", + "%d source": + "%d kaynak", + "%d sources": + "%d kaynak", + "Update to %@": + "%@ sürümüne güncelle", + "Install %@ %@?": + "%@ %@ yüklensin mi?", + "Version %@ · from %@": + "Sürüm %@ · kaynak: %@", + "%@ installed · %@ available": + "%@ yüklü · %@ mevcut", + "%@ installed · up to date": + "%@ yüklü · güncel", + "That source is already added.": + "Bu kaynak zaten eklendi.", + "The source answered with HTTP %d.": + "Kaynak HTTP %d ile yanıt verdi.", + "Couldn't reach the source: %@": + "Kaynağa ulaşılamadı: %@", + "That isn't a source link. Paste the whole https:// address of the source.": + "Bu bir kaynak bağlantısı değil. Kaynağın https:// adresinin tamamını yapıştırın.", + "That link didn't return a source. It has to be the source's JSON file itself.": + "Bu bağlantı bir kaynak döndürmedi. Kaynağın JSON dosyasının kendisi olmalı.", + "Downloads the IPA from the source, then signs it with your Apple ID and installs it, as a custom .ipa would be.": + "IPA'yı kaynaktan indirir, ardından Apple Kimliğinizle imzalayıp yükler; özel bir .ipa gibi.", + "This version is older than the newest one. It's installed over the copy on this iPhone, which may not open data a newer version saved.": + "Bu sürüm en yenisinden daha eski. Bu iPhone'daki kopyanın üzerine yüklenir ve daha yeni bir sürümün kaydettiği verileri açamayabilir.", ] diff --git a/ios-app/UpdateChecker.swift b/ios-app/UpdateChecker.swift index a0d319d3..597333d2 100644 --- a/ios-app/UpdateChecker.swift +++ b/ios-app/UpdateChecker.swift @@ -59,7 +59,7 @@ final class UpdateChecker: ObservableObject { /// Compare dotted versions numerically, so "0.10.0" > "0.9.0". Anything /// after a "-" (e.g. "-beta.1") is ignored. - static func isNewer(_ lhs: String, than rhs: String) -> Bool { + nonisolated static func isNewer(_ lhs: String, than rhs: String) -> Bool { func parts(_ v: String) -> [Int] { let core = v.split(separator: "-", maxSplits: 1).first ?? "" return core.split(separator: ".").map { Int($0) ?? 0 } diff --git a/ios-app/VietnameseStrings.swift b/ios-app/VietnameseStrings.swift index fe1c2c95..a83731c3 100644 --- a/ios-app/VietnameseStrings.swift +++ b/ios-app/VietnameseStrings.swift @@ -1321,4 +1321,73 @@ let vietnameseStrings: [String: String] = [ "Pick Again": "Chọn lại", "The next sign-in with “%@” asks which developer team signs.": "Lần đăng nhập tiếp theo bằng “%@” sẽ hỏi ký bằng nhóm nhà phát triển nào.", + + // MARK: - Sources + + "Suggested": + "Gợi ý", + + "Paste the link of a SideStore or AltStore source, or of a .json source file. Its apps, their updates and release notes show here.": + "Dán liên kết của một nguồn SideStore hoặc AltStore, hoặc của một tệp nguồn .json. Ứng dụng, bản cập nhật và ghi chú phát hành của nguồn sẽ hiện ở đây.", + + "Sources": + "Nguồn", + "Add a source": + "Thêm nguồn", + "Add": + "Thêm", + "Apps": + "Ứng dụng", + "Updates": + "Cập nhật", + "Update": + "Cập nhật", + "Your sources": + "Nguồn của bạn", + "Check for updates": + "Kiểm tra cập nhật", + "Copy link": + "Sao chép liên kết", + "Source options": + "Tùy chọn nguồn", + "Loading…": + "Đang tải…", + "What's new": + "Có gì mới", + "Version history": + "Lịch sử phiên bản", + "This version has no release notes.": + "Phiên bản này không có ghi chú phát hành.", + "%d update": + "%d bản cập nhật", + "%d updates": + "%d bản cập nhật", + "%d source": + "%d nguồn", + "%d sources": + "%d nguồn", + "Update to %@": + "Cập nhật lên %@", + "Install %@ %@?": + "Cài %@ %@?", + "Version %@ · from %@": + "Phiên bản %@ · từ %@", + "%@ installed · %@ available": + "Đã cài %@ · có %@", + "%@ installed · up to date": + "Đã cài %@ · mới nhất", + "That source is already added.": + "Nguồn đó đã được thêm.", + "The source answered with HTTP %d.": + "Nguồn trả về HTTP %d.", + "Couldn't reach the source: %@": + "Không thể kết nối tới nguồn: %@", + "That isn't a source link. Paste the whole https:// address of the source.": + "Đó không phải liên kết nguồn. Hãy dán toàn bộ địa chỉ https:// của nguồn.", + "That link didn't return a source. It has to be the source's JSON file itself.": + "Liên kết đó không trả về nguồn. Nó phải là chính tệp JSON của nguồn.", + "Downloads the IPA from the source, then signs it with your Apple ID and installs it, as a custom .ipa would be.": + "Tải IPA từ nguồn, rồi ký bằng Apple ID của bạn và cài đặt, giống như một .ipa tùy chỉnh.", + "This version is older than the newest one. It's installed over the copy on this iPhone, which may not open data a newer version saved.": + "Phiên bản này cũ hơn bản mới nhất. Nó được cài đè lên bản trên iPhone này và có thể không mở được dữ liệu mà phiên bản mới hơn đã lưu.", ]