From 098ea3e73db543345a02dee762d400e0636fc0ac Mon Sep 17 00:00:00 2001 From: HR0101 Date: Thu, 29 Oct 2026 14:16:42 +0900 Subject: [PATCH 1/5] =?UTF-8?q?feat(updates):=20GitHub=20Releases=E9=80=A3?= =?UTF-8?q?=E6=90=BA=E3=81=AE=E3=82=A2=E3=83=83=E3=83=97=E3=83=87=E3=83=BC?= =?UTF-8?q?=E3=83=88=E7=A2=BA=E8=AA=8D=E3=83=BB=E3=83=80=E3=82=A6=E3=83=B3?= =?UTF-8?q?=E3=83=AD=E3=83=BC=E3=83=89=E6=A9=9F=E8=83=BD=E3=81=A8UI?= =?UTF-8?q?=E3=82=92=E8=BF=BD=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Features/Updates/AppUpdateView.swift | 103 +++++++ .../Features/Updates/AppUpdater.swift | 270 ++++++++++++++++++ 2 files changed, 373 insertions(+) create mode 100644 AllServerForMac/Features/Updates/AppUpdateView.swift create mode 100644 AllServerForMac/Features/Updates/AppUpdater.swift diff --git a/AllServerForMac/Features/Updates/AppUpdateView.swift b/AllServerForMac/Features/Updates/AppUpdateView.swift new file mode 100644 index 0000000..b6b290f --- /dev/null +++ b/AllServerForMac/Features/Updates/AppUpdateView.swift @@ -0,0 +1,103 @@ +import SwiftUI + +struct AppUpdateView: View { + @ObservedObject var updater: AppUpdater + + var body: some View { + VStack(alignment: .leading, spacing: 16) { + Text("ソフトウェアアップデート").font(.title2.bold()) + Text("現在のバージョン: \(updater.currentVersion)(ビルド \(updater.currentBuild))") + .foregroundStyle(.secondary) + switch updater.state { + case .idle: + Text("最新バージョンを確認できます。") + Button("アップデートを確認") { updater.check(manual: true) } + case .checking: + ProgressView("アップデートを確認中…") + case .available(let release): + Text("\(release.tag_name) に更新できます。全ての処理が終わってからアプリを終了し、ダウンロードしたアプリに差し替えてください。") + ScrollView { + Text(release.body.flatMap { $0.isEmpty ? nil : $0 } ?? "リリースノートはありません。") + .frame(maxWidth: .infinity, alignment: .leading) + .textSelection(.enabled) + }.frame(height: 180) + HStack { + if release.downloadURL != nil { + Button("更新をダウンロード") { updater.download(release) } + .keyboardShortcut(.defaultAction) + } + Button("リリースページを開く") { updater.openReleases() } + } + HStack { + Button("後で") { updater.remindLater() } + Button("このバージョンをスキップ") { updater.skip(release) } + } + Text("後で更新する場合は、このウィンドウを閉じてください。") + .font(.caption).foregroundStyle(.secondary) + case .upToDate: + Text("現在のバージョンは最新です。") + case .noRelease: + Text("公開されたリリースはまだありません。") + case .downloading: + if let progress = updater.progress { + ProgressView(value: progress) { Text("ダウンロード中…") } + } else { + ProgressView("ダウンロード中…") + } + Button("キャンセル") { updater.cancelDownload() } + case .downloaded(let url): + Text("ダウンロードしました: \(url.lastPathComponent)") + Text("サーバーを停止し、インポート・解析・書き出しの完了を確認してから通常の終了操作を行ってください。ZIPを展開し、現在のアプリを差し替えて起動すると更新が完了します。ライブラリの保存場所は変わりません。") + case .failed(let message): + Text(message).foregroundStyle(.red) + HStack { + Button("再試行") { updater.check(manual: true) } + Button("リリースページを開く") { updater.openReleases() } + } + } + } + .padding(24) + .frame(width: 620, alignment: .leading) + .frame(minHeight: 200) + } +} + +struct UpdateSettingsSection: View { + @ObservedObject private var updater = AppUpdater.shared + var body: some View { + Section("アップデート") { + LabeledContent("現在のバージョン", value: "\(updater.currentVersion)(ビルド \(updater.currentBuild))") + Toggle("起動時に自動でアップデートを確認", isOn: $updater.automaticallyChecks) + LabeledContent("最終確認") { + if let date = updater.lastCheck { + Text(date, format: .dateTime.year().month().day().hour().minute()) + } else { + Text("未確認") + } + } + AppUpdateAvailabilityButton() + Button(updater.isBusy ? "アップデートの状況を表示" : "今すぐアップデートを確認") { + updater.check(manual: true) + } + } + } +} + +/// Observes update availability independently of the library and playback views. +struct AppUpdateAvailabilityButton: View { + @ObservedObject private var updater = AppUpdater.shared + + var body: some View { + if case .available(let release) = updater.state { + Button { + updater.showWindow() + } label: { + Label("アップデート可能", systemImage: "arrow.down.circle.fill") + } + .labelStyle(.titleAndIcon) + .tint(NeomorphicTheme.accent) + .help("新しいバージョン \(release.tag_name) の詳細を表示") + .accessibilityIdentifier("updateAvailableButton") + } + } +} diff --git a/AllServerForMac/Features/Updates/AppUpdater.swift b/AllServerForMac/Features/Updates/AppUpdater.swift new file mode 100644 index 0000000..9d74108 --- /dev/null +++ b/AllServerForMac/Features/Updates/AppUpdater.swift @@ -0,0 +1,270 @@ +import SwiftUI +import AppKit +import Combine +import Foundation + +/// SemVer precedence; shortened versions such as 1.2 are padded with zeroes. +struct UpdateVersion: Comparable { + let core: [Int] + let prerelease: [String] + let build: Int? + + init?(_ text: String) { + let raw = text.hasPrefix("v") ? String(text.dropFirst()) : text + let metadata = raw.split(separator: "+", omittingEmptySubsequences: false) + guard metadata.count <= 2 else { return nil } + let parts = metadata[0].split(separator: "-", maxSplits: 1, omittingEmptySubsequences: false) + let numbers = parts[0].split(separator: ".", omittingEmptySubsequences: false) + guard (1...3).contains(numbers.count), numbers.allSatisfy({ Self.validNumber(String($0)) }) else { return nil } + core = numbers.map { Int($0)! } + Array(repeating: 0, count: 3 - numbers.count) + let pre = parts.count == 2 ? parts[1].split(separator: ".", omittingEmptySubsequences: false).map(String.init) : [] + guard pre.allSatisfy({ Self.validIdentifier($0) && (!Self.isNumeric($0) || Self.validNumber($0)) }) else { return nil } + prerelease = pre + if metadata.count == 2 { + let identifiers = metadata[1].split(separator: ".", omittingEmptySubsequences: false).map(String.init) + guard identifiers.allSatisfy(Self.validIdentifier) else { return nil } + build = Int(metadata[1]) + } else { + build = nil + } + } + + private static func isNumeric(_ s: String) -> Bool { !s.isEmpty && s.utf8.allSatisfy { (48...57).contains($0) } } + private static func validNumber(_ s: String) -> Bool { + isNumeric(s) && (s.count == 1 || s.first != "0") && Int(s) != nil + } + private static func validIdentifier(_ s: String) -> Bool { + !s.isEmpty && s.utf8.allSatisfy { (48...57).contains($0) || (65...90).contains($0) || (97...122).contains($0) || $0 == 45 } + } + static func == (lhs: Self, rhs: Self) -> Bool { lhs.core == rhs.core && lhs.prerelease == rhs.prerelease } + static func < (lhs: Self, rhs: Self) -> Bool { + if lhs.core != rhs.core { return lhs.core.lexicographicallyPrecedes(rhs.core) } + if lhs.prerelease.isEmpty { return false } + if rhs.prerelease.isEmpty { return true } + for (a, b) in zip(lhs.prerelease, rhs.prerelease) where a != b { + if Self.isNumeric(a), Self.isNumeric(b) { + return a.count == b.count ? a < b : a.count < b.count + } + if Self.isNumeric(a) != Self.isNumeric(b) { return Self.isNumeric(a) } + return a < b + } + return lhs.prerelease.count < rhs.prerelease.count + } + + func isNewer(than current: Self, currentBuild: Int) -> Bool { + self > current || (self == current && build.map { $0 > currentBuild } == true) + } +} + +struct AppRelease: Decodable, Equatable { + struct Asset: Decodable, Equatable { + let name: String + let browser_download_url: URL + } + let tag_name: String + let html_url: URL + let body: String? + let draft: Bool + let prerelease: Bool + let assets: [Asset] + + var downloadURL: URL? { + assets.first { $0.name == "AllServerForMac.app.zip" && Self.trustedURL($0.browser_download_url, download: true) }?.browser_download_url + } + static func trustedURL(_ url: URL, download: Bool = false) -> Bool { + url.scheme == "https" && url.host == "github.com" && url.user == nil && url.password == nil + && url.port == nil && url.path.hasPrefix("/HR0101/AllServerForMac/releases/" + (download ? "download/" : "")) + } +} + +enum AppUpdateError: LocalizedError { + case response, rateLimited, http(Int), invalidRelease + var errorDescription: String? { + switch self { + case .response: return "更新サーバーから有効な応答を取得できませんでした。" + case .rateLimited: return "GitHubのアクセス制限に達しました。しばらく待ってから再試行してください。" + case .http(let code): return "更新サーバーでエラーが発生しました(HTTP \(code))。" + case .invalidRelease: return "リリース情報の形式が正しくありません。" + } + } +} + +@MainActor +final class AppUpdater: ObservableObject { + static let shared = AppUpdater() + static let automaticKey = "updates.checkAtLaunch" + static let skippedKey = "updates.skippedVersion" + static let lastCheckKey = "updates.lastCheck" + static let latestURL = URL(string: "https://api.github.com/repos/HR0101/AllServerForMac/releases/latest")! + + enum State: Equatable { + case idle, checking, available(AppRelease), upToDate, noRelease + case downloading(AppRelease), downloaded(URL), failed(String) + } + @Published private(set) var state: State = .idle + @Published private(set) var progress: Double? + @Published private(set) var lastCheck: Date? + @Published var automaticallyChecks: Bool { + didSet { defaults.set(automaticallyChecks, forKey: Self.automaticKey) } + } + let currentVersion: String + let currentBuild: String + private let defaults: UserDefaults + private let session: URLSession + private var operation: Task? + private var downloadID: UUID? + private var window: NSWindow? + private var manualRequested = false + private let presentsWindows: Bool + + init(defaults: UserDefaults = .standard, session: URLSession = .shared, + version: String? = nil, build: String? = nil, presentsWindows: Bool = true) { + self.defaults = defaults + self.session = session + self.presentsWindows = presentsWindows + currentVersion = version ?? Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "0.0.0" + currentBuild = build ?? Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "0" + automaticallyChecks = defaults.object(forKey: Self.automaticKey) as? Bool ?? true + lastCheck = defaults.object(forKey: Self.lastCheckKey) as? Date + } + + var isBusy: Bool { + switch state { case .checking, .downloading: return true; default: return false } + } + + func check(manual: Bool) { + if manual { + manualRequested = true + showWindow() + } + guard !isBusy else { return } + manualRequested = manual + state = .checking + operation = Task { + do { + var request = URLRequest(url: Self.latestURL, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 20) + request.setValue("application/vnd.github+json", forHTTPHeaderField: "Accept") + request.setValue("AllServerForMac", forHTTPHeaderField: "User-Agent") + let (data, response) = try await session.data(for: request) + try Task.checkCancellation() + guard let http = response as? HTTPURLResponse else { throw AppUpdateError.response } + if http.statusCode == 404 { + recordCheck() + state = .noRelease + return + } + try Self.validateHTTP(http) + let release: AppRelease + do { release = try JSONDecoder().decode(AppRelease.self, from: data) } + catch { throw AppUpdateError.invalidRelease } + guard !release.draft, !release.prerelease, + AppRelease.trustedURL(release.html_url), + let remote = UpdateVersion(release.tag_name), + let current = UpdateVersion(currentVersion) else { throw AppUpdateError.invalidRelease } + recordCheck() + if remote.isNewer(than: current, currentBuild: Int(currentBuild) ?? 0) { + if !manualRequested && defaults.string(forKey: Self.skippedKey) == release.tag_name { + state = .idle + } else { + state = .available(release) + // Background checks only expose the in-app update button. + // Details are presented when the user requests them. + } + } else { + state = .upToDate + } + } catch { + guard !Task.isCancelled else { return } + state = manualRequested ? .failed(error.localizedDescription) : .idle + } + } + } + + private func recordCheck() { + lastCheck = Date() + defaults.set(lastCheck, forKey: Self.lastCheckKey) + } + + static func validateHTTP(_ http: HTTPURLResponse) throws { + if http.statusCode == 403 || http.statusCode == 429 { throw AppUpdateError.rateLimited } + guard (200...299).contains(http.statusCode) else { throw AppUpdateError.http(http.statusCode) } + } + + func skip(_ release: AppRelease) { + defaults.set(release.tag_name, forKey: Self.skippedKey) + state = .idle + window?.close() + } + + /// Download only: unsigned/ad-hoc releases must never replace the running bundle. + /// This also works from read-only DMGs and leaves server/library jobs untouched. + func download(_ release: AppRelease) { + guard !isBusy, let url = release.downloadURL else { return } + let id = UUID() + downloadID = id + state = .downloading(release) + progress = nil + operation = Task { + do { + let delegate = UpdateDownloadProgress { [weak self] value in + Task { @MainActor in + guard self?.downloadID == id, case .downloading = self?.state else { return } + self?.progress = value + } + } + let (temporary, response) = try await session.download(for: URLRequest(url: url, timeoutInterval: 300), delegate: delegate) + defer { try? FileManager.default.removeItem(at: temporary) } + try Task.checkCancellation() + guard let http = response as? HTTPURLResponse else { throw AppUpdateError.response } + try Self.validateHTTP(http) + let directory = try FileManager.default.url(for: .downloadsDirectory, in: .userDomainMask, appropriateFor: nil, create: true) + let destination = directory.appendingPathComponent("AllServerForMac-\(UUID().uuidString).app.zip") + try FileManager.default.moveItem(at: temporary, to: destination) + downloadID = nil + state = .downloaded(destination) + NSWorkspace.shared.activateFileViewerSelecting([destination]) + } catch { + guard !Task.isCancelled else { return } + downloadID = nil + state = .failed("ダウンロードできませんでした。\(error.localizedDescription) リリースページから手動でダウンロードできます。") + } + } + } + + func cancelDownload() { + guard case .downloading(let release) = state else { return } + operation?.cancel() + downloadID = nil + state = .available(release) + progress = nil + } + + func remindLater() { window?.close() } + + func openReleases() { + NSWorkspace.shared.open(URL(string: "https://github.com/HR0101/AllServerForMac/releases/latest")!) + } + + func showWindow() { + guard presentsWindows else { return } + if window == nil { + let window = NSWindow(contentViewController: NSHostingController(rootView: AppUpdateView(updater: self))) + window.title = "AllServerForMac アップデート" + window.styleMask = [.titled, .closable, .miniaturizable] + window.isReleasedWhenClosed = false + window.center() + self.window = window + } + window?.makeKeyAndOrderFront(nil) + } +} + +private final class UpdateDownloadProgress: NSObject, URLSessionDownloadDelegate, @unchecked Sendable { + nonisolated let report: @Sendable (Double?) -> Void + nonisolated init(report: @escaping @Sendable (Double?) -> Void) { self.report = report } + nonisolated func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {} + nonisolated func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { + report(totalBytesExpectedToWrite > 0 ? min(1, Double(totalBytesWritten) / Double(totalBytesExpectedToWrite)) : nil) + } +} From 3df5d5815090d759179f1a57a5db60ec26ae1148 Mon Sep 17 00:00:00 2001 From: HR0101 Date: Thu, 29 Oct 2026 14:16:43 +0900 Subject: [PATCH 2/5] =?UTF-8?q?feat(updates):=20=E3=83=A1=E3=83=8B?= =?UTF-8?q?=E3=83=A5=E3=83=BC=E3=83=BB=E8=A8=AD=E5=AE=9A=E7=94=BB=E9=9D=A2?= =?UTF-8?q?=E3=83=BB=E3=83=84=E3=83=BC=E3=83=AB=E3=83=90=E3=83=BC=E3=81=B8?= =?UTF-8?q?=E3=82=A2=E3=83=83=E3=83=97=E3=83=87=E3=83=BC=E3=83=88=E7=A2=BA?= =?UTF-8?q?=E8=AA=8D=E5=B0=8E=E7=B7=9A=E3=82=92=E7=B5=B1=E5=90=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AllServerForMac/App/AllServerForMacApp.swift | 10 ++++++++++ AllServerForMac/App/Views/ContentView.swift | 3 +++ .../Features/Settings/Views/PreferencesView.swift | 4 ++++ 3 files changed, 17 insertions(+) diff --git a/AllServerForMac/App/AllServerForMacApp.swift b/AllServerForMac/App/AllServerForMacApp.swift index cac9dbd..26cbf4e 100644 --- a/AllServerForMac/App/AllServerForMacApp.swift +++ b/AllServerForMac/App/AllServerForMacApp.swift @@ -74,8 +74,13 @@ extension FocusedValues { struct AppMenuCommands: Commands { @FocusedValue(\.appMenuContext) private var context + @ObservedObject private var updater = AppUpdater.shared var body: some Commands { + CommandGroup(after: .appInfo) { + Button("アップデートを確認…") { updater.check(manual: true) } + } + CommandGroup(after: .toolbar) { Button("全画面表示/解除") { toggleFullScreen() @@ -203,6 +208,11 @@ struct AppMenuCommands: Commands { /// そこへ AppKit のビューを割り込ませると矢印キーでの項目移動が壊れる。 /// チェーンの終点であるアプリのデリゲートで受ければ、フォーカスに一切触らずに済む。 final class AppDelegate: NSObject, NSApplicationDelegate { + func applicationDidFinishLaunching(_ notification: Notification) { + guard NSClassFromString("XCTestCase") == nil, AppUpdater.shared.automaticallyChecks else { return } + AppUpdater.shared.check(manual: false) + } + override func acceptsPreviewPanelControl(_ panel: QLPreviewPanel!) -> Bool { true } diff --git a/AllServerForMac/App/Views/ContentView.swift b/AllServerForMac/App/Views/ContentView.swift index b5c4300..dc642c9 100644 --- a/AllServerForMac/App/Views/ContentView.swift +++ b/AllServerForMac/App/Views/ContentView.swift @@ -364,6 +364,9 @@ struct ContentView: View { } } .toolbar { + ToolbarItem(placement: .primaryAction) { + AppUpdateAvailabilityButton() + } ToolbarItemGroup(placement: .navigation) { Button { withAnimation(.easeInOut(duration: 0.2)) { isSidebarVisible.toggle() } diff --git a/AllServerForMac/Features/Settings/Views/PreferencesView.swift b/AllServerForMac/Features/Settings/Views/PreferencesView.swift index 3812304..0b7237e 100644 --- a/AllServerForMac/Features/Settings/Views/PreferencesView.swift +++ b/AllServerForMac/Features/Settings/Views/PreferencesView.swift @@ -20,6 +20,7 @@ struct PreferencesView: View { case server = "保護" case performance = "性能" case export = "書き出し" + case updates = "更新" case shortcuts = "ショートカット" var id: String { rawValue } } @@ -200,6 +201,9 @@ struct PreferencesView: View { } .id(SettingsSection.export) + UpdateSettingsSection() + .id(SettingsSection.updates) + MediaShortcutSettingsSection() .id(SettingsSection.shortcuts) } From 9cb620154edc064b74238b5d03a26a77c84ca95d Mon Sep 17 00:00:00 2001 From: HR0101 Date: Thu, 29 Oct 2026 14:16:43 +0900 Subject: [PATCH 3/5] =?UTF-8?q?test(updates):=20=E3=82=BB=E3=83=9E?= =?UTF-8?q?=E3=83=B3=E3=83=86=E3=82=A3=E3=83=83=E3=82=AF=E3=83=90=E3=83=BC?= =?UTF-8?q?=E3=82=B8=E3=83=A7=E3=83=B3=E6=AF=94=E8=BC=83=E3=81=A8=E3=82=A2?= =?UTF-8?q?=E3=83=83=E3=83=97=E3=83=87=E3=83=BC=E3=83=88=E7=8A=B6=E6=85=8B?= =?UTF-8?q?=E9=81=B7=E7=A7=BB=E3=81=AE=E5=8D=98=E4=BD=93=E3=83=86=E3=82=B9?= =?UTF-8?q?=E3=83=88=E3=82=92=E8=BF=BD=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AllServerForMacTests/AppUpdaterTests.swift | 150 +++++++++++++++++++++ 1 file changed, 150 insertions(+) create mode 100644 AllServerForMacTests/AppUpdaterTests.swift diff --git a/AllServerForMacTests/AppUpdaterTests.swift b/AllServerForMacTests/AppUpdaterTests.swift new file mode 100644 index 0000000..2b9108d --- /dev/null +++ b/AllServerForMacTests/AppUpdaterTests.swift @@ -0,0 +1,150 @@ +import Foundation +import Testing +@testable import AllServerForMac + +@Suite(.serialized) +@MainActor +struct AppUpdaterTests { + @Test func semanticVersions() throws { + let ordered = ["1.0.0-alpha", "1.0.0-alpha.1", "1.0.0-alpha.beta", "1.0.0-beta", "1.0.0-beta.2", "1.0.0-beta.11", "1.0.0-rc.1", "1.0.0", "1.0.1", "1.2", "1.10"] + let versions = try ordered.map { try #require(UpdateVersion($0)) } + for (a, b) in zip(versions, versions.dropFirst()) { #expect(a < b) } + #expect(UpdateVersion("v1.2.0") == UpdateVersion("1.2")) + #expect(UpdateVersion("1.0.0+build.2") == UpdateVersion("1.0.0+build.1")) + for invalid in ["", "1..2", "1.2.3.4", "1.0.0-", "01.2.3", "1.0.0-01", "1.0.0+", "garbage"] { + #expect(UpdateVersion(invalid) == nil) + } + let current = try #require(UpdateVersion("1.0.0")) + #expect(try #require(UpdateVersion("1.0.0+2")).isNewer(than: current, currentBuild: 1)) + #expect(!current.isNewer(than: current, currentBuild: 1)) + #expect(!(try #require(UpdateVersion("0.9.0+99"))).isNewer(than: current, currentBuild: 1)) + } + + @Test func checksAndSkipPersistence() async throws { + let (updater, defaults, session, suite) = try fixture() + defer { defaults.removePersistentDomain(forName: suite); session.invalidateAndCancel() } + UpdateMockProtocol.response = (200, releaseJSON(), nil) + // Automatic detection stops at availability; download requires user action. + updater.check(manual: false) + #expect(updater.state == .checking) + await finish(updater) + guard case .available(let release) = updater.state else { Issue.record("Expected update"); return } + #expect(release.downloadURL != nil) + #expect(updater.lastCheck != nil) + updater.skip(release) + #expect(updater.state == .idle) + updater.check(manual: false) + await finish(updater) + #expect(updater.state == .idle) + updater.check(manual: true) + await finish(updater) + #expect(updater.state == .available(release)) + updater.automaticallyChecks = false + let restored = AppUpdater(defaults: defaults, session: session, version: "1.0", build: "1", presentsWindows: false) + #expect(!restored.automaticallyChecks) + #expect(restored.lastCheck != nil) + UpdateMockProtocol.response = (200, releaseJSON(tag: "v3.0.0"), nil) + updater.check(manual: false) + await finish(updater) + guard case .available(let newer) = updater.state else { Issue.record("New version should not be skipped"); return } + #expect(newer.tag_name == "v3.0.0") + } + + @Test func sameAndOlderAreUpToDate() async throws { + let (updater, defaults, session, suite) = try fixture() + defer { defaults.removePersistentDomain(forName: suite); session.invalidateAndCancel() } + for tag in ["v1.0.0", "v0.9.0"] { + UpdateMockProtocol.response = (200, releaseJSON(tag: tag), nil) + updater.check(manual: true) + await finish(updater) + #expect(updater.state == .upToDate) + } + UpdateMockProtocol.response = (404, Data(), nil) + updater.check(manual: true) + await finish(updater) + #expect(updater.state == .noRelease) + } + + @Test func malformedAndNetworkErrors() async throws { + let (updater, defaults, session, suite) = try fixture() + defer { defaults.removePersistentDomain(forName: suite); session.invalidateAndCancel() } + for response: (Int, Data, Error?) in [ + (200, Data("not JSON".utf8), nil), + (200, releaseJSON(tag: "nonsense"), nil), + (403, Data(), nil), (429, Data(), nil), (500, Data(), nil), + (200, Data(), URLError(.notConnectedToInternet)), + (200, Data(), URLError(.timedOut)) + ] { + UpdateMockProtocol.response = response + updater.check(manual: true) + await finish(updater) + guard case .failed = updater.state else { Issue.record("Expected visible manual error"); continue } + #expect(updater.lastCheck == nil) + updater.check(manual: false) + await finish(updater) + #expect(updater.state == .idle) + } + } + + @Test func downloadCancellationRestoresOffer() async throws { + let (updater, defaults, session, suite) = try fixture() + defer { defaults.removePersistentDomain(forName: suite); session.invalidateAndCancel() } + let release = try JSONDecoder().decode(AppRelease.self, from: releaseJSON()) + updater.download(release) + #expect(updater.state == .downloading(release)) + updater.check(manual: true) + #expect(updater.state == .downloading(release)) + updater.cancelDownload() + #expect(updater.state == .available(release)) + try await Task.sleep(for: .milliseconds(50)) + #expect(updater.state == .available(release)) + #expect(updater.progress == nil) + } + + @Test func onlyRepositoryAssetsAreTrusted() throws { + #expect(!AppRelease.trustedURL(URL(string: "http://github.com/HR0101/AllServerForMac/releases/tag/v2")!)) + #expect(!AppRelease.trustedURL(URL(string: "https://evil.example/HR0101/AllServerForMac/releases/tag/v2")!)) + #expect(!AppRelease.trustedURL(URL(string: "https://github.com/HR0101/Other/releases/tag/v2")!)) + #expect(AppRelease.trustedURL(URL(string: "https://github.com/HR0101/AllServerForMac/releases/download/v2/AllServerForMac.app.zip")!, download: true)) + } + + private func fixture() throws -> (AppUpdater, UserDefaults, URLSession, String) { + let suite = "UpdaterTests-\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suite)) + let configuration = URLSessionConfiguration.ephemeral + configuration.protocolClasses = [UpdateMockProtocol.self] + let session = URLSession(configuration: configuration) + return (AppUpdater(defaults: defaults, session: session, version: "1.0", build: "1", presentsWindows: false), defaults, session, suite) + } + + private func finish(_ updater: AppUpdater) async { + for _ in 0..<500 { + if !updater.isBusy { return } + try? await Task.sleep(for: .milliseconds(10)) + } + Issue.record("Update check timed out") + } + + private func releaseJSON(tag: String = "v2.0.0") -> Data { + Data(""" + {"tag_name":"\(tag)","html_url":"https://github.com/HR0101/AllServerForMac/releases/tag/\(tag)", + "body":"Release notes","draft":false,"prerelease":false, + "assets":[{"name":"AllServerForMac.app.zip","browser_download_url":"https://github.com/HR0101/AllServerForMac/releases/download/\(tag)/AllServerForMac.app.zip"}]} + """.utf8) + } +} + +private final class UpdateMockProtocol: URLProtocol, @unchecked Sendable { + nonisolated(unsafe) static var response: (Int, Data, Error?) = (200, Data(), nil) + override class func canInit(with request: URLRequest) -> Bool { true } + override class func canonicalRequest(for request: URLRequest) -> URLRequest { request } + override func startLoading() { + let (status, data, error) = Self.response + if let error { client?.urlProtocol(self, didFailWithError: error); return } + let response = HTTPURLResponse(url: request.url!, statusCode: status, httpVersion: nil, headerFields: nil)! + client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) + client?.urlProtocol(self, didLoad: data) + client?.urlProtocolDidFinishLoading(self) + } + override func stopLoading() {} +} From d2bbb591fa081245b7404a0849d58a931de98832 Mon Sep 17 00:00:00 2001 From: HR0101 Date: Thu, 29 Oct 2026 14:16:43 +0900 Subject: [PATCH 4/5] =?UTF-8?q?ci(release):=20=E3=82=BF=E3=82=B0push?= =?UTF-8?q?=E9=80=A3=E5=8B=95=E3=81=AEUniversal=20Release=E3=83=93?= =?UTF-8?q?=E3=83=AB=E3=83=89=E3=83=BBGitHub=20Releases=E5=85=AC=E9=96=8B?= =?UTF-8?q?=E3=83=AF=E3=83=BC=E3=82=AF=E3=83=95=E3=83=AD=E3=83=BC=E3=82=92?= =?UTF-8?q?=E8=BF=BD=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/release.yml | 61 +++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 .github/workflows/release.yml diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..64fb01a --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,61 @@ +name: Release + +on: + push: + tags: + - 'v*.*.*' + +permissions: + contents: write + +concurrency: + group: release-${{ github.ref }} + cancel-in-progress: false + +jobs: + release: + runs-on: macos-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v7 + - name: Read version from tag + env: + RELEASE_TAG: ${{ github.ref_name }} + run: | + python3 - <<'PY' + import os, re + tag = os.environ['RELEASE_TAG'] + match = re.fullmatch(r'v((?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*))(?:\+([1-9][0-9]*))?', tag) + if not match: + raise SystemExit('Use a stable vMAJOR.MINOR.PATCH tag, optionally +BUILD (positive integer)') + with open(os.environ['GITHUB_ENV'], 'a') as output: + output.write(f'APP_VERSION={match[1]}\nAPP_BUILD={match[2] or "1"}\n') + PY + - name: Test + run: >- + xcodebuild test -project AllServerForMac.xcodeproj -scheme AllServerForMac + -destination 'platform=macOS' -only-testing:AllServerForMacTests + -derivedDataPath "$RUNNER_TEMP/AllServerForMacDerivedData" + CODE_SIGNING_ALLOWED=NO + - name: Build universal release + run: >- + xcodebuild build -project AllServerForMac.xcodeproj -scheme AllServerForMac + -configuration Release -destination 'generic/platform=macOS' + -derivedDataPath "$RUNNER_TEMP/AllServerForMacRelease" + ARCHS='arm64 x86_64' ONLY_ACTIVE_ARCH=NO + MARKETING_VERSION="$APP_VERSION" CURRENT_PROJECT_VERSION="$APP_BUILD" + CODE_SIGNING_ALLOWED=NO + - name: Package app + run: | + codesign --force --deep --sign - "$RUNNER_TEMP/AllServerForMacRelease/Build/Products/Release/AllServerForMac.app" + ditto -c -k --sequesterRsrc --keepParent "$RUNNER_TEMP/AllServerForMacRelease/Build/Products/Release/AllServerForMac.app" AllServerForMac.app.zip + - name: Publish release + env: + GH_TOKEN: ${{ github.token }} + RELEASE_TAG: ${{ github.ref_name }} + run: | + if ! gh release view "$RELEASE_TAG" >/dev/null 2>&1; then + gh release create "$RELEASE_TAG" --verify-tag --generate-notes --draft + fi + gh release upload "$RELEASE_TAG" AllServerForMac.app.zip --clobber + gh release edit "$RELEASE_TAG" --draft=false --latest From 1630b8b871d63589256a85ca0f55c65c67f766b5 Mon Sep 17 00:00:00 2001 From: HR0101 Date: Thu, 29 Oct 2026 14:16:43 +0900 Subject: [PATCH 5/5] =?UTF-8?q?docs(updates):=20=E3=82=A2=E3=83=83?= =?UTF-8?q?=E3=83=97=E3=83=87=E3=83=BC=E3=83=88=E6=A9=9F=E8=83=BD=E3=81=AE?= =?UTF-8?q?=E4=BB=95=E6=A7=98=E3=81=A8=E3=83=AA=E3=83=AA=E3=83=BC=E3=82=B9?= =?UTF-8?q?=E9=85=8D=E4=BF=A1=E3=83=AB=E3=83=BC=E3=83=AB=E3=82=92=E8=BF=BD?= =?UTF-8?q?=E8=A8=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 12 ++++++++++ RELEASING.md | 65 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+) create mode 100644 RELEASING.md diff --git a/README.md b/README.md index 626815a..c3bcffa 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,18 @@ > スケジュール起動を使う場合は、ビルドしたアプリを `/Applications` など**固定の場所**へ配置してから設定画面で「適用」してください(plist にアプリのパスを書き込むため)。 +## アップデート + +配信担当者向けの手順・タグとバージョン番号のルールは [アップデート配信ルール](RELEASING.md) を参照してください。 + +アプリケーションメニューの「アップデートを確認…」または詳細設定の「更新」から、GitHub Releasesの最新公開版を確認できます。起動時の自動確認は同じ設定画面で切り替えられます。新しいバージョンを検知すると、メイン画面のツールバーと詳細設定に「アップデート可能」ボタンを表示します。自動確認では案内ウィンドウを開かず、ボタンを押すとリリースノートとダウンロード操作を表示します。ダウンロードはユーザーの操作で開始します。自動確認の通信失敗は通知せず、手動確認ではエラーを表示します。最終確認日時は正常に確認できた場合だけ更新されます。 + +更新案内には現在と新しいバージョン、リリースノートを表示します。「このバージョンをスキップ」は自動通知だけを抑制し、手動確認では再表示できます。「更新をダウンロード」でZIPをダウンロードフォルダに保存します。進捗表示とキャンセルに対応し、アセットがない場合や保存に失敗した場合はリリースページから取得できます。 + +配信にはIssue #39の方式A(GitHub Releases API)を採用し、適用は手動で行います。サーバーを停止し、インポート・解析・書き出しが完了してから通常の終了操作を行い、ZIPを展開して既存のアプリを差し替え、起動してください。自動終了・再起動・実行中のアプリの置換は行いません。読み取り専用DMGからの起動時も同じ手順で更新できます。ライブラリはアプリ外の既存の保存先を引き続き使用します。 + +リリース担当者は `v1.2.3` の形式でタグをpushすると、GitHub Actionsがテスト、arm64/x86_64のReleaseビルド、アドホック署名、ZIP添付、リリース公開を実行します。Developer ID署名・公証は含みません。タグのバージョンはアプリの `CFBundleShortVersionString` に反映されます。同一バージョンのビルド更新は `v1.2.3+2` のように正の整数を付けます(省略時のビルド番号は1)。比較はSemVer準拠で、`1.2` と `1.2.0` は同一、数値のビルド指定がある場合のみ同一バージョンのビルド番号も比較します。安定版のみを配信します。 + ## チャンネル・気分ミックス・時間指定・場面ストック 一覧の「お楽しみ再生」メニューから利用します. diff --git a/RELEASING.md b/RELEASING.md new file mode 100644 index 0000000..cf05766 --- /dev/null +++ b/RELEASING.md @@ -0,0 +1,65 @@ +# アップデート配信ルール + +## 配信の仕組み + +配信元は `HR0101/AllServerForMac` の GitHub Releases です。コードを `main` にpushするだけでは、アップデートは配信されません。新しいバージョンのタグをpushすると、[リリースワークフロー](.github/workflows/release.yml)がテスト・ビルド・ZIP添付・リリース公開を行います。 + +アプリ側の自動処理は **更新の検知まで** です。更新を検知すると、メイン画面のツールバーと詳細設定に「アップデート可能」ボタンを表示します。ボタンを押すと更新内容とダウンロード操作を表示します。 + +## バージョン番号 + +通常は、現在の公開版より大きい `vMAJOR.MINOR.PATCH` 形式のタグを使用します。 + +| 用途 | 例 | アプリのバージョン | ビルド番号 | +| --- | --- | --- | --- | +| 通常の更新 | `v1.0.1` | `1.0.1` | `1` | +| 機能追加 | `v1.1.0` | `1.1.0` | `1` | +| 同じバージョンのビルド更新 | `v1.1.0+2` | `1.1.0` | `2` | + +- 各数値に不要な先頭ゼロを付けません。`v01.0.1` は使用できません。 +- `+BUILD` は正の整数です。省略するとビルド番号は `1` になります。 +- バージョン番号が同じ場合、タグに数値の `+BUILD` があるときだけ、インストール済みのビルド番号と比較します。 +- `1.2` と `1.2.0` は同じバージョンとして比較します。 +- 現在のワークフローは安定版専用です。`v1.1.0-beta.1` などのプレリリースタグは受け付けません。 +- 公開済みタグは使い回さず、修正版には新しいバージョンまたはビルド番号を付けます。 + +## 配信手順 + +1. 配信する変更と `.github/workflows/release.yml` をコミットし、GitHubの `main` に反映します。初回はアップデート検知機能のコードも含めます。 +2. リリース対象のコミットでテストが成功していることを確認します。 +3. 対象のコミットに新しいタグを付けてpushします。以下は `v1.0.1` を配信する例です。番号は実際の次のバージョンに置き換えてください。 + + ```sh + git switch main + git pull --ff-only origin main + git status --short + git tag -a v1.0.1 -m "Release v1.0.1" + git push origin v1.0.1 + ``` + + タグは現在のコミットを指します。タグを付ける前に、配信したい変更がコミット済みであることを確認してください。 + +4. GitHub Actionsの `Release` が成功するまで待ちます。テスト、arm64/x86_64のReleaseビルド、アドホック署名、ZIP生成を順に実行します。タグの値がアプリのバージョン・ビルド番号に反映されます。 +5. GitHub Releasesで、該当タグのリリースが公開され、`Latest` になっていることと、`AllServerForMac.app.zip` が添付されていることを確認します。リリースノートは自動生成されるので、必要に応じて変更点を追記します。 +6. 以前のバージョンのアプリで手動の「アップデートを確認…」を実行し、「アップデート可能」ボタン、バージョン番号、リリースノートを確認します。 + +ワークフローが失敗した場合は、GitHub Actionsのログで原因を確認してください。処理が途中で止まると、リリースがドラフトのまま残る場合があります。 + +## アプリ側でボタンが出る条件 + +- アップデート検知機能を含むアプリを使用していること。この機能が入っていない旧アプリへの初回導入は手動で行います。 +- GitHub Releasesの最新公開版が、使用中のアプリより新しいこと。同じ、または古いバージョンでは表示しません。 +- 更新確認が成功すること。起動時の自動確認をオンにしていれば、次の起動時に確認します。起動中の定期確認は行いません。すぐ確認する場合は、アプリメニューか詳細設定から手動確認します。 +- 自動確認の場合、そのタグを「このバージョンをスキップ」に指定していないこと。スキップ済みでも、手動確認なら再表示できます。 + +アプリは `/repos/HR0101/AllServerForMac/releases/latest` を参照します。過去の全リリースから更新候補を探す方式ではないため、配信対象の最新版を `Latest` として公開してください。ドラフト・プレリリースは更新対象外です。 + +自動確認の通信失敗は表示せず、手動確認ではエラーを表示します。 + +## ダウンロードと適用 + +「アップデート可能」を押し、更新案内の「更新をダウンロード」を押すと、ZIPをダウンロードフォルダに保存します。アセット名は **`AllServerForMac.app.zip`** に統一してください。このアセットがない場合は、リリースページを開く導線を使用します。 + +自動ダウンロード・自動終了・自動再起動・アプリの自動置換は行いません。利用者がサーバーを停止し、インポート・解析・書き出しの完了を確認してから通常の終了操作を行い、ZIPを展開して既存のアプリを差し替え、起動します。ライブラリは既存の保存先を引き続き使用します。 + +現在の配信物はアドホック署名です。Developer ID署名・Appleによる公証は、現在のワークフローには含まれません。