-
Notifications
You must be signed in to change notification settings - Fork 776
feat(providers): Add Xiaomi MiMo balance provider #596
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
rolandkakonyi
wants to merge
13
commits into
steipete:main
Choose a base branch
from
rolandkakonyi:feature/xiaomi-mimo-balance
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 2 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
fcae5f3
Add Xiaomi MiMo balance support
7be116f
Document Xiaomi MiMo provider
ec7499a
Polish MiMo provider follow-up
145127b
Align MiMo web labeling
ab3cf93
improve MiMo icon
3e41ab3
reverting unintended default switch cases
b43d91b
Fix MiMo cookie matching
d6dfcdd
Fix MiMo cookie path matching
d7ece0d
Merge MiMo cookie stores
3f84020
Enforce MiMo manual cookies
005f186
Handle MiMo slash path cookies
e056bf9
Merge branch 'main' into feature/xiaomi-mimo-balance
e545cc9
Merge branch 'main' into feature/xiaomi-mimo-balance
rolandkakonyi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
97 changes: 97 additions & 0 deletions
97
Sources/CodexBar/Providers/MiMo/MiMoProviderImplementation.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,97 @@ | ||
| import AppKit | ||
| import CodexBarCore | ||
| import CodexBarMacroSupport | ||
| import Foundation | ||
| import SwiftUI | ||
|
|
||
| @ProviderImplementationRegistration | ||
| struct MiMoProviderImplementation: ProviderImplementation { | ||
| let id: UsageProvider = .mimo | ||
| let supportsLoginFlow: Bool = true | ||
|
|
||
| @MainActor | ||
| func observeSettings(_ settings: SettingsStore) { | ||
| _ = settings.miMoCookieSource | ||
| _ = settings.miMoCookieHeader | ||
| } | ||
|
|
||
| @MainActor | ||
| func settingsSnapshot(context: ProviderSettingsSnapshotContext) -> ProviderSettingsSnapshotContribution? { | ||
| .mimo(context.settings.miMoSettingsSnapshot(tokenOverride: context.tokenOverride)) | ||
| } | ||
|
|
||
| @MainActor | ||
| func settingsPickers(context: ProviderSettingsContext) -> [ProviderSettingsPickerDescriptor] { | ||
| let cookieBinding = Binding( | ||
| get: { context.settings.miMoCookieSource.rawValue }, | ||
| set: { raw in | ||
| context.settings.miMoCookieSource = ProviderCookieSource(rawValue: raw) ?? .auto | ||
| }) | ||
| let cookieOptions = ProviderCookieSourceUI.options( | ||
| allowsOff: false, | ||
| keychainDisabled: context.settings.debugDisableKeychainAccess) | ||
| let cookieSubtitle: () -> String? = { | ||
| ProviderCookieSourceUI.subtitle( | ||
| source: context.settings.miMoCookieSource, | ||
| keychainDisabled: context.settings.debugDisableKeychainAccess, | ||
| auto: "Automatic imports Chrome browser cookies from Xiaomi MiMo.", | ||
| manual: "Paste a Cookie header from platform.xiaomimimo.com.", | ||
| off: "Xiaomi MiMo cookies are disabled.") | ||
| } | ||
|
|
||
| return [ | ||
| ProviderSettingsPickerDescriptor( | ||
| id: "mimo-cookie-source", | ||
| title: "Cookie source", | ||
| subtitle: "Automatic imports Chrome browser cookies from Xiaomi MiMo.", | ||
| dynamicSubtitle: cookieSubtitle, | ||
| binding: cookieBinding, | ||
| options: cookieOptions, | ||
| isVisible: nil, | ||
| onChange: nil, | ||
| trailingText: { | ||
| guard let entry = CookieHeaderCache.load(provider: .mimo) else { return nil } | ||
| let when = entry.storedAt.relativeDescription() | ||
| return "Cached: \(entry.sourceLabel) • \(when)" | ||
| }), | ||
| ] | ||
| } | ||
|
|
||
| @MainActor | ||
| func settingsFields(context: ProviderSettingsContext) -> [ProviderSettingsFieldDescriptor] { | ||
| [ | ||
| ProviderSettingsFieldDescriptor( | ||
| id: "mimo-cookie", | ||
| title: "", | ||
| subtitle: "", | ||
| kind: .secure, | ||
| placeholder: "Cookie: ...", | ||
| binding: context.stringBinding(\.miMoCookieHeader), | ||
| actions: [ | ||
| ProviderSettingsActionDescriptor( | ||
| id: "mimo-open-balance", | ||
| title: "Open MiMo Balance", | ||
| style: .link, | ||
| isVisible: nil, | ||
| perform: { | ||
| guard let url = URL(string: "https://platform.xiaomimimo.com/#/console/balance") else { | ||
| return | ||
| } | ||
| NSWorkspace.shared.open(url) | ||
| }), | ||
| ], | ||
| isVisible: { context.settings.miMoCookieSource == .manual }, | ||
| onActivate: { context.settings.ensureMiMoCookieLoaded() }), | ||
| ] | ||
| } | ||
|
|
||
| @MainActor | ||
| func runLoginFlow(context _: ProviderLoginContext) async -> Bool { | ||
| let loginURL = "https://platform.xiaomimimo.com/api/v1/genLoginUrl?currentPath=%2F%23%2Fconsole%2Fbalance" | ||
| guard let url = URL(string: loginURL) else { | ||
| return false | ||
| } | ||
| NSWorkspace.shared.open(url) | ||
| return false | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| import CodexBarCore | ||
| import Foundation | ||
|
|
||
| extension SettingsStore { | ||
| var miMoCookieHeader: String { | ||
| get { self.configSnapshot.providerConfig(for: .mimo)?.sanitizedCookieHeader ?? "" } | ||
| set { | ||
| self.updateProviderConfig(provider: .mimo) { entry in | ||
| entry.cookieHeader = self.normalizedConfigValue(newValue) | ||
| } | ||
| self.logSecretUpdate(provider: .mimo, field: "cookieHeader", value: newValue) | ||
| } | ||
| } | ||
|
|
||
| var miMoCookieSource: ProviderCookieSource { | ||
| get { self.resolvedCookieSource(provider: .mimo, fallback: .auto) } | ||
| set { | ||
| self.updateProviderConfig(provider: .mimo) { entry in | ||
| entry.cookieSource = newValue | ||
| } | ||
| self.logProviderModeChange(provider: .mimo, field: "cookieSource", value: newValue.rawValue) | ||
| } | ||
| } | ||
|
|
||
| func ensureMiMoCookieLoaded() {} | ||
| } | ||
|
|
||
| extension SettingsStore { | ||
| func miMoSettingsSnapshot(tokenOverride: TokenAccountOverride?) -> ProviderSettingsSnapshot.MiMoProviderSettings { | ||
| _ = tokenOverride | ||
| return ProviderSettingsSnapshot.MiMoProviderSettings( | ||
| cookieSource: self.miMoCookieSource, | ||
| manualCookieHeader: self.miMoCookieHeader) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
131 changes: 131 additions & 0 deletions
131
Sources/CodexBarCore/Providers/MiMo/MiMoCookieImporter.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,131 @@ | ||
| import Foundation | ||
|
|
||
| enum MiMoCookieHeader { | ||
| static let requiredCookieNames: Set<String> = [ | ||
| "api-platform_serviceToken", | ||
| "userId", | ||
| ] | ||
| static let knownCookieNames: Set<String> = requiredCookieNames.union([ | ||
| "api-platform_ph", | ||
| "api-platform_slh", | ||
| ]) | ||
|
|
||
| static func normalizedHeader(from raw: String?) -> String? { | ||
| guard let normalized = CookieHeaderNormalizer.normalize(raw) else { return nil } | ||
| let pairs = CookieHeaderNormalizer.pairs(from: normalized) | ||
| guard !pairs.isEmpty else { return nil } | ||
|
|
||
| var byName: [String: String] = [:] | ||
| for pair in pairs { | ||
| let name = pair.name.trimmingCharacters(in: .whitespacesAndNewlines) | ||
| let value = pair.value.trimmingCharacters(in: .whitespacesAndNewlines) | ||
| guard self.knownCookieNames.contains(name), !value.isEmpty else { continue } | ||
| byName[name] = value | ||
| } | ||
|
|
||
| guard self.requiredCookieNames.isSubset(of: Set(byName.keys)) else { return nil } | ||
| return byName.keys.sorted().compactMap { name in | ||
| guard let value = byName[name] else { return nil } | ||
| return "\(name)=\(value)" | ||
| }.joined(separator: "; ") | ||
| } | ||
|
|
||
| static func header(from cookies: [HTTPCookie]) -> String? { | ||
| var byName: [String: HTTPCookie] = [:] | ||
|
|
||
| for cookie in cookies { | ||
| guard self.knownCookieNames.contains(cookie.name) else { continue } | ||
| guard !cookie.value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { continue } | ||
| if let expiry = cookie.expiresDate, expiry < Date() { continue } | ||
|
|
||
| if let existing = byName[cookie.name] { | ||
| let existingExpiry = existing.expiresDate ?? .distantPast | ||
| let candidateExpiry = cookie.expiresDate ?? .distantPast | ||
| if candidateExpiry >= existingExpiry { | ||
| byName[cookie.name] = cookie | ||
| } | ||
| } else { | ||
| byName[cookie.name] = cookie | ||
| } | ||
| } | ||
|
|
||
| guard self.requiredCookieNames.isSubset(of: Set(byName.keys)) else { return nil } | ||
| return byName.keys.sorted().compactMap { name in | ||
| guard let cookie = byName[name] else { return nil } | ||
| return "\(cookie.name)=\(cookie.value)" | ||
| }.joined(separator: "; ") | ||
| } | ||
| } | ||
|
|
||
| #if os(macOS) | ||
| import SweetCookieKit | ||
|
|
||
| private let miMoCookieImportOrder: BrowserCookieImportOrder = | ||
| ProviderDefaults.metadata[.mimo]?.browserCookieOrder ?? Browser.defaultImportOrder | ||
|
|
||
| public enum MiMoCookieImporter { | ||
| private static let cookieClient = BrowserCookieClient() | ||
| private static let cookieDomains = [ | ||
| "platform.xiaomimimo.com", | ||
| "xiaomimimo.com", | ||
| ] | ||
|
|
||
| public struct SessionInfo: Sendable { | ||
| public let cookieHeader: String | ||
| public let sourceLabel: String | ||
|
|
||
| public init(cookieHeader: String, sourceLabel: String) { | ||
| self.cookieHeader = cookieHeader | ||
| self.sourceLabel = sourceLabel | ||
| } | ||
| } | ||
|
|
||
| nonisolated(unsafe) static var importSessionsOverrideForTesting: | ||
| ((BrowserDetection, ((String) -> Void)?) throws -> [SessionInfo])? | ||
|
|
||
| public static func importSessions( | ||
| browserDetection: BrowserDetection, | ||
| logger: ((String) -> Void)? = nil) throws -> [SessionInfo] | ||
| { | ||
| if let override = self.importSessionsOverrideForTesting { | ||
| return try override(browserDetection, logger) | ||
| } | ||
|
|
||
| let log: (String) -> Void = { msg in logger?("[mimo-cookie] \(msg)") } | ||
| var sessions: [SessionInfo] = [] | ||
| let installed = miMoCookieImportOrder.cookieImportCandidates(using: browserDetection) | ||
| let labels = installed.map(\.displayName).joined(separator: ", ") | ||
| log("Cookie import candidates: \(labels)") | ||
|
|
||
| for browserSource in installed { | ||
| do { | ||
| let query = BrowserCookieQuery(domains: self.cookieDomains) | ||
| let sources = try Self.cookieClient.records( | ||
| matching: query, | ||
| in: browserSource, | ||
| logger: log) | ||
|
|
||
| for source in sources where !source.records.isEmpty { | ||
| let cookies = BrowserCookieClient.makeHTTPCookies(source.records, origin: query.origin) | ||
| guard let cookieHeader = MiMoCookieHeader.header(from: cookies) else { | ||
| continue | ||
rolandkakonyi marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| } | ||
| sessions.append(SessionInfo(cookieHeader: cookieHeader, sourceLabel: source.label)) | ||
| } | ||
| } catch { | ||
| BrowserCookieAccessGate.recordIfNeeded(error) | ||
| log("\(browserSource.displayName) cookie import failed: \(error.localizedDescription)") | ||
| } | ||
| } | ||
|
|
||
| return sessions | ||
| } | ||
|
|
||
| public static func hasSession( | ||
| browserDetection: BrowserDetection, | ||
| logger: ((String) -> Void)? = nil) -> Bool | ||
| { | ||
| (try? self.importSessions(browserDetection: browserDetection, logger: logger).isEmpty == false) ?? false | ||
| } | ||
| } | ||
| #endif | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.