mirror of
https://github.com/majd/ipatool
synced 2026-11-29 02:37:52 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3040955de1 | ||
|
|
f0c7e02db9 | ||
|
|
cd54b3bbcb | ||
|
|
82f70f23c7 | ||
|
|
96115462d0 | ||
|
|
1b65463007 |
No files matched your search
@@ -17,7 +17,7 @@ jobs:
|
||||
version: ${{ steps.set_output.outputs.version }}
|
||||
test:
|
||||
name: Run tests
|
||||
runs-on: macos-11
|
||||
runs-on: macos-12
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v2
|
||||
@@ -29,7 +29,7 @@ jobs:
|
||||
run: swift test
|
||||
build:
|
||||
name: Build
|
||||
runs-on: macos-11
|
||||
runs-on: macos-12
|
||||
needs: [get_version, test]
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -83,4 +83,4 @@ jobs:
|
||||
git config --local user.email ${{ secrets.GH_EMAIL }}
|
||||
git add Casks/ipatool.rb
|
||||
git commit -m "Update ipatool to v${{ needs.get_version.outputs.version }}"
|
||||
git push "https://${{ secrets.GH_TOKEN }}@github.com/${{ secrets.HOMEBREW_REPO }}.git" --set-upstream "main"
|
||||
git push "https://${{ secrets.GH_TOKEN }}@github.com/${{ secrets.HOMEBREW_REPO }}.git" --set-upstream "main"
|
||||
@@ -8,7 +8,7 @@ on:
|
||||
jobs:
|
||||
build:
|
||||
name: Build
|
||||
runs-on: macos-11
|
||||
runs-on: macos-12
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v2
|
||||
@@ -29,8 +29,8 @@ jobs:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
macos: [macos-10.15, macos-11]
|
||||
command: [download, search]
|
||||
macos: [macos-10.15, macos-11, macos-12]
|
||||
command: [auth, download, purchase, search]
|
||||
steps:
|
||||
- name: Download binary
|
||||
uses: actions/download-artifact@v2
|
||||
|
||||
@@ -8,7 +8,7 @@ on:
|
||||
jobs:
|
||||
test-networking:
|
||||
name: Test Networking
|
||||
runs-on: macos-11
|
||||
runs-on: macos-12
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v2
|
||||
|
||||
@@ -76,6 +76,20 @@
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "Persistence"
|
||||
BuildableName = "Persistence"
|
||||
BlueprintName = "Persistence"
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
|
||||
@@ -1,6 +1,15 @@
|
||||
{
|
||||
"object": {
|
||||
"pins": [
|
||||
{
|
||||
"package": "KeychainAccess",
|
||||
"repositoryURL": "https://github.com/kishikawakatsumi/KeychainAccess",
|
||||
"state": {
|
||||
"branch": "v4.2.2",
|
||||
"revision": "84e546727d66f1adc5439debad16270d0fdd04e7",
|
||||
"version": null
|
||||
}
|
||||
},
|
||||
{
|
||||
"package": "swift-argument-parser",
|
||||
"repositoryURL": "https://github.com/apple/swift-argument-parser",
|
||||
|
||||
+10
-4
@@ -8,11 +8,13 @@ let package = Package(
|
||||
products: [
|
||||
.executable(name: "ipatool", targets: ["CLI"]),
|
||||
.library(name: "StoreAPI", targets: ["StoreAPI"]),
|
||||
.library(name: "Networking", targets: ["Networking"])
|
||||
.library(name: "Networking", targets: ["Networking"]),
|
||||
.library(name: "Persistence", targets: ["Persistence"])
|
||||
],
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/apple/swift-argument-parser", revision: "1.0.2"),
|
||||
.package(url: "https://github.com/weichsel/ZIPFoundation", revision: "0.9.14")
|
||||
.package(url: "https://github.com/weichsel/ZIPFoundation", revision: "0.9.14"),
|
||||
.package(url: "https://github.com/kishikawakatsumi/KeychainAccess", revision: "v4.2.2")
|
||||
],
|
||||
targets: [
|
||||
.executableTarget(
|
||||
@@ -20,7 +22,8 @@ let package = Package(
|
||||
dependencies: [
|
||||
.product(name: "ArgumentParser", package: "swift-argument-parser"),
|
||||
.byName(name: "Networking"),
|
||||
.byName(name: "StoreAPI")
|
||||
.byName(name: "StoreAPI"),
|
||||
.byName(name: "Persistence")
|
||||
]
|
||||
),
|
||||
.target(
|
||||
@@ -32,6 +35,9 @@ let package = Package(
|
||||
]
|
||||
),
|
||||
.target(name: "Networking", dependencies: []),
|
||||
.testTarget(name: "NetworkingTests", dependencies: ["Networking"])
|
||||
.testTarget(name: "NetworkingTests", dependencies: ["Networking"]),
|
||||
.target(name: "Persistence", dependencies: [
|
||||
.byName(name: "KeychainAccess")
|
||||
]),
|
||||
]
|
||||
)
|
||||
@@ -1,4 +1,5 @@
|
||||
# IPATool
|
||||
|
||||
[](https://GitHub.com/majd/ipatool/releases/)
|
||||
[](https://github.com/majd/ipatool/blob/main/LICENSE)
|
||||
[](https://github.com/majd/ipatool/actions/workflows/unit-tests.yml)
|
||||
@@ -10,17 +11,18 @@
|
||||
|
||||

|
||||
|
||||
* [Requirements](#requirements)
|
||||
* [Installation](#installation)
|
||||
* [Manual](#manual)
|
||||
* [Homebrew](#homebrew)
|
||||
* [Usage](#usage)
|
||||
* [FAQ](https://github.com/majd/ipatool/wiki/FAQ)
|
||||
* [License](#license)
|
||||
- [Requirements](#requirements)
|
||||
- [Installation](#installation)
|
||||
- [Manual](#manual)
|
||||
- [Homebrew](#homebrew)
|
||||
- [Usage](#usage)
|
||||
- [FAQ](https://github.com/majd/ipatool/wiki/FAQ)
|
||||
- [License](#license)
|
||||
|
||||
## Requirements
|
||||
* macOS 10.15 or later.
|
||||
* Apple ID set up to use the App Store.
|
||||
|
||||
- macOS 10.15 or later.
|
||||
- Apple ID set up to use the App Store.
|
||||
|
||||
## Installation
|
||||
|
||||
@@ -39,6 +41,24 @@ $ brew install ipatool
|
||||
|
||||
## Usage
|
||||
|
||||
To authenticate with the App Store, use the `auth` command.
|
||||
|
||||
```
|
||||
OVERVIEW: Authenticate with the App Store.
|
||||
|
||||
USAGE: ipatool auth <subcommand>
|
||||
|
||||
OPTIONS:
|
||||
--version Show the version.
|
||||
-h, --help Show help information.
|
||||
|
||||
SUBCOMMANDS:
|
||||
login Login to the App Store.
|
||||
revoke Revoke your App Store credentials.
|
||||
|
||||
See 'ipatool help auth <subcommand>' for detailed help.
|
||||
```
|
||||
|
||||
To search for apps on the App Store, use the `search` command.
|
||||
|
||||
```
|
||||
@@ -50,11 +70,33 @@ ARGUMENTS:
|
||||
<term> The term to search for.
|
||||
|
||||
OPTIONS:
|
||||
-l, --limit <limit> The maximum amount of search results to retrieve. (default: 5)
|
||||
-c, --country <country> The two-letter (ISO 3166-1 alpha-2) country code for the
|
||||
iTunes Store. (default: US)
|
||||
-l, --limit <limit> The maximum amount of search results to retrieve.
|
||||
(default: 5)
|
||||
-c, --country <country> The two-letter (ISO 3166-1 alpha-2) country code for
|
||||
the iTunes Store. (default: US)
|
||||
-d, --device-family <device-family>
|
||||
The device family to limit the search query to. (default: iPhone)
|
||||
The device family to limit the search query to.
|
||||
(default: iPhone)
|
||||
--log-level <log-level> The log level. (default: info)
|
||||
--version Show the version.
|
||||
-h, --help Show help information.
|
||||
```
|
||||
|
||||
To obtain a license for an app, use the `purchase` command.
|
||||
|
||||
```
|
||||
OVERVIEW: Obtain a license for the app from the App Store.
|
||||
|
||||
USAGE: ipatool purchase --bundle-identifier <bundle-identifier> [--country <country>] [--device-family <device-family>] [--log-level <log-level>]
|
||||
|
||||
OPTIONS:
|
||||
-b, --bundle-identifier <bundle-identifier>
|
||||
The bundle identifier of the target iOS app.
|
||||
-c, --country <country> The two-letter (ISO 3166-1 alpha-2) country code for
|
||||
the iTunes Store. (default: US)
|
||||
-d, --device-family <device-family>
|
||||
The device family to limit the search query to.
|
||||
(default: iPhone)
|
||||
--log-level <log-level> The log level. (default: info)
|
||||
--version Show the version.
|
||||
-h, --help Show help information.
|
||||
@@ -65,28 +107,25 @@ To download a copy of the ipa file, use the `download` command.
|
||||
```
|
||||
OVERVIEW: Download (encrypted) iOS app packages from the App Store.
|
||||
|
||||
USAGE: ipatool download --bundle-identifier <bundle-identifier> [--email <email>] [--password <password>] [--auth-code <auth-code>] [--country <country>] [--device-family <device-family>] [--output <output>] [--log-level <log-level>]
|
||||
USAGE: ipatool download --bundle-identifier <bundle-identifier> [--country <country>] [--device-family <device-family>] [--output <output>] [--log-level <log-level>] [--purchase]
|
||||
|
||||
OPTIONS:
|
||||
-b, --bundle-identifier <bundle-identifier>
|
||||
The bundle identifier of the target iOS app.
|
||||
-e, --email <email> The email address for the Apple ID.
|
||||
-p, --password <password>
|
||||
The password for the Apple ID.
|
||||
--auth-code <auth-code> The 2FA code for the Apple ID.
|
||||
-c, --country <country> The two-letter (ISO 3166-1 alpha-2)
|
||||
country code for the iTunes Store. (default: US)
|
||||
-c, --country <country> The two-letter (ISO 3166-1 alpha-2) country code for
|
||||
the iTunes Store. (default: US)
|
||||
-d, --device-family <device-family>
|
||||
The device family to limit the search query to. (default: iPhone)
|
||||
The device family to limit the search query to.
|
||||
(default: iPhone)
|
||||
-o, --output <output> The destination path of the downloaded app package.
|
||||
--log-level <log-level> The log level. (default: info)
|
||||
--purchase Obtain a license for the app if needed.
|
||||
--version Show the version.
|
||||
-h, --help Show help information.
|
||||
|
||||
```
|
||||
|
||||
**Note:** You can specify the Apple ID email address and username as arguments when using the tool or by setting them as environment variables (`IPATOOL_EMAIL` and `IPATOOL_PASSWORD`). If you do not specify this information using either of those methods, the tool will prompt for user input in an interactive session. Similarly, you can supply the 2FA code interactively or using the environment variable `IPATOOL_2FA_CODE`.
|
||||
|
||||
## License
|
||||
|
||||
IPATool is released under the [MIT license](https://github.com/majd/ipatool/blob/main/LICENSE).
|
||||
IPATool is released under the [MIT license](https://github.com/majd/ipatool/blob/main/LICENSE).
|
||||
@@ -0,0 +1,201 @@
|
||||
//
|
||||
// Auth.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 21.03.22.
|
||||
//
|
||||
|
||||
import ArgumentParser
|
||||
import Foundation
|
||||
import Networking
|
||||
import StoreAPI
|
||||
import Persistence
|
||||
|
||||
struct Auth: AsyncParsableCommand {
|
||||
static var configuration: CommandConfiguration {
|
||||
return .init(
|
||||
commandName: "auth",
|
||||
abstract: "Authenticate with the App Store.",
|
||||
subcommands: [Login.self, Revoke.self],
|
||||
defaultSubcommand: nil
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
extension Auth {
|
||||
struct Login: AsyncParsableCommand {
|
||||
static var configuration: CommandConfiguration {
|
||||
return .init(abstract: "Login to the App Store.")
|
||||
}
|
||||
|
||||
@Option(name: [.short, .customLong("email")], help: "The email address for the Apple ID.")
|
||||
private var emailArgument: String?
|
||||
|
||||
@Option(name: [.short, .customLong("password")], help: "The password for the Apple ID.")
|
||||
private var passwordArgument: String?
|
||||
|
||||
@Option(name: [.customLong("auth-code")], help: "The 2FA code for the Apple ID.")
|
||||
private var authCodeArgument: String?
|
||||
|
||||
@Option(name: [.long], help: "The log level.")
|
||||
private var logLevel: LogLevel = .info
|
||||
|
||||
lazy var logger = ConsoleLogger(level: logLevel)
|
||||
}
|
||||
|
||||
struct Revoke: AsyncParsableCommand {
|
||||
static var configuration: CommandConfiguration {
|
||||
return .init(abstract: "Revoke your App Store credentials.")
|
||||
}
|
||||
|
||||
@Option(name: [.long], help: "The log level.")
|
||||
private var logLevel: LogLevel = .info
|
||||
|
||||
lazy var logger = ConsoleLogger(level: logLevel)
|
||||
}
|
||||
}
|
||||
|
||||
extension Auth.Login {
|
||||
private mutating func email() -> String {
|
||||
if let email = emailArgument {
|
||||
return email
|
||||
} else if let email = ProcessInfo.processInfo.environment["IPATOOL_EMAIL"] {
|
||||
return email
|
||||
} else if let email = String(validatingUTF8: UnsafePointer<CChar>(getpass(logger.compile("Enter Apple ID email: ", level: .warning)))) {
|
||||
return email
|
||||
} else {
|
||||
logger.log("An Apple ID email address is required.", level: .error)
|
||||
_exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
private mutating func password() -> String {
|
||||
if let password = passwordArgument {
|
||||
return password
|
||||
} else if let password = ProcessInfo.processInfo.environment["IPATOOL_PASSWORD"] {
|
||||
return password
|
||||
} else if let password = String(validatingUTF8: UnsafePointer<CChar>(getpass(logger.compile("Enter Apple ID password: ", level: .warning)))) {
|
||||
return password
|
||||
} else {
|
||||
logger.log("An Apple ID password is required.", level: .error)
|
||||
_exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
private mutating func authCode() -> String {
|
||||
if let authCode = authCodeArgument {
|
||||
return authCode
|
||||
} else if let authCode = ProcessInfo.processInfo.environment["IPATOOL_2FA_CODE"] {
|
||||
return authCode
|
||||
} else if let authCode = String(validatingUTF8: UnsafePointer<CChar>(getpass(logger.compile("Enter 2FA code: ", level: .warning)))) {
|
||||
return authCode
|
||||
} else {
|
||||
logger.log("A 2FA auth-code is required.", level: .error)
|
||||
_exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
private mutating func authenticate(email: String, password: String) async -> Account {
|
||||
logger.log("Creating HTTP client...", level: .debug)
|
||||
let httpClient = HTTPClient(session: URLSession.shared)
|
||||
|
||||
logger.log("Creating App Store client...", level: .debug)
|
||||
let storeClient = StoreClient(httpClient: httpClient)
|
||||
|
||||
do {
|
||||
logger.log("Authenticating with the App Store...", level: .info)
|
||||
let account = try await storeClient.authenticate(email: email, password: password, code: nil)
|
||||
return Account(
|
||||
name: "\(account.firstName) \(account.lastName)",
|
||||
email: email,
|
||||
passwordToken: account.passwordToken,
|
||||
directoryServicesIdentifier: account.directoryServicesIdentifier
|
||||
)
|
||||
} catch {
|
||||
switch error {
|
||||
case StoreResponse.Error.codeRequired:
|
||||
do {
|
||||
let account = try await storeClient.authenticate(email: email, password: password, code: authCode())
|
||||
return Account(
|
||||
name: "\(account.firstName) \(account.lastName)",
|
||||
email: email,
|
||||
passwordToken: account.passwordToken,
|
||||
directoryServicesIdentifier: account.directoryServicesIdentifier
|
||||
)
|
||||
} catch {
|
||||
logger.log("\(error)", level: .debug)
|
||||
|
||||
switch error {
|
||||
case StoreClient.Error.invalidResponse:
|
||||
logger.log("Received invalid response.", level: .error)
|
||||
case StoreResponse.Error.invalidAccount:
|
||||
logger.log("This Apple ID has not been set up to use the App Store.", level: .error)
|
||||
case StoreResponse.Error.invalidCredentials:
|
||||
logger.log("Invalid credentials.", level: .error)
|
||||
case StoreResponse.Error.lockedAccount:
|
||||
logger.log("This Apple ID has been disabled for security reasons.", level: .error)
|
||||
default:
|
||||
logger.log("An unknown error has occurred.", level: .error)
|
||||
}
|
||||
|
||||
_exit(1)
|
||||
}
|
||||
default:
|
||||
logger.log("\(error)", level: .debug)
|
||||
|
||||
switch error {
|
||||
case StoreClient.Error.invalidResponse:
|
||||
logger.log("Received invalid response.", level: .error)
|
||||
case StoreResponse.Error.invalidAccount:
|
||||
logger.log("This Apple ID has not been set up to use the App Store.", level: .error)
|
||||
case StoreResponse.Error.invalidCredentials:
|
||||
logger.log("Invalid credentials.", level: .error)
|
||||
case StoreResponse.Error.lockedAccount:
|
||||
logger.log("This Apple ID has been disabled for security reasons.", level: .error)
|
||||
default:
|
||||
logger.log("An unknown error has occurred.", level: .error)
|
||||
}
|
||||
|
||||
_exit(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mutating func run() async throws {
|
||||
// Get Apple ID email
|
||||
let email: String = email()
|
||||
|
||||
// Get Apple ID password
|
||||
let password: String = password()
|
||||
|
||||
// Authenticate with the App Store
|
||||
let account: Account = await authenticate(email: email, password: password)
|
||||
|
||||
// Store data in keychain
|
||||
do {
|
||||
let keychainStore = KeychainStore(service: "ipatool.service")
|
||||
try keychainStore.setValue(account, forKey: "account")
|
||||
|
||||
logger.log("Authenticated as '\(account.name)'.", level: .info)
|
||||
} catch {
|
||||
logger.log("Failed to save account data in keychain.", level: .error)
|
||||
logger.log("\(error)", level: .debug)
|
||||
|
||||
_exit(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Auth.Revoke {
|
||||
mutating func run() async throws {
|
||||
let keychainStore = KeychainStore(service: "ipatool.service")
|
||||
|
||||
guard let account: Account = try keychainStore.value(forKey: "account") else {
|
||||
logger.log("No credentials available to revoke.", level: .error)
|
||||
_exit(1)
|
||||
}
|
||||
|
||||
try keychainStore.remove("account")
|
||||
logger.log("Revoked credentials for '\(account.name)'.", level: .info)
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import ArgumentParser
|
||||
import Foundation
|
||||
import Networking
|
||||
import StoreAPI
|
||||
import Persistence
|
||||
|
||||
struct Download: AsyncParsableCommand {
|
||||
static var configuration: CommandConfiguration {
|
||||
@@ -18,17 +19,11 @@ struct Download: AsyncParsableCommand {
|
||||
@Option(name: [.short, .long], help: "The bundle identifier of the target iOS app.")
|
||||
private var bundleIdentifier: String
|
||||
|
||||
@Option(name: [.short, .customLong("email")], help: "The email address for the Apple ID.")
|
||||
private var emailArgument: String?
|
||||
|
||||
@Option(name: [.short, .customLong("password")], help: "The password for the Apple ID.")
|
||||
private var passwordArgument: String?
|
||||
|
||||
@Option(name: [.customLong("auth-code")], help: "The 2FA code for the Apple ID.")
|
||||
private var authCodeArgument: String?
|
||||
|
||||
@Option(name: [.short, .long], help: "The two-letter (ISO 3166-1 alpha-2) country code for the iTunes Store.")
|
||||
private var country: String = "US"
|
||||
@Option(
|
||||
name: [.customShort("c"), .customLong("country")],
|
||||
help: "The two-letter (ISO 3166-1 alpha-2) country code for the iTunes Store."
|
||||
)
|
||||
private var countryCode: String = "US"
|
||||
|
||||
@Option(name: [.short, .long], help: "The device family to limit the search query to.")
|
||||
private var deviceFamily: DeviceFamily = .phone
|
||||
@@ -39,11 +34,14 @@ struct Download: AsyncParsableCommand {
|
||||
@Option(name: [.long], help: "The log level.")
|
||||
private var logLevel: LogLevel = .info
|
||||
|
||||
@Flag(name: .long, help: "Obtain a license for the app if needed.")
|
||||
private var purchase: Bool = false
|
||||
|
||||
lazy var logger = ConsoleLogger(level: logLevel)
|
||||
}
|
||||
|
||||
extension Download {
|
||||
private mutating func app(with bundleIdentifier: String, country: String) async -> iTunesResponse.Result {
|
||||
private mutating func app(with bundleIdentifier: String, countryCode: String) async -> iTunesResponse.Result {
|
||||
logger.log("Creating HTTP client...", level: .debug)
|
||||
let httpClient = HTTPClient(session: URLSession.shared)
|
||||
|
||||
@@ -51,10 +49,10 @@ extension Download {
|
||||
let itunesClient = iTunesClient(httpClient: httpClient)
|
||||
|
||||
do {
|
||||
logger.log("Querying the iTunes Store for '\(bundleIdentifier)' in country '\(country)'...", level: .info)
|
||||
logger.log("Querying the iTunes Store for '\(bundleIdentifier)' in country '\(countryCode)'...", level: .info)
|
||||
return try await itunesClient.lookup(
|
||||
bundleIdentifier: bundleIdentifier,
|
||||
country: country,
|
||||
countryCode: countryCode,
|
||||
deviceFamily: deviceFamily
|
||||
)
|
||||
} catch {
|
||||
@@ -70,47 +68,14 @@ extension Download {
|
||||
_exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
private mutating func email() -> String {
|
||||
if let email = emailArgument {
|
||||
return email
|
||||
} else if let email = ProcessInfo.processInfo.environment["IPATOOL_EMAIL"] {
|
||||
return email
|
||||
} else if let email = String(validatingUTF8: UnsafePointer<CChar>(getpass(logger.compile("Enter Apple ID email: ", level: .warning)))) {
|
||||
return email
|
||||
} else {
|
||||
logger.log("An Apple ID email address is required.", level: .error)
|
||||
_exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
private mutating func password() -> String {
|
||||
if let password = passwordArgument {
|
||||
return password
|
||||
} else if let password = ProcessInfo.processInfo.environment["IPATOOL_PASSWORD"] {
|
||||
return password
|
||||
} else if let password = String(validatingUTF8: UnsafePointer<CChar>(getpass(logger.compile("Enter Apple ID password: ", level: .warning)))) {
|
||||
return password
|
||||
} else {
|
||||
logger.log("An Apple ID password is required.", level: .error)
|
||||
_exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
private mutating func authCode() -> String {
|
||||
if let authCode = authCodeArgument {
|
||||
return authCode
|
||||
} else if let authCode = ProcessInfo.processInfo.environment["IPATOOL_2FA_CODE"] {
|
||||
return authCode
|
||||
} else if let authCode = String(validatingUTF8: UnsafePointer<CChar>(getpass(logger.compile("Enter 2FA code: ", level: .warning)))) {
|
||||
return authCode
|
||||
} else {
|
||||
logger.log("A 2FA auth-code is required.", level: .error)
|
||||
|
||||
private mutating func purchase(app: iTunesResponse.Result, account: Account) async {
|
||||
guard app.price == 0 else {
|
||||
logger.log("It is only possible to obtain a license for free apps. Purchase the app manually and run the \"download\" command again.", level: .error)
|
||||
_exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
private mutating func authenticate(email: String, password: String) async -> StoreResponse.Account {
|
||||
logger.log("Creating HTTP client...", level: .debug)
|
||||
let httpClient = HTTPClient(session: URLSession.shared)
|
||||
|
||||
@@ -118,56 +83,39 @@ extension Download {
|
||||
let storeClient = StoreClient(httpClient: httpClient)
|
||||
|
||||
do {
|
||||
logger.log("Authenticating with the App Store...", level: .info)
|
||||
return try await storeClient.authenticate(email: email, password: password, code: nil)
|
||||
logger.log("Obtaining a license for '\(app.identifier)' from the App Store...", level: .info)
|
||||
try await storeClient.purchase(
|
||||
identifier: "\(app.identifier)",
|
||||
directoryServicesIdentifier: account.directoryServicesIdentifier,
|
||||
passwordToken: account.passwordToken,
|
||||
countryCode: countryCode
|
||||
)
|
||||
} catch {
|
||||
switch error {
|
||||
case StoreResponse.Error.codeRequired:
|
||||
do {
|
||||
return try await storeClient.authenticate(email: email, password: password, code: authCode())
|
||||
} catch {
|
||||
logger.log("\(error)", level: .debug)
|
||||
|
||||
switch error {
|
||||
case StoreClient.Error.invalidResponse:
|
||||
logger.log("Received invalid response.", level: .error)
|
||||
case StoreResponse.Error.invalidAccount:
|
||||
logger.log("This Apple ID has not been set up to use the App Store.", level: .error)
|
||||
case StoreResponse.Error.invalidCredentials:
|
||||
logger.log("Invalid credentials.", level: .error)
|
||||
case StoreResponse.Error.lockedAccount:
|
||||
logger.log("This Apple ID has been disabled for security reasons.", level: .error)
|
||||
default:
|
||||
logger.log("An unknown error has occurred.", level: .error)
|
||||
}
|
||||
|
||||
_exit(1)
|
||||
}
|
||||
default:
|
||||
logger.log("\(error)", level: .debug)
|
||||
|
||||
switch error {
|
||||
case StoreClient.Error.invalidResponse:
|
||||
logger.log("Received invalid response.", level: .error)
|
||||
case StoreResponse.Error.invalidAccount:
|
||||
logger.log("This Apple ID has not been set up to use the App Store.", level: .error)
|
||||
case StoreResponse.Error.invalidCredentials:
|
||||
logger.log("Invalid credentials.", level: .error)
|
||||
case StoreResponse.Error.lockedAccount:
|
||||
logger.log("This Apple ID has been disabled for security reasons.", level: .error)
|
||||
default:
|
||||
logger.log("An unknown error has occurred.", level: .error)
|
||||
}
|
||||
|
||||
_exit(1)
|
||||
}
|
||||
}
|
||||
logger.log("\(error)", level: .debug)
|
||||
|
||||
switch error {
|
||||
case StoreClient.Error.purchaseFailed:
|
||||
logger.log("Purchase failed.", level: .error)
|
||||
case StoreClient.Error.duplicateLicense:
|
||||
logger.log("A license already exists for this item.", level: .error)
|
||||
case StoreResponse.Error.priceMismatch:
|
||||
logger.log("Pirce mismatch. It is only possible to obtain a license for free apps.", level: .error)
|
||||
case StoreResponse.Error.invalidCountry:
|
||||
logger.log("The country provided does not match with the account you are using. Supply a valid country using the \"--country\" flag.", level: .error)
|
||||
case StoreResponse.Error.passwordTokenExpired:
|
||||
logger.log("Token expired. Login again using the \"auth\" command.", level: .error)
|
||||
default:
|
||||
logger.log("An unknown error has occurred.", level: .error)
|
||||
}
|
||||
|
||||
_exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private mutating func item(
|
||||
from app: iTunesResponse.Result,
|
||||
account: StoreResponse.Account
|
||||
account: Account,
|
||||
purchaseAttempted: Bool = false
|
||||
) async -> StoreResponse.Item {
|
||||
logger.log("Creating HTTP client...", level: .debug)
|
||||
let httpClient = HTTPClient(session: URLSession.shared)
|
||||
@@ -190,7 +138,20 @@ extension Download {
|
||||
case StoreResponse.Error.invalidItem:
|
||||
logger.log("Received invalid store item.", level: .error)
|
||||
case StoreResponse.Error.invalidLicense:
|
||||
logger.log("Your Apple ID does not have a license for this app. Download the app on an iOS device to obtain a license.", level: .error)
|
||||
if !purchaseAttempted, purchase {
|
||||
logger.log("License is missing.", level: .info)
|
||||
|
||||
await purchase(app: app, account: account)
|
||||
logger.log("Obtained a license for '\(app.identifier)'.", level: .debug)
|
||||
|
||||
return await item(from: app, account: account, purchaseAttempted: true)
|
||||
} else {
|
||||
logger.log("Your Apple ID does not have a license for this app. Use the \"purchase\" command or the \"--purchase\" to obtain a license.", level: .error)
|
||||
}
|
||||
case StoreResponse.Error.invalidCountry:
|
||||
logger.log("The country provided does not match with the account you are using. Supply a valid country using the \"--country\" flag.", level: .error)
|
||||
case StoreResponse.Error.passwordTokenExpired:
|
||||
logger.log("Token expired. Login again using the \"auth\" command.", level: .error)
|
||||
default:
|
||||
logger.log("An unknown error has occurred.", level: .error)
|
||||
}
|
||||
@@ -256,19 +217,18 @@ extension Download {
|
||||
}
|
||||
|
||||
mutating func run() async throws {
|
||||
// Query for app
|
||||
let app: iTunesResponse.Result = await app(with: bundleIdentifier, country: country)
|
||||
logger.log("Found app: \(app.name) (\(app.version)).", level: .debug)
|
||||
|
||||
// Get Apple ID email
|
||||
let email: String = email()
|
||||
|
||||
// Get Apple ID password
|
||||
let password: String = password()
|
||||
|
||||
// Authenticate with the App Store
|
||||
let account: StoreResponse.Account = await authenticate(email: email, password: password)
|
||||
logger.log("Authenticated as '\(account.firstName) \(account.lastName)'.", level: .info)
|
||||
let keychainStore = KeychainStore(service: "ipatool.service")
|
||||
|
||||
guard let account: Account = try keychainStore.value(forKey: "account") else {
|
||||
logger.log("Authentication required. Run \"ipatool auth --help\" for help.", level: .error)
|
||||
_exit(1)
|
||||
}
|
||||
logger.log("Authenticated as '\(account.name)'.", level: .info)
|
||||
|
||||
// Query for app
|
||||
let app: iTunesResponse.Result = await app(with: bundleIdentifier, countryCode: countryCode)
|
||||
logger.log("Found app: \(app.name) (\(app.version)).", level: .debug)
|
||||
|
||||
// Query for store item
|
||||
let item: StoreResponse.Item = await item(from: app, account: account)
|
||||
@@ -283,7 +243,7 @@ extension Download {
|
||||
logger.log("Saved app package to \(URL(fileURLWithPath: path).lastPathComponent).", level: .info)
|
||||
|
||||
// Apply patches
|
||||
applyPatches(item: item, email: email, path: path)
|
||||
applyPatches(item: item, email: account.email, path: path)
|
||||
logger.log("Done.", level: .info)
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,7 @@ struct IPATool: ParsableCommand {
|
||||
commandName: "ipatool",
|
||||
abstract: "A cli tool for interacting with Apple's ipa files.",
|
||||
version: Package.version,
|
||||
subcommands: [Download.self, Search.self]
|
||||
subcommands: [Auth.self, Download.self, Purchase.self, Search.self]
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
//
|
||||
// Purchase.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.03.22.
|
||||
//
|
||||
|
||||
import ArgumentParser
|
||||
import Foundation
|
||||
import Networking
|
||||
import StoreAPI
|
||||
import Persistence
|
||||
|
||||
struct Purchase: AsyncParsableCommand {
|
||||
static var configuration: CommandConfiguration {
|
||||
return .init(abstract: "Obtain a license for the app from the App Store.")
|
||||
}
|
||||
|
||||
@Option(name: [.short, .long], help: "The bundle identifier of the target iOS app.")
|
||||
private var bundleIdentifier: String
|
||||
|
||||
@Option(
|
||||
name: [.customShort("c"), .customLong("country")],
|
||||
help: "The two-letter (ISO 3166-1 alpha-2) country code for the iTunes Store."
|
||||
)
|
||||
private var countryCode: String = "US"
|
||||
|
||||
@Option(name: [.short, .long], help: "The device family to limit the search query to.")
|
||||
private var deviceFamily: DeviceFamily = .phone
|
||||
|
||||
@Option(name: [.long], help: "The log level.")
|
||||
private var logLevel: LogLevel = .info
|
||||
|
||||
lazy var logger = ConsoleLogger(level: logLevel)
|
||||
}
|
||||
|
||||
extension Purchase {
|
||||
private mutating func app(with bundleIdentifier: String) async -> iTunesResponse.Result {
|
||||
logger.log("Creating HTTP client...", level: .debug)
|
||||
let httpClient = HTTPClient(session: URLSession.shared)
|
||||
|
||||
logger.log("Creating iTunes client...", level: .debug)
|
||||
let itunesClient = iTunesClient(httpClient: httpClient)
|
||||
|
||||
do {
|
||||
logger.log("Querying the iTunes Store for '\(bundleIdentifier)' in country '\(countryCode)'...", level: .info)
|
||||
let app = try await itunesClient.lookup(
|
||||
bundleIdentifier: bundleIdentifier,
|
||||
countryCode: countryCode,
|
||||
deviceFamily: deviceFamily
|
||||
)
|
||||
|
||||
guard app.price == 0 else {
|
||||
logger.log("Only free apps are supported.", level: .error)
|
||||
_exit(1)
|
||||
}
|
||||
|
||||
return app
|
||||
} catch {
|
||||
logger.log("\(error)", level: .debug)
|
||||
|
||||
switch error {
|
||||
case iTunesClient.Error.appNotFound:
|
||||
logger.log("Could not find app.", level: .error)
|
||||
default:
|
||||
logger.log("An unknown error has occurred.", level: .error)
|
||||
}
|
||||
|
||||
_exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
private mutating func purchase(app: iTunesResponse.Result, account: Account) async {
|
||||
logger.log("Creating HTTP client...", level: .debug)
|
||||
let httpClient = HTTPClient(session: URLSession.shared)
|
||||
|
||||
logger.log("Creating App Store client...", level: .debug)
|
||||
let storeClient = StoreClient(httpClient: httpClient)
|
||||
|
||||
do {
|
||||
logger.log("Obtaining a license for '\(app.identifier)' from the App Store...", level: .info)
|
||||
try await storeClient.purchase(
|
||||
identifier: "\(app.identifier)",
|
||||
directoryServicesIdentifier: account.directoryServicesIdentifier,
|
||||
passwordToken: account.passwordToken,
|
||||
countryCode: countryCode
|
||||
)
|
||||
} catch {
|
||||
logger.log("\(error)", level: .debug)
|
||||
|
||||
switch error {
|
||||
case StoreClient.Error.purchaseFailed:
|
||||
logger.log("Purchase failed.", level: .error)
|
||||
case StoreClient.Error.duplicateLicense:
|
||||
logger.log("A license already exists for this item.", level: .error)
|
||||
case StoreResponse.Error.priceMismatch:
|
||||
logger.log("Pirce mismatch. It is only possible to obtain a license for free apps.", level: .error)
|
||||
case StoreResponse.Error.invalidCountry:
|
||||
logger.log("The country provided does not match with the account you are using. Supply a valid country using the \"--country\" flag.", level: .error)
|
||||
case StoreResponse.Error.passwordTokenExpired:
|
||||
logger.log("Token expired. Login again using the \"auth\" command.", level: .error)
|
||||
default:
|
||||
logger.log("An unknown error has occurred.", level: .error)
|
||||
}
|
||||
|
||||
_exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
mutating func run() async throws {
|
||||
// Authenticate with the App Store
|
||||
let keychainStore = KeychainStore(service: "ipatool.service")
|
||||
|
||||
guard let account: Account = try keychainStore.value(forKey: "account") else {
|
||||
logger.log("Authentication required. Run \"ipatool auth --help\" for help.", level: .error)
|
||||
_exit(1)
|
||||
}
|
||||
logger.log("Authenticated as '\(account.name)'.", level: .info)
|
||||
|
||||
// Query for app
|
||||
let app: iTunesResponse.Result = await app(with: bundleIdentifier)
|
||||
logger.log("Found app: \(app.name) (\(app.version)).", level: .debug)
|
||||
|
||||
// Obtain a license
|
||||
await purchase(app: app, account: account)
|
||||
logger.log("Obtained a license for '\(app.identifier)'.", level: .debug)
|
||||
logger.log("Done.", level: .info)
|
||||
}
|
||||
}
|
||||
@@ -21,8 +21,11 @@ struct Search: AsyncParsableCommand {
|
||||
@Option(name: [.short, .long], help: "The maximum amount of search results to retrieve.")
|
||||
private var limit: Int = 5
|
||||
|
||||
@Option(name: [.short, .long], help: "The two-letter (ISO 3166-1 alpha-2) country code for the iTunes Store.")
|
||||
private var country: String = "US"
|
||||
@Option(
|
||||
name: [.customShort("c"), .customLong("country")],
|
||||
help: "The two-letter (ISO 3166-1 alpha-2) country code for the iTunes Store."
|
||||
)
|
||||
private var countryCode: String = "US"
|
||||
|
||||
@Option(name: [.short, .long], help: "The device family to limit the search query to.")
|
||||
private var deviceFamily: DeviceFamily = .phone
|
||||
@@ -34,20 +37,20 @@ struct Search: AsyncParsableCommand {
|
||||
}
|
||||
|
||||
extension Search {
|
||||
mutating func results(with term: String, country: String) async -> [iTunesResponse.Result] {
|
||||
mutating func results(with term: String) async -> [iTunesResponse.Result] {
|
||||
logger.log("Creating HTTP client...", level: .debug)
|
||||
let httpClient = HTTPClient(session: URLSession.shared)
|
||||
|
||||
logger.log("Creating iTunes client...", level: .debug)
|
||||
let itunesClient = iTunesClient(httpClient: httpClient)
|
||||
|
||||
logger.log("Searching for '\(term)' using the '\(country)' store front...", level: .info)
|
||||
logger.log("Searching for '\(term)' using the '\(countryCode)' store front...", level: .info)
|
||||
|
||||
do {
|
||||
let results = try await itunesClient.search(
|
||||
term: term,
|
||||
limit: limit,
|
||||
country: country,
|
||||
countryCode: countryCode,
|
||||
deviceFamily: deviceFamily
|
||||
)
|
||||
|
||||
@@ -66,7 +69,7 @@ extension Search {
|
||||
|
||||
mutating func run() async throws {
|
||||
// Search the iTunes store
|
||||
let results = await results(with: term, country: country)
|
||||
let results = await results(with: term)
|
||||
|
||||
// Compile output
|
||||
let output = results
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
//
|
||||
// Account.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 21.03.22.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
struct Account: Codable {
|
||||
let name: String
|
||||
let email: String
|
||||
let passwordToken: String
|
||||
let directoryServicesIdentifier: String
|
||||
}
|
||||
@@ -8,8 +8,8 @@
|
||||
import Foundation
|
||||
|
||||
public struct HTTPResponse {
|
||||
let statusCode: Int
|
||||
let data: Data?
|
||||
public let statusCode: Int
|
||||
public let data: Data?
|
||||
}
|
||||
|
||||
extension HTTPResponse {
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
//
|
||||
// KeychainStore.swift
|
||||
// Persistence
|
||||
//
|
||||
// Created by Majd Alfhaily on 21.03.22.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import KeychainAccess
|
||||
|
||||
public protocol KeychainStoreInterface {
|
||||
func value<T: Codable>(forKey itemKey: String) throws -> T?
|
||||
func setValue<T: Codable>(_ item: T, forKey itemKey: String) throws
|
||||
func remove(_ key: String) throws
|
||||
}
|
||||
|
||||
public class KeychainStore: KeychainStoreInterface {
|
||||
private let keychain: Keychain
|
||||
|
||||
public init(service: String) {
|
||||
self.keychain = Keychain(service: service)
|
||||
}
|
||||
|
||||
public func value<T: Codable>(forKey itemKey: String) throws -> T? {
|
||||
guard let data = try keychain.getData(itemKey) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
return try JSONDecoder().decode(T.self, from: data)
|
||||
}
|
||||
|
||||
public func setValue<T: Codable>(_ item: T, forKey itemKey: String) throws {
|
||||
let data = try JSONEncoder().encode(item)
|
||||
try keychain.set(data, key: itemKey)
|
||||
}
|
||||
|
||||
public func remove(_ key: String) throws {
|
||||
try keychain.remove(key)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
//
|
||||
// Storefront.swift
|
||||
// StoreAPI
|
||||
//
|
||||
// Created by Benjamin Altpeter on 20.03.22.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
// https://web.archive.org/web/20191206001952/https://affiliate.itunes.apple.com/resources/documentation/linking-to-the-itunes-music-store
|
||||
public enum Storefront: String, CaseIterable {
|
||||
case AE = "143481"
|
||||
case AG = "143540"
|
||||
case AI = "143538"
|
||||
case AM = "143524"
|
||||
case AO = "143564"
|
||||
case AR = "143505"
|
||||
case AT = "143445"
|
||||
case AU = "143460"
|
||||
case AZ = "143568"
|
||||
case BB = "143541"
|
||||
case BD = "143490"
|
||||
case BE = "143446"
|
||||
case BG = "143526"
|
||||
case BH = "143559"
|
||||
case BM = "143542"
|
||||
case BN = "143560"
|
||||
case BO = "143556"
|
||||
case BR = "143503"
|
||||
case BS = "143539"
|
||||
case BW = "143525"
|
||||
case BY = "143565"
|
||||
case BZ = "143555"
|
||||
case CA = "143455"
|
||||
case CH = "143459"
|
||||
case CI = "143527"
|
||||
case CL = "143483"
|
||||
case CN = "143465"
|
||||
case CO = "143501"
|
||||
case CR = "143495"
|
||||
case CY = "143557"
|
||||
case CZ = "143489"
|
||||
case DE = "143443"
|
||||
case DK = "143458"
|
||||
case DM = "143545"
|
||||
case DO = "143508"
|
||||
case DZ = "143563"
|
||||
case EC = "143509"
|
||||
case EE = "143518"
|
||||
case EG = "143516"
|
||||
case ES = "143454"
|
||||
case FI = "143447"
|
||||
case FR = "143442"
|
||||
case GB = "143444"
|
||||
case GD = "143546"
|
||||
case GH = "143573"
|
||||
case GR = "143448"
|
||||
case GT = "143504"
|
||||
case GY = "143553"
|
||||
case HK = "143463"
|
||||
case HN = "143510"
|
||||
case HR = "143494"
|
||||
case HU = "143482"
|
||||
case ID = "143476"
|
||||
case IE = "143449"
|
||||
case IL = "143491"
|
||||
case IN = "143467"
|
||||
case IS = "143558"
|
||||
case IT = "143450"
|
||||
case JM = "143511"
|
||||
case JO = "143528"
|
||||
case JP = "143462"
|
||||
case KE = "143529"
|
||||
case KN = "143548"
|
||||
case KR = "143466"
|
||||
case KW = "143493"
|
||||
case KY = "143544"
|
||||
case KZ = "143517"
|
||||
case LB = "143497"
|
||||
case LC = "143549"
|
||||
case LI = "143522"
|
||||
case LK = "143486"
|
||||
case LT = "143520"
|
||||
case LU = "143451"
|
||||
case LV = "143519"
|
||||
case MD = "143523"
|
||||
case MG = "143531"
|
||||
case MK = "143530"
|
||||
case ML = "143532"
|
||||
case MO = "143515"
|
||||
case MS = "143547"
|
||||
case MT = "143521"
|
||||
case MU = "143533"
|
||||
case MV = "143488"
|
||||
case MX = "143468"
|
||||
case MY = "143473"
|
||||
case NE = "143534"
|
||||
case NG = "143561"
|
||||
case NI = "143512"
|
||||
case NL = "143452"
|
||||
case NO = "143457"
|
||||
case NP = "143484"
|
||||
case NZ = "143461"
|
||||
case OM = "143562"
|
||||
case PA = "143485"
|
||||
case PE = "143507"
|
||||
case PH = "143474"
|
||||
case PK = "143477"
|
||||
case PL = "143478"
|
||||
case PT = "143453"
|
||||
case PY = "143513"
|
||||
case QA = "143498"
|
||||
case RO = "143487"
|
||||
case RS = "143500"
|
||||
case RU = "143469"
|
||||
case SA = "143479"
|
||||
case SE = "143456"
|
||||
case SG = "143464"
|
||||
case SI = "143499"
|
||||
case SK = "143496"
|
||||
case SN = "143535"
|
||||
case SR = "143554"
|
||||
case SV = "143506"
|
||||
case TC = "143552"
|
||||
case TH = "143475"
|
||||
case TN = "143536"
|
||||
case TR = "143480"
|
||||
case TT = "143551"
|
||||
case TW = "143470"
|
||||
case TZ = "143572"
|
||||
case UA = "143492"
|
||||
case UG = "143537"
|
||||
case US = "143441"
|
||||
case UY = "143514"
|
||||
case UZ = "143566"
|
||||
case VC = "143550"
|
||||
case VE = "143502"
|
||||
case VG = "143543"
|
||||
case VN = "143471"
|
||||
case YE = "143571"
|
||||
case ZA = "143472"
|
||||
|
||||
init?(countryCode: String) {
|
||||
guard let value = Storefront.allCases.first(where: { "\($0)" == countryCode }) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
self = value
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,12 @@ import Networking
|
||||
public protocol StoreClientInterface {
|
||||
func authenticate(email: String, password: String, code: String?) async throws -> StoreResponse.Account
|
||||
func item(identifier: String, directoryServicesIdentifier: String) async throws -> StoreResponse.Item
|
||||
func purchase(
|
||||
identifier: String,
|
||||
directoryServicesIdentifier: String,
|
||||
passwordToken: String,
|
||||
countryCode: String
|
||||
) async throws
|
||||
}
|
||||
|
||||
public final class StoreClient: StoreClientInterface {
|
||||
@@ -30,15 +36,50 @@ public final class StoreClient: StoreClientInterface {
|
||||
directoryServicesIdentifier: directoryServicesIdentifier
|
||||
)
|
||||
let response = try await httpClient.send(request)
|
||||
let decoded = try response.decode(StoreResponse.self, as: .xml)
|
||||
let storeResponse = try response.decode(StoreResponse.self, as: .xml)
|
||||
|
||||
switch decoded {
|
||||
switch storeResponse {
|
||||
case let .item(item):
|
||||
return item
|
||||
case .account:
|
||||
throw Error.invalidResponse
|
||||
case let .failure(error):
|
||||
throw error
|
||||
default:
|
||||
throw Error.invalidResponse
|
||||
}
|
||||
}
|
||||
|
||||
public func purchase(
|
||||
identifier: String,
|
||||
directoryServicesIdentifier: String,
|
||||
passwordToken: String,
|
||||
countryCode: String
|
||||
) async throws {
|
||||
let request = StoreRequest.purchase(
|
||||
appIdentifier: identifier,
|
||||
directoryServicesIdentifier: directoryServicesIdentifier,
|
||||
passwordToken: passwordToken,
|
||||
countryCode: countryCode
|
||||
)
|
||||
|
||||
let response = try await httpClient.send(request)
|
||||
|
||||
// Returns status code 500 if the Apple ID already contains a license
|
||||
switch response.statusCode {
|
||||
case 500:
|
||||
throw Error.duplicateLicense
|
||||
default:
|
||||
let response = try response.decode(StoreResponse.self, as: .xml)
|
||||
|
||||
switch response {
|
||||
case let .purchase(receipt):
|
||||
guard receipt.statusCode == 0, receipt.status == .success else {
|
||||
throw Error.purchaseFailed
|
||||
}
|
||||
case let .failure(error):
|
||||
throw error
|
||||
default:
|
||||
throw Error.invalidResponse
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,8 +94,6 @@ public final class StoreClient: StoreClientInterface {
|
||||
switch decoded {
|
||||
case let .account(account):
|
||||
return account
|
||||
case .item:
|
||||
throw Error.invalidResponse
|
||||
case let .failure(error):
|
||||
switch error {
|
||||
case StoreResponse.Error.invalidCredentials:
|
||||
@@ -66,6 +105,8 @@ public final class StoreClient: StoreClientInterface {
|
||||
default:
|
||||
throw error
|
||||
}
|
||||
default:
|
||||
throw Error.invalidResponse
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -74,5 +115,7 @@ extension StoreClient {
|
||||
public enum Error: Swift.Error {
|
||||
case timeout
|
||||
case invalidResponse
|
||||
case purchaseFailed
|
||||
case duplicateLicense
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import Networking
|
||||
enum StoreEndpoint {
|
||||
case authenticate(prefix: String, guid: String)
|
||||
case download(guid: String)
|
||||
case purchase
|
||||
}
|
||||
|
||||
extension StoreEndpoint: HTTPEndpoint {
|
||||
@@ -27,6 +28,8 @@ extension StoreEndpoint: HTTPEndpoint {
|
||||
return "\(prefix)-buy.itunes.apple.com"
|
||||
case .download:
|
||||
return "p25-buy.itunes.apple.com"
|
||||
case .purchase:
|
||||
return "buy.itunes.apple.com"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,6 +39,8 @@ extension StoreEndpoint: HTTPEndpoint {
|
||||
return "/WebObjects/MZFinance.woa/wa/authenticate?guid=\(guid)"
|
||||
case let .download(guid):
|
||||
return "/WebObjects/MZFinance.woa/wa/volumeStoreDownloadProduct?guid=\(guid)"
|
||||
case .purchase:
|
||||
return "/WebObjects/MZBuy.woa/wa/buyProduct"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,12 @@ import Networking
|
||||
enum StoreRequest {
|
||||
case authenticate(email: String, password: String, code: String? = nil)
|
||||
case download(appIdentifier: String, directoryServicesIdentifier: String)
|
||||
case purchase(
|
||||
appIdentifier: String,
|
||||
directoryServicesIdentifier: String,
|
||||
passwordToken: String,
|
||||
countryCode: String
|
||||
)
|
||||
}
|
||||
|
||||
extension StoreRequest: HTTPRequest {
|
||||
@@ -20,6 +26,8 @@ extension StoreRequest: HTTPRequest {
|
||||
return StoreEndpoint.authenticate(prefix: (code == nil) ? "p25" : "p71", guid: guid)
|
||||
case .download:
|
||||
return StoreEndpoint.download(guid: guid)
|
||||
case .purchase:
|
||||
return StoreEndpoint.purchase
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,6 +47,12 @@ extension StoreRequest: HTTPRequest {
|
||||
case let .download(_, directoryServicesIdentifier):
|
||||
headers["X-Dsid"] = directoryServicesIdentifier
|
||||
headers["iCloud-DSID"] = directoryServicesIdentifier
|
||||
case let .purchase(_, directoryServicesIdentifier, passwordToken, countryCode):
|
||||
headers["X-Dsid"] = directoryServicesIdentifier
|
||||
headers["iCloud-DSID"] = directoryServicesIdentifier
|
||||
headers["Content-Type"] = "application/x-apple-plist"
|
||||
headers["X-Apple-Store-Front"] = Storefront(countryCode: countryCode)?.rawValue
|
||||
headers["X-Token"] = passwordToken
|
||||
}
|
||||
|
||||
return headers
|
||||
@@ -62,6 +76,21 @@ extension StoreRequest: HTTPRequest {
|
||||
"guid": guid,
|
||||
"salableAdamId": "\(appIdentifier)"
|
||||
])
|
||||
case let .purchase(appIdentifier, _, _, _):
|
||||
return .xml([
|
||||
"appExtVrsId": "0",
|
||||
"hasAskedToFulfillPreorder": "true",
|
||||
"buyWithoutAuthorization": "true",
|
||||
"hasDoneAgeCheck": "true",
|
||||
"guid": guid,
|
||||
"needDiv": "0",
|
||||
"origPage": "Software-" + appIdentifier,
|
||||
"origPageLocation": "Buy",
|
||||
"price": "0",
|
||||
"pricingParameters": "STDQ",
|
||||
"productType": "C",
|
||||
"salableAdamId": appIdentifier
|
||||
])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,21 +11,7 @@ public enum StoreResponse {
|
||||
case failure(error: Swift.Error)
|
||||
case account(Account)
|
||||
case item(Item)
|
||||
}
|
||||
|
||||
extension StoreResponse {
|
||||
public struct Account {
|
||||
public let firstName: String
|
||||
public let lastName: String
|
||||
public let directoryServicesIdentifier: String
|
||||
}
|
||||
|
||||
public struct Item {
|
||||
public let url: URL
|
||||
public let md5: String
|
||||
public let signatures: [Signature]
|
||||
public let metadata: [String: Any]
|
||||
}
|
||||
case purchase(Receipt)
|
||||
|
||||
public enum Error: Int, Swift.Error {
|
||||
case unknownError = 0
|
||||
@@ -36,6 +22,9 @@ extension StoreResponse {
|
||||
case invalidAccount = 5001
|
||||
case invalidItem = -10000
|
||||
case lockedAccount = -10001
|
||||
case invalidCountry = -128
|
||||
case passwordTokenExpired = 2034
|
||||
case priceMismatch = 2019
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,14 +37,27 @@ extension StoreResponse: Decodable {
|
||||
|
||||
if container.contains(.account) {
|
||||
let directoryServicesIdentifier = try container.decode(String.self, forKey: .directoryServicesIdentifier)
|
||||
let passwordToken = try container.decode(String.self, forKey: .passwordToken)
|
||||
let accountContainer = try container.nestedContainer(keyedBy: AccountInfoCodingKeys.self, forKey: .account)
|
||||
let addressContainer = try accountContainer.nestedContainer(keyedBy: AddressCodingKeys.self, forKey: .address)
|
||||
let firstName = try addressContainer.decode(String.self, forKey: .firstName)
|
||||
let lastName = try addressContainer.decode(String.self, forKey: .lastName)
|
||||
|
||||
self = .account(.init(firstName: firstName, lastName: lastName, directoryServicesIdentifier: directoryServicesIdentifier))
|
||||
self = .account(
|
||||
Account(
|
||||
firstName: firstName,
|
||||
lastName: lastName,
|
||||
directoryServicesIdentifier: directoryServicesIdentifier,
|
||||
passwordToken: passwordToken
|
||||
)
|
||||
)
|
||||
} else if let items = try container.decodeIfPresent([Item].self, forKey: .items), let item = items.first {
|
||||
self = .item(item)
|
||||
} else if container.contains(.statusCode) {
|
||||
let statusCode = try container.decode(Int.self, forKey: .statusCode)
|
||||
let statusType = try container.decode(String.self, forKey: .statusType)
|
||||
|
||||
self = .purchase(Receipt(statusCode: statusCode, status: Receipt.Status(rawValue: statusType)))
|
||||
} else if let error = error, !error.isEmpty {
|
||||
self = .failure(error: Error(rawValue: Int(error) ?? 0) ?? .unknownError)
|
||||
} else {
|
||||
@@ -76,10 +78,13 @@ extension StoreResponse: Decodable {
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case directoryServicesIdentifier = "dsPersonId"
|
||||
case passwordToken = "passwordToken"
|
||||
case message = "customerMessage"
|
||||
case items = "songList"
|
||||
case error = "failureType"
|
||||
case account = "accountInfo"
|
||||
case statusCode = "status"
|
||||
case statusType = "jingleDocType"
|
||||
}
|
||||
|
||||
private enum AccountInfoCodingKeys: String, CodingKey {
|
||||
@@ -92,42 +97,83 @@ extension StoreResponse: Decodable {
|
||||
}
|
||||
}
|
||||
|
||||
extension StoreResponse.Item: Decodable {
|
||||
public init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
let md5 = try container.decode(String.self, forKey: .md5)
|
||||
// MARK: - Account
|
||||
|
||||
guard let key = CodingUserInfoKey(rawValue: "data"),
|
||||
let data = decoder.userInfo[key] as? Data,
|
||||
let json = try PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [String: Any],
|
||||
let items = json["songList"] as? [[String: Any]],
|
||||
let item = items.first(where: { $0["md5"] as? String == md5 }),
|
||||
let metadata = item["metadata"] as? [String: Any]
|
||||
else { throw StoreResponse.Error.invalidItem }
|
||||
|
||||
let absoluteUrl = try container.decode(String.self, forKey: .url)
|
||||
|
||||
self.md5 = md5
|
||||
self.metadata = metadata
|
||||
self.signatures = try container.decode([Signature].self, forKey: .signatures)
|
||||
|
||||
if let url = URL(string: absoluteUrl) {
|
||||
self.url = url
|
||||
} else {
|
||||
let context = DecodingError.Context(codingPath: [CodingKeys.url], debugDescription: "URL contains illegal characters: \(absoluteUrl).")
|
||||
throw DecodingError.keyNotFound(CodingKeys.url, context)
|
||||
extension StoreResponse {
|
||||
public struct Account {
|
||||
public let firstName: String
|
||||
public let lastName: String
|
||||
public let directoryServicesIdentifier: String
|
||||
public let passwordToken: String
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Item
|
||||
|
||||
extension StoreResponse {
|
||||
public struct Item: Decodable {
|
||||
public let url: URL
|
||||
public let md5: String
|
||||
public let signatures: [Signature]
|
||||
public let metadata: [String: Any]
|
||||
|
||||
public init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
let md5 = try container.decode(String.self, forKey: .md5)
|
||||
|
||||
guard let key = CodingUserInfoKey(rawValue: "data"),
|
||||
let data = decoder.userInfo[key] as? Data,
|
||||
let json = try PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any],
|
||||
let items = json["songList"] as? [[String: Any]],
|
||||
let item = items.first(where: { $0["md5"] as? String == md5 }),
|
||||
let metadata = item["metadata"] as? [String: Any]
|
||||
else { throw StoreResponse.Error.invalidItem }
|
||||
|
||||
let absoluteUrl = try container.decode(String.self, forKey: .url)
|
||||
|
||||
self.md5 = md5
|
||||
self.metadata = metadata
|
||||
self.signatures = try container.decode([Signature].self, forKey: .signatures)
|
||||
|
||||
if let url = URL(string: absoluteUrl) {
|
||||
self.url = url
|
||||
} else {
|
||||
let context = DecodingError.Context(
|
||||
codingPath: [CodingKeys.url],
|
||||
debugDescription: "URL contains illegal characters: \(absoluteUrl)."
|
||||
)
|
||||
throw DecodingError.keyNotFound(CodingKeys.url, context)
|
||||
}
|
||||
}
|
||||
|
||||
public struct Signature: Decodable {
|
||||
public let id: Int
|
||||
public let sinf: Data
|
||||
}
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case url = "URL"
|
||||
case metadata
|
||||
case md5
|
||||
case signatures = "sinfs"
|
||||
}
|
||||
}
|
||||
|
||||
public struct Signature: Decodable {
|
||||
public let id: Int
|
||||
public let sinf: Data
|
||||
}
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case url = "URL"
|
||||
case metadata
|
||||
case md5
|
||||
case signatures = "sinfs"
|
||||
}
|
||||
|
||||
// MARK: - Receipt
|
||||
|
||||
extension StoreResponse {
|
||||
public struct Receipt {
|
||||
public let statusCode: Int
|
||||
public let status: Status
|
||||
|
||||
public enum Status {
|
||||
case success
|
||||
case failure
|
||||
|
||||
init(rawValue: String) {
|
||||
self = rawValue == "purchaseSuccess" ? .success : .failure
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,14 +11,14 @@ import Networking
|
||||
public protocol iTunesClientInterface {
|
||||
func lookup(
|
||||
bundleIdentifier: String,
|
||||
country: String,
|
||||
countryCode: String,
|
||||
deviceFamily: DeviceFamily
|
||||
) async throws -> iTunesResponse.Result
|
||||
|
||||
func search(
|
||||
term: String,
|
||||
limit: Int,
|
||||
country: String,
|
||||
countryCode: String,
|
||||
deviceFamily: DeviceFamily
|
||||
) async throws -> [iTunesResponse.Result]
|
||||
}
|
||||
@@ -32,12 +32,12 @@ public final class iTunesClient: iTunesClientInterface {
|
||||
|
||||
public func lookup(
|
||||
bundleIdentifier: String,
|
||||
country: String,
|
||||
countryCode: String,
|
||||
deviceFamily: DeviceFamily
|
||||
) async throws -> iTunesResponse.Result {
|
||||
let request = iTunesRequest.lookup(
|
||||
bundleIdentifier: bundleIdentifier,
|
||||
country: country,
|
||||
countryCode: countryCode,
|
||||
deviceFamily: deviceFamily
|
||||
)
|
||||
let response = try await httpClient.send(request)
|
||||
@@ -49,10 +49,15 @@ public final class iTunesClient: iTunesClientInterface {
|
||||
public func search(
|
||||
term: String,
|
||||
limit: Int,
|
||||
country: String,
|
||||
countryCode: String,
|
||||
deviceFamily: DeviceFamily
|
||||
) async throws -> [iTunesResponse.Result] {
|
||||
let request = iTunesRequest.search(term: term, limit: limit, country: country, deviceFamily: deviceFamily)
|
||||
let request = iTunesRequest.search(
|
||||
term: term,
|
||||
limit: limit,
|
||||
countryCode: countryCode,
|
||||
deviceFamily: deviceFamily
|
||||
)
|
||||
let response = try await httpClient.send(request)
|
||||
let decoded = try response.decode(iTunesResponse.self, as: .json)
|
||||
return decoded.results
|
||||
|
||||
@@ -9,8 +9,8 @@ import ArgumentParser
|
||||
import Networking
|
||||
|
||||
enum iTunesRequest {
|
||||
case search(term: String, limit: Int, country: String, deviceFamily: DeviceFamily = .phone)
|
||||
case lookup(bundleIdentifier: String, country: String, deviceFamily: DeviceFamily = .phone)
|
||||
case search(term: String, limit: Int, countryCode: String, deviceFamily: DeviceFamily = .phone)
|
||||
case lookup(bundleIdentifier: String, countryCode: String, deviceFamily: DeviceFamily = .phone)
|
||||
}
|
||||
|
||||
extension iTunesRequest: HTTPRequest {
|
||||
@@ -29,20 +29,20 @@ extension iTunesRequest: HTTPRequest {
|
||||
|
||||
var payload: HTTPPayload? {
|
||||
switch self {
|
||||
case let .lookup(bundleIdentifier, country, deviceFamily):
|
||||
case let .lookup(bundleIdentifier, countryCode, deviceFamily):
|
||||
return .urlEncoding([
|
||||
"media": "software",
|
||||
"bundleId": bundleIdentifier,
|
||||
"limit": "1",
|
||||
"country": country,
|
||||
"country": countryCode,
|
||||
"entity": deviceFamily.entity
|
||||
])
|
||||
case let .search(term, limit, country, deviceFamily):
|
||||
case let .search(term, limit, countryCode, deviceFamily):
|
||||
return .urlEncoding([
|
||||
"media": "software",
|
||||
"term": term,
|
||||
"limit": "\(limit)",
|
||||
"country": country,
|
||||
"country": countryCode,
|
||||
"entity": deviceFamily.entity
|
||||
])
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ extension iTunesResponse {
|
||||
public let version: String
|
||||
public let identifier: Int
|
||||
public let name: String
|
||||
public let price: Float
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,5 +35,6 @@ extension iTunesResponse.Result: Codable {
|
||||
case name = "trackName"
|
||||
case bundleIdentifier = "bundleId"
|
||||
case version
|
||||
case price
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user