-
Notifications
You must be signed in to change notification settings - Fork 295
feat: add Poe provider for point balance display #272
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
garethpaul
wants to merge
2
commits into
steipete:main
Choose a base branch
from
garethpaul:feat/add-poe-provider
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 all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
There are no files selected for viewing
18 changes: 18 additions & 0 deletions
18
Sources/CodexBar/Providers/Poe/PoeProviderImplementation.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,18 @@ | ||
| import CodexBarCore | ||
| import CodexBarMacroSupport | ||
| import Foundation | ||
|
|
||
| @ProviderImplementationRegistration | ||
| struct PoeProviderImplementation: ProviderImplementation { | ||
| let id: UsageProvider = .poe | ||
|
|
||
| @MainActor | ||
| func isAvailable(context: ProviderAvailabilityContext) -> Bool { | ||
| ProviderTokenResolver.poeToken(environment: context.environment) != nil | ||
| } | ||
|
|
||
| @MainActor | ||
| func sourceMode(context _: ProviderSourceModeContext) -> ProviderSourceMode { | ||
| .api | ||
| } | ||
| } |
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,56 @@ | ||
| import Foundation | ||
|
|
||
| public struct PoeBalanceResponse: Decodable, Sendable { | ||
| public let currentPointBalance: Int | ||
|
|
||
| private enum CodingKeys: String, CodingKey { | ||
| case currentPointBalance = "current_point_balance" | ||
| } | ||
| } | ||
|
|
||
| public struct PoeUsageSnapshot: Sendable { | ||
| public let pointBalance: Int | ||
| public let updatedAt: Date | ||
|
|
||
| public init(pointBalance: Int, updatedAt: Date) { | ||
| self.pointBalance = pointBalance | ||
| self.updatedAt = updatedAt | ||
| } | ||
|
|
||
| public func toUsageSnapshot() -> UsageSnapshot { | ||
| let formatted = Self.formatPoints(self.pointBalance) | ||
|
|
||
| let rateWindow = RateWindow( | ||
| usedPercent: 0, | ||
| windowMinutes: nil, | ||
| resetsAt: nil, | ||
| resetDescription: formatted) | ||
|
|
||
| let identity = ProviderIdentitySnapshot( | ||
| providerID: .poe, | ||
| accountEmail: nil, | ||
| accountOrganization: nil, | ||
| loginMethod: nil) | ||
|
|
||
| return UsageSnapshot( | ||
| primary: rateWindow, | ||
| secondary: nil, | ||
| tertiary: nil, | ||
| providerCost: nil, | ||
| updatedAt: self.updatedAt, | ||
| identity: identity) | ||
| } | ||
|
|
||
| public static func formatPoints(_ points: Int) -> String { | ||
| switch points { | ||
| case 1_000_000_000...: | ||
| return String(format: "%.1fB pts", Double(points) / 1_000_000_000) | ||
| case 1_000_000...: | ||
| return String(format: "%.1fM pts", Double(points) / 1_000_000) | ||
| case 1_000...: | ||
| return String(format: "%.1fK pts", Double(points) / 1_000) | ||
| default: | ||
| return "\(points) pts" | ||
| } | ||
| } | ||
| } |
66 changes: 66 additions & 0 deletions
66
Sources/CodexBarCore/Providers/Poe/PoeProviderDescriptor.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,66 @@ | ||
| import CodexBarMacroSupport | ||
| import Foundation | ||
|
|
||
| @ProviderDescriptorRegistration | ||
| @ProviderDescriptorDefinition | ||
| public enum PoeProviderDescriptor { | ||
| static func makeDescriptor() -> ProviderDescriptor { | ||
| ProviderDescriptor( | ||
| id: .poe, | ||
| metadata: ProviderMetadata( | ||
| id: .poe, | ||
| displayName: "Poe", | ||
| sessionLabel: "Points", | ||
| weeklyLabel: "", | ||
| opusLabel: nil, | ||
| supportsOpus: false, | ||
| supportsCredits: false, | ||
| creditsHint: "", | ||
| toggleTitle: "Show Poe usage", | ||
| cliName: "poe", | ||
| defaultEnabled: false, | ||
| isPrimaryProvider: false, | ||
| usesAccountFallback: false, | ||
| browserCookieOrder: nil, | ||
| dashboardURL: "https://poe.com", | ||
| statusPageURL: nil), | ||
| branding: ProviderBranding( | ||
| iconStyle: .poe, | ||
| iconResourceName: "ProviderIcon-poe", | ||
| color: ProviderColor(red: 101 / 255, green: 78 / 255, blue: 163 / 255)), | ||
| tokenCost: ProviderTokenCostConfig( | ||
| supportsTokenCost: false, | ||
| noDataMessage: { "Poe cost summary is not available." }), | ||
| fetchPlan: ProviderFetchPlan( | ||
| sourceModes: [.auto, .api], | ||
| pipeline: ProviderFetchPipeline(resolveStrategies: { _ in [PoeAPIFetchStrategy()] })), | ||
| cli: ProviderCLIConfig( | ||
| name: "poe", | ||
| versionDetector: nil)) | ||
| } | ||
| } | ||
|
|
||
| struct PoeAPIFetchStrategy: ProviderFetchStrategy { | ||
| let id: String = "poe.api" | ||
| let kind: ProviderFetchKind = .apiToken | ||
|
|
||
| func isAvailable(_ context: ProviderFetchContext) async -> Bool { | ||
| Self.resolveToken(environment: context.env) != nil | ||
| } | ||
|
|
||
| func fetch(_ context: ProviderFetchContext) async throws -> ProviderFetchResult { | ||
| guard let apiKey = Self.resolveToken(environment: context.env) else { | ||
| throw PoeUsageError.missingCredentials | ||
| } | ||
| let usage = try await PoeUsageFetcher.fetchUsage(apiKey: apiKey) | ||
| return self.makeResult( | ||
| usage: usage.toUsageSnapshot(), | ||
| sourceLabel: "api") | ||
| } | ||
|
|
||
| func shouldFallback(on _: Error, context _: ProviderFetchContext) -> Bool { false } | ||
|
|
||
| private static func resolveToken(environment: [String: String]) -> String? { | ||
| ProviderTokenResolver.poeToken(environment: environment) | ||
| } | ||
| } |
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,74 @@ | ||
| import Foundation | ||
| #if canImport(FoundationNetworking) | ||
| import FoundationNetworking | ||
| #endif | ||
|
|
||
| public enum PoeUsageError: LocalizedError, Sendable { | ||
| case missingCredentials | ||
| case networkError(String) | ||
| case apiError(String) | ||
| case parseFailed(String) | ||
|
|
||
| public var errorDescription: String? { | ||
| switch self { | ||
| case .missingCredentials: | ||
| "Missing POE_API_KEY environment variable." | ||
| case let .networkError(message): | ||
| "Poe network error: \(message)" | ||
| case let .apiError(message): | ||
| "Poe API error: \(message)" | ||
| case let .parseFailed(message): | ||
| "Failed to parse Poe response: \(message)" | ||
| } | ||
| } | ||
| } | ||
|
|
||
| public struct PoeUsageFetcher: Sendable { | ||
| private static let log = CodexBarLog.logger(LogCategories.poeUsage) | ||
| private static let balanceURL = URL(string: "https://api.poe.com/usage/current_balance")! | ||
|
|
||
| public static func fetchUsage(apiKey: String) async throws -> PoeUsageSnapshot { | ||
| guard !apiKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { | ||
| throw PoeUsageError.missingCredentials | ||
| } | ||
|
|
||
| var request = URLRequest(url: self.balanceURL) | ||
| request.httpMethod = "GET" | ||
| request.timeoutInterval = 30 | ||
| request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization") | ||
| request.setValue("application/json", forHTTPHeaderField: "Accept") | ||
|
|
||
| let (data, response) = try await URLSession.shared.data(for: request) | ||
|
|
||
| guard let httpResponse = response as? HTTPURLResponse else { | ||
| throw PoeUsageError.networkError("Invalid response") | ||
| } | ||
|
|
||
| guard httpResponse.statusCode == 200 else { | ||
| let body = String(data: data, encoding: .utf8) ?? "HTTP \(httpResponse.statusCode)" | ||
| Self.log.error("Poe API returned \(httpResponse.statusCode): \(body)") | ||
| throw PoeUsageError.apiError(body) | ||
| } | ||
|
|
||
| if let jsonString = String(data: data, encoding: .utf8) { | ||
| Self.log.debug("Poe API response: \(jsonString)") | ||
| } | ||
|
|
||
| return try Self.parseBalance(from: data) | ||
| } | ||
|
|
||
| /// Internal method for testing response parsing. | ||
| public static func _parseBalanceForTesting(_ data: Data) throws -> PoeUsageSnapshot { | ||
| try self.parseBalance(from: data) | ||
| } | ||
|
|
||
| private static func parseBalance(from data: Data) throws -> PoeUsageSnapshot { | ||
| do { | ||
| let decoded = try JSONDecoder().decode(PoeBalanceResponse.self, from: data) | ||
| return PoeUsageSnapshot(pointBalance: decoded.currentPointBalance, updatedAt: Date()) | ||
| } catch { | ||
| Self.log.error("Poe JSON decoding error: \(error.localizedDescription)") | ||
| throw PoeUsageError.parseFailed(error.localizedDescription) | ||
| } | ||
| } | ||
| } |
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
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
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,49 @@ | ||
| import CodexBarCore | ||
| import Foundation | ||
| import Testing | ||
|
|
||
| @Suite | ||
| struct PoeModelsTests { | ||
| @Test | ||
| func formatPointsRawNumbers() { | ||
| #expect(PoeUsageSnapshot.formatPoints(0) == "0 pts") | ||
| #expect(PoeUsageSnapshot.formatPoints(1) == "1 pts") | ||
| #expect(PoeUsageSnapshot.formatPoints(500) == "500 pts") | ||
| #expect(PoeUsageSnapshot.formatPoints(999) == "999 pts") | ||
| } | ||
|
|
||
| @Test | ||
| func formatPointsThousands() { | ||
| #expect(PoeUsageSnapshot.formatPoints(1_000) == "1.0K pts") | ||
| #expect(PoeUsageSnapshot.formatPoints(1_500) == "1.5K pts") | ||
| #expect(PoeUsageSnapshot.formatPoints(10_000) == "10.0K pts") | ||
| #expect(PoeUsageSnapshot.formatPoints(999_999) == "1000.0K pts") | ||
| } | ||
|
|
||
| @Test | ||
| func formatPointsMillions() { | ||
| #expect(PoeUsageSnapshot.formatPoints(1_000_000) == "1.0M pts") | ||
| #expect(PoeUsageSnapshot.formatPoints(1_500_000) == "1.5M pts") | ||
| #expect(PoeUsageSnapshot.formatPoints(295_932_027) == "295.9M pts") | ||
| #expect(PoeUsageSnapshot.formatPoints(999_999_999) == "1000.0M pts") | ||
| } | ||
|
|
||
| @Test | ||
| func formatPointsBillions() { | ||
| #expect(PoeUsageSnapshot.formatPoints(1_000_000_000) == "1.0B pts") | ||
| #expect(PoeUsageSnapshot.formatPoints(1_500_000_000) == "1.5B pts") | ||
| #expect(PoeUsageSnapshot.formatPoints(10_000_000_000) == "10.0B pts") | ||
| } | ||
|
|
||
| @Test | ||
| func toUsageSnapshotCreatesValidSnapshot() { | ||
| let snapshot = PoeUsageSnapshot(pointBalance: 295_932_027, updatedAt: Date()) | ||
| let usageSnapshot = snapshot.toUsageSnapshot() | ||
|
|
||
| #expect(usageSnapshot.primary?.resetDescription == "295.9M pts") | ||
| #expect(usageSnapshot.primary?.usedPercent == 0) | ||
| #expect(usageSnapshot.identity?.providerID == .poe) | ||
| #expect(usageSnapshot.secondary == nil) | ||
| #expect(usageSnapshot.tertiary == nil) | ||
| } | ||
| } |
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.