diff --git a/ArkServer/Features/Library/ViewModels/LibraryViewModel.swift b/ArkServer/Features/Library/ViewModels/LibraryViewModel.swift index 33e8cb0..b660b78 100644 --- a/ArkServer/Features/Library/ViewModels/LibraryViewModel.swift +++ b/ArkServer/Features/Library/ViewModels/LibraryViewModel.swift @@ -293,7 +293,7 @@ class LibraryViewModel: ObservableObject { /// 排他ロックを取得する。取得したファイル記述子は意図的に開いたままにし、 /// プロセス終了(クラッシュ含む)でOSが自動解放するのに任せる。 nonisolated static func acquireInstanceLock(at url: URL) -> Bool { - let fd = open(url.path, O_CREAT | O_RDWR, 0o644) + let fd = open(url.path, O_CREAT | O_RDWR | O_CLOEXEC, 0o644) guard fd != -1 else { return true } // ロックファイル自体を作れない環境では起動を妨げない if flock(fd, LOCK_EX | LOCK_NB) != 0 { close(fd) diff --git a/ArkServer/Features/Updates/AppUpdateView.swift b/ArkServer/Features/Updates/AppUpdateView.swift index a031ec7..ca4b91a 100644 --- a/ArkServer/Features/Updates/AppUpdateView.swift +++ b/ArkServer/Features/Updates/AppUpdateView.swift @@ -1,3 +1,4 @@ +import AppKit import SwiftUI struct AppUpdateView: View { @@ -5,60 +6,479 @@ struct AppUpdateView: View { var body: some View { VStack(alignment: .leading, spacing: 16) { - Text("ソフトウェアアップデート").font(.appTitle) - Text("現在のバージョン: \(updater.currentVersion)(ビルド \(updater.currentBuild))") - .foregroundStyle(.secondary) + SheetHeader( + icon: "arrow.down.circle", + title: "ソフトウェアアップデート", + subtitle: "現在のバージョン: \(updater.currentVersion)(ビルド \(updater.currentBuild))" + ) + + Divider().overlay(NeomorphicTheme.separator) + switch updater.state { case .idle: - Text("最新バージョンを確認できます。") - Button("アップデートを確認") { updater.check(manual: true) } + statusCard( + icon: "arrow.clockwise.circle", + iconColor: NeomorphicTheme.muted, + title: "最新バージョンを確認できます", + detail: "GitHub Releases から公開済みの最新バージョンを確認します。" + ) { + HStack(spacing: 10) { + Spacer() + Button("アップデートを確認") { updater.check(manual: true) } + .buttonStyle(UpdateAccentButtonStyle()) + .keyboardShortcut(.defaultAction) + } + } + case .checking: - ProgressView("アップデートを確認中…") + statusCard( + icon: nil, + iconColor: NeomorphicTheme.accent, + title: "アップデートを確認中…", + detail: "最新リリースの情報を取得しています。" + ) { + EmptyView() + } + 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) } + availableView(for: release) + + case .upToDate: + statusCard( + icon: "checkmark.circle.fill", + iconColor: NeomorphicTheme.online, + title: "現在のバージョンは最新です", + detail: "お使いの Ark Server(\(updater.currentVersion))は最新バージョンです。" + ) { + HStack(spacing: 10) { + Spacer() + Button("再確認") { updater.check(manual: true) } + .buttonStyle(AppActionButtonStyle()) + Button("閉じる") { updater.remindLater() } + .buttonStyle(UpdateAccentButtonStyle()) + .keyboardShortcut(.defaultAction) + } + } + + case .noRelease: + statusCard( + icon: "shippingbox", + iconColor: NeomorphicTheme.muted, + title: "公開されたリリースはまだありません", + detail: "新しいリリースが公開されると、ここから更新できます。" + ) { + HStack(spacing: 10) { + Spacer() + Button("閉じる") { updater.remindLater() } + .buttonStyle(AppActionButtonStyle()) .keyboardShortcut(.defaultAction) } - Button("リリースページを開く") { updater.openReleases() } } + + case .downloading(let release): + VStack(alignment: .leading, spacing: 14) { + HStack(spacing: 10) { + ProgressView() + .controlSize(.small) + Text("\(release.tag_name) をダウンロードしています…") + .font(.appHeadline) + .foregroundStyle(NeomorphicTheme.ink) + Spacer() + if let progress = updater.progress { + Text("\(Int((progress * 100).rounded()))%") + .font(.appMonoCaption) + .foregroundStyle(NeomorphicTheme.muted) + } + } + if let progress = updater.progress { + ProgressView(value: progress) + .tint(NeomorphicTheme.accent) + } else { + ProgressView() + .progressViewStyle(.linear) + .tint(NeomorphicTheme.accent) + } + Text("ダウンロード完了後、自動的に検証とインストールへ進みます。") + .font(.appCaption) + .foregroundStyle(NeomorphicTheme.muted) + } + .padding(18) + .frame(maxWidth: .infinity, alignment: .leading) + .background(GlassCardSurface()) + + Spacer(minLength: 0) + HStack { - Button("後で") { updater.remindLater() } - Button("このバージョンをスキップ") { updater.skip(release) } + Spacer() + Button("キャンセル") { updater.cancelDownload() } + .buttonStyle(AppActionButtonStyle()) + .keyboardShortcut(.cancelAction) } - Text("後で更新する場合は、このウィンドウを閉じてください。") - .font(.caption).foregroundStyle(.secondary) - case .upToDate: - Text("現在のバージョンは最新です。") - case .noRelease: - Text("公開されたリリースはまだありません。") - case .downloading: - if let progress = updater.progress { - ProgressView(value: progress) { Text("ダウンロード中…") } - } else { - ProgressView("ダウンロード中…") + + case .installing(let release): + statusCard( + icon: nil, + iconColor: NeomorphicTheme.accent, + title: "\(release.tag_name) をインストールして再起動しています…", + detail: "署名とバンドルを検証し、アプリを置き換えています。完了すると自動的に再起動します。" + ) { + EmptyView() } - Button("キャンセル") { updater.cancelDownload() } + case .downloaded(let url): - Text("ダウンロードしました: \(url.lastPathComponent)") - Text("サーバーを停止し、インポート・解析・書き出しの完了を確認してから通常の終了操作を行ってください。DMGを開き、現在のアプリを差し替えて起動すると更新が完了します。ライブラリの保存場所は変わりません。") + statusCard( + icon: "arrow.down.doc.fill", + iconColor: NeomorphicTheme.accent, + title: "ダウンロードが完了しました", + detail: "保存ファイル: \(url.lastPathComponent)\n「このDMGから今すぐアップデート」を押すと、現在のアプリを自動で置き換えて再起動します(ライブラリの保存場所は変わりません)。" + ) { + HStack(spacing: 10) { + Button("Finderで表示") { + NSWorkspace.shared.activateFileViewerSelecting([url]) + } + .buttonStyle(AppActionButtonStyle()) + Spacer() + Button("このDMGから今すぐアップデート") { + updater.install(dmgURL: url) + } + .buttonStyle(UpdateAccentButtonStyle()) + .keyboardShortcut(.defaultAction) + } + } + case .failed(let message): - Text(message).foregroundStyle(.red) - HStack { - Button("再試行") { updater.check(manual: true) } - Button("リリースページを開く") { updater.openReleases() } + statusCard( + icon: "exclamationmark.triangle.fill", + iconColor: NeomorphicTheme.negative, + title: "アップデートを完了できませんでした", + detail: message + ) { + HStack(spacing: 8) { + Button("リリースページを開く") { updater.openReleases() } + .buttonStyle(AppActionButtonStyle()) + Button("再確認") { updater.check(manual: true) } + .buttonStyle(AppActionButtonStyle()) + Spacer() + if let release = updater.availableRelease, release.downloadURL != nil { + Button("DMGのみ保存") { updater.download(release) } + .buttonStyle(AppActionButtonStyle()) + Button("今すぐアップデートを再試行") { updater.install(release) } + .buttonStyle(UpdateAccentButtonStyle()) + .keyboardShortcut(.defaultAction) + } + } } } } .padding(24) - .frame(width: 620, alignment: .leading) - .frame(minHeight: 200) + .frame(minWidth: 560, idealWidth: 680, maxWidth: .infinity, minHeight: 420, idealHeight: 560, maxHeight: .infinity, alignment: .topLeading) + .appSheet() + .environment(\.colorScheme, NeomorphicTheme.isDarkBase ? .dark : .light) + } + + @ViewBuilder + private func availableView(for release: AppRelease) -> some View { + let notes = FormattedReleaseNotes.parse(release.body) + + // バージョン概要カード + HStack(alignment: .center, spacing: 16) { + VStack(alignment: .leading, spacing: 4) { + Text("新しいバージョンが利用可能です") + .font(.appHeadline) + .foregroundStyle(NeomorphicTheme.ink) + Text("「今すぐアップデート」を押すと、最新版をダウンロードしてアプリを自動で置き換え、再起動します。") + .font(.appCaption) + .foregroundStyle(NeomorphicTheme.muted) + .fixedSize(horizontal: false, vertical: true) + } + Spacer(minLength: 12) + HStack(spacing: 6) { + Text(updater.currentVersion) + .font(.appMonoCaption) + .foregroundStyle(NeomorphicTheme.muted) + Image(systemName: "arrow.right") + .font(.system(size: 10, weight: .semibold)) + .foregroundStyle(NeomorphicTheme.muted) + Text(release.tag_name) + .font(.appMonoBody.weight(.semibold)) + .foregroundStyle(NeomorphicTheme.accent) + .padding(.horizontal, 8) + .padding(.vertical, 3) + .background( + Capsule().fill(NeomorphicTheme.accent.opacity(0.14)) + ) + } + .fixedSize() + } + .padding(14) + .background(GlassCardSurface()) + + // リリースノート見出し行 + HStack(alignment: .firstTextBaseline, spacing: 8) { + Text("更新内容") + .font(.appBodyStrong) + .foregroundStyle(NeomorphicTheme.ink) + if notes.changeCount > 0 { + Text("\(notes.changeCount)件") + .font(.appMicroStrong.monospacedDigit()) + .foregroundStyle(NeomorphicTheme.muted) + .padding(.horizontal, 7) + .padding(.vertical, 2) + .background(Capsule().fill(NeomorphicTheme.control)) + } + Spacer() + if let compareURL = notes.compareURL { + Button { + NSWorkspace.shared.open(compareURL) + } label: { + HStack(spacing: 3) { + Text("変更差分") + Image(systemName: "arrow.up.right") + .font(.system(size: 9, weight: .semibold)) + } + } + .buttonStyle(.quiet) + } + Button { + updater.openReleases() + } label: { + HStack(spacing: 3) { + Text("リリースページ") + Image(systemName: "arrow.up.right") + .font(.system(size: 9, weight: .semibold)) + } + } + .buttonStyle(.quiet) + } + + // 整形済みリリースノート一覧 + ScrollView { + if notes.isEmpty { + Text("リリースノートはありません。") + .font(.appBody) + .foregroundStyle(NeomorphicTheme.muted) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(16) + } else { + VStack(alignment: .leading, spacing: 14) { + ForEach(notes.sections) { section in + VStack(alignment: .leading, spacing: 0) { + if let title = section.title { + Text(title) + .font(.appCaptionStrong) + .foregroundStyle(NeomorphicTheme.muted) + .padding(.horizontal, 16) + .padding(.top, 12) + .padding(.bottom, 6) + } + ForEach(Array(section.items.enumerated()), id: \.element.id) { index, item in + ReleaseNoteRowView(item: item) + if index < section.items.count - 1 { + Divider() + .overlay(NeomorphicTheme.separator) + .padding(.leading, 16) + } + } + } + } + } + .padding(.vertical, 4) + } + } + .frame(maxWidth: .infinity, minHeight: 200, maxHeight: .infinity) + .background(GlassCardSurface()) + .clipShape(RoundedRectangle(cornerRadius: DS.cardCornerRadius, style: .continuous)) + + // 下部アクションバー + HStack(spacing: 8) { + Button("後で") { updater.remindLater() } + .buttonStyle(AppActionButtonStyle()) + .keyboardShortcut(.cancelAction) + Button("このバージョンをスキップ") { updater.skip(release) } + .buttonStyle(AppActionButtonStyle()) + + Spacer(minLength: 12) + + if release.downloadURL != nil { + Button("DMGのみ保存") { updater.download(release) } + .buttonStyle(AppActionButtonStyle()) + Button { + updater.install(release) + } label: { + HStack(spacing: 6) { + Image(systemName: "arrow.triangle.2.circlepath") + .font(.system(size: 11, weight: .semibold)) + Text("今すぐアップデート") + } + } + .buttonStyle(UpdateAccentButtonStyle()) + .keyboardShortcut(.defaultAction) + .accessibilityIdentifier("installUpdateButton") + } else { + Button("リリースページを開く") { updater.openReleases() } + .buttonStyle(UpdateAccentButtonStyle()) + .keyboardShortcut(.defaultAction) + } + } + } + + @ViewBuilder + private func statusCard( + icon: String?, + iconColor: Color, + title: String, + detail: String, + @ViewBuilder actions: () -> Actions + ) -> some View { + VStack(alignment: .leading, spacing: 14) { + HStack(alignment: .top, spacing: 12) { + if let icon { + Image(systemName: icon) + .font(.system(size: 20, weight: .medium)) + .foregroundStyle(iconColor) + .frame(width: 24, height: 24) + } else { + ProgressView() + .controlSize(.small) + .frame(width: 24, height: 24) + } + VStack(alignment: .leading, spacing: 5) { + Text(title) + .font(.appHeadline) + .foregroundStyle(NeomorphicTheme.ink) + Text(detail) + .font(.appBody) + .foregroundStyle(NeomorphicTheme.muted) + .lineSpacing(3) + .fixedSize(horizontal: false, vertical: true) + .textSelection(.enabled) + } + } + } + .padding(18) + .frame(maxWidth: .infinity, alignment: .leading) + .background(GlassCardSurface()) + + Spacer(minLength: 0) + + actions() + } +} + +private struct ReleaseNoteRowView: View { + let item: FormattedReleaseNotes.Item + + var body: some View { + switch item.kind { + case .change(let category): + HStack(alignment: .firstTextBaseline, spacing: 10) { + categoryBadge(for: category) + .frame(width: 48, alignment: .leading) + + Text(Self.inlineMarkdown(item.text)) + .font(.appBody) + .foregroundStyle(category == .internalChange ? NeomorphicTheme.muted : NeomorphicTheme.ink) + .lineSpacing(3) + .frame(maxWidth: .infinity, alignment: .leading) + .fixedSize(horizontal: false, vertical: true) + .textSelection(.enabled) + + if let prNumber = item.pullNumber { + if let prURL = item.pullURL { + Button { + NSWorkspace.shared.open(prURL) + } label: { + Text("#\(prNumber)") + .font(.appMonoMicro) + .foregroundStyle(NeomorphicTheme.muted) + } + .buttonStyle(.plain) + .help("Pull Request #\(prNumber) を開く") + } else { + Text("#\(prNumber)") + .font(.appMonoMicro) + .foregroundStyle(NeomorphicTheme.muted) + } + } + } + .padding(.horizontal, 16) + .padding(.vertical, 10) + + case .paragraph: + Text(Self.inlineMarkdown(item.text)) + .font(.appBody) + .foregroundStyle(NeomorphicTheme.ink) + .lineSpacing(4) + .frame(maxWidth: .infinity, alignment: .leading) + .fixedSize(horizontal: false, vertical: true) + .textSelection(.enabled) + .padding(.horizontal, 16) + .padding(.vertical, 10) + } + } + + @ViewBuilder + private func categoryBadge(for category: FormattedReleaseNotes.Category) -> some View { + if let label = category.label { + let style = badgeColors(for: category) + Text(label) + .font(.appMicroStrong) + .foregroundStyle(style.foreground) + .padding(.horizontal, 6) + .padding(.vertical, 2) + .background( + RoundedRectangle(cornerRadius: 5, style: .continuous) + .fill(style.background) + ) + } else { + Text("•") + .font(.appBodyStrong) + .foregroundStyle(NeomorphicTheme.accent) + .padding(.leading, 6) + } + } + + private func badgeColors(for category: FormattedReleaseNotes.Category) -> (foreground: Color, background: Color) { + switch category { + case .feature: + return (NeomorphicTheme.accent, NeomorphicTheme.accent.opacity(0.15)) + case .fix: + return (NeomorphicTheme.online, NeomorphicTheme.online.opacity(0.15)) + case .improvement: + return (NeomorphicTheme.ink, NeomorphicTheme.controlSelected) + case .docs, .internalChange, .general: + return (NeomorphicTheme.muted, NeomorphicTheme.control) + } + } + + private static func inlineMarkdown(_ text: String) -> AttributedString { + if let attributed = try? AttributedString( + markdown: text, + options: AttributedString.MarkdownParsingOptions(interpretedSyntax: .inlineOnlyPreservingWhitespace) + ) { + return attributed + } + return AttributedString(text) + } +} + +private struct UpdateAccentButtonStyle: ButtonStyle { + @Environment(\.isEnabled) private var isEnabled + @State private var isHovering = false + + func makeBody(configuration: Configuration) -> some View { + configuration.label + .font(.appCaptionStrong) + .foregroundStyle(Color.white) + .padding(.horizontal, 14) + .padding(.vertical, 8) + .background( + RoundedRectangle(cornerRadius: 8, style: .continuous) + .fill(NeomorphicTheme.accent.opacity(isHovering ? 0.88 : 1.0)) + ) + .contentShape(RoundedRectangle(cornerRadius: 8, style: .continuous)) + .opacity(isEnabled ? (configuration.isPressed ? 0.78 : 1) : 0.4) + .onHover { isHovering = $0 } } } @@ -88,6 +508,14 @@ struct UpdateSettingsSection: View { } SettingsRow(title: updater.isBusy ? "アップデートの状況" : "アップデートを確認") { HStack(spacing: 8) { + if case .available(let release) = updater.state, release.downloadURL != nil { + Button("今すぐアップデート") { + updater.showWindow() + updater.install(release) + } + .tint(NeomorphicTheme.accent) + .accessibilityIdentifier("settingsInstallUpdateButton") + } AppUpdateAvailabilityButton() Button(updater.isBusy ? "状況を表示" : "今すぐ確認") { updater.check(manual: true) @@ -113,7 +541,7 @@ struct AppUpdateAvailabilityButton: View { } .labelStyle(.titleAndIcon) .tint(NeomorphicTheme.accent) - .help("新しいバージョン \(release.tag_name) の詳細を表示") + .help("新しいバージョン \(release.tag_name) の詳細と自動アップデートを表示") .accessibilityIdentifier("updateAvailableButton") } } diff --git a/ArkServer/Features/Updates/AppUpdater.swift b/ArkServer/Features/Updates/AppUpdater.swift index 9ca6357..47293a8 100644 --- a/ArkServer/Features/Updates/AppUpdater.swift +++ b/ArkServer/Features/Updates/AppUpdater.swift @@ -1,6 +1,7 @@ import SwiftUI import AppKit import Combine +import Darwin import Foundation /// SemVer precedence; shortened versions such as 1.2 are padded with zeroes. @@ -75,18 +76,541 @@ struct AppRelease: Decodable, Equatable { url.scheme == "https" && url.host == "github.com" && url.user == nil && url.password == nil && url.port == nil && url.path.hasPrefix("/HR0101/ArkServer/releases/" + (download ? "download/" : "")) } + static func trustedRepositoryWebURL(_ url: URL) -> Bool { + url.scheme == "https" && url.host == "github.com" && url.user == nil && url.password == nil + && url.port == nil && url.path.hasPrefix("/HR0101/ArkServer/") + } } -enum AppUpdateError: LocalizedError { - case response, rateLimited, http(Int), invalidRelease +struct FormattedReleaseNotes: Equatable { + enum Category: Int, Comparable, Equatable { + case feature = 0 + case fix = 1 + case improvement = 2 + case general = 3 + case docs = 4 + case internalChange = 5 + + static func < (lhs: Self, rhs: Self) -> Bool { lhs.rawValue < rhs.rawValue } + + var label: String? { + switch self { + case .feature: return "新機能" + case .fix: return "修正" + case .improvement: return "改善" + case .general: return nil + case .docs: return "案内" + case .internalChange: return "基盤" + } + } + } + + struct Item: Equatable, Identifiable { + enum Kind: Equatable { + case change(Category) + case paragraph + } + let id: Int + let kind: Kind + let text: String + let pullNumber: Int? + let pullURL: URL? + } + + struct Section: Equatable, Identifiable { + let id: Int + let title: String? + let items: [Item] + } + + let sections: [Section] + let compareURL: URL? + + var isEmpty: Bool { + sections.allSatisfy { $0.items.isEmpty } + } + + var changeCount: Int { + sections.reduce(0) { total, section in + total + section.items.filter { + if case .change = $0.kind { return true } + return false + }.count + } + } + + static func parse(_ rawBody: String?) -> FormattedReleaseNotes { + guard let rawBody else { return FormattedReleaseNotes(sections: [], compareURL: nil) } + let normalized = rawBody.replacingOccurrences(of: "\r\n", with: "\n") + .replacingOccurrences(of: "\r", with: "\n") + let lines = normalized.components(separatedBy: "\n") + + var sections: [(title: String?, items: [Item])] = [] + var currentTitle: String? = nil + var currentItems: [Item] = [] + var compareURL: URL? = nil + var nextID = 0 + var skippingIgnoredSection = false + + func flushSection() { + guard !currentItems.isEmpty else { return } + let sortedItems = Self.sortChangeItemsIfAppropriate(currentItems) + sections.append((title: currentTitle, items: sortedItems)) + currentItems = [] + } + + for rawLine in lines { + let line = rawLine.trimmingCharacters(in: .whitespaces) + if line.isEmpty { continue } + + // Full Changelog フッターの抽出 + if let extractedCompare = Self.extractFullChangelogURL(from: line) { + compareURL = extractedCompare + continue + } + + // Markdown 見出し (# / ## / ###) + if line.hasPrefix("#") { + let heading = line.drop(while: { $0 == "#" }).trimmingCharacters(in: .whitespaces) + let lower = heading.lowercased() + if lower == "new contributors" { + flushSection() + skippingIgnoredSection = true + currentTitle = nil + continue + } + skippingIgnoredSection = false + if lower == "what's changed" || lower == "whats changed" || lower == "changes" { + flushSection() + currentTitle = nil + continue + } + flushSection() + currentTitle = heading.isEmpty ? nil : heading + continue + } + + if skippingIgnoredSection { continue } + + // 箇条書き (* / - / +) + if let bulletBody = Self.stripBulletPrefix(line) { + if bulletBody.contains("made their first contribution in ") { + continue + } + let (cleanedWithoutPR, prNumber, prURL) = Self.extractTrailingPRReference(from: bulletBody) + let (category, cleanedSummary) = Self.extractConventionalPrefix(from: cleanedWithoutPR) + guard !cleanedSummary.isEmpty else { continue } + currentItems.append( + Item( + id: nextID, + kind: .change(category), + text: cleanedSummary, + pullNumber: prNumber, + pullURL: prURL + ) + ) + nextID += 1 + } else { + currentItems.append( + Item( + id: nextID, + kind: .paragraph, + text: line, + pullNumber: nil, + pullURL: nil + ) + ) + nextID += 1 + } + } + + flushSection() + + let builtSections = sections.enumerated().map { index, entry in + Section(id: index, title: entry.title, items: entry.items) + } + return FormattedReleaseNotes(sections: builtSections, compareURL: compareURL) + } + + private static func sortChangeItemsIfAppropriate(_ items: [Item]) -> [Item] { + // 段落混じりの手動リリースノートは記述順を維持し、箇条書きのみのセクションは種別順(新機能→修正→改善→基盤)に整列する。 + let hasParagraph = items.contains { + if case .paragraph = $0.kind { return true } + return false + } + guard !hasParagraph else { return items } + return items.enumerated().sorted { lhs, rhs in + guard case .change(let leftCat) = lhs.element.kind, + case .change(let rightCat) = rhs.element.kind else { + return lhs.offset < rhs.offset + } + if leftCat != rightCat { return leftCat < rightCat } + return lhs.offset < rhs.offset + }.map(\.element) + } + + private static func stripBulletPrefix(_ line: String) -> String? { + for prefix in ["* ", "- ", "+ ", "・"] { + if line.hasPrefix(prefix) { + return String(line.dropFirst(prefix.count)).trimmingCharacters(in: .whitespaces) + } + } + return nil + } + + private static func extractFullChangelogURL(from line: String) -> URL? { + let stripped = line.replacingOccurrences(of: "*", with: "").trimmingCharacters(in: .whitespaces) + guard stripped.lowercased().hasPrefix("full changelog:") else { return nil } + let urlPart = stripped.dropFirst("full changelog:".count).trimmingCharacters(in: .whitespaces) + guard let url = URL(string: urlPart), AppRelease.trustedRepositoryWebURL(url) else { return nil } + return url + } + + private static func extractTrailingPRReference(from text: String) -> (String, Int?, URL?) { + // 例: "... by @HR0101 in https://github.com/HR0101/ArkServer/pull/60" + // または "... in https://github.com/HR0101/ArkServer/pull/60" + if let range = text.range( + of: #"(?:\s+by\s+@[\w\-]+)?\s+in\s+(https://github\.com/HR0101/ArkServer/pull/(\d+))\s*$"#, + options: .regularExpression + ) { + let suffix = String(text[range]) + let cleaned = String(text[.. (Category, String) { + // 例: "feat(ui/musicvideo): 説明" / "fix: 説明" + guard let matchRange = text.range( + of: #"^([A-Za-z]+)(?:\([^)]*\))?!?\s*[::]\s*"#, + options: .regularExpression + ) else { + return (.general, text) + } + let prefixHeader = String(text[matchRange]) + let remainder = String(text[matchRange.upperBound...]).trimmingCharacters(in: .whitespaces) + guard !remainder.isEmpty else { return (.general, text) } + + let typeToken = prefixHeader + .prefix(while: { $0.isLetter }) + .lowercased() + + let category: Category? = switch typeToken { + case "feat", "add": .feature + case "fix", "bugfix", "hotfix": .fix + case "refactor", "perf", "style", "ui", "improve": .improvement + case "docs", "doc": .docs + case "test", "tests", "ci", "build", "chore", "merge", "revert": .internalChange + default: nil + } + + guard let category else { + return (.general, text) + } + return (category, remainder) + } +} + +enum AppUpdateError: LocalizedError, Equatable { + case response + case rateLimited + case http(Int) + case invalidRelease + case nonWritableLocation(String) + case mountFailed(String) + case appNotFoundInDMG + case copyFailed(String) + case invalidAppBundle + case bundleIdentifierMismatch(expected: String, actual: String?) + case signatureVerificationFailed(String) + case relaunchFailed(String) + var errorDescription: String? { switch self { - case .response: return "更新サーバーから有効な応答を取得できませんでした。" - case .rateLimited: return "GitHubのアクセス制限に達しました。しばらく待ってから再試行してください。" - case .http(let code): return "更新サーバーでエラーが発生しました(HTTP \(code))。" - case .invalidRelease: return "リリース情報の形式が正しくありません。" + case .response: + return "更新サーバーから有効な応答を取得できませんでした。" + case .rateLimited: + return "GitHubのアクセス制限に達しました。しばらく待ってから再試行してください。" + case .http(let code): + return "更新サーバーでエラーが発生しました(HTTP \(code))。" + case .invalidRelease: + return "リリース情報の形式が正しくありません。" + case .nonWritableLocation(let path): + return "現在の場所(\(path))にあるアプリは書き換えできないため、自動アップデートできません。アプリを「アプリケーション」フォルダへ移動してから再試行してください。" + case .mountFailed(let detail): + return "アップデート用ディスクイメージを開けませんでした(\(detail))。" + case .appNotFoundInDMG: + return "ディスクイメージ内にアプリケーションが見つかりませんでした。" + case .copyFailed(let detail): + return "新しいアプリケーションの配置に失敗しました(\(detail))。" + case .invalidAppBundle: + return "ダウンロードしたアプリケーションの形式が正しくありません。" + case .bundleIdentifierMismatch(let expected, let actual): + return "アプリケーションの識別子が一致しません(期待値: \(expected), 実際: \(actual ?? "不明"))。" + case .signatureVerificationFailed(let detail): + return "ダウンロードしたアプリケーションの署名検証に失敗しました(\(detail))。" + case .relaunchFailed(let detail): + return "更新後の再起動処理を開始できませんでした(\(detail))。" + } + } +} + +enum AppUpdateInstaller { + struct CommandOutput: Sendable { + let status: Int32 + let stdout: String + let stderr: String + } + + nonisolated static func runCommand(_ executablePath: String, _ arguments: [String]) throws -> CommandOutput { + let process = Process() + process.executableURL = URL(fileURLWithPath: executablePath) + process.arguments = arguments + process.standardInput = FileHandle.nullDevice + let stdoutPipe = Pipe() + let stderrPipe = Pipe() + process.standardOutput = stdoutPipe + process.standardError = stderrPipe + try process.run() + let stdoutData = stdoutPipe.fileHandleForReading.readDataToEndOfFile() + let stderrData = stderrPipe.fileHandleForReading.readDataToEndOfFile() + process.waitUntilExit() + return CommandOutput( + status: process.terminationStatus, + stdout: String(decoding: stdoutData, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines), + stderr: String(decoding: stderrData, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines) + ) + } + + nonisolated static func canWrite(to targetBundleURL: URL) -> Bool { + let fm = FileManager.default + guard targetBundleURL.pathExtension == "app", + !targetBundleURL.path.contains("/AppTranslocation/") else { + return false + } + let parentURL = targetBundleURL.deletingLastPathComponent() + var statInfo = statfs() + if statfs(parentURL.path, &statInfo) == 0 { + if (statInfo.f_flags & UInt32(MNT_RDONLY)) != 0 { + return false + } + } + return fm.isWritableFile(atPath: parentURL.path) && fm.isWritableFile(atPath: targetBundleURL.path) + } + + nonisolated static func validateWritableTarget(_ targetBundleURL: URL) throws { + guard canWrite(to: targetBundleURL) else { + throw AppUpdateError.nonWritableLocation(targetBundleURL.path) + } + } + + /// DMGをマウントして中の `.app` を検証し、対象アプリと同じ親ディレクトリ内に一時配置して返す。 + nonisolated static func stageUpdate( + fromDMG dmgURL: URL, + targetBundleURL: URL, + expectedBundleIdentifier: String?, + verifySignature: Bool = true + ) throws -> URL { + try validateWritableTarget(targetBundleURL) + let fm = FileManager.default + let workDir = fm.temporaryDirectory.appendingPathComponent("ArkServerUpdateStage-\(UUID().uuidString)", isDirectory: true) + try fm.createDirectory(at: workDir, withIntermediateDirectories: true) + defer { try? fm.removeItem(at: workDir) } + + let mountPoint = workDir.appendingPathComponent("mnt", isDirectory: true) + try fm.createDirectory(at: mountPoint, withIntermediateDirectories: true) + + let attach = try runCommand( + "/usr/bin/hdiutil", + ["attach", "-nobrowse", "-readonly", "-noverify", "-noautoopen", "-mountpoint", mountPoint.path, dmgURL.path] + ) + guard attach.status == 0 else { + let detail = attach.stderr.isEmpty ? attach.stdout : attach.stderr + throw AppUpdateError.mountFailed(detail.isEmpty ? "exit \(attach.status)" : detail) + } + defer { + _ = try? runCommand("/usr/bin/hdiutil", ["detach", mountPoint.path, "-force"]) + } + + guard let appInDMG = try findAppBundle(in: mountPoint, preferredName: targetBundleURL.lastPathComponent) else { + throw AppUpdateError.appNotFoundInDMG + } + + let extractedAppURL = workDir.appendingPathComponent(targetBundleURL.lastPathComponent, isDirectory: true) + let copyFromDMG = try runCommand("/usr/bin/ditto", [appInDMG.path, extractedAppURL.path]) + guard copyFromDMG.status == 0 else { + let detail = copyFromDMG.stderr.isEmpty ? "exit \(copyFromDMG.status)" : copyFromDMG.stderr + throw AppUpdateError.copyFailed(detail) + } + + _ = try? runCommand("/usr/bin/xattr", ["-dr", "com.apple.quarantine", extractedAppURL.path]) + + let infoPlistURL = extractedAppURL.appendingPathComponent("Contents/Info.plist") + guard let plistData = try? Data(contentsOf: infoPlistURL), + let plist = try? PropertyListSerialization.propertyList(from: plistData, options: [], format: nil) as? [String: Any], + let executableName = plist["CFBundleExecutable"] as? String, + !executableName.isEmpty else { + throw AppUpdateError.invalidAppBundle + } + let executableURL = extractedAppURL.appendingPathComponent("Contents/MacOS").appendingPathComponent(executableName) + guard fm.isExecutableFile(atPath: executableURL.path) else { + throw AppUpdateError.invalidAppBundle + } + + let actualBundleID = plist["CFBundleIdentifier"] as? String + if let expected = expectedBundleIdentifier, actualBundleID != expected { + throw AppUpdateError.bundleIdentifierMismatch(expected: expected, actual: actualBundleID) + } + + if verifySignature { + let verify = try runCommand("/usr/bin/codesign", ["--verify", "--deep", "--strict", extractedAppURL.path]) + guard verify.status == 0 else { + let detail = verify.stderr.isEmpty ? verify.stdout : verify.stderr + throw AppUpdateError.signatureVerificationFailed(detail.isEmpty ? "exit \(verify.status)" : detail) + } + } + + let parentDir = targetBundleURL.deletingLastPathComponent() + let baseName = targetBundleURL.deletingPathExtension().lastPathComponent + let stagedInParentURL = parentDir.appendingPathComponent(".\(baseName)-update-\(UUID().uuidString).app", isDirectory: true) + let stageCopy = try runCommand("/usr/bin/ditto", [extractedAppURL.path, stagedInParentURL.path]) + guard stageCopy.status == 0 else { + try? fm.removeItem(at: stagedInParentURL) + let detail = stageCopy.stderr.isEmpty ? "exit \(stageCopy.status)" : stageCopy.stderr + throw AppUpdateError.copyFailed(detail) + } + + return stagedInParentURL + } + + /// ステージ済み `.app` で対象 `.app` をアトミックに置き換える(失敗時は元のアプリへロールバック)。 + nonisolated static func replaceAppBundle(targetBundleURL: URL, withStagedBundleURL stagedBundleURL: URL) throws { + let fm = FileManager.default + let parentDir = targetBundleURL.deletingLastPathComponent() + let baseName = targetBundleURL.deletingPathExtension().lastPathComponent + let backupURL = parentDir.appendingPathComponent(".\(baseName)-backup-\(UUID().uuidString).app", isDirectory: true) + try? fm.removeItem(at: backupURL) + do { + try fm.moveItem(at: targetBundleURL, to: backupURL) + do { + try fm.moveItem(at: stagedBundleURL, to: targetBundleURL) + try? fm.removeItem(at: backupURL) + } catch { + try? fm.moveItem(at: backupURL, to: targetBundleURL) + try? fm.removeItem(at: stagedBundleURL) + throw AppUpdateError.copyFailed(error.localizedDescription) + } + } catch let error as AppUpdateError { + throw error + } catch { + try? fm.removeItem(at: stagedBundleURL) + throw AppUpdateError.copyFailed(error.localizedDescription) } } + + /// 現在のプロセス終了を待ってからアプリバンドルを差し替え、新しいアプリを起動する独立プロセスを開始する。 + nonisolated static func launchReplacementScriptAndRelaunch( + targetBundleURL: URL, + stagedBundleURL: URL, + waitingForPID pid: Int32, + reopen: Bool = true + ) throws { + let parentDir = targetBundleURL.deletingLastPathComponent() + let baseName = targetBundleURL.deletingPathExtension().lastPathComponent + let backupURL = parentDir.appendingPathComponent(".\(baseName)-backup-\(UUID().uuidString).app", isDirectory: true) + + let script = """ + trap '' HUP INT TERM PIPE + PID="$1" + TARGET="$2" + STAGED="$3" + BACKUP="$4" + REOPEN="$5" + + i=0 + while kill -0 "$PID" 2>/dev/null; do + i=$((i + 1)) + if [ "$i" -ge 300 ]; then + rm -rf "$STAGED" + exit 1 + fi + sleep 0.1 + done + + rm -rf "$BACKUP" + if mv "$TARGET" "$BACKUP" && mv "$STAGED" "$TARGET"; then + rm -rf "$BACKUP" + if [ "$REOPEN" = "1" ]; then + /usr/bin/open "$TARGET" + fi + exit 0 + else + if [ ! -e "$TARGET" ] && [ -e "$BACKUP" ]; then + mv "$BACKUP" "$TARGET" + fi + rm -rf "$STAGED" + if [ "$REOPEN" = "1" ]; then + /usr/bin/open "$TARGET" + fi + exit 1 + fi + """ + + let process = Process() + process.executableURL = URL(fileURLWithPath: "/bin/sh") + process.arguments = [ + "-c", + script, + "arkserver-updater", + "\(pid)", + targetBundleURL.path, + stagedBundleURL.path, + backupURL.path, + reopen ? "1" : "0" + ] + process.standardInput = FileHandle.nullDevice + process.standardOutput = FileHandle.nullDevice + process.standardError = FileHandle.nullDevice + do { + try process.run() + } catch { + try? FileManager.default.removeItem(at: stagedBundleURL) + throw AppUpdateError.relaunchFailed(error.localizedDescription) + } + } + + private nonisolated static func findAppBundle(in mountPoint: URL, preferredName: String) throws -> URL? { + let fm = FileManager.default + for candidateName in [preferredName, "ArkServer.app"] { + let candidate = mountPoint.appendingPathComponent(candidateName, isDirectory: true) + if isRealAppDirectory(candidate) { + return candidate + } + } + let items = try fm.contentsOfDirectory( + at: mountPoint, + includingPropertiesForKeys: [.isDirectoryKey, .isSymbolicLinkKey], + options: [.skipsHiddenFiles] + ) + return items.first { isRealAppDirectory($0) } + } + + private nonisolated static func isRealAppDirectory(_ url: URL) -> Bool { + guard url.pathExtension == "app", + let values = try? url.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]), + values.isDirectory == true, + values.isSymbolicLink != true else { + return false + } + return true + } } @MainActor @@ -97,18 +621,23 @@ final class AppUpdater: ObservableObject { static let lastCheckKey = "updates.lastCheck" static let latestURL = URL(string: "https://api.github.com/repos/HR0101/ArkServer/releases/latest")! + typealias RelaunchHandler = @MainActor (_ targetBundleURL: URL, _ stagedBundleURL: URL) throws -> Void + enum State: Equatable { case idle, checking, available(AppRelease), upToDate, noRelease - case downloading(AppRelease), downloaded(URL), failed(String) + case downloading(AppRelease), installing(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 private(set) var availableRelease: AppRelease? @Published var automaticallyChecks: Bool { didSet { defaults.set(automaticallyChecks, forKey: Self.automaticKey) } } let currentVersion: String let currentBuild: String + let targetBundleURL: URL + let expectedBundleIdentifier: String? private let defaults: UserDefaults private let session: URLSession private var operation: Task? @@ -116,12 +645,24 @@ final class AppUpdater: ObservableObject { private var window: NSWindow? private var manualRequested = false private let presentsWindows: Bool + private let relaunchHandler: RelaunchHandler? - init(defaults: UserDefaults = .standard, session: URLSession = .shared, - version: String? = nil, build: String? = nil, presentsWindows: Bool = true) { + init( + defaults: UserDefaults = .standard, + session: URLSession = .shared, + version: String? = nil, + build: String? = nil, + presentsWindows: Bool = true, + targetBundleURL: URL = Bundle.main.bundleURL, + expectedBundleIdentifier: String? = Bundle.main.bundleIdentifier, + relaunchHandler: RelaunchHandler? = nil + ) { self.defaults = defaults self.session = session self.presentsWindows = presentsWindows + self.targetBundleURL = targetBundleURL + self.expectedBundleIdentifier = expectedBundleIdentifier + self.relaunchHandler = relaunchHandler 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 @@ -129,7 +670,7 @@ final class AppUpdater: ObservableObject { } var isBusy: Bool { - switch state { case .checking, .downloading: return true; default: return false } + switch state { case .checking, .downloading, .installing: return true; default: return false } } func check(manual: Bool) { @@ -150,6 +691,7 @@ final class AppUpdater: ObservableObject { guard let http = response as? HTTPURLResponse else { throw AppUpdateError.response } if http.statusCode == 404 { recordCheck() + availableRelease = nil state = .noRelease return } @@ -164,13 +706,14 @@ final class AppUpdater: ObservableObject { recordCheck() if remote.isNewer(than: current, currentBuild: Int(currentBuild) ?? 0) { if !manualRequested && defaults.string(forKey: Self.skippedKey) == release.tag_name { + availableRelease = nil state = .idle } else { + availableRelease = release state = .available(release) - // Background checks only expose the in-app update button. - // Details are presented when the user requests them. } } else { + availableRelease = nil state = .upToDate } } catch { @@ -192,16 +735,128 @@ final class AppUpdater: ObservableObject { func skip(_ release: AppRelease) { defaults.set(release.tag_name, forKey: Self.skippedKey) + availableRelease = nil 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. + /// DMGの自動ダウンロード・マウント・署名/識別子検証・アプリバンドルの自動置換・再起動を一括で行う。 + func install(_ release: AppRelease) { + guard !isBusy, let url = release.downloadURL else { return } + do { + try AppUpdateInstaller.validateWritableTarget(targetBundleURL) + } catch { + availableRelease = release + state = .failed(error.localizedDescription) + return + } + let id = UUID() + downloadID = id + availableRelease = release + state = .downloading(release) + progress = nil + operation = Task { + let workDir = FileManager.default.temporaryDirectory + .appendingPathComponent("ArkServerDownload-\(UUID().uuidString)", isDirectory: true) + defer { try? FileManager.default.removeItem(at: workDir) } + do { + try FileManager.default.createDirectory(at: workDir, withIntermediateDirectories: true) + 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 dmgURL = workDir.appendingPathComponent("ArkServer.dmg") + try FileManager.default.moveItem(at: temporary, to: dmgURL) + try Task.checkCancellation() + + downloadID = nil + progress = nil + state = .installing(release) + + try await performInstallation(fromDMG: dmgURL) + } catch { + guard !Task.isCancelled else { return } + downloadID = nil + progress = nil + state = .failed("アップデートできませんでした。\(error.localizedDescription)") + } + } + } + + /// ダウンロード済みのDMGから直接アップデートを適用して再起動する。 + func install(dmgURL: URL) { + guard !isBusy else { return } + do { + try AppUpdateInstaller.validateWritableTarget(targetBundleURL) + } catch { + state = .failed(error.localizedDescription) + return + } + let release = availableRelease ?? AppRelease( + tag_name: "最新版", + html_url: URL(string: "https://github.com/HR0101/ArkServer/releases/latest")!, + body: nil, + draft: false, + prerelease: false, + assets: [] + ) + state = .installing(release) + progress = nil + operation = Task { + do { + try await performInstallation(fromDMG: dmgURL) + } catch { + guard !Task.isCancelled else { return } + state = .failed("アップデートできませんでした。\(error.localizedDescription)") + } + } + } + + private func performInstallation(fromDMG dmgURL: URL) async throws { + let targetURL = targetBundleURL + let expectedBundleID = expectedBundleIdentifier + let stagedBundleURL = try await Task.detached(priority: .userInitiated) { + try AppUpdateInstaller.stageUpdate( + fromDMG: dmgURL, + targetBundleURL: targetURL, + expectedBundleIdentifier: expectedBundleID + ) + }.value + + if let relaunchHandler { + try relaunchHandler(targetURL, stagedBundleURL) + } else { + NotificationCenter.default.post(name: NSApplication.willTerminateNotification, object: NSApp) + try AppUpdateInstaller.launchReplacementScriptAndRelaunch( + targetBundleURL: targetURL, + stagedBundleURL: stagedBundleURL, + waitingForPID: ProcessInfo.processInfo.processIdentifier, + reopen: true + ) + NSApplication.shared.terminate(nil) + DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + 2) { + exit(0) + } + } + } + + /// DMGをダウンロードフォルダへ保存する(手動適用または読み取り専用環境向けのフォールバック)。 func download(_ release: AppRelease) { guard !isBusy, let url = release.downloadURL else { return } let id = UUID() downloadID = id + availableRelease = release state = .downloading(release) progress = nil operation = Task { @@ -248,14 +903,22 @@ final class AppUpdater: ObservableObject { func showWindow() { guard presentsWindows else { return } if window == nil { - let window = NSWindow(contentViewController: NSHostingController(rootView: AppUpdateView(updater: self))) + let hosting = NSHostingController(rootView: AppUpdateView(updater: self)) + let window = NSWindow(contentViewController: hosting) window.title = "Ark Server アップデート" - window.styleMask = [.titled, .closable, .miniaturizable] + window.styleMask = [.titled, .closable, .miniaturizable, .resizable] + window.titlebarAppearsTransparent = true + window.isOpaque = true window.isReleasedWhenClosed = false + window.minSize = NSSize(width: 560, height: 420) + window.setContentSize(NSSize(width: 680, height: 560)) window.center() self.window = window } + window?.appearance = NSAppearance(named: NeomorphicTheme.isDarkBase ? .darkAqua : .aqua) + window?.backgroundColor = NSColor(NeomorphicTheme.canvas) window?.makeKeyAndOrderFront(nil) + NSApp.activate(ignoringOtherApps: true) } } diff --git a/ArkServerTests/AppUpdaterTests.swift b/ArkServerTests/AppUpdaterTests.swift index 95d1b03..c8076b4 100644 --- a/ArkServerTests/AppUpdaterTests.swift +++ b/ArkServerTests/AppUpdaterTests.swift @@ -24,7 +24,7 @@ struct AppUpdaterTests { 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. + // Automatic detection stops at availability; installation requires user action. updater.check(manual: false) #expect(updater.state == .checking) await finish(updater) @@ -108,13 +108,209 @@ struct AppUpdaterTests { #expect(AppRelease.trustedURL(URL(string: "https://github.com/HR0101/ArkServer/releases/download/v2/ArkServer.dmg")!, download: true)) } - private func fixture() throws -> (AppUpdater, UserDefaults, URLSession, String) { + @Test func formatsGitHubAndCustomReleaseNotesCleanly() throws { + let githubGenerated = """ + ## What's Changed + * ci(release): Developer ID署名とApple公証に対応 by @HR0101 in https://github.com/HR0101/ArkServer/pull/70 + * fix(security): 認証オフ時の削除PINにも総当たり制限を適用する by @HR0101 in https://github.com/HR0101/ArkServer/pull/58 + * feat(musicvideo): 曲の拍に合わせて自動編集する機能を追加 by @HR0101 in https://github.com/HR0101/ArkServer/pull/60 + * refactor(musicvideo): プレビューと3つの操作パネルに画面を整理 by @HR0101 in https://github.com/HR0101/ArkServer/pull/67 + + ## New Contributors + * @HR0101 made their first contribution in https://github.com/HR0101/ArkServer/pull/58 + + **Full Changelog**: https://github.com/HR0101/ArkServer/compare/v1.0.0...v1.0.1 + """ + + let parsed = FormattedReleaseNotes.parse(githubGenerated) + #expect(parsed.sections.count == 1) + #expect(parsed.sections[0].title == nil) + #expect(parsed.changeCount == 4) + #expect(parsed.compareURL?.absoluteString == "https://github.com/HR0101/ArkServer/compare/v1.0.0...v1.0.1") + + let items = parsed.sections[0].items + #expect(items.map(\.text) == [ + "曲の拍に合わせて自動編集する機能を追加", + "認証オフ時の削除PINにも総当たり制限を適用する", + "プレビューと3つの操作パネルに画面を整理", + "Developer ID署名とApple公証に対応" + ]) + #expect(items.map(\.pullNumber) == [60, 58, 67, 70]) + #expect(items[0].kind == .change(.feature)) + #expect(items[1].kind == .change(.fix)) + #expect(items[2].kind == .change(.improvement)) + #expect(items[3].kind == .change(.internalChange)) + + let customMarkdown = """ + ## 主な変更点 + - **自動アップデート**に対応しました + 細かな安定性も改善しています。 + """ + let customParsed = FormattedReleaseNotes.parse(customMarkdown) + #expect(customParsed.sections.count == 1) + #expect(customParsed.sections[0].title == "主な変更点") + #expect(customParsed.sections[0].items.count == 2) + } + + @Test func installAutomaticallyMountsDMGVerifiesAndReplacesAppBundle() async throws { + let fm = FileManager.default + let tempRoot = fm.temporaryDirectory.appendingPathComponent("UpdaterInstallTests-\(UUID().uuidString)", isDirectory: true) + try fm.createDirectory(at: tempRoot, withIntermediateDirectories: true) + defer { try? fm.removeItem(at: tempRoot) } + + let installDir = tempRoot.appendingPathComponent("Applications", isDirectory: true) + try fm.createDirectory(at: installDir, withIntermediateDirectories: true) + let targetAppURL = installDir.appendingPathComponent("ArkServer.app", isDirectory: true) + try makeSignedDummyApp(at: targetAppURL, bundleID: "hr.AllServerForMac", version: "1.0.0", build: "1") + + let dmgURL = tempRoot.appendingPathComponent("ArkServer.dmg") + try makeDummyReleaseDMG(at: dmgURL, bundleID: "hr.AllServerForMac", version: "2.0.0", build: "2") + let dmgData = try Data(contentsOf: dmgURL) + + var relaunchedTarget: URL? + let (updater, defaults, session, suite) = try fixture( + targetBundleURL: targetAppURL, + expectedBundleIdentifier: "hr.AllServerForMac" + ) { target, staged in + try AppUpdateInstaller.replaceAppBundle(targetBundleURL: target, withStagedBundleURL: staged) + relaunchedTarget = target + } + defer { defaults.removePersistentDomain(forName: suite); session.invalidateAndCancel() } + + let release = try JSONDecoder().decode(AppRelease.self, from: releaseJSON(tag: "v2.0.0")) + UpdateMockProtocol.response = (200, dmgData, nil) + + updater.install(release) + for _ in 0..<500 { + if relaunchedTarget != nil { break } + if case .failed = updater.state { break } + try? await Task.sleep(for: .milliseconds(20)) + } + + #expect(relaunchedTarget == targetAppURL) + let updatedPlist = try readInfoPlist(of: targetAppURL) + #expect(updatedPlist["CFBundleShortVersionString"] as? String == "2.0.0") + #expect(updatedPlist["CFBundleVersion"] as? String == "2") + let remainingItems = try fm.contentsOfDirectory(atPath: installDir.path) + #expect(remainingItems == ["ArkServer.app"]) + } + + @Test func installRejectsBundleIdentifierMismatchAndPreservesExistingApp() async throws { + let fm = FileManager.default + let tempRoot = fm.temporaryDirectory.appendingPathComponent("UpdaterMismatchTests-\(UUID().uuidString)", isDirectory: true) + try fm.createDirectory(at: tempRoot, withIntermediateDirectories: true) + defer { try? fm.removeItem(at: tempRoot) } + + let installDir = tempRoot.appendingPathComponent("Applications", isDirectory: true) + try fm.createDirectory(at: installDir, withIntermediateDirectories: true) + let targetAppURL = installDir.appendingPathComponent("ArkServer.app", isDirectory: true) + try makeSignedDummyApp(at: targetAppURL, bundleID: "hr.AllServerForMac", version: "1.0.0", build: "1") + + let dmgURL = tempRoot.appendingPathComponent("ArkServer.dmg") + try makeDummyReleaseDMG(at: dmgURL, bundleID: "com.example.UnexpectedApp", version: "2.0.0", build: "2") + let dmgData = try Data(contentsOf: dmgURL) + + var relaunchCalled = false + let (updater, defaults, session, suite) = try fixture( + targetBundleURL: targetAppURL, + expectedBundleIdentifier: "hr.AllServerForMac" + ) { _, _ in + relaunchCalled = true + } + defer { defaults.removePersistentDomain(forName: suite); session.invalidateAndCancel() } + + let release = try JSONDecoder().decode(AppRelease.self, from: releaseJSON(tag: "v2.0.0")) + UpdateMockProtocol.response = (200, dmgData, nil) + + updater.install(release) + await finish(updater) + + #expect(!relaunchCalled) + guard case .failed(let message) = updater.state else { + Issue.record("Expected installation failure on bundle ID mismatch") + return + } + #expect(message.contains("識別子")) + let currentPlist = try readInfoPlist(of: targetAppURL) + #expect(currentPlist["CFBundleShortVersionString"] as? String == "1.0.0") + } + + @Test func installRejectsTranslocatedOrNonWritableLocation() async throws { + let translocatedURL = URL(fileURLWithPath: "/private/var/folders/xx/yy/T/AppTranslocation/ABC/d/ArkServer.app") + let (updater, defaults, session, suite) = try fixture( + targetBundleURL: translocatedURL, + expectedBundleIdentifier: "hr.AllServerForMac" + ) + defer { defaults.removePersistentDomain(forName: suite); session.invalidateAndCancel() } + + let release = try JSONDecoder().decode(AppRelease.self, from: releaseJSON(tag: "v2.0.0")) + updater.install(release) + guard case .failed(let message) = updater.state else { + Issue.record("Expected non-writable location failure") + return + } + #expect(message.contains("アプリケーション")) + #expect(updater.availableRelease == release) + } + + @Test func launchReplacementScriptWaitsForProcessExitAndSwapsBundle() async throws { + let fm = FileManager.default + let tempRoot = fm.temporaryDirectory.appendingPathComponent("UpdaterScriptTests-\(UUID().uuidString)", isDirectory: true) + try fm.createDirectory(at: tempRoot, withIntermediateDirectories: true) + defer { try? fm.removeItem(at: tempRoot) } + + let targetAppURL = tempRoot.appendingPathComponent("ArkServer.app", isDirectory: true) + let stagedAppURL = tempRoot.appendingPathComponent(".ArkServer-update-test.app", isDirectory: true) + try makeSignedDummyApp(at: targetAppURL, bundleID: "hr.AllServerForMac", version: "1.0.0", build: "1") + try makeSignedDummyApp(at: stagedAppURL, bundleID: "hr.AllServerForMac", version: "2.1.0", build: "3") + + let sleeper = Process() + sleeper.executableURL = URL(fileURLWithPath: "/bin/sleep") + sleeper.arguments = ["0.2"] + try sleeper.run() + + try AppUpdateInstaller.launchReplacementScriptAndRelaunch( + targetBundleURL: targetAppURL, + stagedBundleURL: stagedAppURL, + waitingForPID: sleeper.processIdentifier, + reopen: false + ) + + var updatedVersion: String? + for _ in 0..<100 { + if !fm.fileExists(atPath: stagedAppURL.path), + let plist = try? readInfoPlist(of: targetAppURL), + let version = plist["CFBundleShortVersionString"] as? String, + version == "2.1.0" { + updatedVersion = version + break + } + try await Task.sleep(for: .milliseconds(50)) + } + #expect(updatedVersion == "2.1.0") + } + + private func fixture( + targetBundleURL: URL = Bundle.main.bundleURL, + expectedBundleIdentifier: String? = Bundle.main.bundleIdentifier, + relaunchHandler: AppUpdater.RelaunchHandler? = nil + ) 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) + let updater = AppUpdater( + defaults: defaults, + session: session, + version: "1.0", + build: "1", + presentsWindows: false, + targetBundleURL: targetBundleURL, + expectedBundleIdentifier: expectedBundleIdentifier, + relaunchHandler: relaunchHandler + ) + return (updater, defaults, session, suite) } private func finish(_ updater: AppUpdater) async { @@ -125,6 +321,68 @@ struct AppUpdaterTests { Issue.record("Update check timed out") } + private func finishInstall(_ updater: AppUpdater) async { + for _ in 0..<1000 { + switch updater.state { + case .downloading: + try? await Task.sleep(for: .milliseconds(20)) + case .installing: + // Wait until either failed or operation finishes + try? await Task.sleep(for: .milliseconds(20)) + default: + return + } + } + } + + private func makeSignedDummyApp(at appURL: URL, bundleID: String, version: String, build: String) throws { + let fm = FileManager.default + let contentsURL = appURL.appendingPathComponent("Contents", isDirectory: true) + let macOSURL = contentsURL.appendingPathComponent("MacOS", isDirectory: true) + try fm.createDirectory(at: macOSURL, withIntermediateDirectories: true) + + let executableURL = macOSURL.appendingPathComponent("ArkServer") + try Data("#!/bin/sh\nexit 0\n".utf8).write(to: executableURL) + try fm.setAttributes([.posixPermissions: 0o755], ofItemAtPath: executableURL.path) + + let plist: [String: Any] = [ + "CFBundleIdentifier": bundleID, + "CFBundleName": "Ark Server", + "CFBundleExecutable": "ArkServer", + "CFBundlePackageType": "APPL", + "CFBundleShortVersionString": version, + "CFBundleVersion": build + ] + let plistData = try PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0) + try plistData.write(to: contentsURL.appendingPathComponent("Info.plist")) + + let sign = try AppUpdateInstaller.runCommand("/usr/bin/codesign", ["--force", "--deep", "--sign", "-", appURL.path]) + try #require(sign.status == 0, "codesign failed: \(sign.stderr)") + } + + private func makeDummyReleaseDMG(at dmgURL: URL, bundleID: String, version: String, build: String) throws { + let fm = FileManager.default + let stagingDir = dmgURL.deletingLastPathComponent().appendingPathComponent("DMGStaging-\(UUID().uuidString)", isDirectory: true) + try fm.createDirectory(at: stagingDir, withIntermediateDirectories: true) + defer { try? fm.removeItem(at: stagingDir) } + + let appURL = stagingDir.appendingPathComponent("ArkServer.app", isDirectory: true) + try makeSignedDummyApp(at: appURL, bundleID: bundleID, version: version, build: build) + try fm.createSymbolicLink(atPath: stagingDir.appendingPathComponent("Applications").path, withDestinationPath: "/Applications") + + let create = try AppUpdateInstaller.runCommand( + "/usr/bin/hdiutil", + ["create", "-volname", "Ark Server", "-srcfolder", stagingDir.path, "-ov", "-format", "UDZO", dmgURL.path] + ) + try #require(create.status == 0, "hdiutil create failed: \(create.stderr)") + } + + private func readInfoPlist(of appURL: URL) throws -> [String: Any] { + let data = try Data(contentsOf: appURL.appendingPathComponent("Contents/Info.plist")) + let plist = try PropertyListSerialization.propertyList(from: data, options: [], format: nil) + return try #require(plist as? [String: Any]) + } + private func releaseJSON(tag: String = "v2.0.0") -> Data { Data(""" {"tag_name":"\(tag)","html_url":"https://github.com/HR0101/ArkServer/releases/tag/\(tag)", diff --git a/README.md b/README.md index 23128b7..ee7a59c 100644 --- a/README.md +++ b/README.md @@ -50,9 +50,9 @@ アプリケーションメニューの「アップデートを確認…」または詳細設定の「更新」から、GitHub Releasesの最新公開版を確認できます。起動時の自動確認は同じ設定画面で切り替えられます。新しいバージョンを検知すると、メイン画面のツールバーと詳細設定に「アップデート可能」ボタンを表示します。自動確認では案内ウィンドウを開かず、ボタンを押すとリリースノートとダウンロード操作を表示します。ダウンロードはユーザーの操作で開始します。自動確認の通信失敗は通知せず、手動確認ではエラーを表示します。最終確認日時は正常に確認できた場合だけ更新されます。 -更新案内には現在と新しいバージョン、リリースノートを表示します。「このバージョンをスキップ」は自動通知だけを抑制し、手動確認では再表示できます。「更新をダウンロード」でDMGをダウンロードフォルダに保存します。進捗表示とキャンセルに対応し、アセットがない場合や保存に失敗した場合はリリースページから取得できます。 +更新案内には現在と新しいバージョン、リリースノートを表示します。「このバージョンをスキップ」は自動通知だけを抑制し、手動確認では再表示できます。「今すぐアップデート」を押すと、DMGのダウンロード・マウント・署名と識別子の検証・アプリの差し替え・再起動までを自動で行います(「DMGのみダウンロード」でダウンロードフォルダへの保存のみ行うことも可能です)。進捗表示とダウンロード中のキャンセルに対応し、アセットがない場合や更新に失敗した場合はリリースページから取得できます。 -配信にはIssue #39の方式A(GitHub Releases API)を採用し、適用は手動で行います。サーバーを停止し、インポート・解析・書き出しが完了してから通常の終了操作を行い、DMGを開いて既存のアプリを差し替え、起動してください。自動終了・再起動・実行中のアプリの置換は行いません。読み取り専用DMGからの起動時も同じ手順で更新できます。ライブラリはアプリ外の既存の保存先を引き続き使用します。 +配信にはGitHub Releases APIを採用しています。読み取り専用DMGやApp Translocation上から直接起動している場合は自動置換を行わず、「アプリケーション」フォルダへ移動してからの再試行または手動差し替えを案内します。ライブラリはアプリ外の既存の保存先を引き続き使用します。 リリース担当者は `v1.2.3` の形式でタグをpushすると、GitHub Actionsがテスト、arm64/x86_64のReleaseビルド、署名、DMG添付、リリース公開を実行します。署名用のSecretsを登録している場合はDeveloper ID署名と公証を行い、未登録の場合はアドホック署名になります(詳細は [RELEASING.md](RELEASING.md))。タグのバージョンはアプリの `CFBundleShortVersionString` に反映されます。同一バージョンのビルド更新は `v1.2.3+2` のように正の整数を付けます(省略時のビルド番号は1)。比較はSemVer準拠で、`1.2` と `1.2.0` は同一、数値のビルド指定がある場合のみ同一バージョンのビルド番号も比較します。安定版のみを配信します。 diff --git a/RELEASING.md b/RELEASING.md index 35f5a7d..5d595a0 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -4,7 +4,7 @@ 配信元は `HR0101/ArkServer` の GitHub Releases です。作業内容はまず `Test` ブランチへまとめ、`Test` から `main` へマージ/push すると、[リリースワークフロー](.github/workflows/release.yml)がテスト・ビルド・署名・公証・DMG生成に加えて、最新タグのパッチ番号を自動で 1 上げたタグ(例: `v1.0.0` → `v1.0.1`)を作成し、GitHub Releases の公開(`Latest` + `ArkServer.dmg` 添付)まで実行します。`v1.1.0` のようにマイナー/メジャー番号を指定したい場合のみ、手動でタグを push してください。 -アプリ側の自動処理は **更新の検知まで** です。更新を検知すると、メイン画面のツールバーと詳細設定に「アップデート可能」ボタンを表示します。ボタンを押すと更新内容とダウンロード操作を表示します。 +起動時の自動処理は **更新の検知まで** です。更新を検知すると、メイン画面のツールバーと詳細設定に「アップデート可能」ボタンを表示します。ボタンを押すと更新内容を確認でき、「今すぐアップデート」ボタンを押すとDMGのダウンロード・検証・アプリの差し替え・再起動までを自動で行います。 ## バージョン番号 @@ -58,9 +58,9 @@ ## ダウンロードと適用 -「アップデート可能」を押し、更新案内の「更新をダウンロード」を押すと、DMGをダウンロードフォルダに保存します。アセット名は **`ArkServer.dmg`** に統一してください。このアセットがない場合は、リリースページを開く導線を使用します。 +「アップデート可能」を押し、更新案内の「今すぐアップデート」(または詳細設定の「今すぐアップデート」)を押すと、`ArkServer.dmg` を自動ダウンロードして一時マウントし、アプリの識別子と署名を検証したうえで既存のアプリを自動で差し替えて再起動します。アセット名は **`ArkServer.dmg`** に統一してください。このアセットがない場合は、リリースページを開く導線を使用します。 -自動ダウンロード・自動終了・自動再起動・アプリの自動置換は行いません。利用者がサーバーを停止し、インポート・解析・書き出しの完了を確認してから通常の終了操作を行い、DMGを開いて既存のアプリを差し替え、起動します。ライブラリは既存の保存先を引き続き使用します。 +「DMGのみダウンロード」を押した場合は、従来どおりDMGをダウンロードフォルダに保存します(保存後の案内画面から「このDMGから今すぐアップデート」を実行することもできます)。読み取り専用の場所から起動している場合など、現在の配置場所を書き換えられない場合はエラーを表示し、「アプリケーション」フォルダへ移動してからの再試行またはDMGの手動適用を案内します。ライブラリはアプリ外の既存の保存先を引き続き使用します。 ## 署名と公証