Compare commits

...
20 Commits
Author SHA1 Message Date
Majd Alfhaily ff43c07a32 Patch old code signature revisions as fallback (#94) 2022-07-03 14:38:57 +00:00
Majd Alfhaily 07a0f3310d Update Makefile (#93) 2022-07-02 21:59:14 +00:00
Majd Alfhaily 9cfd72d142 Fix keychain access on iOS (#92) 2022-07-02 21:24:39 +00:00
Majd Alfhaily a16afb5c7b Upload iOS releases to GitHub (#86) 2022-06-17 22:45:27 +02:00
Majd Alfhaily ec4b6cfc29 Build releases for iOS (#85) 2022-06-17 22:28:32 +02:00
Majd Alfhaily 83515013cd Add linter (#84)
* Add linter

* Fix building universal binary with SwiftPM

* Run unit and integration tests on main branch
2022-06-16 22:21:58 +00:00
Majd Alfhaily 1577e1b8bc Disable print buffering and output errors to stderr (#83) 2022-06-14 22:27:45 +00:00
Majd Alfhaily 8d3167cc6e Improve error message for expired token (#79) 2022-05-29 12:39:10 +00:00
Majd Alfhaily 964fbe1fe7 Add backward-compatibility for macOS 10.11+ (#78)
* Add backward-compatibility for macOS 10.11+
* Update restore-keys for GitHub cache
* Update path for GitHub cache
2022-05-29 14:23:26 +02:00
Majd Alfhaily 943a7aff05 Cache SwiftPM packages in GitHub workflows (#77) 2022-05-29 14:09:12 +02:00
Majd Alfhaily 8c591f0a1f Remove usage of Swift concurrency (#76)
* Remove usage of Swift concurrency
* Update integration tests workflow
2022-05-29 14:04:41 +02:00
Majd Alfhaily 119c55359b Update swift-argument-parser dependency (#68) 2022-04-17 14:51:09 +02:00
Majd Alfhaily 4df3c492f6 Add issue templates (#66) 2022-04-05 19:03:24 +02:00
liorazi cea1db77e9 Fix typos (#59) 2022-03-23 19:26:24 +01:00
Majd Alfhaily 3040955de1 Add price checks for purchase flow (#58) 2022-03-22 23:28:54 +01:00
Majd Alfhaily f0c7e02db9 Implement --purchase flag in download command (#57) 2022-03-22 22:56:50 +01:00
Majd Alfhaily cd54b3bbcb Implement purchase command (#56) 2022-03-22 22:15:06 +01:00
Majd Alfhaily 82f70f23c7 Implement auth command (#55) 2022-03-22 22:03:18 +01:00
Majd Alfhaily 96115462d0 Use macOS 12 runner on GitHub Actions (#54) 2022-03-21 19:37:07 +01:00
Benjamin Altpeter 1b65463007 Add support for buying new (free) apps (#51) 2022-03-21 00:00:08 +01:00
45 changed files with 1792 additions and 517 deletions

No files matched your search

+25
View File
@@ -0,0 +1,25 @@
name: Bug Report
description: File a bug report
labels:
- bug
body:
- type: textarea
id: description
attributes:
label: What happened?
description: Also share, what did you expect to happen?
validations:
required: true
- type: input
id: version
attributes:
label: Version
description: What version of ipatool are you running?
validations:
required: true
- type: textarea
id: logs
attributes:
label: Relevant log output
description: Please copy and paste any relevant log output. This will be automatically formatted into code, so no need for backticks.
render: shell
@@ -0,0 +1,12 @@
name: Feature Request
description: Submit a feature request
labels:
- feature request
body:
- type: textarea
id: description
attributes:
label: Description
description: Please provide details about the desired feature.
validations:
required: true
+81 -20
View File
@@ -17,53 +17,113 @@ 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
- name: Cache SwiftPM packages
uses: actions/cache@v3
with:
path: .build/checkouts
key: ${{ runner.os }}-spm-${{ hashFiles('Package.resolved') }}
restore-keys: |
${{ runner.os }}-spm-${{ hashFiles('Package.resolved') }}
${{ runner.os }}-spm-
- name: Inject version
run: ./Scripts/version
- name: Build
run: swift build
- name: Run tests
run: swift test
build:
name: Build
runs-on: macos-11
build_macos:
name: Build (macOS)
runs-on: macos-12
needs: [get_version, test]
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Cache SwiftPM packages
uses: actions/cache@v3
with:
path: .build/checkouts
key: ${{ runner.os }}-spm-${{ hashFiles('Package.resolved') }}
restore-keys: |
${{ runner.os }}-spm-${{ hashFiles('Package.resolved') }}
${{ runner.os }}-spm-
- name: Inject version
run: ./Scripts/version
- name: Build
run: make build
run: make build-macos
- name: Upload binary
uses: actions/upload-artifact@v2
with:
name: ipatool-v${{ needs.get_version.outputs.version }}
name: ipatool-macos-v${{ needs.get_version.outputs.version }}
path: .build/ipatool
if-no-files-found: error
build_ios:
name: Build (iOS)
runs-on: macos-12
needs: [get_version, test]
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Cache SwiftPM packages
uses: actions/cache@v3
with:
path: .build/checkouts
key: ${{ runner.os }}-spm-${{ hashFiles('Package.resolved') }}
restore-keys: |
${{ runner.os }}-spm-${{ hashFiles('Package.resolved') }}
${{ runner.os }}-spm-
- name: Inject version
run: ./Scripts/version
- name: Install dependencies
run: brew install xcodegen ldid
- name: Build
run: make build-ios
- name: Upload binary
uses: actions/upload-artifact@v2
with:
name: ipatool-ios-v${{ needs.get_version.outputs.version }}
path: .build/ipatool
if-no-files-found: error
distribute:
name: Distribute
runs-on: ubuntu-20.04
needs: [get_version, build]
needs: [get_version, build_ios, build_macos]
steps:
- name: Download binary
- name: Download binary (macOS)
uses: actions/download-artifact@v2
with:
name: ipatool-v${{ needs.get_version.outputs.version }}
path: ipatool-v${{ needs.get_version.outputs.version }}
- name: Archive binary
name: ipatool-macos-v${{ needs.get_version.outputs.version }}
path: ipatool-macos-v${{ needs.get_version.outputs.version }}
- name: Archive binary (macOS)
run: |
mv ipatool-v${{ needs.get_version.outputs.version }}/ipatool ipatool
zip ipatool-v${{ needs.get_version.outputs.version }}.zip ipatool
- name: Upload binary to release
mv ipatool-macos-v${{ needs.get_version.outputs.version }}/ipatool ipatool
zip ipatool-macos-v${{ needs.get_version.outputs.version }}.zip ipatool
rm ipatool
- name: Upload release (macOS)
uses: svenstaro/upload-release-action@v2
with:
repo_token: ${{ secrets.GITHUB_TOKEN }}
file: ipatool-v${{ needs.get_version.outputs.version }}.zip
asset_name: ipatool-v${{ needs.get_version.outputs.version }}.zip
file: ipatool-macos-v${{ needs.get_version.outputs.version }}.zip
asset_name: ipatool-macos-v${{ needs.get_version.outputs.version }}.zip
tag: ${{ github.ref }}
overwrite: false
- name: Download binary (iOS)
uses: actions/download-artifact@v2
with:
name: ipatool-ios-v${{ needs.get_version.outputs.version }}
path: ipatool-ios-v${{ needs.get_version.outputs.version }}
- name: Archive binary (iOS)
run: |
mv ipatool-ios-v${{ needs.get_version.outputs.version }}/ipatool ipatool
zip ipatool-ios-v${{ needs.get_version.outputs.version }}.zip ipatool
rm ipatool
- name: Upload release (iOS)
uses: svenstaro/upload-release-action@v2
with:
repo_token: ${{ secrets.GITHUB_TOKEN }}
file: ipatool-ios-v${{ needs.get_version.outputs.version }}.zip
asset_name: ipatool-ios-v${{ needs.get_version.outputs.version }}.zip
tag: ${{ github.ref }}
overwrite: false
- name: Checkout homebrew repo
@@ -75,12 +135,13 @@ jobs:
token: ${{ secrets.GH_TOKEN }}
- name: Update homebrew repo
run: |
SHA256=$(sha256sum ipatool-v${{ needs.get_version.outputs.version }}.zip | awk '{print $1}')
SHA256=$(sha256sum ipatool-macos-v${{ needs.get_version.outputs.version }}.zip | awk '{print $1}')
cd repo
sed -i "3s/.*/ sha256 \"$SHA256\"/" Casks/ipatool.rb
sed -i "2s/.*/ version \"${{ needs.get_version.outputs.version }}\"/" Casks/ipatool.rb
sed -i "5s/.*/ url \"https:\/\/github.com\/majd\/ipatool\/releases\/download\/v${{ needs.get_version.outputs.version }}\/ipatool-macos-v${{ needs.get_version.outputs.version }}.zip\"/" Casks/ipatool.rb
git config --local user.name ${{ secrets.GH_NAME }}
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"
+50
View File
@@ -0,0 +1,50 @@
name: Dry Builds
on:
pull_request:
branches:
- main
jobs:
build_ios:
name: Dry build (iOS)
runs-on: macos-12
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Cache SwiftPM packages
uses: actions/cache@v3
with:
path: .build/checkouts
key: ${{ runner.os }}-spm-${{ hashFiles('Package.resolved') }}
restore-keys: |
${{ runner.os }}-spm-${{ hashFiles('Package.resolved') }}
${{ runner.os }}-spm-
- name: Install dependencies
run: brew install xcodegen ldid
- name: Inject version
run: ./Scripts/version
- name: Build
run: |
make build-ios
file .build/ipatool
build_macos:
name: Dry build (macOS)
runs-on: macos-12
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Cache SwiftPM packages
uses: actions/cache@v3
with:
path: .build/checkouts
key: ${{ runner.os }}-spm-${{ hashFiles('Package.resolved') }}
restore-keys: |
${{ runner.os }}-spm-${{ hashFiles('Package.resolved') }}
${{ runner.os }}-spm-
- name: Inject version
run: ./Scripts/version
- name: Build
run: |
make build-macos
file .build/ipatool
+16 -11
View File
@@ -1,6 +1,9 @@
name: Integration Tests
on:
push:
branches:
- main
pull_request:
branches:
- main
@@ -8,14 +11,22 @@ on:
jobs:
build:
name: Build
runs-on: macos-11
runs-on: macos-12
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Cache SwiftPM packages
uses: actions/cache@v3
with:
path: .build/checkouts
key: ${{ runner.os }}-spm-${{ hashFiles('Package.resolved') }}
restore-keys: |
${{ runner.os }}-spm-${{ hashFiles('Package.resolved') }}
${{ runner.os }}-spm-
- name: Inject version
run: ./Scripts/version
- name: Build
run: make build
run: make build-macos
- name: Upload binary
uses: actions/upload-artifact@v2
with:
@@ -29,8 +40,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
@@ -39,11 +50,5 @@ jobs:
path: ipatool-current
- name: Update permissions
run: chmod +x ./ipatool-current/ipatool
- name: Install Swift toolchain
run: |
wget https://download.swift.org/swift-5.5.3-release/xcode/swift-5.5.3-RELEASE/swift-5.5.3-RELEASE-osx.pkg
sudo installer -pkg swift-5.5.3-RELEASE-osx.pkg -target /
- name: Run tests
run: |
export DYLD_LIBRARY_PATH=/Library/Developer/Toolchains/swift-5.5.3-RELEASE.xctoolchain/usr/lib/swift/macosx
./ipatool-current/ipatool ${{ matrix.command }} --help
run: ./ipatool-current/ipatool ${{ matrix.command }} --help
+12 -1
View File
@@ -1,6 +1,9 @@
name: Unit Tests
on:
push:
branches:
- main
pull_request:
branches:
- main
@@ -8,10 +11,18 @@ on:
jobs:
test-networking:
name: Test Networking
runs-on: macos-11
runs-on: macos-12
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Cache SwiftPM packages
uses: actions/cache@v3
with:
path: .build/checkouts
key: ${{ runner.os }}-spm-${{ hashFiles('Package.resolved') }}
restore-keys: |
${{ runner.os }}-spm-${{ hashFiles('Package.resolved') }}
${{ runner.os }}-spm-
- name: Inject version
run: ./Scripts/version
- name: Build
+1
View File
@@ -2,6 +2,7 @@
.DS_Store
.AppleDouble
.LSOverride
.vscode/
# Icon must end with two \r
Icon
+46
View File
@@ -0,0 +1,46 @@
disabled_rules:
- cyclomatic_complexity
- type_body_length
- identifier_name
- function_body_length
opt_in_rules:
- multiline_function_chains
- anyobject_protocol
- overridden_super_call
- prohibited_super_call
- last_where
- contains_over_first_not_nil
- vertical_parameter_alignment_on_call
- multiline_arguments
- multiline_literal_brackets
- closure_end_indentation
- collection_alignment
- reduce_into
- explicit_init
- static_operator
- sorted_first_last
- no_space_in_method_call
- contains_over_filter_count
- contains_over_filter_is_empty
- empty_collection_literal
- empty_count
type_name:
validates_start_with_lowercase: false
nesting:
type_level:
warning: 3
line_length:
warning: 120
error: 120
ignore_comments: true
ignore_urls: true
file_length:
warning: 1000
error: 1000
reporter: "xcode"
@@ -76,6 +76,34 @@
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>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "SwiftLint"
BuildableName = "SwiftLint"
BlueprintName = "SwiftLint"
ReferencedContainer = "container:">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
+44 -6
View File
@@ -1,19 +1,57 @@
prefix ?= /usr/local
bindir = $(prefix)/bin
build:
swift build --product ipatool --configuration release --triple arm64-apple-macosx
swift build --product ipatool --configuration release --triple x86_64-apple-macosx
define ios_entitlements
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>keychain-access-groups</key>
<array>
<string>ipatool</string>
</array>
<key>application-identifier</key>
<string>ipatool</string>
<key>platform-application</key>
<true />
<key>com.apple.private.security.container-required</key>
<false />
</dict>
</plist>
endef
lint:
swiftlint lint --config .swiftlint.yml --path Sources/ Tests/m Plugins/
build-macos: lint
swift build -c release --arch arm64
swift build -c release --arch x86_64
lipo -create -output .build/ipatool .build/arm64-apple-macosx/release/ipatool .build/x86_64-apple-macosx/release/ipatool
install: build
build-ios: lint
xcodegen -s ios-project.yml
xcodebuild archive -scheme CLI \
-sdk iphoneos \
-configuration Release \
-derivedDataPath .build \
-archivePath .build/ipatool.xcarchive \
CODE_SIGN_IDENTITY='' \
CODE_SIGNING_REQUIRED=NO \
CODE_SIGN_ENTITLEMENTS='' \
CODE_SIGNING_ALLOWED=NO
cp .build/ipatool.xcarchive/Products/Applications/CLI.app/CLI .build/ipatool
echo "$$ios_entitlements" > "${PWD}/.build/entitlements.xml"
ldid -S.build/entitlements.xml ./.build/ipatool
install-macos: build
install -d "$(bindir)"
install ".build/ipatool" "$(bindir)"
uninstall:
uninstall-macos:
rm -rf "$(bindir)/ipatool"
clean:
rm -rf .build
.PHONY: build install uninstall clean
.PHONY: build-macos install-macos uninstall-macos clean
export ios_entitlements
+29 -22
View File
@@ -1,25 +1,32 @@
{
"object": {
"pins": [
{
"package": "swift-argument-parser",
"repositoryURL": "https://github.com/apple/swift-argument-parser",
"state": {
"branch": "1.0.2",
"revision": "e1465042f195f374b94f915ba8ca49de24300a0d",
"version": null
}
},
{
"package": "ZIPFoundation",
"repositoryURL": "https://github.com/weichsel/ZIPFoundation",
"state": {
"branch": "0.9.14",
"revision": "7254c74b49cec2cb81520523ba993c671f71b066",
"version": null
}
"pins" : [
{
"identity" : "keychainaccess",
"kind" : "remoteSourceControl",
"location" : "https://github.com/kishikawakatsumi/KeychainAccess",
"state" : {
"branch" : "v4.2.2",
"revision" : "84e546727d66f1adc5439debad16270d0fdd04e7"
}
]
},
"version": 1
},
{
"identity" : "swift-argument-parser",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-argument-parser",
"state" : {
"branch" : "1.1.2",
"revision" : "f3c9084a71ef4376f2fabbdf1d3d90a49f1fabdb"
}
},
{
"identity" : "zipfoundation",
"kind" : "remoteSourceControl",
"location" : "https://github.com/weichsel/ZIPFoundation",
"state" : {
"branch" : "0.9.14",
"revision" : "7254c74b49cec2cb81520523ba993c671f71b066"
}
}
],
"version" : 2
}
+39 -10
View File
@@ -1,37 +1,66 @@
// swift-tools-version:5.5
// swift-tools-version:5.6
import PackageDescription
let package = Package(
name: "IPATool",
platforms: [.macOS(.v10_15)],
platforms: [.macOS(.v10_11)],
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/apple/swift-argument-parser", revision: "1.1.2"),
.package(url: "https://github.com/weichsel/ZIPFoundation", revision: "0.9.14"),
.package(url: "https://github.com/kishikawakatsumi/KeychainAccess", revision: "v4.2.2")
],
targets: [
// IPATool CLI
.executableTarget(
name: "CLI",
dependencies: [
.product(name: "ArgumentParser", package: "swift-argument-parser"),
.byName(name: "Networking"),
.byName(name: "StoreAPI")
]
.byName(name: "StoreAPI"),
.byName(name: "Persistence")
],
plugins: ["SwiftLint"]
),
// StoreAPI
.target(
name: "StoreAPI",
dependencies: [
.product(name: "ArgumentParser", package: "swift-argument-parser"),
.product(name: "ZIPFoundation", package: "ZIPFoundation"),
.byName(name: "Networking"),
]
],
plugins: ["SwiftLint"]
),
.target(name: "Networking", dependencies: []),
.testTarget(name: "NetworkingTests", dependencies: ["Networking"])
// Networking
.target(
name: "Networking",
plugins: ["SwiftLint"]
),
.testTarget(
name: "NetworkingTests",
dependencies: ["Networking"],
plugins: ["SwiftLint"]
),
// Persistence
.target(
name: "Persistence",
dependencies: [
.byName(name: "KeychainAccess")
],
plugins: ["SwiftLint"]
),
// SwiftLint
.plugin(name: "SwiftLint", capability: .buildTool())
]
)
+51
View File
@@ -0,0 +1,51 @@
//
// main.swift
// SwiftLint
//
// Created by Majd Alfhaily on 15.06.22.
//
import PackagePlugin
import Foundation
@main
struct SwiftLint: BuildToolPlugin {
func createBuildCommands(context: PluginContext, target: Target) async throws -> [Command] {
let toolPath = try determinePath(forTool: "swiftlint")
let configPath = context.package.directory.appending(".swiftlint.yml")
return [
.buildCommand(
displayName: "Run SwiftLint",
executable: toolPath,
arguments: [
"lint",
"--in-process-sourcekit",
"--config",
configPath.string,
"--path",
target.directory.string
]
)
]
}
private func determinePath(forTool toolName: String) throws -> Path {
let prefixes: [String] = [
"/opt/homebrew/bin",
"/usr/local/bin",
"/usr/bin",
"/bin"
]
for path in prefixes where FileManager.default.fileExists(atPath: "\(path)/\(toolName)") {
return Path("\(path)/\(toolName)")
}
throw NSError(
domain: Bundle.main.bundleIdentifier ?? String(describing: type(of: self)),
code: 0,
userInfo: [NSLocalizedDescriptionKey: "Could not find tool: \(toolName)."]
)
}
}
+66 -27
View File
@@ -1,26 +1,28 @@
# IPATool
[![Release](https://img.shields.io/github/release/majd/ipatool.svg?label=Release)](https://GitHub.com/majd/ipatool/releases/)
[![License](https://img.shields.io/badge/License-MIT-yellow.svg)](https://github.com/majd/ipatool/blob/main/LICENSE)
[![Unit Tests](https://github.com/majd/ipatool/actions/workflows/unit-tests.yml/badge.svg)](https://github.com/majd/ipatool/actions/workflows/unit-tests.yml)
[![Integration Tests](https://github.com/majd/ipatool/actions/workflows/integration-tests.yml/badge.svg)](https://github.com/majd/ipatool/actions/workflows/integration-tests.yml)
![Swift](https://img.shields.io/badge/Swift-5.5-green.svg)
![macOS](https://img.shields.io/badge/macOS-10.15%2B-green.svg)
[![Unit Tests](https://github.com/majd/ipatool/actions/workflows/unit-tests.yml/badge.svg?branch=main)](https://github.com/majd/ipatool/actions/workflows/unit-tests.yml)
[![Integration Tests](https://github.com/majd/ipatool/actions/workflows/integration-tests.yml/badge.svg?branch=main)](https://github.com/majd/ipatool/actions/workflows/integration-tests.yml)
![Swift](https://img.shields.io/badge/Swift-5.6-green.svg)
![macOS](https://img.shields.io/badge/macOS-10.11%2B-green.svg)
`ipatool` is a command line tool that allows you to search for iOS apps on the [App Store](https://apps.apple.com) and download a copy of the app package, known as an _ipa_ file.
![Demo](./demo.gif)
* [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.11 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).
-38
View File
@@ -1,38 +0,0 @@
//
// AsyncSupport.swift
// IPATool
//
// Created by Majd Alfhaily on 04.01.22.
//
import Foundation
import ArgumentParser
protocol AsyncParsableCommand: ParsableCommand {
mutating func run() async throws
}
extension AsyncParsableCommand {
mutating func run() throws {
throw CleanExit.helpRequest(self)
}
}
protocol AsyncMain {
associatedtype Command: ParsableCommand
}
extension AsyncMain {
static func main() async {
do {
var command = try Command.parseAsRoot()
if var command = command as? AsyncParsableCommand {
try await command.run()
} else {
try command.run()
}
} catch {
Command.exit(withError: error)
}
}
}
+207
View File
@@ -0,0 +1,207 @@
//
// Auth.swift
// IPATool
//
// Created by Majd Alfhaily on 21.03.22.
//
import ArgumentParser
import Foundation
import Networking
import StoreAPI
import Persistence
struct Auth: ParsableCommand {
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: ParsableCommand {
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: ParsableCommand {
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) -> 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 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 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() 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 = 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() 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)
}
}
+130 -129
View File
@@ -9,8 +9,9 @@ import ArgumentParser
import Foundation
import Networking
import StoreAPI
import Persistence
struct Download: AsyncParsableCommand {
struct Download: ParsableCommand {
static var configuration: CommandConfiguration {
return .init(abstract: "Download (encrypted) iOS app packages from the App Store.")
}
@@ -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) -> iTunesResponse.Result {
logger.log("Creating HTTP client...", level: .debug)
let httpClient = HTTPClient(session: URLSession.shared)
@@ -51,10 +49,13 @@ extension Download {
let itunesClient = iTunesClient(httpClient: httpClient)
do {
logger.log("Querying the iTunes Store for '\(bundleIdentifier)' in country '\(country)'...", level: .info)
return try await itunesClient.lookup(
logger.log(
"Querying the iTunes Store for '\(bundleIdentifier)' in country '\(countryCode)'...",
level: .info
)
return try itunesClient.lookup(
bundleIdentifier: bundleIdentifier,
country: country,
countryCode: countryCode,
deviceFamily: deviceFamily
)
} catch {
@@ -70,47 +71,16 @@ 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) {
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."
].joined(separator: " "), 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,57 +88,43 @@ 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 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("Price 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."
].joined(separator: " "), level: .error)
case StoreResponse.Error.passwordTokenExpired, StoreResponse.Error.passwordChanged:
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
) async -> StoreResponse.Item {
account: Account,
purchaseAttempted: Bool = false
) -> StoreResponse.Item {
logger.log("Creating HTTP client...", level: .debug)
let httpClient = HTTPClient(session: URLSession.shared)
@@ -177,35 +133,57 @@ extension Download {
do {
logger.log("Requesting a signed copy of '\(app.identifier)' from the App Store...", level: .info)
return try await storeClient.item(
return try storeClient.item(
identifier: "\(app.identifier)",
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.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)
purchase(app: app, account: account)
logger.log("Obtained a license for '\(app.identifier)'.", level: .debug)
return 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."
].joined(separator: " "), 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."
].joined(separator: " "), level: .error)
case StoreResponse.Error.passwordTokenExpired, StoreResponse.Error.passwordChanged:
logger.log("Token expired. Login again using the \"auth\" command.", level: .error)
default:
logger.log("An unknown error has occurred.", level: .error)
logger.log([
"An unknown error has occurred.",
"The token may have already expired - try loggin in again using the \"auth\" command."
].joined(separator: " "), level: .error)
}
_exit(1)
}
}
private mutating func download(item: StoreResponse.Item, to targetURL: URL) async {
private mutating func download(item: StoreResponse.Item, to targetURL: URL) {
logger.log("Creating download client...", level: .debug)
let downloadClient = HTTPDownloadClient()
do {
logger.log("Downloading app package...", level: .info)
try await downloadClient.download(from: item.url, to: targetURL) { [logger] progress in
try downloadClient.download(from: item.url, to: targetURL) { [logger] progress in
logger.log("Downloading app package... [\(Int((progress * 100).rounded()))%]",
prefix: "\u{1B}[1A\u{1B}[K",
level: .info)
@@ -216,7 +194,7 @@ extension Download {
_exit(1)
}
}
private mutating func applyPatches(item: StoreResponse.Item, email: String, path: String) {
logger.log("Creating signature client...", level: .debug)
let signatureClient = SignatureClient(fileManager: .default, filePath: path)
@@ -225,53 +203,76 @@ extension Download {
logger.log("Applying patches...", level: .info)
try signatureClient.appendMetadata(item: item, email: email)
try signatureClient.appendSignature(item: item)
} catch {
switch error {
case SignatureClient.Error.fileNotFound:
logger.log(
"App uses old code signature version, falling back to alternative patching mechanism.",
level: .debug
)
logger.log("The produced app package may not be compatible with modern iOS releases.", level: .info)
applyOldPatches(item: item, email: email, path: path)
default:
logger.log("\(error)", level: .debug)
logger.log("Failed to apply patches. The ipa file will be left incomplete.", level: .error)
_exit(1)
}
}
}
private mutating func applyOldPatches(item: StoreResponse.Item, email: String, path: String) {
logger.log("Creating signature client...", level: .debug)
let signatureClient = SignatureClient(fileManager: .default, filePath: path)
do {
logger.log("Applying fallback patches...", level: .info)
try signatureClient.appendOldSignature(item: item)
} catch {
logger.log("\(error)", level: .debug)
logger.log("Failed to apply patches. The ipa file will be left incomplete.", level: .error)
_exit(1)
}
}
private mutating func makeOutputPath(app: iTunesResponse.Result) -> String {
let fileName: String = "/\(bundleIdentifier)_\(app.identifier)_v\(app.version)_\(Int.random(in: 100...999)).ipa"
guard let output = output else {
return FileManager.default.currentDirectoryPath.appending(fileName)
}
var isDirectory: ObjCBool = false
FileManager.default.fileExists(atPath: output, isDirectory: &isDirectory)
return isDirectory.boolValue ? output.appending(fileName) : output
}
mutating func validate() throws {
guard let output = output else { return }
var isDirectory: ObjCBool = false
guard !FileManager.default.fileExists(atPath: output, isDirectory: &isDirectory) || isDirectory.boolValue else {
logger.log("A file already exists at \(output).", level: .error)
_exit(1)
}
}
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()
mutating func run() throws {
// 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 = 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)
let item: StoreResponse.Item = item(from: app, account: account)
logger.log("Received a response of the signed copy: \(item.md5).", level: .debug)
// Generate file name
@@ -279,11 +280,11 @@ extension Download {
logger.log("Output path: \(path).", level: .debug)
// Download app package
await download(item: item, to: URL(fileURLWithPath: path))
download(item: item, to: URL(fileURLWithPath: path))
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)
}
}
+1 -5
View File
@@ -13,11 +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]
)
}
}
@main enum Main: AsyncMain {
typealias Command = IPATool
}
+135
View File
@@ -0,0 +1,135 @@
//
// Purchase.swift
// IPATool
//
// Created by Majd Alfhaily on 22.03.22.
//
import ArgumentParser
import Foundation
import Networking
import StoreAPI
import Persistence
struct Purchase: ParsableCommand {
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) -> 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 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) {
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 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("Price 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."
].joined(separator: " "), level: .error)
case StoreResponse.Error.passwordTokenExpired, StoreResponse.Error.passwordChanged:
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() 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 = app(with: bundleIdentifier)
logger.log("Found app: \(app.name) (\(app.version)).", level: .debug)
// Obtain a license
purchase(app: app, account: account)
logger.log("Obtained a license for '\(app.identifier)'.", level: .debug)
logger.log("Done.", level: .info)
}
}
+14 -11
View File
@@ -10,7 +10,7 @@ import Foundation
import Networking
import StoreAPI
struct Search: AsyncParsableCommand {
struct Search: ParsableCommand {
static var configuration: CommandConfiguration {
return .init(abstract: "Search for iOS apps available on the App Store.")
}
@@ -21,33 +21,36 @@ 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
@Option(name: [.long], help: "The log level.")
private var logLevel: LogLevel = .info
lazy var logger = ConsoleLogger(level: logLevel)
}
extension Search {
mutating func results(with term: String, country: String) async -> [iTunesResponse.Result] {
mutating func results(with term: String) -> [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(
let results = try itunesClient.search(
term: term,
limit: limit,
country: country,
countryCode: countryCode,
deviceFamily: deviceFamily
)
@@ -63,10 +66,10 @@ extension Search {
_exit(1)
}
}
mutating func run() async throws {
mutating func run() throws {
// Search the iTunes store
let results = await results(with: term, country: country)
let results = results(with: term)
// Compile output
let output = results
+17 -5
View File
@@ -6,22 +6,34 @@
//
import Foundation
import Darwin
final class ConsoleLogger: Logging {
private let level: LogLevel
init(level: LogLevel) {
self.level = level
}
func log(_ message: String, level: LogLevel) {
guard level <= self.level else { return }
print(compile(message, level: level))
switch level {
case .error:
fputs("\(compile(message, level: level))\n", stderr)
default:
print(compile(message, level: level))
}
}
func log(_ message: String, prefix: String, level: LogLevel) {
guard level <= self.level else { return }
print("\(prefix)\(compile(message, level: level))")
switch level {
case .error:
fputs("\(prefix)\(compile(message, level: level))\n", stderr)
default:
print("\(prefix)\(compile(message, level: level))")
}
}
func compile(_ message: String, level: LogLevel) -> String {
+1 -1
View File
@@ -28,7 +28,7 @@ extension LogLevel {
return "🛠\t[Debug] "
}
}
var priority: Int {
switch self {
case .error:
+15
View File
@@ -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
}
+16
View File
@@ -0,0 +1,16 @@
//
// main.swift
// IPATool
//
// Created by Majd Alfhaily on 15.06.22.
//
import Foundation
func disablePrintBuffering() {
setbuf(stderr, nil)
setbuf(stdout, nil)
}
disablePrintBuffering()
IPATool.main()
+23 -9
View File
@@ -8,27 +8,41 @@
import Foundation
public protocol HTTPClientInterface {
func send(_ request: HTTPRequest) async throws -> HTTPResponse
func send(_ request: HTTPRequest) throws -> HTTPResponse
}
public final class HTTPClient: HTTPClientInterface {
private let session: URLSessionInterface
public init(session: URLSessionInterface) {
self.session = session
}
public func send(_ request: HTTPRequest) async throws -> HTTPResponse {
public func send(_ request: HTTPRequest) throws -> HTTPResponse {
let request = try makeURLRequest(from: request)
let (data, response) = try await session.data(for: request)
let semaphore = DispatchSemaphore(value: 0)
var result: (data: Data?, response: URLResponse?, error: Swift.Error?)
guard let response = response as? HTTPURLResponse else {
throw Error.invalidResponse(response)
session
.dataTask(with: request) { (data, response, error) in
result = (data, response, error)
semaphore.signal()
}
.resume()
semaphore.wait()
if let error = result.error {
throw error
}
return HTTPResponse(statusCode: response.statusCode, data: data)
guard let response = result.response as? HTTPURLResponse else {
throw Error.invalidResponse(result.response)
}
return HTTPResponse(statusCode: response.statusCode, data: result.data)
}
private func makeURLRequest(from request: HTTPRequest) throws -> URLRequest {
var urlRequest = URLRequest(url: request.endpoint.url)
urlRequest.httpMethod = request.method.rawValue
@@ -57,7 +71,7 @@ public final class HTTPClient: HTTPClientInterface {
urlRequest.setValue("application/xml", forHTTPHeaderField: "Content-Type")
urlRequest.httpBody = try PropertyListSerialization.data(fromPropertyList: value, format: .xml, options: 0)
}
request.headers.forEach { urlRequest.setValue($0.value, forHTTPHeaderField: $0.key) }
return urlRequest
+30 -19
View File
@@ -8,32 +8,40 @@
import Foundation
public protocol HTTPDownloadClientInterface {
func download(from source: URL, to target: URL, progress: @escaping (Float) -> Void) async throws
func download(from source: URL, to target: URL, progress: @escaping (Float) -> Void) throws
}
public final class HTTPDownloadClient: NSObject, HTTPDownloadClientInterface {
private var session: URLSession!
private var progressHandler: ((Float) -> Void)?
private var continuation: CheckedContinuation<Void, Swift.Error>?
private var semaphore: DispatchSemaphore?
private var targetURL: URL?
private var result: Result<Void, Swift.Error>?
public override init() {
super.init()
self.session = URLSession(configuration: .default, delegate: self, delegateQueue: nil)
}
public func download(from source: URL, to target: URL, progress: @escaping (Float) -> Void) async throws {
public func download(from source: URL, to target: URL, progress: @escaping (Float) -> Void) throws {
assert(progressHandler == nil)
assert(continuation == nil)
assert(semaphore == nil)
assert(targetURL == nil)
progressHandler = progress
targetURL = target
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Swift.Error>) in
self.continuation = continuation
let task = session.downloadTask(with: source)
task.resume()
semaphore = DispatchSemaphore(value: 0)
session.downloadTask(with: source).resume()
semaphore?.wait()
switch result {
case let .failure(error):
throw error
case .success:
break
case .none:
preconditionFailure()
}
}
}
@@ -45,14 +53,15 @@ extension HTTPDownloadClient: URLSessionDownloadDelegate {
}
defer {
semaphore?.signal()
progressHandler = nil
continuation = nil
semaphore = nil
targetURL = nil
}
continuation?.resume(throwing: error)
result = .failure(error)
}
public func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
@@ -62,27 +71,29 @@ extension HTTPDownloadClient: URLSessionDownloadDelegate {
) {
progressHandler?(Float(totalBytesWritten) / Float(totalBytesExpectedToWrite))
}
public func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didFinishDownloadingTo location: URL
) {
defer {
semaphore?.signal()
progressHandler = nil
continuation = nil
semaphore = nil
targetURL = nil
}
guard let target = targetURL else {
return continuation?.resume(throwing: Error.invalidTarget) ?? ()
result = .failure(Error.invalidTarget)
return
}
do {
try FileManager.default.moveItem(at: location, to: target)
continuation?.resume()
result = .success(())
} catch {
continuation?.resume(throwing: error)
result = .failure(error)
}
}
}
+4 -4
View File
@@ -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 {
@@ -17,7 +17,7 @@ extension HTTPResponse {
guard let data = data else {
throw Error.noData
}
switch decoder {
case .json:
let decoder = JSONDecoder()
@@ -36,7 +36,7 @@ extension HTTPResponse {
case json
case xml
}
public enum Error: Swift.Error {
case noData
}
+17 -15
View File
@@ -7,23 +7,25 @@
import Foundation
public protocol URLSessionInterface {
func data(for request: URLRequest) async throws -> (Data, URLResponse)
public protocol URLSessionDataTaskInterface {
func resume()
}
public protocol URLSessionInterface {
func dataTask(
with request: URLRequest,
completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void
) -> URLSessionDataTaskInterface
}
extension URLSessionDataTask: URLSessionDataTaskInterface {}
extension URLSession: URLSessionInterface {
public func data(for request: URLRequest) async throws -> (Data, URLResponse) {
try await withCheckedThrowingContinuation { continuation in
let task = dataTask(with: request) { data, response, error in
guard let data = data, let response = response else {
let error = error ?? URLError(.badServerResponse)
return continuation.resume(throwing: error)
}
continuation.resume(returning: (data, response))
}
task.resume()
}
public func dataTask(
with request: URLRequest,
completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void
) -> URLSessionDataTaskInterface {
let task: URLSessionDataTask = dataTask(with: request, completionHandler: completionHandler)
return task
}
}
+40
View File
@@ -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)
}
}
+151
View File
@@ -0,0 +1,151 @@
//
// 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
}
}
@@ -16,14 +16,14 @@ public protocol SignatureClientInterface {
public final class SignatureClient: SignatureClientInterface {
private let fileManager: FileManager
private let filePath: String
public init(fileManager: FileManager, filePath: String) {
self.fileManager = fileManager
self.filePath = filePath
}
public func appendMetadata(item: StoreResponse.Item, email: String) throws {
guard let archive = Archive(url: URL(fileURLWithPath: filePath), accessMode: .update) else {
guard let archive = Archive(url: URL(fileURLWithPath: filePath), accessMode: .update) else {
throw Error.invalidArchive
}
@@ -31,31 +31,56 @@ public final class SignatureClient: SignatureClientInterface {
metadata["apple-id"] = email
metadata["userName"] = email
let metadataUrl = URL(fileURLWithPath: NSTemporaryDirectory().appending("\(UUID().uuidString)/iTunesMetadata.plist"))
let metadataPath = NSTemporaryDirectory().appending("\(UUID().uuidString)/iTunesMetadata.plist")
let metadataUrl = URL(fileURLWithPath: metadataPath)
try fileManager.createDirectory(at: metadataUrl.deletingLastPathComponent(), withIntermediateDirectories: true)
try PropertyListSerialization.data(fromPropertyList: metadata, format: .xml, options: .zero).write(to: metadataUrl)
try PropertyListSerialization
.data(
fromPropertyList: metadata,
format: .xml,
options: .zero
)
.write(to: metadataUrl)
try archive.addEntry(with: metadataUrl.lastPathComponent, relativeTo: metadataUrl.deletingLastPathComponent())
try fileManager.removeItem(at: metadataUrl)
}
public func appendSignature(item: StoreResponse.Item) throws {
guard let archive = Archive(url: URL(fileURLWithPath: filePath), accessMode: .update) else {
guard let archive = Archive(url: URL(fileURLWithPath: filePath), accessMode: .update) else {
throw Error.invalidArchive
}
let manifest = try readPlist(archive: archive, matchingSuffix: ".app/SC_Info/Manifest.plist", type: Manifest.self)
try appendSignatureFromManfiest(forItem: item, inArchive: archive)
}
public func appendOldSignature(item: StoreResponse.Item) throws {
guard let archive = Archive(url: URL(fileURLWithPath: filePath), accessMode: .update) else {
throw Error.invalidArchive
}
try appendOldSignature(forItem: item, inArchive: archive)
}
private func appendSignatureFromManfiest(forItem item: StoreResponse.Item, inArchive archive: Archive) throws {
let manifest = try readPlist(
archive: archive,
matchingSuffix: ".app/SC_Info/Manifest.plist",
type: Manifest.self
)
guard let infoEntry = archive.first(where: { $0.path.hasSuffix(".app/Info.plist") }) else {
throw Error.invalidAppBundle
}
let appBundleName = URL(fileURLWithPath: infoEntry.path)
.deletingLastPathComponent()
.deletingPathExtension()
.lastPathComponent
guard let signatureItem = item.signatures.first(where: { $0.id == 0 }), let signatureTargetPath = manifest.paths.first else {
guard let signatureItem = item.signatures.first(where: {
return $0.id == 0
}), let signatureTargetPath = manifest.paths.first else {
throw Error.invalidSignature
}
@@ -65,7 +90,7 @@ public final class SignatureClient: SignatureClientInterface {
.appendingPathComponent(appBundleName)
.appendingPathExtension("app")
.appendingPathComponent(signatureTargetPath)
let signatureRelativePath = signatureUrl.path.replacingOccurrences(of: "\(signatureBaseUrl.path)/", with: "")
try fileManager.createDirectory(at: signatureUrl.deletingLastPathComponent(), withIntermediateDirectories: true)
@@ -73,13 +98,61 @@ public final class SignatureClient: SignatureClientInterface {
try archive.addEntry(with: signatureRelativePath, relativeTo: signatureBaseUrl)
try fileManager.removeItem(at: signatureBaseUrl)
}
private func appendOldSignature(forItem item: StoreResponse.Item, inArchive archive: Archive) throws {
guard let infoEntry = archive.first(where: { $0.path.hasSuffix(".app/Info.plist") }) else {
throw Error.invalidAppBundle
}
let temporaryInfoURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(UUID().uuidString)
_ = try archive.extract(infoEntry, to: temporaryInfoURL, skipCRC32: true)
let infoData = try Data(contentsOf: temporaryInfoURL)
guard let infoPlist = try PropertyListSerialization.propertyList(
from: infoData,
format: nil
) as? [String: Any] else {
throw Error.invalidAppBundle
}
guard let executableName = infoPlist["CFBundleExecutable"] as? String else {
throw Error.invalidAppBundle
}
let appBundleName = URL(fileURLWithPath: infoEntry.path)
.deletingLastPathComponent()
.deletingPathExtension()
.lastPathComponent
guard let signatureItem = item.signatures.first(where: { $0.id == 0 }) else {
throw Error.invalidSignature
}
let signatureBaseUrl = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(UUID().uuidString)
let signatureUrl = signatureBaseUrl
.appendingPathComponent("Payload")
.appendingPathComponent(appBundleName)
.appendingPathExtension("app")
.appendingPathComponent("SC_Info")
.appendingPathComponent(executableName)
.appendingPathExtension("sinf")
let signatureRelativePath = signatureUrl.path.replacingOccurrences(of: "\(signatureBaseUrl.path)/", with: "")
try fileManager.createDirectory(at: signatureUrl.deletingLastPathComponent(), withIntermediateDirectories: true)
try signatureItem.sinf.write(to: signatureUrl)
try archive.addEntry(with: signatureRelativePath, relativeTo: signatureBaseUrl)
try fileManager.removeItem(at: signatureBaseUrl)
}
private func readPlist<T: Decodable>(archive: Archive, matchingSuffix: String, type: T.Type) throws -> T {
guard let entry = archive.first(where: { $0.path.hasSuffix(matchingSuffix) }) else {
throw Error.fileNotFound(matchingSuffix)
}
let url = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent(UUID().uuidString).appendingPathExtension("plist")
let url = URL(fileURLWithPath: NSHomeDirectory())
.appendingPathComponent(UUID().uuidString)
.appendingPathExtension("plist")
_ = try archive.extract(entry, to: url)
let data = try Data(contentsOf: url)
@@ -94,13 +167,13 @@ public final class SignatureClient: SignatureClientInterface {
extension SignatureClient {
struct Manifest: Codable {
let paths: [String]
enum CodingKeys: String, CodingKey {
case paths = "SinfPaths"
}
}
enum Error: Swift.Error {
public enum Error: Swift.Error {
case invalidArchive
case invalidAppBundle
case invalidSignature
+62 -19
View File
@@ -9,63 +9,104 @@ import Foundation
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 authenticate(email: String, password: String, code: String?) throws -> StoreResponse.Account
func item(identifier: String, directoryServicesIdentifier: String) throws -> StoreResponse.Item
func purchase(
identifier: String,
directoryServicesIdentifier: String,
passwordToken: String,
countryCode: String
) throws
}
public final class StoreClient: StoreClientInterface {
private let httpClient: HTTPClient
public init(httpClient: HTTPClient) {
self.httpClient = httpClient
}
public func authenticate(email: String, password: String, code: String?) async throws -> StoreResponse.Account {
try await authenticate(email: email, password: password, code: code, isFirstAttempt: true)
public func authenticate(email: String, password: String, code: String?) throws -> StoreResponse.Account {
try authenticate(email: email, password: password, code: code, isFirstAttempt: true)
}
public func item(identifier: String, directoryServicesIdentifier: String) async throws -> StoreResponse.Item {
public func item(identifier: String, directoryServicesIdentifier: String) throws -> StoreResponse.Item {
let request = StoreRequest.download(
appIdentifier: identifier,
directoryServicesIdentifier: directoryServicesIdentifier
)
let response = try await httpClient.send(request)
let decoded = try response.decode(StoreResponse.self, as: .xml)
let response = try httpClient.send(request)
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
) throws {
let request = StoreRequest.purchase(
appIdentifier: identifier,
directoryServicesIdentifier: directoryServicesIdentifier,
passwordToken: passwordToken,
countryCode: countryCode
)
let response = try 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
}
}
}
private func authenticate(email: String,
password: String,
code: String?,
isFirstAttempt: Bool) async throws -> StoreResponse.Account {
isFirstAttempt: Bool) throws -> StoreResponse.Account {
let request = StoreRequest.authenticate(email: email, password: password, code: code)
let response = try await httpClient.send(request)
let response = try httpClient.send(request)
let decoded = try response.decode(StoreResponse.self, as: .xml)
switch decoded {
case let .account(account):
return account
case .item:
throw Error.invalidResponse
case let .failure(error):
switch error {
case StoreResponse.Error.invalidCredentials:
if isFirstAttempt {
return try await authenticate(email: email, password: password, code: code, isFirstAttempt: false)
return try authenticate(email: email, password: password, code: code, isFirstAttempt: false)
}
throw error
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
}
}
+7 -2
View File
@@ -11,6 +11,7 @@ import Networking
enum StoreEndpoint {
case authenticate(prefix: String, guid: String)
case download(guid: String)
case purchase
}
extension StoreEndpoint: HTTPEndpoint {
@@ -20,22 +21,26 @@ extension StoreEndpoint: HTTPEndpoint {
components.host = host
return components.url!
}
private var host: String {
switch self {
case let .authenticate(prefix, _):
return "\(prefix)-buy.itunes.apple.com"
case .download:
return "p25-buy.itunes.apple.com"
case .purchase:
return "buy.itunes.apple.com"
}
}
private var path: String {
switch self {
case let .authenticate(_, guid):
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"
}
}
}
+38 -9
View File
@@ -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,30 +26,38 @@ 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
}
}
var method: HTTPMethod {
return .post
}
var headers: [String: String] {
var headers: [String: String] = [
"User-Agent": "Configurator/2.15 (Macintosh; OS X 11.0.0; 16G29) AppleWebKit/2603.3.8",
"Content-Type": "application/x-www-form-urlencoded"
]
switch self {
case .authenticate:
break
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
}
var payload: HTTPPayload? {
switch self {
case let .authenticate(email, password, code):
@@ -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
])
}
}
}
@@ -75,8 +104,8 @@ extension StoreRequest {
let bsds: [String] = ["en0", "en1"]
var bsd: String = bsds[0]
var length : size_t = 0
var buffer : [CChar]
var length: size_t = 0
var buffer: [CChar]
var bsdIndex = Int32(if_nametoindex(bsd))
if bsdIndex == 0 {
@@ -84,7 +113,7 @@ extension StoreRequest {
bsdIndex = Int32(if_nametoindex(bsd))
guard bsdIndex != 0 else { fatalError("Could not read MAC address") }
}
let bsdData = Data(bsd.utf8)
var managementInfoBase = [CTL_NET, AF_ROUTE, 0, AF_LINK, NET_RT_IFLIST, bsdIndex]
@@ -107,7 +136,7 @@ extension StoreRequest {
let lower = rangeOfToken.upperBound
let upper = lower + MAC_ADDRESS_LENGTH
let macAddressData = infoData[lower..<upper]
let addressBytes = macAddressData.map{ String(format:"%02x", $0) }
let addressBytes = macAddressData.map { String(format: "%02x", $0) }
return addressBytes.joined().uppercased()
}
}
+112 -56
View File
@@ -11,24 +11,11 @@ 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
case passwordChanged = 2002
case genericError = 5002
case codeRequired = 1
case invalidLicense = 9610
@@ -36,6 +23,9 @@ extension StoreResponse {
case invalidAccount = 5001
case invalidItem = -10000
case lockedAccount = -10001
case invalidCountry = -128
case passwordTokenExpired = 2034
case priceMismatch = 2019
}
}
@@ -48,40 +38,65 @@ 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 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 {
switch message {
case "Your account information was entered incorrectly.":
self = .failure(error: Error.invalidCredentials)
case "An Apple ID verification code is required to sign in. Type your password followed by the verification code shown on your other devices.":
case [
"An Apple ID verification code is required to sign in.",
"Type your password followed by the verification code shown on your other devices."
].joined(separator: " "):
self = .failure(error: Error.codeRequired)
case "MZFinance.BadLogin.Configurator_message":
self = .failure(error: Error.codeRequired)
case "This Apple ID has been locked for security reasons. Visit iForgot to reset your account (https://iforgot.apple.com).":
case [
"This Apple ID has been locked for security reasons.",
"Visit iForgot to reset your account (https://iforgot.apple.com)."
].joined(separator: " "):
self = .failure(error: Error.lockedAccount)
default:
self = .failure(error: Error.unknownError)
}
}
}
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 {
case address
}
@@ -92,42 +107,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
}
}
}
}
+20 -15
View File
@@ -11,49 +11,54 @@ import Networking
public protocol iTunesClientInterface {
func lookup(
bundleIdentifier: String,
country: String,
countryCode: String,
deviceFamily: DeviceFamily
) async throws -> iTunesResponse.Result
) throws -> iTunesResponse.Result
func search(
term: String,
limit: Int,
country: String,
countryCode: String,
deviceFamily: DeviceFamily
) async throws -> [iTunesResponse.Result]
) throws -> [iTunesResponse.Result]
}
public final class iTunesClient: iTunesClientInterface {
private let httpClient: HTTPClient
public init(httpClient: HTTPClient) {
self.httpClient = httpClient
}
public func lookup(
bundleIdentifier: String,
country: String,
countryCode: String,
deviceFamily: DeviceFamily
) async throws -> iTunesResponse.Result {
) throws -> iTunesResponse.Result {
let request = iTunesRequest.lookup(
bundleIdentifier: bundleIdentifier,
country: country,
countryCode: countryCode,
deviceFamily: deviceFamily
)
let response = try await httpClient.send(request)
let response = try httpClient.send(request)
let decoded = try response.decode(iTunesResponse.self, as: .json)
guard let result = decoded.results.first else { throw Error.appNotFound }
return result
}
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 response = try await httpClient.send(request)
) throws -> [iTunesResponse.Result] {
let request = iTunesRequest.search(
term: term,
limit: limit,
countryCode: countryCode,
deviceFamily: deviceFamily
)
let response = try httpClient.send(request)
let decoded = try response.decode(iTunesResponse.self, as: .json)
return decoded.results
}
+1 -1
View File
@@ -20,7 +20,7 @@ extension iTunesEndpoint: HTTPEndpoint {
components.host = "itunes.apple.com"
return components.url!
}
private var path: String {
switch self {
case .search:
+6 -6
View File
@@ -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
}
}
+44 -40
View File
@@ -11,18 +11,20 @@ import XCTest
final class HTTPClientTests: XCTestCase {
private var sut: HTTPClient!
private var session: URLSessionMock!
override func setUp() {
super.setUp()
session = URLSessionMock()
sut = HTTPClient(session: session)
}
func test_GET_success_returnsValidResposne() async throws {
session.onData = { request in
func test_GET_success_returnsValidResposne() throws {
session.onDataTask = { request in
let url = try XCTUnwrap(request.url?.absoluteString)
XCTAssertTrue(url.hasPrefix("https://api.example.com"))
XCTAssertEqual(request.httpMethod, "GET")
let data = try XCTUnwrap("foo".data(using: .utf8))
let response = HTTPURLResponse(
url: URL(string: "https://example.com")!,
@@ -32,20 +34,20 @@ final class HTTPClientTests: XCTestCase {
)
return (data, response)
}
let response = try await sut.send(TestRequest.get(nil))
let response = try sut.send(TestRequest.get(nil))
let data = try XCTUnwrap(response.data)
XCTAssertEqual(String(data: data, encoding: .utf8), "foo")
}
func test_GET_failure_returnsInvalidResposne() async throws {
session.onData = { request in
func test_GET_failure_returnsInvalidResposne() throws {
session.onDataTask = { request in
let url = try XCTUnwrap(request.url?.absoluteString)
XCTAssertTrue(url.hasPrefix("https://api.example.com"))
XCTAssertEqual(request.httpMethod, "GET")
let data = try XCTUnwrap("foo".data(using: .utf8))
let response = URLResponse(
url: URL(string: "https://example.com")!,
mimeType: nil,
@@ -56,26 +58,28 @@ final class HTTPClientTests: XCTestCase {
}
do {
_ = try await sut.send(TestRequest.get(nil))
XCTFail()
_ = try sut.send(TestRequest.get(nil))
XCTFail("Call succeeded while expecting a failure.")
} catch {
XCTAssertNotNil(error)
}
}
func test_POST_xmlEncoding_returnsValidResponse() async throws {
session.onData = { request in
func test_POST_xmlEncoding_returnsValidResponse() throws {
session.onDataTask = { request in
let url = try XCTUnwrap(request.url?.absoluteString)
XCTAssertTrue(url.hasPrefix("https://api.example.com"))
XCTAssertEqual(request.httpMethod, "POST")
let data = try XCTUnwrap(request.httpBody)
let decoded = try PropertyListSerialization.propertyList(
from: data,
options: [],
format: nil
) as! [String: String]
let decoded = try XCTUnwrap(
PropertyListSerialization.propertyList(
from: data,
options: [],
format: nil
) as? [String: String]
)
XCTAssertEqual(decoded["foo"], "bar")
let response = HTTPURLResponse(
@@ -86,12 +90,12 @@ final class HTTPClientTests: XCTestCase {
)
return (data, response)
}
_ = try await sut.send(TestRequest.post(.xml(["foo": "bar"])))
_ = try sut.send(TestRequest.post(.xml(["foo": "bar"])))
}
func test_GET_urlEncoding_returnsValidResponse() async throws {
session.onData = { request in
func test_GET_urlEncoding_returnsValidResponse() throws {
session.onDataTask = { request in
let url = try XCTUnwrap(request.url?.absoluteString)
XCTAssertTrue(url.hasPrefix("https://api.example.com"))
XCTAssertTrue(url.hasSuffix("?foo=bar"))
@@ -105,17 +109,17 @@ final class HTTPClientTests: XCTestCase {
)
return (Data(), response)
}
_ = try await sut.send(TestRequest.get(.urlEncoding(["foo": "bar"])))
_ = try sut.send(TestRequest.get(.urlEncoding(["foo": "bar"])))
}
func test_POST_urlEncoding_returnsValidResponse() async throws {
session.onData = { request in
func test_POST_urlEncoding_returnsValidResponse() throws {
session.onDataTask = { request in
let url = try XCTUnwrap(request.url?.absoluteString)
let data = try XCTUnwrap(request.httpBody)
let decoded = String(data: data, encoding: .utf8)
let headerValue = try XCTUnwrap(request.allHTTPHeaderFields?["X-Test"])
XCTAssertTrue(url.hasPrefix("https://api.example.com"))
XCTAssertEqual(decoded, "foo=bar")
XCTAssertEqual(request.httpMethod, "POST")
@@ -129,15 +133,15 @@ final class HTTPClientTests: XCTestCase {
)
return (Data(), response)
}
_ = try await sut.send(TestRequest.post(.urlEncoding(["foo": "bar"])))
_ = try sut.send(TestRequest.post(.urlEncoding(["foo": "bar"])))
}
}
private enum TestRequest: HTTPRequest {
case get(HTTPPayload?)
case post(HTTPPayload)
var method: HTTPMethod {
switch self {
case .get:
@@ -146,14 +150,14 @@ private enum TestRequest: HTTPRequest {
return .post
}
}
var endpoint: HTTPEndpoint {
switch self {
case .get, .post:
return TestEndpoint.generic
}
}
var payload: HTTPPayload? {
switch self {
case let .get(payload):
@@ -162,7 +166,7 @@ private enum TestRequest: HTTPRequest {
return payload
}
}
var headers: [String: String] {
switch self {
case .get, .post:
@@ -173,7 +177,7 @@ private enum TestRequest: HTTPRequest {
private enum TestEndpoint: HTTPEndpoint {
case generic
var url: URL {
switch self {
case .generic:
@@ -10,30 +10,32 @@ import XCTest
final class HTTPDownloadClientTests: XCTestCase {
private var sut: HTTPDownloadClient!
override func setUp() {
super.setUp()
sut = HTTPDownloadClient()
}
func test_download_success_returnsValidResponse() async throws {
func test_download_success_returnsValidResponse() throws {
let source = try XCTUnwrap(URL(string: "https://proof.ovh.net/files/1Mb.dat"))
let target = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(UUID().uuidString)
var lastValue: Float = 0
try await sut.download(from: source, to: target) { value in
try sut.download(from: source, to: target) { value in
XCTAssertGreaterThanOrEqual(value, lastValue)
lastValue = value
}
XCTAssertTrue(FileManager.default.fileExists(atPath: target.path))
}
func test_download_failure_throwsError() async throws {
func test_download_failure_throwsError() throws {
let source = try XCTUnwrap(URL(string: "https://\(UUID().uuidString).test"))
let target = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(UUID().uuidString)
do {
try await sut.download(from: source, to: target) { _ in }
try sut.download(from: source, to: target) { _ in }
} catch {
XCTAssertNotNil(error)
}
@@ -9,28 +9,28 @@ import XCTest
@testable import Networking
final class HTTPResponseTests: XCTestCase {
func test_decode_jsonData_returnsObject() async throws {
func test_decode_jsonData_returnsObject() throws {
let data = try JSONEncoder().encode(["foo": "bar"])
let response = HTTPResponse(statusCode: 200, data: data)
let object = try response.decode([String: String].self, as: .json)
XCTAssertEqual(object["foo"], "bar")
}
func test_decode_xmlData_returnsObject() async throws {
func test_decode_xmlData_returnsObject() throws {
let data = try PropertyListEncoder().encode(["foo": "bar"])
let response = HTTPResponse(statusCode: 200, data: data)
let object = try response.decode([String: String].self, as: .xml)
XCTAssertEqual(object["foo"], "bar")
}
func test_decode_noData_returnsObject() async throws {
func test_decode_noData_returnsObject() throws {
let response = HTTPResponse(statusCode: 200, data: nil)
XCTAssertThrowsError(try response.decode([String: String].self, as: .xml))
}
func test_decode_invalidData_returnsObject() async throws {
func test_decode_invalidData_returnsObject() throws {
let data = try PropertyListEncoder().encode(["foo": "bar"])
let response = HTTPResponse(statusCode: 200, data: data)
@@ -0,0 +1,21 @@
//
// URLSessionDataTaskMock.swift
// NetworkingTests
//
// Created by Majd Alfhaily on 29.05.22.
//
import Foundation
import Networking
final class URLSessionDataTaskMock: URLSessionDataTaskInterface {
var onResume: (() -> Void)?
func resume() {
guard let onResume = onResume else {
fatalError("Override implementation using `onResume`.")
}
onResume()
}
}
+20 -6
View File
@@ -9,13 +9,27 @@ import Foundation
import Networking
final class URLSessionMock: URLSessionInterface {
var onData: ((_ request: URLRequest) async throws -> (Data, URLResponse))?
var onDataTask: ((URLRequest) throws -> (data: Data?, response: URLResponse?))?
func data(for request: URLRequest) async throws -> (Data, URLResponse) {
guard let onData = onData else {
fatalError("Override implementation using `onData`.")
func dataTask(
with request: URLRequest,
completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void
) -> URLSessionDataTaskInterface {
guard let onDataTask = onDataTask else {
fatalError("Override implementation using `onDataTask`.")
}
return try await onData(request)
let dataTask = URLSessionDataTaskMock()
dataTask.onResume = {
do {
let result = try onDataTask(request)
completionHandler(result.data, result.response, nil)
} catch {
completionHandler(nil, nil, error)
}
}
return dataTask
}
}
+53
View File
@@ -0,0 +1,53 @@
name: IPATool
packages:
ArgumentParser:
url: https://github.com/apple/swift-argument-parser
revision: 1.1.2
ZIPFoundation:
url: https://github.com/weichsel/ZIPFoundation
revision: 0.9.14
KeychainAccess:
url: https://github.com/kishikawakatsumi/KeychainAccess
revision: v4.2.2
targets:
CLI:
type: application
platform: iOS
deploymentTarget: 13.0
settings:
ENABLE_BITCODE: NO
PRODUCT_BUNDLE_IDENTIFIER: ipatool
CODE_SIGN_STYLE: Manual
sources:
- Sources/CLI
dependencies:
- package: ArgumentParser
- package: KeychainAccess
- package: ZIPFoundation
- target: StoreAPI
- target: Networking
- target: Persistence
StoreAPI:
type: library.static
platform: iOS
deploymentTarget: 13.0
sources:
- Sources/StoreAPI
dependencies:
- package: ArgumentParser
- package: ZIPFoundation
- target: Networking
Networking:
type: library.static
platform: iOS
deploymentTarget: 13.0
sources:
- Sources/Networking
Persistence:
type: library.static
platform: iOS
deploymentTarget: 13.0
sources:
- Sources/Persistence
dependencies:
- package: KeychainAccess