mirror of
https://github.com/majd/ipatool
synced 2026-11-29 02:37:52 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4f3115d60f | ||
|
|
0e38e43d8b | ||
|
|
73e9bd90d1 | ||
|
|
e76dbf044e | ||
|
|
d82e819d4e | ||
|
|
19ac47d098 | ||
|
|
fece9ea79c | ||
|
|
1b31ee6556 | ||
|
|
fbd9d74729 | ||
|
|
8d2467491e | ||
|
|
4eba914bff | ||
|
|
56cc64fcef | ||
|
|
7813e78e3c | ||
|
|
50a1e546ef | ||
|
|
094ff93693 | ||
|
|
5d014266e3 | ||
|
|
8dd1a8508d | ||
|
|
dff5a5ad0b | ||
|
|
6356b522df | ||
|
|
a2cb7c653e | ||
|
|
2f154ad4f9 | ||
|
|
a3b322c8da | ||
|
|
5386d36275 | ||
|
|
7e21c8571a | ||
|
|
ff582bb97b | ||
|
|
98bd6f0e45 | ||
|
|
40d1f700b5 | ||
|
|
a2ce1c4213 | ||
|
|
d42ba7ef4b | ||
|
|
721e23fd8a | ||
|
|
15dbfe423a | ||
|
|
f77b0d94d9 | ||
|
|
99c1bf1013 | ||
|
|
1a71cf89b4 | ||
|
|
3088cde9ba | ||
|
|
5d6e83c2e9 | ||
|
|
001ee4ca12 | ||
|
|
0e57952e06 | ||
|
|
12db867c54 | ||
|
|
d5c4f88533 | ||
|
|
65439346eb | ||
|
|
eb42a63845 | ||
|
|
4633cf17b6 | ||
|
|
b73de7cd88 | ||
|
|
169a17f7ac | ||
|
|
d913b16c55 | ||
|
|
915c70dcfa | ||
|
|
b2711aa8b4 | ||
|
|
9c00557474 | ||
|
|
5e06154ccb | ||
|
|
102f510ddb | ||
|
|
bd8d4e7e3f | ||
|
|
19196d70ce | ||
|
|
bdee2b94c2 | ||
|
|
ff43c07a32 | ||
|
|
07a0f3310d | ||
|
|
9cfd72d142 | ||
|
|
a16afb5c7b | ||
|
|
ec4b6cfc29 | ||
|
|
83515013cd | ||
|
|
1577e1b8bc | ||
|
|
8d3167cc6e | ||
|
|
964fbe1fe7 | ||
|
|
943a7aff05 | ||
|
|
8c591f0a1f | ||
|
|
119c55359b | ||
|
|
4df3c492f6 | ||
|
|
cea1db77e9 | ||
|
|
3040955de1 | ||
|
|
f0c7e02db9 | ||
|
|
cd54b3bbcb | ||
|
|
82f70f23c7 | ||
|
|
96115462d0 | ||
|
|
1b65463007 | ||
|
|
dba1d3b195 | ||
|
|
eee3416b67 | ||
|
|
2f3b0330e0 | ||
|
|
b257a5c8b1 | ||
|
|
df45f1cc44 | ||
|
|
a92c829fb7 | ||
|
|
7569f89208 | ||
|
|
8003c042f4 | ||
|
|
74165461cb | ||
|
|
fdccf874b9 | ||
|
|
29731ec0b1 | ||
|
|
97edbccc58 | ||
|
|
1463c85279 | ||
|
|
7d8531b3e0 | ||
|
|
7507290769 | ||
|
|
644d6a7104 | ||
|
|
dfd2709d2a | ||
|
|
e3adde06b3 | ||
|
|
fc49c7af91 | ||
|
|
234ee2fe52 | ||
|
|
b030cd454f | ||
|
|
f3a54098ea | ||
|
|
69c07d0062 | ||
|
|
f0922b303e | ||
|
|
5a4d2f5e8d | ||
|
|
972f0b2cd0 | ||
|
|
03993b2b93 | ||
|
|
5009048d44 | ||
|
|
59fb28cee0 | ||
|
|
5f1fb02a12 | ||
|
|
32c6012918 | ||
|
|
f55e9ac53b | ||
|
|
a83dcb2849 | ||
|
|
6ff82c66aa | ||
|
|
c4610ca808 | ||
|
|
1563a82a20 | ||
|
|
48ed1df5c7 | ||
|
|
1448ca3ebc | ||
|
|
a3e483830f | ||
|
|
8cfd902bbf | ||
|
|
8165331378 | ||
|
|
bed12a55a9 | ||
|
|
73a416c917 |
No files matched your search
@@ -0,0 +1 @@
|
||||
github: majd
|
||||
@@ -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
|
||||
@@ -0,0 +1,64 @@
|
||||
name: Dry Build
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
build_windows:
|
||||
name: Build for Windows
|
||||
runs-on: macos-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
arch: [ arm64, amd64 ]
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/setup-go@v3
|
||||
with:
|
||||
go-version: '1.19.3'
|
||||
cache: true
|
||||
- run: ./tools/version.sh
|
||||
- run: go build -o ipatool-$GOOS-$GOARCH.exe
|
||||
env:
|
||||
GOOS: windows
|
||||
GOARCH: ${{ matrix.arch }}
|
||||
build_linux:
|
||||
name: Build for Linux
|
||||
runs-on: macos-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
arch: [ arm64, amd64 ]
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/setup-go@v3
|
||||
with:
|
||||
go-version: '1.19.3'
|
||||
cache: true
|
||||
- run: ./tools/version.sh
|
||||
- run: go build -o ipatool-$GOOS-$GOARCH
|
||||
env:
|
||||
GOOS: linux
|
||||
GOARCH: ${{ matrix.arch }}
|
||||
build_macos:
|
||||
name: Build for macOS
|
||||
runs-on: macos-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
arch: [ arm64, amd64 ]
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/setup-go@v3
|
||||
with:
|
||||
go-version: '1.19.3'
|
||||
cache: true
|
||||
- run: ./tools/version.sh
|
||||
- run: go build -o ipatool-$GOOS-$GOARCH
|
||||
env:
|
||||
GOOS: darwin
|
||||
GOARCH: ${{ matrix.arch }}
|
||||
CGO_CFLAGS: -mmacosx-version-min=10.15
|
||||
CGO_LDFLAGS: -mmacosx-version-min=10.15
|
||||
@@ -0,0 +1,44 @@
|
||||
name: Integration Tests
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Build
|
||||
runs-on: macos-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/setup-go@v3
|
||||
with:
|
||||
go-version: '1.19.3'
|
||||
cache: true
|
||||
- run: ./tools/version.sh
|
||||
- run: go build -o ipatool
|
||||
env:
|
||||
CGO_CFLAGS: -mmacosx-version-min=10.15
|
||||
CGO_LDFLAGS: -mmacosx-version-min=10.15
|
||||
- uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: ipatool
|
||||
path: ipatool
|
||||
if-no-files-found: error
|
||||
test:
|
||||
name: Test
|
||||
runs-on: macos-latest
|
||||
needs: [build]
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
command: [auth, download, purchase, search]
|
||||
steps:
|
||||
- uses: actions/download-artifact@v2
|
||||
with:
|
||||
name: ipatool
|
||||
path: build
|
||||
- run: chmod +x ./build/ipatool
|
||||
- run: ./build/ipatool ${{ matrix.command }} --help
|
||||
@@ -0,0 +1,18 @@
|
||||
name: Issues Cleanup
|
||||
|
||||
on:
|
||||
issue_comment:
|
||||
types: [created]
|
||||
schedule:
|
||||
- cron: "0 * * * *" # Every hour, every day
|
||||
|
||||
jobs:
|
||||
scan-issues:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: lee-dohm/no-response@v0.5.0
|
||||
with:
|
||||
token: ${{ github.token }}
|
||||
daysUntilClose: 7
|
||||
closeComment: This issue has been automatically closed because there has been no response from the original author.
|
||||
responseRequiredLabel: auto-close
|
||||
@@ -0,0 +1,212 @@
|
||||
name: Release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "v*"
|
||||
|
||||
jobs:
|
||||
get_version:
|
||||
name: Get version
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- id: set_output
|
||||
run: echo ::set-output name=version::${GITHUB_REF#refs/tags/v}
|
||||
outputs:
|
||||
version: ${{ steps.set_output.outputs.version }}
|
||||
test:
|
||||
name: Run tests
|
||||
runs-on: macos-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/setup-go@v3
|
||||
with:
|
||||
go-version: '1.19.3'
|
||||
cache: true
|
||||
- run: ./tools/version.sh
|
||||
- run: go test -v github.com/majd/ipatool/...
|
||||
build:
|
||||
name: Build
|
||||
runs-on: macos-latest
|
||||
needs: [get_version, test]
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/setup-go@v3
|
||||
with:
|
||||
go-version: '1.19.3'
|
||||
cache: true
|
||||
- run: ./tools/version.sh
|
||||
- run: go build -o ipatool-${{ needs.get_version.outputs.version }}-windows-arm64.exe
|
||||
env:
|
||||
GOOS: windows
|
||||
GOARCH: arm64
|
||||
- run: go build -o ipatool-${{ needs.get_version.outputs.version }}-windows-amd64.exe
|
||||
env:
|
||||
GOOS: windows
|
||||
GOARCH: amd64
|
||||
- run: go build -o ipatool-${{ needs.get_version.outputs.version }}-linux-arm64
|
||||
env:
|
||||
GOOS: linux
|
||||
GOARCH: arm64
|
||||
- run: go build -o ipatool-${{ needs.get_version.outputs.version }}-linux-amd64
|
||||
env:
|
||||
GOOS: linux
|
||||
GOARCH: amd64
|
||||
- run: go build -o ipatool-${{ needs.get_version.outputs.version }}-macos-arm64
|
||||
env:
|
||||
GOOS: darwin
|
||||
GOARCH: arm64
|
||||
CGO_CFLAGS: -mmacosx-version-min=10.15
|
||||
CGO_LDFLAGS: -mmacosx-version-min=10.15
|
||||
CGO_ENABLED: 1
|
||||
- run: go build -o ipatool-${{ needs.get_version.outputs.version }}-macos-amd64
|
||||
env:
|
||||
GOOS: darwin
|
||||
GOARCH: amd64
|
||||
CGO_CFLAGS: -mmacosx-version-min=10.15
|
||||
CGO_LDFLAGS: -mmacosx-version-min=10.15
|
||||
CGO_ENABLED: 1
|
||||
- uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-windows-arm64.exe
|
||||
path: ipatool-${{ needs.get_version.outputs.version }}-windows-arm64.exe
|
||||
if-no-files-found: error
|
||||
- uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-windows-amd64.exe
|
||||
path: ipatool-${{ needs.get_version.outputs.version }}-windows-amd64.exe
|
||||
if-no-files-found: error
|
||||
- uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-linux-arm64
|
||||
path: ipatool-${{ needs.get_version.outputs.version }}-linux-arm64
|
||||
if-no-files-found: error
|
||||
- uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-linux-amd64
|
||||
path: ipatool-${{ needs.get_version.outputs.version }}-linux-amd64
|
||||
if-no-files-found: error
|
||||
- uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-macos-arm64
|
||||
path: ipatool-${{ needs.get_version.outputs.version }}-macos-arm64
|
||||
if-no-files-found: error
|
||||
- uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-macos-amd64
|
||||
path: ipatool-${{ needs.get_version.outputs.version }}-macos-amd64
|
||||
if-no-files-found: error
|
||||
release_windows:
|
||||
name: Release for Windows
|
||||
runs-on: ubuntu-latest
|
||||
needs: [get_version, build]
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
arch: [ arm64, amd64 ]
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/download-artifact@v2
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-windows-${{ matrix.arch }}.exe
|
||||
path: bin
|
||||
- run: tar -czvf $FILE.tar.gz bin/$FILE.exe
|
||||
env:
|
||||
FILE: ipatool-${{ needs.get_version.outputs.version }}-windows-${{ matrix.arch }}
|
||||
- run: ./tools/sha256sum.sh $TARBALL > $TARBALL.sha256sum
|
||||
env:
|
||||
TARBALL: ipatool-${{ needs.get_version.outputs.version }}-windows-${{ matrix.arch }}.tar.gz
|
||||
- uses: svenstaro/upload-release-action@v2
|
||||
with:
|
||||
repo_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
file: ipatool-${{ needs.get_version.outputs.version }}-windows-${{ matrix.arch }}.*
|
||||
tag: ${{ github.ref }}
|
||||
overwrite: false
|
||||
file_glob: true
|
||||
release_linux:
|
||||
name: Release for Linux
|
||||
runs-on: ubuntu-latest
|
||||
needs: [get_version, build, release_windows]
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
arch: [ arm64, amd64 ]
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/download-artifact@v2
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-linux-${{ matrix.arch }}
|
||||
path: bin
|
||||
- run: tar -czvf $FILE.tar.gz bin/$FILE
|
||||
env:
|
||||
FILE: ipatool-${{ needs.get_version.outputs.version }}-linux-${{ matrix.arch }}
|
||||
- run: ./tools/sha256sum.sh $TARBALL > $TARBALL.sha256sum
|
||||
env:
|
||||
TARBALL: ipatool-${{ needs.get_version.outputs.version }}-linux-${{ matrix.arch }}.tar.gz
|
||||
- uses: svenstaro/upload-release-action@v2
|
||||
with:
|
||||
repo_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
file: ipatool-${{ needs.get_version.outputs.version }}-linux-${{ matrix.arch }}.*
|
||||
tag: ${{ github.ref }}
|
||||
overwrite: false
|
||||
file_glob: true
|
||||
release_macos:
|
||||
name: Release for macOS
|
||||
runs-on: ubuntu-latest
|
||||
needs: [get_version, build, release_windows, release_linux]
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
with:
|
||||
path: ./ipatool
|
||||
- uses: actions/download-artifact@v2
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-macos-arm64
|
||||
path: bin
|
||||
- run: tar -czvf $BIN.tar.gz bin/$BIN && rm -rf bin/
|
||||
env:
|
||||
BIN: ipatool-${{ needs.get_version.outputs.version }}-macos-arm64
|
||||
- uses: actions/download-artifact@v2
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-macos-amd64
|
||||
path: bin
|
||||
- run: tar -czvf $FILE.tar.gz bin/$FILE && rm -rf bin/
|
||||
env:
|
||||
FILE: ipatool-${{ needs.get_version.outputs.version }}-macos-amd64
|
||||
- id: sha256
|
||||
run: |
|
||||
SHA256_ARM64=$(./ipatool/tools/sha256sum.sh ipatool-${{ needs.get_version.outputs.version }}-macos-arm64.tar.gz)
|
||||
SHA256_AMD64=$(./ipatool/tools/sha256sum.sh ipatool-${{ needs.get_version.outputs.version }}-macos-amd64.tar.gz)
|
||||
echo $SHA256_ARM64 > ipatool-${{ needs.get_version.outputs.version }}-macos-arm64.tar.gz.sha256sum
|
||||
echo $SHA256_AMD64 > ipatool-${{ needs.get_version.outputs.version }}-macos-amd64.tar.gz.sha256sum
|
||||
echo ::set-output name=sha256_arm64::$SHA256_ARM64
|
||||
echo ::set-output name=sha256_amd64::$SHA256_AMD64
|
||||
- uses: svenstaro/upload-release-action@v2
|
||||
with:
|
||||
repo_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
file: ipatool-${{ needs.get_version.outputs.version }}-macos-*
|
||||
tag: ${{ github.ref }}
|
||||
overwrite: false
|
||||
file_glob: true
|
||||
- uses: actions/checkout@v2
|
||||
with:
|
||||
repository: ${{ secrets.HOMEBREW_REPO }}
|
||||
ref: main
|
||||
token: ${{ secrets.GH_TOKEN }}
|
||||
path: homebrew-repo
|
||||
- run: |
|
||||
cd homebrew-repo
|
||||
sed -i "3s/.*/ sha256 \"$SHA256_ARM64\"/" Casks/ipatool.rb
|
||||
sed -i "4s/.*/ url \"https:\/\/github.com\/majd\/ipatool\/releases\/download\/v${{ needs.get_version.outputs.version }}\/ipatool-${{ needs.get_version.outputs.version }}-macos-arm64.tar.gz\"/" Casks/ipatool.rb
|
||||
sed -i "5s/.*/ binary \"bin\/ipatool-${{ needs.get_version.outputs.version }}-macos-arm64\", target: \"ipatool\"/" Casks/ipatool.rb
|
||||
sed -i "7s/.*/ sha256 \"$SHA256_AMD64\"/" Casks/ipatool.rb
|
||||
sed -i "8s/.*/ url \"https:\/\/github.com\/majd\/ipatool\/releases\/download\/v${{ needs.get_version.outputs.version }}\/ipatool-${{ needs.get_version.outputs.version }}-macos-amd64.tar.gz\"/" Casks/ipatool.rb
|
||||
sed -i "9s/.*/ binary \"bin\/ipatool-${{ needs.get_version.outputs.version }}-macos-amd64\", target: \"ipatool\"/" Casks/ipatool.rb
|
||||
sed -i "12s/.*/ version \"${{ needs.get_version.outputs.version }}\"/" 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"
|
||||
env:
|
||||
SHA256_ARM64: ${{ steps.sha256.outputs.sha256_arm64 }}
|
||||
SHA256_AMD64: ${{ steps.sha256.outputs.sha256_amd64 }}
|
||||
@@ -0,0 +1,19 @@
|
||||
name: Unit Tests
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
run_tests:
|
||||
name: Run tests
|
||||
runs-on: macos-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/setup-go@v3
|
||||
with:
|
||||
go-version: '1.19.3'
|
||||
cache: true
|
||||
- run: ./tools/version.sh
|
||||
- run: go test -v github.com/majd/ipatool/...
|
||||
+3
-126
@@ -1,129 +1,6 @@
|
||||
### macOS ###
|
||||
# General
|
||||
.DS_Store
|
||||
.AppleDouble
|
||||
.LSOverride
|
||||
|
||||
# Icon must end with two \r
|
||||
Icon
|
||||
|
||||
|
||||
# Thumbnails
|
||||
._*
|
||||
|
||||
# Files that might appear in the root of a volume
|
||||
.DocumentRevisions-V100
|
||||
.fseventsd
|
||||
.Spotlight-V100
|
||||
.TemporaryItems
|
||||
.Trashes
|
||||
.VolumeIcon.icns
|
||||
.com.apple.timemachine.donotpresent
|
||||
|
||||
# Directories potentially created on remote AFP share
|
||||
.AppleDB
|
||||
.AppleDesktop
|
||||
Network Trash Folder
|
||||
Temporary Items
|
||||
.apdisk
|
||||
|
||||
### Swift ###
|
||||
# Xcode
|
||||
#
|
||||
# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
|
||||
|
||||
## User settings
|
||||
xcuserdata/
|
||||
|
||||
## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9)
|
||||
*.xcscmblueprint
|
||||
*.xccheckout
|
||||
|
||||
## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4)
|
||||
build/
|
||||
DerivedData/
|
||||
*.moved-aside
|
||||
*.pbxuser
|
||||
!default.pbxuser
|
||||
*.mode1v3
|
||||
!default.mode1v3
|
||||
*.mode2v3
|
||||
!default.mode2v3
|
||||
*.perspectivev3
|
||||
!default.perspectivev3
|
||||
|
||||
## Obj-C/Swift specific
|
||||
*.hmap
|
||||
|
||||
## App packaging
|
||||
*.ipa
|
||||
*.dSYM.zip
|
||||
*.dSYM
|
||||
|
||||
## Playgrounds
|
||||
timeline.xctimeline
|
||||
playground.xcworkspace
|
||||
|
||||
# Swift Package Manager
|
||||
# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies.
|
||||
# Packages/
|
||||
# Package.pins
|
||||
# Package.resolved
|
||||
# *.xcodeproj
|
||||
# Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata
|
||||
# hence it is not needed unless you have added a package configuration file to your project
|
||||
# .swiftpm
|
||||
|
||||
.build/
|
||||
|
||||
# CocoaPods
|
||||
# We recommend against adding the Pods directory to your .gitignore. However
|
||||
# you should judge for yourself, the pros and cons are mentioned at:
|
||||
# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control
|
||||
# Pods/
|
||||
# Add this line if you want to avoid checking in source code from the Xcode workspace
|
||||
# *.xcworkspace
|
||||
|
||||
# Carthage
|
||||
# Add this line if you want to avoid checking in source code from Carthage dependencies.
|
||||
# Carthage/Checkouts
|
||||
|
||||
Carthage/Build/
|
||||
|
||||
# Add this lines if you are using Accio dependency management (Deprecated since Xcode 12)
|
||||
# Dependencies/
|
||||
# .accio/
|
||||
|
||||
# fastlane
|
||||
# It is recommended to not store the screenshots in the git repo.
|
||||
# Instead, use fastlane to re-generate the screenshots whenever they are needed.
|
||||
# For more information about the recommended setup visit:
|
||||
# https://docs.fastlane.tools/best-practices/source-control/#source-control
|
||||
|
||||
fastlane/report.xml
|
||||
fastlane/Preview.html
|
||||
fastlane/screenshots/**/*.png
|
||||
fastlane/test_output
|
||||
|
||||
# Code Injection
|
||||
# After new code Injection tools there's a generated folder /iOSInjectionProject
|
||||
# https://github.com/johnno1962/injectionforxcode
|
||||
|
||||
iOSInjectionProject/
|
||||
|
||||
### Xcode ###
|
||||
# Xcode
|
||||
# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
|
||||
|
||||
|
||||
|
||||
|
||||
## Gcc Patch
|
||||
/*.gcno
|
||||
|
||||
### Xcode Patch ###
|
||||
*.xcodeproj/*
|
||||
!*.xcodeproj/project.pbxproj
|
||||
!*.xcodeproj/xcshareddata/
|
||||
!*.xcworkspace/contents.xcworkspacedata
|
||||
**/xcshareddata/WorkspaceSettings.xcsettings
|
||||
.vscode/
|
||||
.idea/
|
||||
cmd/version.go
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
## Changelog
|
||||
|
||||
### Version [2.0.3](https://github.com/majd/ipatool/releases/tag/v2.0.3)
|
||||
|
||||
- Added support for downloading Apple Arcade games.
|
||||
- Fixed windows builds not having exe extension.
|
||||
|
||||
|
||||
### Version [2.0.2](https://github.com/majd/ipatool/releases/tag/v2.0.2)
|
||||
|
||||
- Fixed Sinf patches when the app contains an Apple Watch app.
|
||||
- Added storefront code for Albania.
|
||||
- Fixed default output path to be current working directory.
|
||||
|
||||
### Version [2.0.1](https://github.com/majd/ipatool/releases/tag/v2.0.1)
|
||||
|
||||
- Linux & Windows releases now include the sha256 hash.
|
||||
- Added storefront code for Mongolia.
|
||||
|
||||
### Version [2.0.0](https://github.com/majd/ipatool/releases/tag/v2.0.0)
|
||||
|
||||
- Added support for Windows.
|
||||
- Added support for Linux.
|
||||
- Added support for generating autocompletion script using the `completion` command.
|
||||
- Implemented new `auth info` command.
|
||||
- Implemented `--verbose` flag that replaces the `--debug-level` flag to enable verbose logging.
|
||||
- Implemented `--format` which allows specifying logs output format to either text or json (default: text).
|
||||
- Implemented `--non-interactive` flag to disable running the tool in an interactive session.
|
||||
- The relevant command (i.e. purchase) will now automatically determine the country and the device family from the authenticated account. The following flags have been deprecated.
|
||||
- `--country`
|
||||
- `--device-family`
|
||||
- Improved structured logging.
|
||||
- Improved error handling.
|
||||
- Improved support for automated systems.
|
||||
- Added unit tests to cover the majority of the private App Store API logic.
|
||||
|
||||
### Version [1.1.4](https://github.com/majd/ipatool/releases/tag/v1.1.4)
|
||||
|
||||
- Add support for patching old code signature revisions as a fallback mechanism.
|
||||
|
||||
### Version [1.1.3](https://github.com/majd/ipatool/releases/tag/v1.1.3)
|
||||
|
||||
- Fixed keychain access on iOS.
|
||||
|
||||
### Version [1.1.2](https://github.com/majd/ipatool/releases/tag/v1.1.2)
|
||||
|
||||
- Improved error message for expired token.
|
||||
- Disabled print buffering and output errors to stderr.
|
||||
- Added linter.
|
||||
- Add support for running on iOS.
|
||||
|
||||
### Version [1.1.1](https://github.com/majd/ipatool/releases/tag/v1.1.1)
|
||||
|
||||
- Update swift-argument-parser dependency.
|
||||
- Remove usage of Swift concurrency.
|
||||
- Add backward-compatibility for macOS 10.11+.
|
||||
|
||||
### Version [1.1.0](https://github.com/majd/ipatool/releases/tag/v1.1.0)
|
||||
|
||||
- Added support for purchasing apps.
|
||||
- Implemented auth command.
|
||||
- Implemented purchase command.
|
||||
- Implemented --purchase flag in download command.
|
||||
- Added price checks for purchase flow.
|
||||
|
||||
|
||||
### Version [1.0.9](https://github.com/majd/ipatool/releases/tag/v1.0.9)
|
||||
|
||||
- Fixed building for older macOS versions.
|
||||
- Fixed 2FA code not being requested.
|
||||
|
||||
|
||||
### Version [1.0.8](https://github.com/majd/ipatool/releases/tag/v1.0.8)
|
||||
|
||||
- Added --output option to the download command for specifying the destination path for the downloaded app package.
|
||||
|
||||
### Version [1.0.7](https://github.com/majd/ipatool/releases/tag/v1.0.7)
|
||||
|
||||
- Fixed login requests to the store API when the 2FA code is required.
|
||||
|
||||
### Version [1.0.6](https://github.com/majd/ipatool/releases/tag/v1.0.6)
|
||||
|
||||
- Added support for supplying 2FA code in non-interactive sessions.
|
||||
|
||||
### Version [1.0.5](https://github.com/majd/ipatool/releases/tag/v1.0.5)
|
||||
|
||||
- Added support for specifying device family.
|
||||
|
||||
### Version [1.0.4](https://github.com/majd/ipatool/releases/tag/v1.0.4)
|
||||
|
||||
- Added support for specifying the iTunes Store region.
|
||||
|
||||
### Version [1.0.3](https://github.com/majd/ipatool/releases/tag/v1.0.3)
|
||||
|
||||
- Improved console logging.
|
||||
|
||||
### Version [1.0.2](https://github.com/majd/ipatool/releases/tag/v1.0.2)
|
||||
|
||||
- Improved error messages.
|
||||
|
||||
### Version [1.0.1](https://github.com/majd/ipatool/releases/tag/v1.0.1)
|
||||
|
||||
- Grammatical fixes.
|
||||
|
||||
### Version [1.0.0](https://github.com/majd/ipatool/releases/tag/v1.0.0)
|
||||
|
||||
- Initial release.
|
||||
@@ -0,0 +1,140 @@
|
||||
# IPATool
|
||||
|
||||
[](https://GitHub.com/majd/ipatool/releases/)
|
||||
[](https://github.com/majd/ipatool/blob/main/LICENSE)
|
||||
|
||||
`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.
|
||||
|
||||

|
||||
|
||||
- [Requirements](#requirements)
|
||||
- [Installation](#installation)
|
||||
- [Manual](#manual)
|
||||
- [Package Manager (macOS)](#package-manager-macos)
|
||||
- [Usage](#usage)
|
||||
- [Compiling](#compiling)
|
||||
- [License](#license)
|
||||
- [Changelog](https://github.com/majd/ipatool/blob/main/CHANGELOG.md)
|
||||
- [FAQ](https://github.com/majd/ipatool/wiki/FAQ)
|
||||
|
||||
## Requirements
|
||||
- Supported operating system (Windows, Linux or macOS).
|
||||
- Apple ID set up to use the App Store.
|
||||
|
||||
## Installation
|
||||
|
||||
### Manual
|
||||
|
||||
You can grab the latest version of `ipatool` from [GitHub releases](https://github.com/majd/ipatool/releases).
|
||||
|
||||
### Package Manager (macOS)
|
||||
|
||||
You can install `ipatool` using [Homebrew](https://brew.sh).
|
||||
|
||||
```shell
|
||||
$ brew tap majd/repo
|
||||
$ brew install ipatool
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
To authenticate with the App Store, use the `auth` command.
|
||||
|
||||
```
|
||||
Authenticate with the App Store
|
||||
|
||||
Usage:
|
||||
ipatool auth [command]
|
||||
|
||||
Available Commands:
|
||||
info Show current account info
|
||||
login Login to the App Store
|
||||
revoke Revoke your App Store credentials
|
||||
|
||||
Flags:
|
||||
-h, --help help for auth
|
||||
|
||||
Global Flags:
|
||||
--format format sets output format for command; can be 'text', 'json' (default text)
|
||||
--non-interactive run in non-interactive session
|
||||
--verbose enables verbose logs
|
||||
|
||||
Use "ipatool auth [command] --help" for more information about a command.
|
||||
```
|
||||
|
||||
To search for apps on the App Store, use the `search` command.
|
||||
|
||||
```
|
||||
Search for iOS apps available on the App Store
|
||||
|
||||
Usage:
|
||||
ipatool search <term> [flags]
|
||||
|
||||
Flags:
|
||||
-h, --help help for search
|
||||
-l, --limit int maximum amount of search results to retrieve (default 5)
|
||||
|
||||
Global Flags:
|
||||
--format format sets output format for command; can be 'text', 'json' (default text)
|
||||
--non-interactive run in non-interactive session
|
||||
--verbose enables verbose logs
|
||||
```
|
||||
|
||||
To obtain a license for an app, use the `purchase` command.
|
||||
|
||||
```
|
||||
Obtain a license for the app from the App Store
|
||||
|
||||
Usage:
|
||||
ipatool purchase [flags]
|
||||
|
||||
Flags:
|
||||
-b, --bundle-identifier string Bundle identifier of the target iOS app (required)
|
||||
-h, --help help for purchase
|
||||
|
||||
Global Flags:
|
||||
--format format sets output format for command; can be 'text', 'json' (default text)
|
||||
--non-interactive run in non-interactive session
|
||||
--verbose enables verbose logs
|
||||
```
|
||||
|
||||
To download a copy of the ipa file, use the `download` command.
|
||||
|
||||
```
|
||||
Download (encrypted) iOS app packages from the App Store
|
||||
|
||||
Usage:
|
||||
ipatool download [flags]
|
||||
|
||||
Flags:
|
||||
-b, --bundle-identifier string The bundle identifier of the target iOS app (required)
|
||||
-h, --help help for download
|
||||
-o, --output string The destination path of the downloaded app package
|
||||
--purchase Obtain a license for the app if needed
|
||||
|
||||
Global Flags:
|
||||
--format format sets output format for command; can be 'text', 'json' (default text)
|
||||
--non-interactive run in non-interactive session
|
||||
--verbose enables verbose logs
|
||||
```
|
||||
|
||||
**Note:** the tool runs in interactive mode by default. Use the `--non-interactive` flag
|
||||
if running in an automated environment.
|
||||
|
||||
## Compiling
|
||||
|
||||
The tool can be compiled using the Go toolchain.
|
||||
|
||||
```shell
|
||||
$ go build -o ipatool
|
||||
```
|
||||
|
||||
Unit tests can be executed with the following command.
|
||||
|
||||
```shell
|
||||
$ go test -v github.com/majd/ipatool/...
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
IPATool is released under the [MIT license](https://github.com/majd/ipatool/blob/main/LICENSE).
|
||||
@@ -1,166 +0,0 @@
|
||||
//
|
||||
// Download.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import ArgumentParser
|
||||
import Foundation
|
||||
|
||||
struct Download: ParsableCommand {
|
||||
static var configuration: CommandConfiguration {
|
||||
return .init(abstract: "Download (encrypted) iOS app packages from the App Store.")
|
||||
}
|
||||
|
||||
@Option(name: [.short, .long], help: "The bundle identifier of the target iOS app.")
|
||||
private var bundleIdentifier: String
|
||||
|
||||
@Option(name: [.short, .long], help: "The email address for the Apple ID.")
|
||||
private var email: String?
|
||||
|
||||
@Option(name: [.short, .long], help: "The password for the Apple ID.")
|
||||
private var password: String?
|
||||
|
||||
@Option
|
||||
private var logLevel: LogLevel = .info
|
||||
}
|
||||
|
||||
extension Download {
|
||||
func run() throws {
|
||||
let logger = ConsoleLogger(level: logLevel)
|
||||
|
||||
logger.log("Creating HTTP client...", level: .debug)
|
||||
let httpClient = HTTPClient(urlSession: URLSession.shared)
|
||||
|
||||
logger.log("Creating iTunes client...", level: .debug)
|
||||
let itunesClient = iTunesClient(httpClient: httpClient)
|
||||
|
||||
logger.log("Creating App Store client...", level: .debug)
|
||||
let storeClient = StoreClient(httpClient: httpClient)
|
||||
|
||||
logger.log("Creating download client...", level: .debug)
|
||||
let downloadClient = HTTPDownloadClient()
|
||||
|
||||
logger.log("Querying the iTunes store for '\(bundleIdentifier)'...", level: .info)
|
||||
let app: iTunesResponse.Result
|
||||
|
||||
do {
|
||||
app = try itunesClient.lookup(bundleIdentifier: bundleIdentifier)
|
||||
} 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)
|
||||
}
|
||||
logger.log("Found app: \(app.name) (\(app.version)).", level: .debug)
|
||||
|
||||
let email: String
|
||||
let password: String
|
||||
|
||||
if let cliEmail = self.email {
|
||||
email = cliEmail
|
||||
} else if let envEmail = ProcessInfo.processInfo.environment["IPATOOL_EMAIL"] {
|
||||
email = envEmail
|
||||
} else if let inputEmail = String(validatingUTF8: UnsafePointer<CChar>(getpass(logger.compile("Enter Apple ID email: ", level: .warning)))) {
|
||||
email = inputEmail
|
||||
} else {
|
||||
logger.log("An Apple ID email address is required.", level: .error)
|
||||
_exit(1)
|
||||
}
|
||||
|
||||
if let cliPassword = self.password {
|
||||
password = cliPassword
|
||||
} else if let envPassword = ProcessInfo.processInfo.environment["IPATOOL_PASSWORD"] {
|
||||
password = envPassword
|
||||
} else if let inputPassword = String(validatingUTF8: UnsafePointer<CChar>(getpass(logger.compile("Enter Apple ID password: ", level: .warning)))) {
|
||||
password = inputPassword
|
||||
} else {
|
||||
logger.log("An Apple ID password is required.", level: .error)
|
||||
_exit(1)
|
||||
}
|
||||
|
||||
let account: StoreResponse.Account
|
||||
|
||||
do {
|
||||
logger.log("Authenticating with the App Store...", level: .info)
|
||||
account = try storeClient.authenticate(email: email, password: password)
|
||||
} catch {
|
||||
switch error {
|
||||
case StoreResponse.Error.codeRequired:
|
||||
let code = String(validatingUTF8: UnsafePointer<CChar>(getpass(logger.compile("Enter 2FA code: ", level: .warning))))
|
||||
|
||||
do {
|
||||
account = try storeClient.authenticate(email: email, password: password, code: code)
|
||||
} 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("Authenticated as '\(account.firstName) \(account.lastName)'.", level: .info)
|
||||
|
||||
logger.log("Requesting a signed copy of '\(app.identifier)' from the App Store...", level: .info)
|
||||
let item = try storeClient.item(identifier: "\(app.identifier)", directoryServicesIdentifier: account.directoryServicesIdentifier)
|
||||
logger.log("Received a response of the signed copy: \(item.md5).", level: .debug)
|
||||
|
||||
logger.log("Creating signature client...", level: .debug)
|
||||
let path = FileManager.default.currentDirectoryPath
|
||||
.appending("/\(bundleIdentifier)_\(app.identifier)_v\(app.version)_\(Int.random(in: 100...999))")
|
||||
.appending(".ipa")
|
||||
|
||||
logger.log("Output path: \(path).", level: .debug)
|
||||
let signatureClient = SignatureClient(fileManager: .default, filePath: path)
|
||||
|
||||
logger.log("Downloading app package...", level: .info)
|
||||
try downloadClient.download(from: item.url, to: URL(fileURLWithPath: path)) { progress in
|
||||
logger.log("Downloading app package... [\(Int((progress * 100).rounded()))%]",
|
||||
prefix: "\u{1B}[1A\u{1B}[K",
|
||||
level: .info)
|
||||
}
|
||||
logger.log("Saved app package to \(URL(fileURLWithPath: path).lastPathComponent).", level: .info)
|
||||
|
||||
logger.log("Applying patches...", level: .info)
|
||||
try signatureClient.appendMetadata(item: item, email: email)
|
||||
try signatureClient.appendSignature(item: item)
|
||||
|
||||
logger.log("Done.", level: .info)
|
||||
}
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
//
|
||||
// Search.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import ArgumentParser
|
||||
import Foundation
|
||||
|
||||
struct Search: ParsableCommand {
|
||||
static var configuration: CommandConfiguration {
|
||||
return .init(abstract: "Search for iOS apps available on the App Store.")
|
||||
}
|
||||
|
||||
@Option
|
||||
private var logLevel: LogLevel = .info
|
||||
|
||||
@Option
|
||||
private var limit: Int = 5
|
||||
|
||||
@Argument(help: "The term to search for.")
|
||||
var term: String
|
||||
}
|
||||
|
||||
extension Search {
|
||||
func run() throws {
|
||||
let logger = ConsoleLogger(level: logLevel)
|
||||
|
||||
logger.log("Creating HTTP client...", level: .debug)
|
||||
let httpClient = HTTPClient(urlSession: URLSession.shared)
|
||||
|
||||
logger.log("Creating iTunes client...", level: .debug)
|
||||
let itunesClient = iTunesClient(httpClient: httpClient)
|
||||
|
||||
do {
|
||||
logger.log("Searching for '\(term)'...", level: .info)
|
||||
let results = try itunesClient.search(term: term, limit: limit)
|
||||
|
||||
guard !results.isEmpty else {
|
||||
logger.log("No results found.", level: .error)
|
||||
_exit(1)
|
||||
}
|
||||
|
||||
logger.log("Found \(results.count) results:\n\(results.enumerated().map({ "\($0 + 1). \($1.name): \($1.bundleIdentifier) (\($1.version))." }).joined(separator: "\n"))", level: .info)
|
||||
} catch {
|
||||
logger.log("\(error)", level: .debug)
|
||||
logger.log("An unknown error has occurred.", level: .error)
|
||||
_exit(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
//
|
||||
// IPATool.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import ArgumentParser
|
||||
|
||||
struct IPATool: ParsableCommand {
|
||||
static var configuration: CommandConfiguration {
|
||||
return .init(commandName: "ipatool",
|
||||
abstract: "A cli tool for interacting with Apple's ipa files.",
|
||||
version: "1.0.0",
|
||||
subcommands: [Download.self, Search.self])
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
//
|
||||
// ConsoleLogger.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
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))
|
||||
}
|
||||
|
||||
func log(_ message: String, prefix: String, level: LogLevel) {
|
||||
guard level <= self.level else { return }
|
||||
print("\(prefix)\(compile(message, level: level))")
|
||||
}
|
||||
|
||||
func compile(_ message: String, level: LogLevel) -> String {
|
||||
return "==> \(level.prefix)\(message)".trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
//
|
||||
// LogLevel.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import ArgumentParser
|
||||
|
||||
enum LogLevel: String, ExpressibleByArgument {
|
||||
case error
|
||||
case warning
|
||||
case info
|
||||
case debug
|
||||
}
|
||||
|
||||
extension LogLevel {
|
||||
var prefix: String {
|
||||
switch self {
|
||||
case .error:
|
||||
return "❌\t[Error] "
|
||||
case .warning:
|
||||
return "⚠️\t[Warning] "
|
||||
case .info:
|
||||
return "ℹ️\t[Info] "
|
||||
case .debug:
|
||||
return "🛠\t[Debug] "
|
||||
}
|
||||
}
|
||||
|
||||
var priority: Int {
|
||||
switch self {
|
||||
case .error:
|
||||
return 0
|
||||
case .warning:
|
||||
return 1
|
||||
case .info:
|
||||
return 2
|
||||
case .debug:
|
||||
return 3
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension LogLevel: Comparable {
|
||||
static func < (lhs: LogLevel, rhs: LogLevel) -> Bool {
|
||||
return lhs.priority < rhs.priority
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
//
|
||||
// Logging.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
protocol Logging {
|
||||
func compile(_ message: String, level: LogLevel) -> String
|
||||
func log(_ message: String, prefix: String, level: LogLevel)
|
||||
func log(_ message: String, level: LogLevel)
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
//
|
||||
// HTTPClient.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
protocol HTTPClientInterface {
|
||||
func send(_ request: HTTPRequest, completion: @escaping (Result<HTTPResponse, Error>) -> Void)
|
||||
}
|
||||
|
||||
extension HTTPClientInterface {
|
||||
func send(_ request: HTTPRequest) throws -> HTTPResponse {
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
var result: Result<HTTPResponse, Error>?
|
||||
|
||||
send(request) {
|
||||
result = $0
|
||||
semaphore.signal()
|
||||
}
|
||||
|
||||
_ = semaphore.wait(timeout: .distantFuture)
|
||||
|
||||
switch result {
|
||||
case .none:
|
||||
throw HTTPClient.Error.timeout
|
||||
case let .failure(error):
|
||||
throw error
|
||||
case let .success(response):
|
||||
return response
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final class HTTPClient: HTTPClientInterface {
|
||||
private let urlSession: URLSessionInterface
|
||||
|
||||
init(urlSession: URLSessionInterface) {
|
||||
self.urlSession = urlSession
|
||||
}
|
||||
|
||||
func send(_ request: HTTPRequest, completion: @escaping (Result<HTTPResponse, Swift.Error>) -> Void) {
|
||||
do {
|
||||
let urlRequest = try makeURLRequest(from: request)
|
||||
|
||||
urlSession.dataTask(with: urlRequest) { (data, response, error) in
|
||||
if let error = error {
|
||||
return completion(.failure(error))
|
||||
}
|
||||
|
||||
guard let response = response as? HTTPURLResponse else {
|
||||
return completion(.failure(Error.invalidResponse(response)))
|
||||
}
|
||||
|
||||
completion(.success(.init(statusCode: response.statusCode, data: data)))
|
||||
}.resume()
|
||||
} catch {
|
||||
completion(.failure(error))
|
||||
}
|
||||
}
|
||||
|
||||
private func makeURLRequest(from request: HTTPRequest) throws -> URLRequest {
|
||||
var urlRequest = URLRequest(url: request.endpoint.url)
|
||||
urlRequest.httpMethod = request.method.rawValue
|
||||
|
||||
switch request.payload {
|
||||
case .none:
|
||||
urlRequest.httpBody = nil
|
||||
case let .urlEncoding(propertyList):
|
||||
urlRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
|
||||
|
||||
var urlComponents = URLComponents(string: request.endpoint.url.absoluteString)
|
||||
urlComponents?.queryItems = !propertyList.isEmpty ? propertyList.map { URLQueryItem(name: $0.0, value: $0.1.description) } : nil
|
||||
|
||||
switch request.method {
|
||||
case .get:
|
||||
urlRequest.url = urlComponents?.url
|
||||
case .post:
|
||||
urlRequest.httpBody = urlComponents?.percentEncodedQuery?.data(using: .utf8, allowLossyConversion: false)
|
||||
}
|
||||
case let .xml(value):
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
extension HTTPClient {
|
||||
enum Error: Swift.Error {
|
||||
case invalidResponse(URLResponse?)
|
||||
case timeout
|
||||
}
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
//
|
||||
// HTTPDownloadClient.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
protocol HTTPDownloadClientInterface {
|
||||
func download(from source: URL, to target: URL, progress: @escaping (Float) -> Void, completion: @escaping (Result<Void, Error>) -> Void)
|
||||
}
|
||||
|
||||
extension HTTPDownloadClientInterface {
|
||||
func download(from source: URL, to target: URL, progress: @escaping (Float) -> Void) throws {
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
var result: Result<Void, Error>?
|
||||
|
||||
download(from: source, to: target, progress: progress) {
|
||||
result = $0
|
||||
semaphore.signal()
|
||||
}
|
||||
|
||||
_ = semaphore.wait(timeout: .distantFuture)
|
||||
|
||||
switch result {
|
||||
case .none:
|
||||
throw HTTPClient.Error.timeout
|
||||
case let .failure(error):
|
||||
throw error
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final class HTTPDownloadClient: NSObject, HTTPDownloadClientInterface {
|
||||
private var urlSession: URLSession!
|
||||
private var progressHandler: ((Float) -> Void)?
|
||||
private var completionHandler: ((Result<Void, Swift.Error>) -> Void)?
|
||||
private var targetURL: URL?
|
||||
|
||||
override init() {
|
||||
super.init()
|
||||
self.urlSession = URLSession(configuration: .default, delegate: self, delegateQueue: nil)
|
||||
}
|
||||
|
||||
func download(from source: URL, to target: URL, progress: @escaping (Float) -> Void, completion: @escaping (Result<Void, Swift.Error>) -> Void) {
|
||||
assert(progressHandler == nil)
|
||||
assert(completionHandler == nil)
|
||||
assert(targetURL == nil)
|
||||
|
||||
progressHandler = progress
|
||||
completionHandler = completion
|
||||
targetURL = target
|
||||
urlSession.downloadTask(with: source).resume()
|
||||
}
|
||||
}
|
||||
|
||||
extension HTTPDownloadClient: URLSessionDownloadDelegate {
|
||||
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
|
||||
progressHandler?(Float(totalBytesWritten) / Float(totalBytesExpectedToWrite))
|
||||
}
|
||||
|
||||
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
|
||||
defer {
|
||||
progressHandler = nil
|
||||
completionHandler = nil
|
||||
targetURL = nil
|
||||
}
|
||||
|
||||
guard let target = targetURL else {
|
||||
return completionHandler?(.failure(Error.invalidTarget)) ?? ()
|
||||
}
|
||||
|
||||
do {
|
||||
try FileManager.default.moveItem(at: location, to: target)
|
||||
completionHandler?(.success(()))
|
||||
} catch {
|
||||
completionHandler?(.failure(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension HTTPDownloadClient {
|
||||
enum Error: Swift.Error {
|
||||
case invalidTarget
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
//
|
||||
// HTTPEndpoint.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
protocol HTTPEndpoint {
|
||||
var url: URL { get }
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
//
|
||||
// HTTPMethod.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
enum HTTPMethod: String {
|
||||
case get = "GET"
|
||||
case post = "POST"
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
//
|
||||
// HTTPPayload.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
enum HTTPPayload {
|
||||
case xml([String: String])
|
||||
case urlEncoding([String: String])
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
//
|
||||
// HTTPRequest.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
protocol HTTPRequest {
|
||||
var method: HTTPMethod { get }
|
||||
var endpoint: HTTPEndpoint { get }
|
||||
var headers: [String: String] { get }
|
||||
var payload: HTTPPayload? { get }
|
||||
}
|
||||
|
||||
extension HTTPRequest {
|
||||
var headers: [String: String] { [:] }
|
||||
var payload: HTTPPayload? { nil }
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
//
|
||||
// HTTPResponse.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
struct HTTPResponse {
|
||||
let statusCode: Int
|
||||
let data: Data?
|
||||
}
|
||||
|
||||
extension HTTPResponse {
|
||||
func decode<T: Decodable>(_ type: T.Type, as decoder: Decoder) throws -> T {
|
||||
guard let data = data else {
|
||||
throw Error.noData
|
||||
}
|
||||
|
||||
switch decoder {
|
||||
case .json:
|
||||
let decoder = JSONDecoder()
|
||||
decoder.userInfo = [.init(rawValue: "data")!: data]
|
||||
return try decoder.decode(type, from: data)
|
||||
case .xml:
|
||||
let decoder = PropertyListDecoder()
|
||||
decoder.userInfo = [.init(rawValue: "data")!: data]
|
||||
return try decoder.decode(type, from: data)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension HTTPResponse {
|
||||
enum Decoder {
|
||||
case json
|
||||
case xml
|
||||
}
|
||||
|
||||
enum Error: Swift.Error {
|
||||
case noData
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
//
|
||||
// URLSession.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
protocol URLSessionInterface {
|
||||
func dataTask(with request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask
|
||||
}
|
||||
|
||||
extension URLSession: URLSessionInterface {}
|
||||
@@ -1,109 +0,0 @@
|
||||
//
|
||||
// SignatureClient.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import ZIPFoundation
|
||||
|
||||
protocol SignatureClientInterface {
|
||||
func appendMetadata(item: StoreResponse.Item, email: String) throws
|
||||
func appendSignature(item: StoreResponse.Item) throws
|
||||
}
|
||||
|
||||
final class SignatureClient: SignatureClientInterface {
|
||||
private let fileManager: FileManager
|
||||
private let filePath: String
|
||||
|
||||
init(fileManager: FileManager, filePath: String) {
|
||||
self.fileManager = fileManager
|
||||
self.filePath = filePath
|
||||
}
|
||||
|
||||
func appendMetadata(item: StoreResponse.Item, email: String) throws {
|
||||
guard let archive = Archive(url: URL(fileURLWithPath: filePath), accessMode: .update) else {
|
||||
throw Error.invalidArchive
|
||||
}
|
||||
|
||||
var metadata = item.metadata
|
||||
metadata["apple-id"] = email
|
||||
metadata["userName"] = email
|
||||
|
||||
let metadataUrl = URL(fileURLWithPath: NSTemporaryDirectory().appending("\(UUID().uuidString)/iTunesMetadata.plist"))
|
||||
|
||||
try fileManager.createDirectory(at: metadataUrl.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
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)
|
||||
}
|
||||
|
||||
func appendSignature(item: StoreResponse.Item) throws {
|
||||
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)
|
||||
|
||||
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 {
|
||||
throw Error.invalidSignature
|
||||
}
|
||||
|
||||
let signatureBaseUrl = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(UUID().uuidString)
|
||||
let signatureUrl = signatureBaseUrl
|
||||
.appendingPathComponent("Payload")
|
||||
.appendingPathComponent(appBundleName)
|
||||
.appendingPathExtension("app")
|
||||
.appendingPathComponent(signatureTargetPath)
|
||||
|
||||
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")
|
||||
_ = try archive.extract(entry, to: url)
|
||||
|
||||
let data = try Data(contentsOf: url)
|
||||
let plist = try PropertyListDecoder().decode(type, from: data)
|
||||
|
||||
try FileManager.default.removeItem(at: url)
|
||||
|
||||
return plist
|
||||
}
|
||||
}
|
||||
|
||||
extension SignatureClient {
|
||||
struct Manifest: Codable {
|
||||
let paths: [String]
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case paths = "SinfPaths"
|
||||
}
|
||||
}
|
||||
|
||||
enum Error: Swift.Error {
|
||||
case invalidArchive
|
||||
case invalidAppBundle
|
||||
case invalidSignature
|
||||
case fileNotFound(String)
|
||||
}
|
||||
}
|
||||
@@ -1,156 +0,0 @@
|
||||
//
|
||||
// StoreClient.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
protocol StoreClientInterface {
|
||||
func authenticate(email: String, password: String, code: String?, completion: @escaping (Result<StoreResponse.Account, Error>) -> Void)
|
||||
func item(identifier: String, directoryServicesIdentifier: String, completion: @escaping (Result<StoreResponse.Item, Error>) -> Void)
|
||||
}
|
||||
|
||||
extension StoreClientInterface {
|
||||
func authenticate(email: String,
|
||||
password: String,
|
||||
code: String? = nil,
|
||||
completion: @escaping (Result<StoreResponse.Account, Swift.Error>) -> Void) {
|
||||
authenticate(email: email, password: password, code: code, completion: completion)
|
||||
}
|
||||
|
||||
func authenticate(email: String, password: String, code: String? = nil) throws -> StoreResponse.Account {
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
var result: Result<StoreResponse.Account, Error>?
|
||||
|
||||
authenticate(email: email, password: password, code: code) {
|
||||
result = $0
|
||||
semaphore.signal()
|
||||
}
|
||||
|
||||
_ = semaphore.wait(timeout: .distantFuture)
|
||||
|
||||
switch result {
|
||||
case .none:
|
||||
throw StoreClient.Error.timeout
|
||||
case let .failure(error):
|
||||
throw error
|
||||
case let .success(result):
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
func item(identifier: String, directoryServicesIdentifier: String) throws -> StoreResponse.Item {
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
var result: Result<StoreResponse.Item, Error>?
|
||||
|
||||
item(identifier: identifier, directoryServicesIdentifier: directoryServicesIdentifier) {
|
||||
result = $0
|
||||
semaphore.signal()
|
||||
}
|
||||
|
||||
_ = semaphore.wait(timeout: .distantFuture)
|
||||
|
||||
switch result {
|
||||
case .none:
|
||||
throw StoreClient.Error.timeout
|
||||
case let .failure(error):
|
||||
throw error
|
||||
case let .success(result):
|
||||
return result
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final class StoreClient: StoreClientInterface {
|
||||
private let httpClient: HTTPClient
|
||||
|
||||
init(httpClient: HTTPClient) {
|
||||
self.httpClient = httpClient
|
||||
}
|
||||
|
||||
func authenticate(email: String, password: String, code: String?, completion: @escaping (Result<StoreResponse.Account, Swift.Error>) -> Void) {
|
||||
authenticate(email: email,
|
||||
password: password,
|
||||
code: code,
|
||||
isFirstAttempt: true,
|
||||
completion: completion)
|
||||
}
|
||||
|
||||
private func authenticate(email: String,
|
||||
password: String,
|
||||
code: String?,
|
||||
isFirstAttempt: Bool,
|
||||
completion: @escaping (Result<StoreResponse.Account, Swift.Error>) -> Void) {
|
||||
let request = StoreRequest.authenticate(email: email, password: password, code: code)
|
||||
|
||||
httpClient.send(request) { [weak self] result in
|
||||
switch result {
|
||||
case let .success(response):
|
||||
do {
|
||||
let decoded = try response.decode(StoreResponse.self, as: .xml)
|
||||
|
||||
switch decoded {
|
||||
case let .account(account):
|
||||
completion(.success(account))
|
||||
case .item:
|
||||
completion(.failure(Error.invalidResponse))
|
||||
case let .failure(error):
|
||||
switch error {
|
||||
case StoreResponse.Error.invalidCredentials:
|
||||
if isFirstAttempt {
|
||||
return self?.authenticate(email: email,
|
||||
password: password,
|
||||
code: code,
|
||||
isFirstAttempt: false,
|
||||
completion: completion) ?? ()
|
||||
}
|
||||
|
||||
completion(.failure(error))
|
||||
default:
|
||||
completion(.failure(error))
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
completion(.failure(error))
|
||||
}
|
||||
case let .failure(error):
|
||||
completion(.failure(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func item(identifier: String, directoryServicesIdentifier: String, completion: @escaping (Result<StoreResponse.Item, Swift.Error>) -> Void) {
|
||||
let request = StoreRequest.download(appIdentifier: identifier, directoryServicesIdentifier: directoryServicesIdentifier)
|
||||
|
||||
httpClient.send(request) { result in
|
||||
switch result {
|
||||
case let .success(response):
|
||||
do {
|
||||
let decoded = try response.decode(StoreResponse.self, as: .xml)
|
||||
|
||||
switch decoded {
|
||||
case let .item(item):
|
||||
completion(.success(item))
|
||||
case .account:
|
||||
completion(.failure(Error.invalidResponse))
|
||||
case let .failure(error):
|
||||
completion(.failure(error))
|
||||
}
|
||||
} catch {
|
||||
completion(.failure(error))
|
||||
}
|
||||
case let .failure(error):
|
||||
completion(.failure(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension StoreClient {
|
||||
enum Error: Swift.Error {
|
||||
case timeout
|
||||
case invalidResponse
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
//
|
||||
// StoreEndpoint.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
enum StoreEndpoint {
|
||||
case authenticate(prefix: String, guid: String)
|
||||
case download(guid: String)
|
||||
}
|
||||
|
||||
extension StoreEndpoint: HTTPEndpoint {
|
||||
var url: URL {
|
||||
var components = URLComponents(string: path)!
|
||||
components.scheme = "https"
|
||||
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"
|
||||
}
|
||||
}
|
||||
|
||||
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)"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,107 +0,0 @@
|
||||
//
|
||||
// StoreRequest.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
enum StoreRequest {
|
||||
case authenticate(email: String, password: String, code: String? = nil)
|
||||
case download(appIdentifier: String, directoryServicesIdentifier: String)
|
||||
}
|
||||
|
||||
extension StoreRequest: HTTPRequest {
|
||||
var endpoint: HTTPEndpoint {
|
||||
switch self {
|
||||
case let .authenticate(_, _, code):
|
||||
return StoreEndpoint.authenticate(prefix: (code == nil) ? "p25" : "p71", guid: guid)
|
||||
case .download:
|
||||
return StoreEndpoint.download(guid: guid)
|
||||
}
|
||||
}
|
||||
|
||||
var method: HTTPMethod {
|
||||
return .post
|
||||
}
|
||||
|
||||
var headers: [String: String] {
|
||||
var headers: [String: String] = [
|
||||
"User-Agent": "Configurator/2.0 (Macintosh; OS X 10.12.6; 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
|
||||
}
|
||||
|
||||
return headers
|
||||
}
|
||||
|
||||
var payload: HTTPPayload? {
|
||||
switch self {
|
||||
case let .authenticate(email, password, code):
|
||||
return .xml([
|
||||
"appleId": email,
|
||||
"attempt": "\(code == nil ? "4" : "2")",
|
||||
"createSession": "true",
|
||||
"guid": guid,
|
||||
"password": "\(password)\(code ?? "")",
|
||||
"rmp": "0",
|
||||
"why": "signIn"
|
||||
])
|
||||
case let .download(appIdentifier, _):
|
||||
return .xml([
|
||||
"creditDisplay": "",
|
||||
"guid": guid,
|
||||
"salableAdamId": "\(appIdentifier)"
|
||||
])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension StoreRequest {
|
||||
// This identifier is calculated by reading the MAC address of the device and stripping the nonalphabetic characters from the string.
|
||||
// https://stackoverflow.com/a/31838376
|
||||
private var guid: String {
|
||||
let MAC_ADDRESS_LENGTH = 6
|
||||
let bsds: [String] = ["en0", "en1"]
|
||||
var bsd: String = bsds[0]
|
||||
|
||||
var length : size_t = 0
|
||||
var buffer : [CChar]
|
||||
|
||||
var bsdIndex = Int32(if_nametoindex(bsd))
|
||||
if bsdIndex == 0 {
|
||||
bsd = bsds[1]
|
||||
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]
|
||||
|
||||
guard sysctl(&managementInfoBase, 6, nil, &length, nil, 0) >= 0 else { fatalError("Could not read MAC address") }
|
||||
|
||||
buffer = [CChar](unsafeUninitializedCapacity: length, initializingWith: {buffer, initializedCount in
|
||||
for x in 0..<length { buffer[x] = 0 }
|
||||
initializedCount = length
|
||||
})
|
||||
|
||||
guard sysctl(&managementInfoBase, 6, &buffer, &length, nil, 0) >= 0 else { fatalError("Could not read MAC address") }
|
||||
|
||||
let infoData = Data(bytes: buffer, count: length)
|
||||
let indexAfterMsghdr = MemoryLayout<if_msghdr>.stride + 1
|
||||
let rangeOfToken = infoData[indexAfterMsghdr...].range(of: bsdData)!
|
||||
let lower = rangeOfToken.upperBound
|
||||
let upper = lower + MAC_ADDRESS_LENGTH
|
||||
let macAddressData = infoData[lower..<upper]
|
||||
let addressBytes = macAddressData.map{ String(format:"%02x", $0) }
|
||||
return addressBytes.joined().uppercased()
|
||||
}
|
||||
}
|
||||
@@ -1,131 +0,0 @@
|
||||
//
|
||||
// StoreResponse.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
enum StoreResponse {
|
||||
case failure(error: Swift.Error)
|
||||
case account(Account)
|
||||
case item(Item)
|
||||
}
|
||||
|
||||
extension StoreResponse {
|
||||
struct Account {
|
||||
let firstName: String
|
||||
let lastName: String
|
||||
let directoryServicesIdentifier: String
|
||||
}
|
||||
|
||||
struct Item {
|
||||
let url: URL
|
||||
let md5: String
|
||||
let signatures: [Signature]
|
||||
let metadata: [String: Any]
|
||||
}
|
||||
|
||||
enum Error: Int, Swift.Error {
|
||||
case unknownError = 0
|
||||
case genericError = 5002
|
||||
case codeRequired = 1
|
||||
case invalidLicense = 9610
|
||||
case invalidCredentials = -5000
|
||||
case invalidAccount = 5001
|
||||
case invalidItem = -10000
|
||||
case lockedAccount = -10001
|
||||
}
|
||||
}
|
||||
|
||||
extension StoreResponse: Decodable {
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
|
||||
let error = try container.decodeIfPresent(String.self, forKey: .error)
|
||||
let message = try container.decodeIfPresent(String.self, forKey: .message)
|
||||
|
||||
if container.contains(.account) {
|
||||
let directoryServicesIdentifier = try container.decode(String.self, forKey: .directoryServicesIdentifier)
|
||||
let accountContainer = try container.nestedContainer(keyedBy: AccountInfoCodingKeys.self, forKey: .account)
|
||||
let addressContainer = try accountContainer.nestedContainer(keyedBy: AddressCodingKeys.self, forKey: .address)
|
||||
let firstName = try addressContainer.decode(String.self, forKey: .firstName)
|
||||
let lastName = try addressContainer.decode(String.self, forKey: .lastName)
|
||||
|
||||
self = .account(.init(firstName: firstName, lastName: lastName, directoryServicesIdentifier: directoryServicesIdentifier))
|
||||
} else if let items = try container.decodeIfPresent([Item].self, forKey: .items), let item = items.first {
|
||||
self = .item(item)
|
||||
} 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.":
|
||||
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).":
|
||||
self = .failure(error: Error.lockedAccount)
|
||||
default:
|
||||
self = .failure(error: Error.unknownError)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case directoryServicesIdentifier = "dsPersonId"
|
||||
case message = "customerMessage"
|
||||
case items = "songList"
|
||||
case error = "failureType"
|
||||
case account = "accountInfo"
|
||||
}
|
||||
|
||||
private enum AccountInfoCodingKeys: String, CodingKey {
|
||||
case address
|
||||
}
|
||||
|
||||
private enum AddressCodingKeys: String, CodingKey {
|
||||
case firstName
|
||||
case lastName
|
||||
}
|
||||
}
|
||||
|
||||
extension StoreResponse.Item: Decodable {
|
||||
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, 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)
|
||||
}
|
||||
}
|
||||
|
||||
struct Signature: Decodable {
|
||||
let id: Int
|
||||
let sinf: Data
|
||||
}
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case url = "URL"
|
||||
case metadata
|
||||
case md5
|
||||
case signatures = "sinfs"
|
||||
}
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
//
|
||||
// iTunesClient.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
protocol iTunesClientInterface {
|
||||
func lookup(bundleIdentifier: String, completion: @escaping (Result<iTunesResponse.Result, Error>) -> Void)
|
||||
func search(term: String, limit: Int, completion: @escaping (Result<[iTunesResponse.Result], Error>) -> Void)
|
||||
}
|
||||
|
||||
extension iTunesClientInterface {
|
||||
func lookup(bundleIdentifier: String) throws -> iTunesResponse.Result {
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
var result: Result<iTunesResponse.Result, Error>?
|
||||
|
||||
lookup(bundleIdentifier: bundleIdentifier) {
|
||||
result = $0
|
||||
semaphore.signal()
|
||||
}
|
||||
|
||||
_ = semaphore.wait(timeout: .distantFuture)
|
||||
|
||||
switch result {
|
||||
case .none:
|
||||
throw iTunesClient.Error.timeout
|
||||
case let .failure(error):
|
||||
throw error
|
||||
case let .success(result):
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
func search(term: String, limit: Int) throws -> [iTunesResponse.Result] {
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
var result: Result<[iTunesResponse.Result], Error>?
|
||||
|
||||
search(term: term, limit: limit) {
|
||||
result = $0
|
||||
semaphore.signal()
|
||||
}
|
||||
|
||||
_ = semaphore.wait(timeout: .distantFuture)
|
||||
|
||||
switch result {
|
||||
case .none:
|
||||
throw iTunesClient.Error.timeout
|
||||
case let .failure(error):
|
||||
throw error
|
||||
case let .success(result):
|
||||
return result
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final class iTunesClient: iTunesClientInterface {
|
||||
private let httpClient: HTTPClient
|
||||
|
||||
init(httpClient: HTTPClient) {
|
||||
self.httpClient = httpClient
|
||||
}
|
||||
|
||||
func lookup(bundleIdentifier: String, completion: @escaping (Result<iTunesResponse.Result, Swift.Error>) -> Void) {
|
||||
let request = iTunesRequest.lookup(bundleIdentifier: bundleIdentifier)
|
||||
|
||||
httpClient.send(request) { result in
|
||||
switch result {
|
||||
case let .success(response):
|
||||
do {
|
||||
let decoded = try response.decode(iTunesResponse.self, as: .json)
|
||||
guard let result = decoded.results.first else { return completion(.failure(Error.appNotFound)) }
|
||||
completion(.success(result))
|
||||
} catch {
|
||||
completion(.failure(error))
|
||||
}
|
||||
case let .failure(error):
|
||||
completion(.failure(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func search(term: String, limit: Int, completion: @escaping (Result<[iTunesResponse.Result], Swift.Error>) -> Void) {
|
||||
let request = iTunesRequest.search(term: term, limit: limit)
|
||||
|
||||
httpClient.send(request) { result in
|
||||
switch result {
|
||||
case let .success(response):
|
||||
do {
|
||||
let decoded = try response.decode(iTunesResponse.self, as: .json)
|
||||
completion(.success(decoded.results))
|
||||
} catch {
|
||||
completion(.failure(error))
|
||||
}
|
||||
case let .failure(error):
|
||||
completion(.failure(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension iTunesClient {
|
||||
enum Error: Swift.Error {
|
||||
case timeout
|
||||
case appNotFound
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
//
|
||||
// iTunesEndpoint.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
enum iTunesEndpoint {
|
||||
case search
|
||||
case lookup
|
||||
}
|
||||
|
||||
extension iTunesEndpoint: HTTPEndpoint {
|
||||
var url: URL {
|
||||
var components = URLComponents(string: path)!
|
||||
components.scheme = "https"
|
||||
components.host = "itunes.apple.com"
|
||||
return components.url!
|
||||
}
|
||||
|
||||
private var path: String {
|
||||
switch self {
|
||||
case .search:
|
||||
return "/search"
|
||||
case .lookup:
|
||||
return "/lookup"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
//
|
||||
// iTunesRequest.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
enum iTunesRequest {
|
||||
case search(term: String, limit: Int)
|
||||
case lookup(bundleIdentifier: String)
|
||||
}
|
||||
|
||||
extension iTunesRequest: HTTPRequest {
|
||||
var method: HTTPMethod {
|
||||
return .get
|
||||
}
|
||||
|
||||
var endpoint: HTTPEndpoint {
|
||||
switch self {
|
||||
case .lookup:
|
||||
return iTunesEndpoint.lookup
|
||||
case .search:
|
||||
return iTunesEndpoint.search
|
||||
}
|
||||
}
|
||||
|
||||
var payload: HTTPPayload? {
|
||||
switch self {
|
||||
case let .lookup(bundleIdentifier):
|
||||
return .urlEncoding(["media": "software", "bundleId": bundleIdentifier, "limit": "1"])
|
||||
case let .search(term, limit):
|
||||
return .urlEncoding(["media": "software", "term": term, "limit": "\(limit)"])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
//
|
||||
// iTunesResponse.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
struct iTunesResponse {
|
||||
let results: [Result]
|
||||
let count: Int
|
||||
}
|
||||
|
||||
extension iTunesResponse {
|
||||
struct Result {
|
||||
let bundleIdentifier: String
|
||||
let version: String
|
||||
let identifier: Int
|
||||
let name: String
|
||||
}
|
||||
}
|
||||
|
||||
extension iTunesResponse: Codable {
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case count = "resultCount"
|
||||
case results
|
||||
}
|
||||
}
|
||||
|
||||
extension iTunesResponse.Result: Codable {
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case identifier = "trackId"
|
||||
case name = "trackName"
|
||||
case bundleIdentifier = "bundleId"
|
||||
case version
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
//
|
||||
// main.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
IPATool.main()
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/99designs/keyring"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var keychainPassphrase string
|
||||
|
||||
func authCmd() *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "auth",
|
||||
Short: "Authenticate with the App Store",
|
||||
}
|
||||
|
||||
if keyringBackendType() == keyring.FileBackend {
|
||||
cmd.PersistentFlags().StringVar(&keychainPassphrase, "keychain-passphrase", "", "passphrase for unlocking keychain")
|
||||
}
|
||||
|
||||
cmd.AddCommand(loginCmd())
|
||||
cmd.AddCommand(infoCmd())
|
||||
cmd.AddCommand(revokeCmd())
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
func loginCmd() *cobra.Command {
|
||||
var email string
|
||||
var password string
|
||||
var authCode string
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "login",
|
||||
Short: "Login to the App Store",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
appstore, err := newAppStore(cmd, keychainPassphrase)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to create appstore client")
|
||||
}
|
||||
|
||||
return appstore.Login(email, password, authCode)
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().StringVarP(&email, "email", "e", "", "email address for the Apple ID (required)")
|
||||
cmd.Flags().StringVarP(&password, "password", "p", "", "password for the Apple ID (required")
|
||||
cmd.Flags().StringVar(&authCode, "auth-code", "", "2FA code for the Apple ID")
|
||||
|
||||
_ = cmd.MarkFlagRequired("email")
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
func infoCmd() *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: "info",
|
||||
Short: "Show current account info",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
appstore, err := newAppStore(cmd, keychainPassphrase)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to create appstore client")
|
||||
}
|
||||
|
||||
return appstore.Info()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func revokeCmd() *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: "revoke",
|
||||
Short: "Revoke your App Store credentials",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
appstore, err := newAppStore(cmd, keychainPassphrase)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to create appstore client")
|
||||
}
|
||||
|
||||
return appstore.Revoke()
|
||||
},
|
||||
}
|
||||
}
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/99designs/keyring"
|
||||
"github.com/juju/persistent-cookiejar"
|
||||
"github.com/majd/ipatool/pkg/appstore"
|
||||
"github.com/majd/ipatool/pkg/keychain"
|
||||
"github.com/majd/ipatool/pkg/log"
|
||||
"github.com/majd/ipatool/pkg/util"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/spf13/cobra"
|
||||
"golang.org/x/exp/slices"
|
||||
"golang.org/x/term"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func newCookieJar() (*cookiejar.Jar, error) {
|
||||
machine := util.NewMachine(util.MachineArgs{
|
||||
OperatingSystem: util.NewOperatingSystem(),
|
||||
})
|
||||
jar, err := cookiejar.New(&cookiejar.Options{
|
||||
Filename: filepath.Join(machine.HomeDirectory(), ConfigDirectoryName, CookieJarFileName),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "failed to create cookie jar")
|
||||
}
|
||||
|
||||
return jar, nil
|
||||
}
|
||||
|
||||
func keyringBackendType() keyring.BackendType {
|
||||
allowedBackends := []keyring.BackendType{
|
||||
keyring.KeychainBackend,
|
||||
keyring.SecretServiceBackend,
|
||||
}
|
||||
|
||||
for _, backend := range allowedBackends {
|
||||
if slices.Contains(keyring.AvailableBackends(), backend) {
|
||||
return backend
|
||||
}
|
||||
}
|
||||
|
||||
return keyring.FileBackend
|
||||
}
|
||||
|
||||
func newKeyring(logger log.Logger, passphrase string, interactive bool) (keyring.Keyring, error) {
|
||||
machine := util.NewMachine(util.MachineArgs{
|
||||
OperatingSystem: util.NewOperatingSystem(),
|
||||
})
|
||||
|
||||
ring, err := keyring.Open(keyring.Config{
|
||||
AllowedBackends: []keyring.BackendType{
|
||||
keyringBackendType(),
|
||||
},
|
||||
ServiceName: KeychainServiceName,
|
||||
FileDir: filepath.Join(machine.HomeDirectory(), ConfigDirectoryName),
|
||||
FilePasswordFunc: func(s string) (string, error) {
|
||||
if passphrase == "" && !interactive {
|
||||
return "", errors.New("keychain passphrase is required when not running in interactive mode; use the \"--keychain-passphrase\" flag")
|
||||
}
|
||||
|
||||
if passphrase != "" {
|
||||
return passphrase, nil
|
||||
}
|
||||
|
||||
path := strings.Split(s, " unlock ")[1]
|
||||
logger.Log().Msgf("enter passphrase to unlock %s (this is separate from your Apple ID password): ", path)
|
||||
bytes, err := term.ReadPassword(int(os.Stdin.Fd()))
|
||||
if err != nil {
|
||||
return "", errors.Wrap(err, "failed to read password")
|
||||
}
|
||||
|
||||
password := string(bytes)
|
||||
password = strings.Trim(password, "\n")
|
||||
password = strings.Trim(password, "\r")
|
||||
|
||||
return password, nil
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "failed to open keyring")
|
||||
}
|
||||
|
||||
return ring, nil
|
||||
}
|
||||
|
||||
func configureConfigDirectory() error {
|
||||
os := util.NewOperatingSystem()
|
||||
machine := util.NewMachine(util.MachineArgs{
|
||||
OperatingSystem: os,
|
||||
})
|
||||
|
||||
configDirectoryPath := filepath.Join(machine.HomeDirectory(), ConfigDirectoryName)
|
||||
_, err := os.Stat(configDirectoryPath)
|
||||
if err != nil && os.IsNotExist(err) {
|
||||
err = os.MkdirAll(configDirectoryPath, 0700)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to create config directory")
|
||||
}
|
||||
} else if err != nil {
|
||||
return errors.Wrap(err, "could not read metadata")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseOutputFormat(value string) (OutputFormat, error) {
|
||||
switch value {
|
||||
case "json":
|
||||
return OutputFormatJSON, nil
|
||||
case "text":
|
||||
return OutputFormatText, nil
|
||||
default:
|
||||
return OutputFormatJSON, errors.Errorf("invalid output format: %s", value)
|
||||
}
|
||||
}
|
||||
|
||||
func newLogger(format OutputFormat, verbose bool) log.Logger {
|
||||
var writer io.Writer
|
||||
|
||||
switch format {
|
||||
case OutputFormatJSON:
|
||||
writer = zerolog.SyncWriter(os.Stdout)
|
||||
case OutputFormatText:
|
||||
writer = log.NewWriter()
|
||||
}
|
||||
|
||||
return log.NewLogger(log.LoggerArgs{
|
||||
Verbose: verbose,
|
||||
Writer: writer,
|
||||
})
|
||||
}
|
||||
|
||||
func newAppStore(
|
||||
cmd *cobra.Command,
|
||||
keychainPassphrase string,
|
||||
) (appstore.AppStore, error) {
|
||||
logger := cmd.Context().Value("logger").(log.Logger)
|
||||
interactive := cmd.Context().Value("interactive").(bool)
|
||||
|
||||
cookieJar, err := newCookieJar()
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "failed to create cookie jar")
|
||||
}
|
||||
|
||||
os := util.NewOperatingSystem()
|
||||
|
||||
keyring, err := newKeyring(logger, keychainPassphrase, interactive)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "failed to create keyring")
|
||||
}
|
||||
|
||||
return appstore.NewAppStore(appstore.AppStoreArgs{
|
||||
Logger: logger,
|
||||
CookieJar: cookieJar,
|
||||
Keychain: keychain.NewKeychain(keychain.KeychainArgs{
|
||||
Keyring: keyring,
|
||||
}),
|
||||
Interactive: interactive,
|
||||
Machine: util.NewMachine(util.MachineArgs{
|
||||
OperatingSystem: os,
|
||||
}),
|
||||
OperatingSystem: os,
|
||||
}), nil
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package cmd
|
||||
|
||||
import "github.com/thediveo/enumflag/v2"
|
||||
|
||||
type OutputFormat enumflag.Flag
|
||||
|
||||
const (
|
||||
OutputFormatText OutputFormat = iota
|
||||
OutputFormatJSON
|
||||
)
|
||||
|
||||
const (
|
||||
ConfigDirectoryName = ".ipatool"
|
||||
CookieJarFileName = "cookies"
|
||||
KeychainServiceName = "ipatool-auth.service"
|
||||
)
|
||||
@@ -0,0 +1,39 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/99designs/keyring"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func downloadCmd() *cobra.Command {
|
||||
var keychainPassphrase string
|
||||
var acquireLicense bool
|
||||
var outputPath string
|
||||
var bundleID string
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "download",
|
||||
Short: "Download (encrypted) iOS app packages from the App Store",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
appstore, err := newAppStore(cmd, keychainPassphrase)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to create appstore client")
|
||||
}
|
||||
|
||||
return appstore.Download(bundleID, outputPath, acquireLicense)
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().StringVarP(&bundleID, "bundle-identifier", "b", "", "The bundle identifier of the target iOS app (required)")
|
||||
cmd.Flags().StringVarP(&outputPath, "output", "o", "", "The destination path of the downloaded app package")
|
||||
cmd.Flags().BoolVar(&acquireLicense, "purchase", false, "Obtain a license for the app if needed")
|
||||
|
||||
if keyringBackendType() == keyring.FileBackend {
|
||||
cmd.Flags().StringVar(&keychainPassphrase, "keychain-passphrase", "", "passphrase for unlocking keychain")
|
||||
}
|
||||
|
||||
_ = cmd.MarkFlagRequired("bundle-identifier")
|
||||
|
||||
return cmd
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/99designs/keyring"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func purchaseCmd() *cobra.Command {
|
||||
var keychainPassphrase string
|
||||
var bundleID string
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "purchase",
|
||||
Short: "Obtain a license for the app from the App Store",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
appstore, err := newAppStore(cmd, keychainPassphrase)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to create appstore client")
|
||||
}
|
||||
|
||||
return appstore.Purchase(bundleID)
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().StringVarP(&bundleID, "bundle-identifier", "b", "", "Bundle identifier of the target iOS app (required)")
|
||||
|
||||
if keyringBackendType() == keyring.FileBackend {
|
||||
cmd.Flags().StringVar(&keychainPassphrase, "keychain-passphrase", "", "passphrase for unlocking keychain")
|
||||
}
|
||||
|
||||
_ = cmd.MarkFlagRequired("bundle-identifier")
|
||||
|
||||
return cmd
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/pkg/errors"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/thediveo/enumflag/v2"
|
||||
"golang.org/x/net/context"
|
||||
)
|
||||
|
||||
func rootCmd() *cobra.Command {
|
||||
var verbose bool
|
||||
var nonInteractive bool
|
||||
var format OutputFormat
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "ipatool",
|
||||
Short: "A cli tool for interacting with Apple's ipa files",
|
||||
SilenceErrors: true,
|
||||
SilenceUsage: true,
|
||||
Version: version,
|
||||
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
|
||||
ctx := context.WithValue(context.Background(), "logger", newLogger(format, verbose))
|
||||
ctx = context.WithValue(ctx, "interactive", nonInteractive == false)
|
||||
cmd.SetContext(ctx)
|
||||
|
||||
err := configureConfigDirectory()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to configure config directory")
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
cmd.PersistentFlags().VarP(
|
||||
enumflag.New(&format, "format", map[OutputFormat][]string{
|
||||
OutputFormatText: {"text"},
|
||||
OutputFormatJSON: {"json"},
|
||||
}, enumflag.EnumCaseSensitive), "format", "", "sets output format for command; can be 'text', 'json'")
|
||||
cmd.PersistentFlags().BoolVar(&verbose, "verbose", false, "enables verbose logs")
|
||||
cmd.PersistentFlags().BoolVarP(&nonInteractive, "non-interactive", "", false, "run in non-interactive session")
|
||||
|
||||
cmd.AddCommand(authCmd())
|
||||
cmd.AddCommand(downloadCmd())
|
||||
cmd.AddCommand(purchaseCmd())
|
||||
cmd.AddCommand(searchCmd())
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
// Execute runs the program and returns the approperiate exit status code.
|
||||
func Execute() (exitCode int) {
|
||||
cmd := rootCmd()
|
||||
err := cmd.Execute()
|
||||
if err != nil {
|
||||
exitCode = 1
|
||||
|
||||
logger := newLogger(OutputFormatText, false)
|
||||
outputFormat, parseErr := parseOutputFormat(cmd.Flag("format").Value.String())
|
||||
if parseErr != nil {
|
||||
logger.Error().Err(parseErr).Send()
|
||||
return
|
||||
}
|
||||
|
||||
logger = newLogger(outputFormat, cmd.Flag("verbose").Value.String() == "true")
|
||||
|
||||
logger.Verbose().Stack().Err(err).Send()
|
||||
logger.Error().
|
||||
Err(err).
|
||||
Bool("success", false).
|
||||
Send()
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/99designs/keyring"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func searchCmd() *cobra.Command {
|
||||
var keychainPassphrase string
|
||||
var limit int64
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "search <term>",
|
||||
Short: "Search for iOS apps available on the App Store",
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
appstore, err := newAppStore(cmd, keychainPassphrase)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to create appstore client")
|
||||
}
|
||||
|
||||
return appstore.Search(args[0], limit)
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().Int64VarP(&limit, "limit", "l", 5, "maximum amount of search results to retrieve")
|
||||
|
||||
if keyringBackendType() == keyring.FileBackend {
|
||||
cmd.PersistentFlags().StringVar(&keychainPassphrase, "keychain-passphrase", "", "passphrase for unlocking keychain")
|
||||
}
|
||||
|
||||
return cmd
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
module github.com/majd/ipatool
|
||||
|
||||
go 1.19
|
||||
|
||||
require (
|
||||
github.com/99designs/keyring v1.2.1
|
||||
github.com/golang/mock v1.6.0
|
||||
github.com/juju/persistent-cookiejar v1.0.0
|
||||
github.com/onsi/ginkgo/v2 v2.5.0
|
||||
github.com/onsi/gomega v1.24.0
|
||||
github.com/pkg/errors v0.9.1
|
||||
github.com/rs/zerolog v1.28.0
|
||||
github.com/spf13/cobra v1.6.1
|
||||
github.com/thediveo/enumflag/v2 v2.0.1
|
||||
golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e
|
||||
golang.org/x/net v0.8.0
|
||||
golang.org/x/term v0.6.0
|
||||
howett.net/plist v1.0.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect
|
||||
github.com/danieljoos/wincred v1.1.2 // indirect
|
||||
github.com/dvsekhvalnov/jose2go v1.5.0 // indirect
|
||||
github.com/go-logr/logr v1.2.3 // indirect
|
||||
github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 // indirect
|
||||
github.com/google/go-cmp v0.5.9 // indirect
|
||||
github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c // indirect
|
||||
github.com/inconshreveable/mousetrap v1.0.1 // indirect
|
||||
github.com/juju/go4 v0.0.0-20160222163258-40d72ab9641a // indirect
|
||||
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||
github.com/mattn/go-isatty v0.0.16 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.14 // indirect
|
||||
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db // indirect
|
||||
github.com/mtibben/percent v0.2.1 // indirect
|
||||
github.com/rivo/uniseg v0.4.3 // indirect
|
||||
github.com/schollz/progressbar/v3 v3.12.1 // indirect
|
||||
github.com/spf13/pflag v1.0.5 // indirect
|
||||
golang.org/x/sys v0.6.0 // indirect
|
||||
golang.org/x/text v0.8.0 // indirect
|
||||
gopkg.in/errgo.v1 v1.0.1 // indirect
|
||||
gopkg.in/retry.v1 v1.0.3 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
@@ -0,0 +1,151 @@
|
||||
github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 h1:/vQbFIOMbk2FiG/kXiLl8BRyzTWDw7gX/Hz7Dd5eDMs=
|
||||
github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4/go.mod h1:hN7oaIRCjzsZ2dE+yG5k+rsdt3qcwykqK6HVGcKwsw4=
|
||||
github.com/99designs/keyring v1.2.1 h1:tYLp1ULvO7i3fI5vE21ReQuj99QFSs7lGm0xWyJo87o=
|
||||
github.com/99designs/keyring v1.2.1/go.mod h1:fc+wB5KTk9wQ9sDx0kFXB3A0MaeGHM9AwRStKOQ5vOA=
|
||||
github.com/coreos/go-systemd/v22 v22.3.3-0.20220203105225-a9a7ef127534/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
|
||||
github.com/danieljoos/wincred v1.1.2 h1:QLdCxFs1/Yl4zduvBdcHB8goaYk9RARS2SgLLRuAyr0=
|
||||
github.com/danieljoos/wincred v1.1.2/go.mod h1:GijpziifJoIBfYh+S7BbkdUTU4LfM+QnGqR5Vl2tAx0=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dvsekhvalnov/jose2go v1.5.0 h1:3j8ya4Z4kMCwT5nXIKFSV84YS+HdqSSO0VsTQxaLAeM=
|
||||
github.com/dvsekhvalnov/jose2go v1.5.0/go.mod h1:QsHjhyTlD/lAVqn/NSbVZmSCGeDehTB/mPZadG+mhXU=
|
||||
github.com/frankban/quicktest v1.2.2 h1:xfmOhhoH5fGPgbEAlhLpJH9p0z/0Qizio9osmvn9IUY=
|
||||
github.com/frankban/quicktest v1.2.2/go.mod h1:Qh/WofXFeiAFII1aEBu529AtJo6Zg2VHscnEsbBnJ20=
|
||||
github.com/go-logr/logr v1.2.3 h1:2DntVwHkVopvECVRSlL5PSo9eG+cAkDCuckLubN+rq0=
|
||||
github.com/go-logr/logr v1.2.3/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
|
||||
github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 h1:ZpnhV/YsD2/4cESfV5+Hoeu/iUR3ruzNvZ+yQfO03a0=
|
||||
github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2/go.mod h1:bBOAhwG1umN6/6ZUMtDFBMQR8jRg9O75tm9K00oMsK4=
|
||||
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
|
||||
github.com/golang/mock v1.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc=
|
||||
github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs=
|
||||
github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw=
|
||||
github.com/google/go-cmp v0.2.1-0.20190312032427-6f77996f0c42/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
|
||||
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c h1:6rhixN/i8ZofjG1Y75iExal34USq5p+wiN1tpie8IrU=
|
||||
github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c/go.mod h1:NMPJylDgVpX0MLRlPy15sqSwOFv/U1GZ2m21JhFfek0=
|
||||
github.com/inconshreveable/mousetrap v1.0.1 h1:U3uMjPSQEBMNp1lFxmllqCPM6P5u/Xq7Pgzkat/bFNc=
|
||||
github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||
github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
|
||||
github.com/juju/go4 v0.0.0-20160222163258-40d72ab9641a h1:45JtCyuNYE+QN9aPuR1ID9++BQU+NMTMudHSuaK0Las=
|
||||
github.com/juju/go4 v0.0.0-20160222163258-40d72ab9641a/go.mod h1:RVHtZuvrpETIepiNUrNlih2OynoFf1eM6DGC6dloXzk=
|
||||
github.com/juju/persistent-cookiejar v1.0.0 h1:Ag7+QLzqC2m+OYXy2QQnRjb3gTkEBSZagZ6QozwT3EQ=
|
||||
github.com/juju/persistent-cookiejar v1.0.0/go.mod h1:zrbmo4nBKaiP/Ez3F67ewkMbzGYfXyMvRtbOfuAwG0w=
|
||||
github.com/k0kubun/go-ansi v0.0.0-20180517002512-3bf9e2903213/go.mod h1:vNUNkEQ1e29fT/6vq2aBdFsgNPmy8qMdSay1npru+Sw=
|
||||
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
|
||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4=
|
||||
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
|
||||
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
|
||||
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
|
||||
github.com/mattn/go-isatty v0.0.16 h1:bq3VjFmv/sOjHtdEhmkEV4x1AJtvUvOJ2PFAZ5+peKQ=
|
||||
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||
github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU=
|
||||
github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
||||
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db h1:62I3jR2EmQ4l5rM/4FEfDWcRD+abF5XlKShorW5LRoQ=
|
||||
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db/go.mod h1:l0dey0ia/Uv7NcFFVbCLtqEBQbrT4OCwCSKTEv6enCw=
|
||||
github.com/mtibben/percent v0.2.1 h1:5gssi8Nqo8QU/r2pynCm+hBQHpkB/uNK7BJCFogWdzs=
|
||||
github.com/mtibben/percent v0.2.1/go.mod h1:KG9uO+SZkUp+VkRHsCdYQV3XSZrrSpR3O9ibNBTZrns=
|
||||
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
|
||||
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
|
||||
github.com/onsi/ginkgo/v2 v2.5.0 h1:TRtrvv2vdQqzkwrQ1ke6vtXf7IK34RBUJafIy1wMwls=
|
||||
github.com/onsi/ginkgo/v2 v2.5.0/go.mod h1:Luc4sArBICYCS8THh8v3i3i5CuSZO+RaQRaJoeNwomw=
|
||||
github.com/onsi/gomega v1.24.0 h1:+0glovB9Jd6z3VR+ScSwQqXVTIfJcGA9UBM8yzQxhqg=
|
||||
github.com/onsi/gomega v1.24.0/go.mod h1:Z/NWtiqwBrwUt4/2loMmHL63EDLnYHmVbuBpDr2vQAg=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||
github.com/rivo/uniseg v0.4.2/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
|
||||
github.com/rivo/uniseg v0.4.3 h1:utMvzDsuh3suAEnhH0RdHmoPbU648o6CvXxTx4SBMOw=
|
||||
github.com/rivo/uniseg v0.4.3/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
|
||||
github.com/rogpeppe/clock v0.0.0-20190514195947-2896927a307a h1:3QH7VyOaaiUHNrA9Se4YQIRkDTCw1EJls9xTUCaCeRM=
|
||||
github.com/rogpeppe/clock v0.0.0-20190514195947-2896927a307a/go.mod h1:4r5QyqhjIWCcK8DO4KMclc5Iknq5qVBAlbYYzAbUScQ=
|
||||
github.com/rs/xid v1.4.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
|
||||
github.com/rs/zerolog v1.28.0 h1:MirSo27VyNi7RJYP3078AA1+Cyzd2GB66qy3aUHvsWY=
|
||||
github.com/rs/zerolog v1.28.0/go.mod h1:NILgTygv/Uej1ra5XxGf82ZFSLk58MFGAUS2o6usyD0=
|
||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/schollz/progressbar/v3 v3.12.1 h1:JAhtIrLWAn6/p7i82SrpSG3fgAwlAxi+Sy12r4AzBvQ=
|
||||
github.com/schollz/progressbar/v3 v3.12.1/go.mod h1:g7QSuwyGpqCjVQPFZXA31MSxtrhka9Y9LMdF+XT77/Y=
|
||||
github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0=
|
||||
github.com/spf13/cobra v1.6.1 h1:o94oiPyS4KD1mPy2fmcYYHHfCxLqYjJOhGsCHFZtEzA=
|
||||
github.com/spf13/cobra v1.6.1/go.mod h1:IOw/AERYS7UzyrGinqmz6HLUo219MORXGxhbaJUqzrY=
|
||||
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
|
||||
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.3.0 h1:NGXK3lHquSN08v5vWalVI/L8XU9hdzE/G6xsrze47As=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/thediveo/enumflag/v2 v2.0.1 h1:2bmWZPD2uSARDsOjXIdLRlNcYBFNF9xX0RNUNF2vKic=
|
||||
github.com/thediveo/enumflag/v2 v2.0.1/go.mod h1:SyxyCNvv0QeRtZ7fjuaUz4FRLC3cWuDiD7QdORU0MGg=
|
||||
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e h1:+WEEuIdZHnUeJJmEUjyYC2gfUMj69yZXw17EnHg/otA=
|
||||
golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e/go.mod h1:Kr81I6Kryrl9sr8s2FK3vxD90NdsKWRuOIl2O4CvYbA=
|
||||
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
|
||||
golang.org/x/net v0.1.0 h1:hZ/3BUoy5aId7sCpA/Tc5lt8DkFgdVS2onTpJsZ/fl0=
|
||||
golang.org/x/net v0.1.0/go.mod h1:Cx3nUiGt4eDBEyega/BKRp+/AlGL8hYe7U9odMt2Cco=
|
||||
golang.org/x/net v0.8.0 h1:Zrh2ngAOFYneWTAIAPethzeaQLuHwhuBkuV6ZiRnUaQ=
|
||||
golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20210819135213-f52c844e1c1c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.2.0 h1:ljd4t30dBnAvMZaQCevtY0xLLD0A+bRZXbgLMLU1F/A=
|
||||
golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.3.0 h1:w8ZOecv6NaNa/zC8944JTU3vz4u6Lagfk4RPQxv92NQ=
|
||||
golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.2.0 h1:z85xZCsEl7bi/KwbNADeBYoOP0++7W1ipu+aGnpwzRM=
|
||||
golang.org/x/term v0.2.0/go.mod h1:TVmDHMZPmdnySmBfhjOoOdhjzdE1h4u1VwSiw2l1Nuc=
|
||||
golang.org/x/term v0.6.0 h1:clScbb1cHjoCkyRbWwBEUZ5H/tIFu5TAXIqaZD0Gcjw=
|
||||
golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.4.0 h1:BrVqGRd7+k1DiOgtnFvAkoQEWQvBc25ouMJM6429SFg=
|
||||
golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.8.0 h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68=
|
||||
golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/protobuf v1.28.0 h1:w43yiav+6bVFTBQFZX0r7ipe9JQ1QsbMgHwbBziscLw=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b h1:QRR6H1YWRnHb4Y/HeNFCTJLFVxaq6wH4YuVdsUOr75U=
|
||||
gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/errgo.v1 v1.0.1 h1:oQFRXzZ7CkBGdm1XZm/EbQYaYNNEElNBOd09M6cqNso=
|
||||
gopkg.in/errgo.v1 v1.0.1/go.mod h1:3NjfXwocQRYAPTq4/fzX+CwUhPRcR/azYRhj8G+LqMo=
|
||||
gopkg.in/retry.v1 v1.0.3 h1:a9CArYczAVv6Qs6VGoLMio99GEs7kY9UzSF9+LD+iGs=
|
||||
gopkg.in/retry.v1 v1.0.3/go.mod h1:FJkXmWiMaAo7xB+xhvDF59zhfjDWyzmyAxiT4dB688g=
|
||||
gopkg.in/yaml.v1 v1.0.0-20140924161607-9f9df34309c0/go.mod h1:WDnlLJ4WF5VGsH/HVa3CI79GS0ol3YnhVnKP89i0kNg=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
howett.net/plist v1.0.0 h1:7CrbWYbPPO/PyNy38b2EB/+gYbjCe2DXBxgtOOZbSQM=
|
||||
howett.net/plist v1.0.0/go.mod h1:lqaXoTrLY4hg8tnEzNru53gicrbv7rrk+2xJA/7hw9g=
|
||||
@@ -1,472 +0,0 @@
|
||||
// !$*UTF8*$!
|
||||
{
|
||||
archiveVersion = 1;
|
||||
classes = {
|
||||
};
|
||||
objectVersion = 52;
|
||||
objects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
A9CA48C22658F93F00BC09D5 /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9CA48C12658F93F00BC09D5 /* main.swift */; };
|
||||
A9CA48CA2658FB6900BC09D5 /* ArgumentParser in Frameworks */ = {isa = PBXBuildFile; productRef = A9CA48C92658FB6900BC09D5 /* ArgumentParser */; };
|
||||
A9CA48CD2658FBF700BC09D5 /* Download.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9CA48CC2658FBF700BC09D5 /* Download.swift */; };
|
||||
A9CA48CF2658FC7400BC09D5 /* IPATool.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9CA48CE2658FC7400BC09D5 /* IPATool.swift */; };
|
||||
A9CA48D2265913B300BC09D5 /* HTTPRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9CA48D1265913B300BC09D5 /* HTTPRequest.swift */; };
|
||||
A9CA48D626591AC200BC09D5 /* HTTPClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9CA48D526591AC200BC09D5 /* HTTPClient.swift */; };
|
||||
A9CA48D826591B0400BC09D5 /* URLSession.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9CA48D726591B0400BC09D5 /* URLSession.swift */; };
|
||||
A9CA48DA26591CE200BC09D5 /* HTTPMethod.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9CA48D926591CE200BC09D5 /* HTTPMethod.swift */; };
|
||||
A9CA48DC26591CF100BC09D5 /* HTTPPayload.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9CA48DB26591CF100BC09D5 /* HTTPPayload.swift */; };
|
||||
A9CA48DE26591D6A00BC09D5 /* HTTPEndpoint.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9CA48DD26591D6A00BC09D5 /* HTTPEndpoint.swift */; };
|
||||
A9CA48E026591E4000BC09D5 /* HTTPResponse.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9CA48DF26591E4000BC09D5 /* HTTPResponse.swift */; };
|
||||
A9CA48E3265926D200BC09D5 /* iTunesClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9CA48E2265926D200BC09D5 /* iTunesClient.swift */; };
|
||||
A9CA48E5265926DB00BC09D5 /* iTunesRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9CA48E4265926DB00BC09D5 /* iTunesRequest.swift */; };
|
||||
A9CA48E72659273700BC09D5 /* iTunesEndpoint.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9CA48E62659273700BC09D5 /* iTunesEndpoint.swift */; };
|
||||
A9CA48E92659281F00BC09D5 /* iTunesResponse.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9CA48E82659281F00BC09D5 /* iTunesResponse.swift */; };
|
||||
A9CA48EC26592DD100BC09D5 /* StoreClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9CA48EB26592DD100BC09D5 /* StoreClient.swift */; };
|
||||
A9CA48EE26592DD800BC09D5 /* StoreEndpoint.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9CA48ED26592DD800BC09D5 /* StoreEndpoint.swift */; };
|
||||
A9CA48F026592DE100BC09D5 /* StoreRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9CA48EF26592DE100BC09D5 /* StoreRequest.swift */; };
|
||||
A9CA48F22659317E00BC09D5 /* StoreResponse.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9CA48F12659317E00BC09D5 /* StoreResponse.swift */; };
|
||||
A9CA48F52659423C00BC09D5 /* ZIPFoundation in Frameworks */ = {isa = PBXBuildFile; productRef = A9CA48F42659423C00BC09D5 /* ZIPFoundation */; };
|
||||
A9CA48F8265942D500BC09D5 /* SignatureClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9CA48F7265942D500BC09D5 /* SignatureClient.swift */; };
|
||||
A9CA48FA2659478600BC09D5 /* HTTPDownloadClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9CA48F92659478600BC09D5 /* HTTPDownloadClient.swift */; };
|
||||
A9CA48FD26594B5F00BC09D5 /* Logging.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9CA48FC26594B5F00BC09D5 /* Logging.swift */; };
|
||||
A9CA48FF26594B7A00BC09D5 /* LogLevel.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9CA48FE26594B7A00BC09D5 /* LogLevel.swift */; };
|
||||
A9CA490126594BB000BC09D5 /* ConsoleLogger.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9CA490026594BB000BC09D5 /* ConsoleLogger.swift */; };
|
||||
A9CA49032659627A00BC09D5 /* Search.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9CA49022659627A00BC09D5 /* Search.swift */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXCopyFilesBuildPhase section */
|
||||
A9CA48BC2658F93F00BC09D5 /* CopyFiles */ = {
|
||||
isa = PBXCopyFilesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
dstPath = /usr/share/man/man1/;
|
||||
dstSubfolderSpec = 0;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 1;
|
||||
};
|
||||
/* End PBXCopyFilesBuildPhase section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
A9CA48BE2658F93F00BC09D5 /* ipatool */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = ipatool; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
A9CA48C12658F93F00BC09D5 /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = "<group>"; };
|
||||
A9CA48CC2658FBF700BC09D5 /* Download.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Download.swift; sourceTree = "<group>"; };
|
||||
A9CA48CE2658FC7400BC09D5 /* IPATool.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IPATool.swift; sourceTree = "<group>"; };
|
||||
A9CA48D1265913B300BC09D5 /* HTTPRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HTTPRequest.swift; sourceTree = "<group>"; };
|
||||
A9CA48D526591AC200BC09D5 /* HTTPClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HTTPClient.swift; sourceTree = "<group>"; };
|
||||
A9CA48D726591B0400BC09D5 /* URLSession.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = URLSession.swift; sourceTree = "<group>"; };
|
||||
A9CA48D926591CE200BC09D5 /* HTTPMethod.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HTTPMethod.swift; sourceTree = "<group>"; };
|
||||
A9CA48DB26591CF100BC09D5 /* HTTPPayload.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HTTPPayload.swift; sourceTree = "<group>"; };
|
||||
A9CA48DD26591D6A00BC09D5 /* HTTPEndpoint.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HTTPEndpoint.swift; sourceTree = "<group>"; };
|
||||
A9CA48DF26591E4000BC09D5 /* HTTPResponse.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HTTPResponse.swift; sourceTree = "<group>"; };
|
||||
A9CA48E2265926D200BC09D5 /* iTunesClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = iTunesClient.swift; sourceTree = "<group>"; };
|
||||
A9CA48E4265926DB00BC09D5 /* iTunesRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = iTunesRequest.swift; sourceTree = "<group>"; };
|
||||
A9CA48E62659273700BC09D5 /* iTunesEndpoint.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = iTunesEndpoint.swift; sourceTree = "<group>"; };
|
||||
A9CA48E82659281F00BC09D5 /* iTunesResponse.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = iTunesResponse.swift; sourceTree = "<group>"; };
|
||||
A9CA48EB26592DD100BC09D5 /* StoreClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StoreClient.swift; sourceTree = "<group>"; };
|
||||
A9CA48ED26592DD800BC09D5 /* StoreEndpoint.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StoreEndpoint.swift; sourceTree = "<group>"; };
|
||||
A9CA48EF26592DE100BC09D5 /* StoreRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StoreRequest.swift; sourceTree = "<group>"; };
|
||||
A9CA48F12659317E00BC09D5 /* StoreResponse.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StoreResponse.swift; sourceTree = "<group>"; };
|
||||
A9CA48F7265942D500BC09D5 /* SignatureClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SignatureClient.swift; sourceTree = "<group>"; };
|
||||
A9CA48F92659478600BC09D5 /* HTTPDownloadClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HTTPDownloadClient.swift; sourceTree = "<group>"; };
|
||||
A9CA48FC26594B5F00BC09D5 /* Logging.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Logging.swift; sourceTree = "<group>"; };
|
||||
A9CA48FE26594B7A00BC09D5 /* LogLevel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LogLevel.swift; sourceTree = "<group>"; };
|
||||
A9CA490026594BB000BC09D5 /* ConsoleLogger.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConsoleLogger.swift; sourceTree = "<group>"; };
|
||||
A9CA49022659627A00BC09D5 /* Search.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Search.swift; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
A9CA48BB2658F93F00BC09D5 /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
A9CA48CA2658FB6900BC09D5 /* ArgumentParser in Frameworks */,
|
||||
A9CA48F52659423C00BC09D5 /* ZIPFoundation in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
A9CA48B52658F93F00BC09D5 = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
A9CA48C02658F93F00BC09D5 /* Source */,
|
||||
A9CA48BF2658F93F00BC09D5 /* Products */,
|
||||
);
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
A9CA48BF2658F93F00BC09D5 /* Products */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
A9CA48BE2658F93F00BC09D5 /* ipatool */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
A9CA48C02658F93F00BC09D5 /* Source */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
A9CA48CB2658FBEB00BC09D5 /* Commands */,
|
||||
A9CA48E1265926BF00BC09D5 /* iTunes */,
|
||||
A9CA48FB26594B5600BC09D5 /* Logger */,
|
||||
A9CA48D02659138600BC09D5 /* Networking */,
|
||||
A9CA48F6265942A600BC09D5 /* Signature */,
|
||||
A9CA48EA265929E000BC09D5 /* Store */,
|
||||
A9CA48CE2658FC7400BC09D5 /* IPATool.swift */,
|
||||
A9CA48C12658F93F00BC09D5 /* main.swift */,
|
||||
);
|
||||
path = Source;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
A9CA48CB2658FBEB00BC09D5 /* Commands */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
A9CA48CC2658FBF700BC09D5 /* Download.swift */,
|
||||
A9CA49022659627A00BC09D5 /* Search.swift */,
|
||||
);
|
||||
path = Commands;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
A9CA48D02659138600BC09D5 /* Networking */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
A9CA48D526591AC200BC09D5 /* HTTPClient.swift */,
|
||||
A9CA48F92659478600BC09D5 /* HTTPDownloadClient.swift */,
|
||||
A9CA48DD26591D6A00BC09D5 /* HTTPEndpoint.swift */,
|
||||
A9CA48D926591CE200BC09D5 /* HTTPMethod.swift */,
|
||||
A9CA48DB26591CF100BC09D5 /* HTTPPayload.swift */,
|
||||
A9CA48D1265913B300BC09D5 /* HTTPRequest.swift */,
|
||||
A9CA48DF26591E4000BC09D5 /* HTTPResponse.swift */,
|
||||
A9CA48D726591B0400BC09D5 /* URLSession.swift */,
|
||||
);
|
||||
path = Networking;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
A9CA48E1265926BF00BC09D5 /* iTunes */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
A9CA48E2265926D200BC09D5 /* iTunesClient.swift */,
|
||||
A9CA48E62659273700BC09D5 /* iTunesEndpoint.swift */,
|
||||
A9CA48E4265926DB00BC09D5 /* iTunesRequest.swift */,
|
||||
A9CA48E82659281F00BC09D5 /* iTunesResponse.swift */,
|
||||
);
|
||||
path = iTunes;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
A9CA48EA265929E000BC09D5 /* Store */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
A9CA48EB26592DD100BC09D5 /* StoreClient.swift */,
|
||||
A9CA48ED26592DD800BC09D5 /* StoreEndpoint.swift */,
|
||||
A9CA48EF26592DE100BC09D5 /* StoreRequest.swift */,
|
||||
A9CA48F12659317E00BC09D5 /* StoreResponse.swift */,
|
||||
);
|
||||
path = Store;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
A9CA48F6265942A600BC09D5 /* Signature */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
A9CA48F7265942D500BC09D5 /* SignatureClient.swift */,
|
||||
);
|
||||
path = Signature;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
A9CA48FB26594B5600BC09D5 /* Logger */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
A9CA48FC26594B5F00BC09D5 /* Logging.swift */,
|
||||
A9CA48FE26594B7A00BC09D5 /* LogLevel.swift */,
|
||||
A9CA490026594BB000BC09D5 /* ConsoleLogger.swift */,
|
||||
);
|
||||
path = Logger;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
A9CA48BD2658F93F00BC09D5 /* IPATool */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = A9CA48C52658F93F00BC09D5 /* Build configuration list for PBXNativeTarget "IPATool" */;
|
||||
buildPhases = (
|
||||
A9CA48BA2658F93F00BC09D5 /* Sources */,
|
||||
A9CA48BB2658F93F00BC09D5 /* Frameworks */,
|
||||
A9CA48BC2658F93F00BC09D5 /* CopyFiles */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
);
|
||||
name = IPATool;
|
||||
packageProductDependencies = (
|
||||
A9CA48C92658FB6900BC09D5 /* ArgumentParser */,
|
||||
A9CA48F42659423C00BC09D5 /* ZIPFoundation */,
|
||||
);
|
||||
productName = ipatool;
|
||||
productReference = A9CA48BE2658F93F00BC09D5 /* ipatool */;
|
||||
productType = "com.apple.product-type.tool";
|
||||
};
|
||||
/* End PBXNativeTarget section */
|
||||
|
||||
/* Begin PBXProject section */
|
||||
A9CA48B62658F93F00BC09D5 /* Project object */ = {
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
LastSwiftUpdateCheck = 1250;
|
||||
LastUpgradeCheck = 1250;
|
||||
TargetAttributes = {
|
||||
A9CA48BD2658F93F00BC09D5 = {
|
||||
CreatedOnToolsVersion = 12.5;
|
||||
};
|
||||
};
|
||||
};
|
||||
buildConfigurationList = A9CA48B92658F93F00BC09D5 /* Build configuration list for PBXProject "ipatool" */;
|
||||
compatibilityVersion = "Xcode 9.3";
|
||||
developmentRegion = en;
|
||||
hasScannedForEncodings = 0;
|
||||
knownRegions = (
|
||||
en,
|
||||
Base,
|
||||
);
|
||||
mainGroup = A9CA48B52658F93F00BC09D5;
|
||||
packageReferences = (
|
||||
A9CA48C82658FB6900BC09D5 /* XCRemoteSwiftPackageReference "swift-argument-parser" */,
|
||||
A9CA48F32659423C00BC09D5 /* XCRemoteSwiftPackageReference "ZIPFoundation" */,
|
||||
);
|
||||
productRefGroup = A9CA48BF2658F93F00BC09D5 /* Products */;
|
||||
projectDirPath = "";
|
||||
projectRoot = "";
|
||||
targets = (
|
||||
A9CA48BD2658F93F00BC09D5 /* IPATool */,
|
||||
);
|
||||
};
|
||||
/* End PBXProject section */
|
||||
|
||||
/* Begin PBXSourcesBuildPhase section */
|
||||
A9CA48BA2658F93F00BC09D5 /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
A9CA48CF2658FC7400BC09D5 /* IPATool.swift in Sources */,
|
||||
A9CA48DE26591D6A00BC09D5 /* HTTPEndpoint.swift in Sources */,
|
||||
A9CA48E026591E4000BC09D5 /* HTTPResponse.swift in Sources */,
|
||||
A9CA48D626591AC200BC09D5 /* HTTPClient.swift in Sources */,
|
||||
A9CA48DA26591CE200BC09D5 /* HTTPMethod.swift in Sources */,
|
||||
A9CA48E3265926D200BC09D5 /* iTunesClient.swift in Sources */,
|
||||
A9CA48F026592DE100BC09D5 /* StoreRequest.swift in Sources */,
|
||||
A9CA48D826591B0400BC09D5 /* URLSession.swift in Sources */,
|
||||
A9CA48E5265926DB00BC09D5 /* iTunesRequest.swift in Sources */,
|
||||
A9CA48D2265913B300BC09D5 /* HTTPRequest.swift in Sources */,
|
||||
A9CA48FD26594B5F00BC09D5 /* Logging.swift in Sources */,
|
||||
A9CA48C22658F93F00BC09D5 /* main.swift in Sources */,
|
||||
A9CA48EC26592DD100BC09D5 /* StoreClient.swift in Sources */,
|
||||
A9CA490126594BB000BC09D5 /* ConsoleLogger.swift in Sources */,
|
||||
A9CA48F8265942D500BC09D5 /* SignatureClient.swift in Sources */,
|
||||
A9CA48E92659281F00BC09D5 /* iTunesResponse.swift in Sources */,
|
||||
A9CA48FF26594B7A00BC09D5 /* LogLevel.swift in Sources */,
|
||||
A9CA48EE26592DD800BC09D5 /* StoreEndpoint.swift in Sources */,
|
||||
A9CA48DC26591CF100BC09D5 /* HTTPPayload.swift in Sources */,
|
||||
A9CA48E72659273700BC09D5 /* iTunesEndpoint.swift in Sources */,
|
||||
A9CA48F22659317E00BC09D5 /* StoreResponse.swift in Sources */,
|
||||
A9CA49032659627A00BC09D5 /* Search.swift in Sources */,
|
||||
A9CA48FA2659478600BC09D5 /* HTTPDownloadClient.swift in Sources */,
|
||||
A9CA48CD2658FBF700BC09D5 /* Download.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXSourcesBuildPhase section */
|
||||
|
||||
/* Begin XCBuildConfiguration section */
|
||||
A9CA48C32658F93F00BC09D5 /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||
CLANG_ANALYZER_NONNULL = YES;
|
||||
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
|
||||
CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
|
||||
CLANG_CXX_LIBRARY = "libc++";
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_ARC = YES;
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
|
||||
CLANG_WARN_BOOL_CONVERSION = YES;
|
||||
CLANG_WARN_COMMA = YES;
|
||||
CLANG_WARN_CONSTANT_CONVERSION = YES;
|
||||
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
|
||||
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
|
||||
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
|
||||
CLANG_WARN_EMPTY_BODY = YES;
|
||||
CLANG_WARN_ENUM_CONVERSION = YES;
|
||||
CLANG_WARN_INFINITE_RECURSION = YES;
|
||||
CLANG_WARN_INT_CONVERSION = YES;
|
||||
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
|
||||
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
|
||||
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
|
||||
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
|
||||
CLANG_WARN_STRICT_PROTOTYPES = YES;
|
||||
CLANG_WARN_SUSPICIOUS_MOVE = YES;
|
||||
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
|
||||
CLANG_WARN_UNREACHABLE_CODE = YES;
|
||||
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
|
||||
COPY_PHASE_STRIP = NO;
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
ENABLE_TESTABILITY = YES;
|
||||
GCC_C_LANGUAGE_STANDARD = gnu11;
|
||||
GCC_DYNAMIC_NO_PIC = NO;
|
||||
GCC_NO_COMMON_BLOCKS = YES;
|
||||
GCC_OPTIMIZATION_LEVEL = 0;
|
||||
GCC_PREPROCESSOR_DEFINITIONS = (
|
||||
"DEBUG=1",
|
||||
"$(inherited)",
|
||||
);
|
||||
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
|
||||
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
|
||||
GCC_WARN_UNDECLARED_SELECTOR = YES;
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
MACOSX_DEPLOYMENT_TARGET = 11.3;
|
||||
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
|
||||
MTL_FAST_MATH = YES;
|
||||
ONLY_ACTIVE_ARCH = YES;
|
||||
SDKROOT = macosx;
|
||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
A9CA48C42658F93F00BC09D5 /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||
CLANG_ANALYZER_NONNULL = YES;
|
||||
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
|
||||
CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
|
||||
CLANG_CXX_LIBRARY = "libc++";
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_ARC = YES;
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
|
||||
CLANG_WARN_BOOL_CONVERSION = YES;
|
||||
CLANG_WARN_COMMA = YES;
|
||||
CLANG_WARN_CONSTANT_CONVERSION = YES;
|
||||
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
|
||||
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
|
||||
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
|
||||
CLANG_WARN_EMPTY_BODY = YES;
|
||||
CLANG_WARN_ENUM_CONVERSION = YES;
|
||||
CLANG_WARN_INFINITE_RECURSION = YES;
|
||||
CLANG_WARN_INT_CONVERSION = YES;
|
||||
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
|
||||
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
|
||||
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
|
||||
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
|
||||
CLANG_WARN_STRICT_PROTOTYPES = YES;
|
||||
CLANG_WARN_SUSPICIOUS_MOVE = YES;
|
||||
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
|
||||
CLANG_WARN_UNREACHABLE_CODE = YES;
|
||||
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
|
||||
COPY_PHASE_STRIP = NO;
|
||||
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
||||
ENABLE_NS_ASSERTIONS = NO;
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
GCC_C_LANGUAGE_STANDARD = gnu11;
|
||||
GCC_NO_COMMON_BLOCKS = YES;
|
||||
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
|
||||
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
|
||||
GCC_WARN_UNDECLARED_SELECTOR = YES;
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
MACOSX_DEPLOYMENT_TARGET = 11.3;
|
||||
MTL_ENABLE_DEBUG_INFO = NO;
|
||||
MTL_FAST_MATH = YES;
|
||||
SDKROOT = macosx;
|
||||
SWIFT_COMPILATION_MODE = wholemodule;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-O";
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
A9CA48C62658F93F00BC09D5 /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
MACOSX_DEPLOYMENT_TARGET = 10.11;
|
||||
PRODUCT_NAME = ipatool;
|
||||
SWIFT_VERSION = 5.0;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
A9CA48C72658F93F00BC09D5 /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
MACOSX_DEPLOYMENT_TARGET = 10.11;
|
||||
PRODUCT_NAME = ipatool;
|
||||
SWIFT_VERSION = 5.0;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
/* End XCBuildConfiguration section */
|
||||
|
||||
/* Begin XCConfigurationList section */
|
||||
A9CA48B92658F93F00BC09D5 /* Build configuration list for PBXProject "ipatool" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
A9CA48C32658F93F00BC09D5 /* Debug */,
|
||||
A9CA48C42658F93F00BC09D5 /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
A9CA48C52658F93F00BC09D5 /* Build configuration list for PBXNativeTarget "IPATool" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
A9CA48C62658F93F00BC09D5 /* Debug */,
|
||||
A9CA48C72658F93F00BC09D5 /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
/* End XCConfigurationList section */
|
||||
|
||||
/* Begin XCRemoteSwiftPackageReference section */
|
||||
A9CA48C82658FB6900BC09D5 /* XCRemoteSwiftPackageReference "swift-argument-parser" */ = {
|
||||
isa = XCRemoteSwiftPackageReference;
|
||||
repositoryURL = "https://github.com/apple/swift-argument-parser";
|
||||
requirement = {
|
||||
kind = exactVersion;
|
||||
version = 0.4.3;
|
||||
};
|
||||
};
|
||||
A9CA48F32659423C00BC09D5 /* XCRemoteSwiftPackageReference "ZIPFoundation" */ = {
|
||||
isa = XCRemoteSwiftPackageReference;
|
||||
repositoryURL = "https://github.com/weichsel/ZIPFoundation.git";
|
||||
requirement = {
|
||||
kind = exactVersion;
|
||||
version = 0.9.12;
|
||||
};
|
||||
};
|
||||
/* End XCRemoteSwiftPackageReference section */
|
||||
|
||||
/* Begin XCSwiftPackageProductDependency section */
|
||||
A9CA48C92658FB6900BC09D5 /* ArgumentParser */ = {
|
||||
isa = XCSwiftPackageProductDependency;
|
||||
package = A9CA48C82658FB6900BC09D5 /* XCRemoteSwiftPackageReference "swift-argument-parser" */;
|
||||
productName = ArgumentParser;
|
||||
};
|
||||
A9CA48F42659423C00BC09D5 /* ZIPFoundation */ = {
|
||||
isa = XCSwiftPackageProductDependency;
|
||||
package = A9CA48F32659423C00BC09D5 /* XCRemoteSwiftPackageReference "ZIPFoundation" */;
|
||||
productName = ZIPFoundation;
|
||||
};
|
||||
/* End XCSwiftPackageProductDependency section */
|
||||
};
|
||||
rootObject = A9CA48B62658F93F00BC09D5 /* Project object */;
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1250"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "A9CA48BD2658F93F00BC09D5"
|
||||
BuildableName = "IPATool"
|
||||
BlueprintName = "IPATool"
|
||||
ReferencedContainer = "container:ipatool.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
</Testables>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "A9CA48BD2658F93F00BC09D5"
|
||||
BuildableName = "IPATool"
|
||||
BlueprintName = "IPATool"
|
||||
ReferencedContainer = "container:ipatool.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "A9CA48BD2658F93F00BC09D5"
|
||||
BuildableName = "IPATool"
|
||||
BlueprintName = "IPATool"
|
||||
ReferencedContainer = "container:ipatool.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -0,0 +1,10 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/majd/ipatool/cmd"
|
||||
"os"
|
||||
)
|
||||
|
||||
func main() {
|
||||
os.Exit(cmd.Execute())
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package appstore
|
||||
|
||||
type Account struct {
|
||||
Email string `json:"email,omitempty"`
|
||||
PasswordToken string `json:"passwordToken,omitempty"`
|
||||
DirectoryServicesID string `json:"directoryServicesIdentifier,omitempty"`
|
||||
Name string `json:"name,omitempty"`
|
||||
StoreFront string `json:"storeFront,omitempty"`
|
||||
Password string `json:"password,omitempty"`
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"github.com/rs/zerolog"
|
||||
)
|
||||
|
||||
type App struct {
|
||||
ID int64 `json:"trackId,omitempty"`
|
||||
BundleID string `json:"bundleId,omitempty"`
|
||||
Name string `json:"trackName,omitempty"`
|
||||
Version string `json:"version,omitempty"`
|
||||
Price float64 `json:"price,omitempty"`
|
||||
}
|
||||
|
||||
type Apps []App
|
||||
|
||||
func (apps Apps) MarshalZerologArray(a *zerolog.Array) {
|
||||
for _, app := range apps {
|
||||
a.Object(app)
|
||||
}
|
||||
}
|
||||
|
||||
func (a App) MarshalZerologObject(event *zerolog.Event) {
|
||||
event.
|
||||
Int64("id", a.ID).
|
||||
Str("bundleID", a.BundleID).
|
||||
Str("name", a.Name).
|
||||
Str("version", a.Version).
|
||||
Float64("price", a.Price)
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"github.com/rs/zerolog"
|
||||
)
|
||||
|
||||
var _ = Describe("App", func() {
|
||||
It("marshals apps array", func() {
|
||||
apps := Apps{
|
||||
{
|
||||
ID: 42,
|
||||
BundleID: "app.bundle.id",
|
||||
Name: "app name",
|
||||
Version: "1.0",
|
||||
Price: 0,
|
||||
},
|
||||
{
|
||||
ID: 1,
|
||||
BundleID: "app.bundle.id2",
|
||||
Name: "app name2",
|
||||
Version: "2.0",
|
||||
Price: 0.99,
|
||||
},
|
||||
}
|
||||
|
||||
buffer := bytes.NewBuffer([]byte{})
|
||||
logger := zerolog.New(buffer)
|
||||
event := logger.Log().Array("apps", apps)
|
||||
event.Send()
|
||||
|
||||
var out map[string]interface{}
|
||||
err := json.Unmarshal(buffer.Bytes(), &out)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(out["apps"]).To(HaveLen(2))
|
||||
})
|
||||
|
||||
It("marshalls app object", func() {
|
||||
app := App{
|
||||
ID: 42,
|
||||
BundleID: "app.bundle.id",
|
||||
Name: "app name",
|
||||
Version: "1.0",
|
||||
Price: 0,
|
||||
}
|
||||
|
||||
buffer := bytes.NewBuffer([]byte{})
|
||||
logger := zerolog.New(buffer)
|
||||
event := logger.Log()
|
||||
app.MarshalZerologObject(event)
|
||||
event.Send()
|
||||
|
||||
var out map[string]interface{}
|
||||
err := json.Unmarshal(buffer.Bytes(), &out)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
Expect(out["id"]).To(Equal(float64(42)))
|
||||
Expect(out["bundleID"]).To(Equal("app.bundle.id"))
|
||||
Expect(out["name"]).To(Equal("app name"))
|
||||
Expect(out["version"]).To(Equal("1.0"))
|
||||
Expect(out["price"]).To(Equal(float64(0)))
|
||||
})
|
||||
|
||||
It("formats ipa name correctly", func() {
|
||||
app := App{
|
||||
ID: 42,
|
||||
BundleID: "app.bundle-id1",
|
||||
Name: " some app&symb.ols2 !!!",
|
||||
Version: "1.0",
|
||||
Price: 0,
|
||||
}
|
||||
|
||||
Expect(fileName(app)).To(Equal("app.bundle-id1_42_1.0.ipa"))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,62 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"github.com/majd/ipatool/pkg/http"
|
||||
"github.com/majd/ipatool/pkg/keychain"
|
||||
"github.com/majd/ipatool/pkg/log"
|
||||
"github.com/majd/ipatool/pkg/util"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
type AppStore interface {
|
||||
Login(email, password, authCode string) error
|
||||
Info() error
|
||||
Revoke() error
|
||||
Search(term string, limit int64) error
|
||||
Purchase(bundleID string) error
|
||||
Download(bundleID string, outputPath string, acquireLicense bool) error
|
||||
}
|
||||
|
||||
type appstore struct {
|
||||
keychain keychain.Keychain
|
||||
loginClient http.Client[LoginResult]
|
||||
searchClient http.Client[SearchResult]
|
||||
purchaseClient http.Client[PurchaseResult]
|
||||
downloadClient http.Client[DownloadResult]
|
||||
httpClient http.Client[interface{}]
|
||||
ioReader io.Reader
|
||||
machine util.Machine
|
||||
os util.OperatingSystem
|
||||
logger log.Logger
|
||||
interactive bool
|
||||
}
|
||||
|
||||
type AppStoreArgs struct {
|
||||
Keychain keychain.Keychain
|
||||
CookieJar http.CookieJar
|
||||
Logger log.Logger
|
||||
OperatingSystem util.OperatingSystem
|
||||
Machine util.Machine
|
||||
Interactive bool
|
||||
}
|
||||
|
||||
func NewAppStore(args AppStoreArgs) AppStore {
|
||||
clientArgs := http.ClientArgs{
|
||||
CookieJar: args.CookieJar,
|
||||
}
|
||||
|
||||
return &appstore{
|
||||
keychain: args.Keychain,
|
||||
loginClient: http.NewClient[LoginResult](clientArgs),
|
||||
searchClient: http.NewClient[SearchResult](clientArgs),
|
||||
purchaseClient: http.NewClient[PurchaseResult](clientArgs),
|
||||
downloadClient: http.NewClient[DownloadResult](clientArgs),
|
||||
httpClient: http.NewClient[interface{}](clientArgs),
|
||||
ioReader: os.Stdin,
|
||||
machine: args.Machine,
|
||||
os: args.OperatingSystem,
|
||||
logger: args.Logger,
|
||||
interactive: args.Interactive,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,459 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"fmt"
|
||||
"github.com/majd/ipatool/pkg/http"
|
||||
"github.com/majd/ipatool/pkg/util"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/schollz/progressbar/v3"
|
||||
"howett.net/plist"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type DownloadSinfResult struct {
|
||||
ID int64 `plist:"id,omitempty"`
|
||||
Data []byte `plist:"sinf,omitempty"`
|
||||
}
|
||||
|
||||
type DownloadItemResult struct {
|
||||
HashMD5 string `plist:"md5,omitempty"`
|
||||
URL string `plist:"URL,omitempty"`
|
||||
Sinfs []DownloadSinfResult `plist:"sinfs,omitempty"`
|
||||
Metadata map[string]interface{} `plist:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
type DownloadResult struct {
|
||||
FailureType string `plist:"failureType,omitempty"`
|
||||
CustomerMessage string `plist:"customerMessage,omitempty"`
|
||||
Items []DownloadItemResult `plist:"songList,omitempty"`
|
||||
}
|
||||
|
||||
type PackageManifest struct {
|
||||
SinfPaths []string `plist:"SinfPaths,omitempty"`
|
||||
}
|
||||
|
||||
type PackageInfo struct {
|
||||
BundleExecutable string `plist:"CFBundleExecutable,omitempty"`
|
||||
}
|
||||
|
||||
func (a *appstore) Download(bundleID string, outputPath string, acquireLicense bool) error {
|
||||
acc, err := a.account()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrGetAccount.Error())
|
||||
}
|
||||
|
||||
countryCode, err := a.countryCodeFromStoreFront(acc.StoreFront)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrInvalidCountryCode.Error())
|
||||
}
|
||||
|
||||
app, err := a.lookup(bundleID, countryCode)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrAppLookup.Error())
|
||||
}
|
||||
|
||||
destination, err := a.resolveDestinationPath(app, outputPath)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrResolveDestinationPath.Error())
|
||||
}
|
||||
|
||||
macAddr, err := a.machine.MacAddress()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrGetMAC.Error())
|
||||
}
|
||||
|
||||
guid := strings.ReplaceAll(strings.ToUpper(macAddr), ":", "")
|
||||
a.logger.Verbose().Str("mac", macAddr).Str("guid", guid).Send()
|
||||
|
||||
err = a.download(acc, app, destination, guid, acquireLicense, true)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrDownloadFile.Error())
|
||||
}
|
||||
|
||||
a.logger.Log().Str("output", destination).Bool("success", true).Send()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *appstore) download(acc Account, app App, dst, guid string, acquireLicense, attemptToRenewCredentials bool) error {
|
||||
req := a.downloadRequest(acc, app, guid)
|
||||
|
||||
res, err := a.downloadClient.Send(req)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrRequest.Error())
|
||||
}
|
||||
|
||||
if res.Data.FailureType == FailureTypePasswordTokenExpired {
|
||||
if attemptToRenewCredentials {
|
||||
a.logger.Verbose().Msg("retrieving new password token")
|
||||
acc, err = a.login(acc.Email, acc.Password, "", guid, 0, true)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrPasswordTokenExpired.Error())
|
||||
}
|
||||
|
||||
return a.download(acc, app, dst, guid, acquireLicense, false)
|
||||
}
|
||||
|
||||
return ErrPasswordTokenExpired
|
||||
}
|
||||
|
||||
if res.Data.FailureType == FailureTypeLicenseNotFound && acquireLicense {
|
||||
a.logger.Verbose().Msg("attempting to acquire license")
|
||||
err = a.purchase(app.BundleID, guid, true)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrPurchase.Error())
|
||||
}
|
||||
|
||||
return a.download(acc, app, dst, guid, false, attemptToRenewCredentials)
|
||||
}
|
||||
|
||||
if res.Data.FailureType == FailureTypeLicenseNotFound {
|
||||
return ErrLicenseRequired
|
||||
}
|
||||
|
||||
if res.Data.FailureType != "" && res.Data.CustomerMessage != "" {
|
||||
a.logger.Verbose().Interface("response", res).Send()
|
||||
return errors.New(res.Data.CustomerMessage)
|
||||
}
|
||||
|
||||
if res.Data.FailureType != "" {
|
||||
a.logger.Verbose().Interface("response", res).Send()
|
||||
return ErrGeneric
|
||||
}
|
||||
|
||||
if len(res.Data.Items) == 0 {
|
||||
a.logger.Verbose().Interface("response", res).Send()
|
||||
return ErrInvalidResponse
|
||||
}
|
||||
|
||||
item := res.Data.Items[0]
|
||||
|
||||
err = a.downloadFile(fmt.Sprintf("%s.tmp", dst), item.URL)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrDownloadFile.Error())
|
||||
}
|
||||
|
||||
err = a.applyPatches(item, acc, fmt.Sprintf("%s.tmp", dst), dst)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrPatchApp.Error())
|
||||
}
|
||||
|
||||
err = a.os.Remove(fmt.Sprintf("%s.tmp", dst))
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrRemoveTempFile.Error())
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *appstore) downloadFile(dst, sourceURL string) (err error) {
|
||||
req, err := a.httpClient.NewRequest("GET", sourceURL, nil)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrCreateRequest.Error())
|
||||
}
|
||||
|
||||
res, err := a.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrRequest.Error())
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if closeErr := res.Body.Close(); closeErr != err && err == nil {
|
||||
err = closeErr
|
||||
}
|
||||
}()
|
||||
|
||||
file, err := a.os.OpenFile(dst, os.O_CREATE|os.O_WRONLY, 0644)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrOpenFile.Error())
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if closeErr := file.Close(); closeErr != err && err == nil {
|
||||
err = closeErr
|
||||
}
|
||||
}()
|
||||
|
||||
sizeMB := float64(res.ContentLength) / (1 << 20)
|
||||
a.logger.Verbose().Str("size", fmt.Sprintf("%.2fMB", sizeMB)).Msg("downloading")
|
||||
|
||||
if a.interactive {
|
||||
bar := progressbar.NewOptions64(res.ContentLength,
|
||||
progressbar.OptionSetDescription("downloading"),
|
||||
progressbar.OptionSetWriter(os.Stdout),
|
||||
progressbar.OptionShowBytes(true),
|
||||
progressbar.OptionSetWidth(20),
|
||||
progressbar.OptionFullWidth(),
|
||||
progressbar.OptionThrottle(65*time.Millisecond),
|
||||
progressbar.OptionShowCount(),
|
||||
progressbar.OptionClearOnFinish(),
|
||||
progressbar.OptionSpinnerType(14),
|
||||
progressbar.OptionSetRenderBlankState(true),
|
||||
progressbar.OptionSetElapsedTime(false),
|
||||
progressbar.OptionSetPredictTime(false),
|
||||
)
|
||||
|
||||
_, err = io.Copy(io.MultiWriter(file, bar), res.Body)
|
||||
} else {
|
||||
_, err = io.Copy(file, res.Body)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrFileWrite.Error())
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (*appstore) downloadRequest(acc Account, app App, guid string) http.Request {
|
||||
host := fmt.Sprintf("%s-%s", PriavteAppStoreAPIDomainPrefixWithoutAuthCode, PrivateAppStoreAPIDomain)
|
||||
return http.Request{
|
||||
URL: fmt.Sprintf("https://%s%s?guid=%s", host, PrivateAppStoreAPIPathDownload, guid),
|
||||
Method: http.MethodPOST,
|
||||
ResponseFormat: http.ResponseFormatXML,
|
||||
Headers: map[string]string{
|
||||
"Content-Type": "application/x-apple-plist",
|
||||
"iCloud-DSID": acc.DirectoryServicesID,
|
||||
"X-Dsid": acc.DirectoryServicesID,
|
||||
},
|
||||
Payload: &http.XMLPayload{
|
||||
Content: map[string]interface{}{
|
||||
"creditDisplay": "",
|
||||
"guid": guid,
|
||||
"salableAdamId": app.ID,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func fileName(app App) string {
|
||||
return fmt.Sprintf("%s_%d_%s.ipa",
|
||||
app.BundleID,
|
||||
app.ID,
|
||||
app.Version)
|
||||
}
|
||||
|
||||
func (a *appstore) resolveDestinationPath(app App, path string) (string, error) {
|
||||
file := fileName(app)
|
||||
|
||||
if path == "" {
|
||||
workdir, err := a.os.Getwd()
|
||||
if err != nil {
|
||||
return "", errors.Wrap(err, ErrGetCurrentDirectory.Error())
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s/%s", workdir, file), nil
|
||||
}
|
||||
|
||||
isDir, err := a.isDirectory(path)
|
||||
if err != nil {
|
||||
return "", errors.Wrap(err, ErrCheckDirectory.Error())
|
||||
}
|
||||
|
||||
if isDir {
|
||||
return fmt.Sprintf("%s/%s", path, file), nil
|
||||
}
|
||||
|
||||
return path, nil
|
||||
}
|
||||
|
||||
func (a *appstore) isDirectory(path string) (bool, error) {
|
||||
info, err := a.os.Stat(path)
|
||||
if err != nil && !os.IsNotExist(err) {
|
||||
return false, errors.Wrap(err, ErrGetFileMetadata.Error())
|
||||
}
|
||||
|
||||
if info == nil {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
return info.IsDir(), nil
|
||||
}
|
||||
|
||||
func (a *appstore) applyPatches(item DownloadItemResult, acc Account, src, dst string) (err error) {
|
||||
dstFile, err := a.os.OpenFile(dst, os.O_CREATE|os.O_WRONLY, 0644)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrOpenFile.Error())
|
||||
}
|
||||
|
||||
srcZip, err := zip.OpenReader(src)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrOpenZipFile.Error())
|
||||
}
|
||||
defer func() {
|
||||
if closeErr := srcZip.Close(); closeErr != err && err == nil {
|
||||
err = closeErr
|
||||
}
|
||||
}()
|
||||
|
||||
dstZip := zip.NewWriter(dstFile)
|
||||
defer func() {
|
||||
if closeErr := dstZip.Close(); closeErr != err && err == nil {
|
||||
err = closeErr
|
||||
}
|
||||
}()
|
||||
|
||||
manifestData := new(bytes.Buffer)
|
||||
infoData := new(bytes.Buffer)
|
||||
|
||||
appBundle, err := a.replicateZip(srcZip, dstZip, infoData, manifestData)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrReplicateZip.Error())
|
||||
}
|
||||
|
||||
err = a.writeMetadata(item.Metadata, acc, dstZip)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrWriteMetadataFile.Error())
|
||||
}
|
||||
|
||||
if manifestData.Len() > 0 {
|
||||
err = a.applySinfPatches(item, dstZip, manifestData.Bytes(), appBundle)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrApplyPatches.Error())
|
||||
}
|
||||
} else {
|
||||
err = a.applyLegacySinfPatches(item, dstZip, infoData.Bytes(), appBundle)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrApplyLegacyPatches.Error())
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *appstore) writeMetadata(metadata map[string]interface{}, acc Account, zip *zip.Writer) error {
|
||||
metadata["apple-id"] = acc.Email
|
||||
metadata["userName"] = acc.Email
|
||||
|
||||
metadataFile, err := zip.Create("iTunesMetadata.plist")
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrCreateMetadataFile.Error())
|
||||
}
|
||||
|
||||
data, err := plist.Marshal(metadata, plist.BinaryFormat)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrEncodeMetadataFile.Error())
|
||||
}
|
||||
|
||||
_, err = metadataFile.Write(data)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrWriteMetadataFile.Error())
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *appstore) replicateZip(src *zip.ReadCloser, dst *zip.Writer, info *bytes.Buffer, manifest *bytes.Buffer) (appBundle string, err error) {
|
||||
for _, file := range src.File {
|
||||
srcFile, err := file.OpenRaw()
|
||||
if err != nil {
|
||||
return "", errors.Wrap(err, ErrOpenFile.Error())
|
||||
}
|
||||
|
||||
if strings.HasSuffix(file.Name, ".app/SC_Info/Manifest.plist") {
|
||||
srcFileD, err := file.Open()
|
||||
if err != nil {
|
||||
return "", errors.Wrap(err, ErrDecompressManifestFile.Error())
|
||||
}
|
||||
|
||||
_, err = io.Copy(manifest, srcFileD)
|
||||
if err != nil {
|
||||
return "", errors.Wrap(err, ErrGetManifestFile.Error())
|
||||
}
|
||||
}
|
||||
|
||||
if strings.Contains(file.Name, ".app/Info.plist") {
|
||||
srcFileD, err := file.Open()
|
||||
if err != nil {
|
||||
return "", errors.Wrap(err, ErrDecompressInfoFile.Error())
|
||||
}
|
||||
|
||||
if !strings.Contains(file.Name, "/Watch/") {
|
||||
appBundle = filepath.Base(strings.TrimSuffix(file.Name, ".app/Info.plist"))
|
||||
}
|
||||
|
||||
_, err = io.Copy(info, srcFileD)
|
||||
if err != nil {
|
||||
return "", errors.Wrap(err, ErrGetInfoFile.Error())
|
||||
}
|
||||
}
|
||||
|
||||
header := file.FileHeader
|
||||
dstFile, err := dst.CreateRaw(&header)
|
||||
if err != nil {
|
||||
return "", errors.Wrap(err, ErrCreateDestinationFile.Error())
|
||||
}
|
||||
|
||||
_, err = io.Copy(dstFile, srcFile)
|
||||
if err != nil {
|
||||
return "", errors.Wrap(err, ErrFileWrite.Error())
|
||||
}
|
||||
}
|
||||
|
||||
if appBundle == "" {
|
||||
return "", ErrGetBundleName
|
||||
}
|
||||
|
||||
return appBundle, nil
|
||||
}
|
||||
|
||||
func (a *appstore) applySinfPatches(item DownloadItemResult, zip *zip.Writer, manifestData []byte, appBundle string) error {
|
||||
var manifest PackageManifest
|
||||
_, err := plist.Unmarshal(manifestData, &manifest)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrUnmarshal.Error())
|
||||
}
|
||||
|
||||
zipped, err := util.Zip(item.Sinfs, manifest.SinfPaths)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrZipSinfs.Error())
|
||||
}
|
||||
|
||||
for _, pair := range zipped {
|
||||
sp := fmt.Sprintf("Payload/%s.app/%s", appBundle, pair.Second)
|
||||
a.logger.Verbose().Str("path", sp).Msg("writing sinf data")
|
||||
|
||||
file, err := zip.Create(sp)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrCreateSinfFile.Error())
|
||||
}
|
||||
|
||||
_, err = file.Write(pair.First.Data)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrWriteSinfData.Error())
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *appstore) applyLegacySinfPatches(item DownloadItemResult, zip *zip.Writer, infoData []byte, appBundle string) error {
|
||||
a.logger.Verbose().Msg("applying legacy sinf patches")
|
||||
|
||||
var info PackageInfo
|
||||
_, err := plist.Unmarshal(infoData, &info)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrUnmarshal.Error())
|
||||
}
|
||||
|
||||
sp := fmt.Sprintf("Payload/%s.app/SC_Info/%s.sinf", appBundle, info.BundleExecutable)
|
||||
a.logger.Verbose().Str("path", sp).Msg("writing sinf data")
|
||||
|
||||
file, err := zip.Create(sp)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrCreateSinfFile.Error())
|
||||
}
|
||||
|
||||
_, err = file.Write(item.Sinfs[0].Data)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrWriteSinfData.Error())
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,877 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
zip "archive/zip"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/golang/mock/gomock"
|
||||
"github.com/majd/ipatool/pkg/http"
|
||||
"github.com/majd/ipatool/pkg/keychain"
|
||||
"github.com/majd/ipatool/pkg/log"
|
||||
"github.com/majd/ipatool/pkg/util"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"howett.net/plist"
|
||||
"io"
|
||||
gohttp "net/http"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var _ = Describe("AppStore (Download)", func() {
|
||||
var (
|
||||
ctrl *gomock.Controller
|
||||
mockKeychain *keychain.MockKeychain
|
||||
mockSearchClient *http.MockClient[SearchResult]
|
||||
mockDownloadClient *http.MockClient[DownloadResult]
|
||||
mockPurchaseClient *http.MockClient[PurchaseResult]
|
||||
mockLoginClient *http.MockClient[LoginResult]
|
||||
mockHTTPClient *http.MockClient[interface{}]
|
||||
mockLogger *log.MockLogger
|
||||
mockOS *util.MockOperatingSystem
|
||||
mockMachine *util.MockMachine
|
||||
as AppStore
|
||||
testErr = errors.New("testErr")
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctrl = gomock.NewController(GinkgoT())
|
||||
mockKeychain = keychain.NewMockKeychain(ctrl)
|
||||
mockLogger = log.NewMockLogger(ctrl)
|
||||
mockSearchClient = http.NewMockClient[SearchResult](ctrl)
|
||||
mockDownloadClient = http.NewMockClient[DownloadResult](ctrl)
|
||||
mockLoginClient = http.NewMockClient[LoginResult](ctrl)
|
||||
mockPurchaseClient = http.NewMockClient[PurchaseResult](ctrl)
|
||||
mockHTTPClient = http.NewMockClient[interface{}](ctrl)
|
||||
mockOS = util.NewMockOperatingSystem(ctrl)
|
||||
mockMachine = util.NewMockMachine(ctrl)
|
||||
as = &appstore{
|
||||
keychain: mockKeychain,
|
||||
loginClient: mockLoginClient,
|
||||
searchClient: mockSearchClient,
|
||||
purchaseClient: mockPurchaseClient,
|
||||
downloadClient: mockDownloadClient,
|
||||
httpClient: mockHTTPClient,
|
||||
machine: mockMachine,
|
||||
os: mockOS,
|
||||
logger: mockLogger,
|
||||
interactive: true,
|
||||
}
|
||||
})
|
||||
|
||||
AfterEach(func() {
|
||||
ctrl.Finish()
|
||||
})
|
||||
|
||||
When("not logged in", func() {
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte{}, testErr)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Download("", "", false)
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrGetAccount.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("fails to determine country code", func() {
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte("{\"storeFront\":\"\"}"), nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Download("", "", false)
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrInvalidCountryCode.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("fails to find app", func() {
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
|
||||
|
||||
mockSearchClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[SearchResult]{}, testErr)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Download("", "", false)
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrAppLookup.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("fails to resolve output path", func() {
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
|
||||
|
||||
mockSearchClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[SearchResult]{
|
||||
StatusCode: 200,
|
||||
Data: SearchResult{
|
||||
Count: 1,
|
||||
Results: []App{{}},
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockOS.EXPECT().
|
||||
Stat(gomock.Any()).
|
||||
Return(nil, testErr)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Download("", "test-out", false)
|
||||
Expect(err).To(MatchError(ContainSubstring("failed to resolve destination path")))
|
||||
})
|
||||
})
|
||||
|
||||
When("fails to read MAC address", func() {
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
|
||||
|
||||
mockSearchClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[SearchResult]{
|
||||
StatusCode: 200,
|
||||
Data: SearchResult{
|
||||
Count: 1,
|
||||
Results: []App{{}},
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockOS.EXPECT().
|
||||
Getwd().
|
||||
Return("", nil)
|
||||
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("", testErr)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Download("", "", false)
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrGetMAC.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("request fails", func() {
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
|
||||
|
||||
mockSearchClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[SearchResult]{
|
||||
StatusCode: 200,
|
||||
Data: SearchResult{
|
||||
Count: 1,
|
||||
Results: []App{{}},
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockOS.EXPECT().
|
||||
Getwd().
|
||||
Return("", nil)
|
||||
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[DownloadResult]{}, testErr)
|
||||
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Download("", "", false)
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrRequest.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("password token is expired", func() {
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
|
||||
|
||||
mockSearchClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[SearchResult]{
|
||||
StatusCode: 200,
|
||||
Data: SearchResult{
|
||||
Count: 1,
|
||||
Results: []App{{}},
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockOS.EXPECT().
|
||||
Getwd().
|
||||
Return("", nil)
|
||||
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[DownloadResult]{
|
||||
Data: DownloadResult{
|
||||
FailureType: FailureTypePasswordTokenExpired,
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil)
|
||||
})
|
||||
|
||||
When("attempts to renew credentials", func() {
|
||||
BeforeEach(func() {
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil).
|
||||
Times(2)
|
||||
})
|
||||
|
||||
When("fails to renew credentials", func() {
|
||||
BeforeEach(func() {
|
||||
mockLoginClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[LoginResult]{}, testErr)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Download("", "", false)
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrPasswordTokenExpired.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("successfully renews credentials", func() {
|
||||
BeforeEach(func() {
|
||||
mockLoginClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[LoginResult]{
|
||||
Data: LoginResult{},
|
||||
}, nil)
|
||||
|
||||
mockKeychain.EXPECT().
|
||||
Set("account", gomock.Any()).
|
||||
Return(nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[DownloadResult]{
|
||||
Data: DownloadResult{
|
||||
FailureType: FailureTypePasswordTokenExpired,
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("attempts to download app", func() {
|
||||
err := as.Download("", "", false)
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrPasswordTokenExpired.Error())))
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
When("license is missing", func() {
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
|
||||
|
||||
mockSearchClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[SearchResult]{
|
||||
StatusCode: 200,
|
||||
Data: SearchResult{
|
||||
Count: 1,
|
||||
Results: []App{{}},
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockOS.EXPECT().
|
||||
Getwd().
|
||||
Return("", nil)
|
||||
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[DownloadResult]{
|
||||
Data: DownloadResult{
|
||||
FailureType: FailureTypeLicenseNotFound,
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Download("", "", false)
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrLicenseRequired.Error())))
|
||||
})
|
||||
|
||||
When("attempts to acquire license", func() {
|
||||
BeforeEach(func() {
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil)
|
||||
})
|
||||
|
||||
When("license is acquired", func() {
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[PurchaseResult]{
|
||||
StatusCode: 200,
|
||||
Data: PurchaseResult{
|
||||
JingleDocType: "purchaseSuccess",
|
||||
Status: 0,
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockSearchClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[SearchResult]{
|
||||
StatusCode: 200,
|
||||
Data: SearchResult{
|
||||
Count: 1,
|
||||
Results: []App{{}},
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[DownloadResult]{}, testErr)
|
||||
})
|
||||
|
||||
It("attempts to download app", func() {
|
||||
err := as.Download("", "", true)
|
||||
Expect(err).To(MatchError(ContainSubstring(testErr.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("fails to acquire license", func() {
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte{}, testErr)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Download("", "", true)
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrPurchase.Error())))
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
When("store API returns error", func() {
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
|
||||
|
||||
mockSearchClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[SearchResult]{
|
||||
StatusCode: 200,
|
||||
Data: SearchResult{
|
||||
Count: 1,
|
||||
Results: []App{{}},
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockOS.EXPECT().
|
||||
Getwd().
|
||||
Return("", nil)
|
||||
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("", nil)
|
||||
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil).
|
||||
Times(2)
|
||||
})
|
||||
|
||||
When("response contains customer message", func() {
|
||||
BeforeEach(func() {
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[DownloadResult]{
|
||||
Data: DownloadResult{
|
||||
FailureType: "test-failure",
|
||||
CustomerMessage: testErr.Error(),
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns customer message as error", func() {
|
||||
err := as.Download("", "", true)
|
||||
Expect(err).To(MatchError(ContainSubstring(testErr.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("response does not contain customer message", func() {
|
||||
BeforeEach(func() {
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[DownloadResult]{
|
||||
Data: DownloadResult{
|
||||
FailureType: "test-failure",
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns generic error", func() {
|
||||
err := as.Download("", "", true)
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrGeneric.Error())))
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
When("store API returns no items", func() {
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
|
||||
|
||||
mockSearchClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[SearchResult]{
|
||||
StatusCode: 200,
|
||||
Data: SearchResult{
|
||||
Count: 1,
|
||||
Results: []App{{}},
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockOS.EXPECT().
|
||||
Getwd().
|
||||
Return("", nil)
|
||||
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("", nil)
|
||||
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil).
|
||||
Times(2)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[DownloadResult]{
|
||||
Data: DownloadResult{
|
||||
Items: []DownloadItemResult{},
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Download("", "", true)
|
||||
Expect(err).To(MatchError(ContainSubstring("received 0 items from the App Store")))
|
||||
})
|
||||
})
|
||||
|
||||
When("fails to download file", func() {
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
|
||||
|
||||
mockSearchClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[SearchResult]{
|
||||
StatusCode: 200,
|
||||
Data: SearchResult{
|
||||
Count: 1,
|
||||
Results: []App{{}},
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockOS.EXPECT().
|
||||
Getwd().
|
||||
Return("", nil)
|
||||
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("", nil)
|
||||
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[DownloadResult]{
|
||||
Data: DownloadResult{
|
||||
Items: []DownloadItemResult{{}},
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
When("fails to create download request", func() {
|
||||
BeforeEach(func() {
|
||||
mockHTTPClient.EXPECT().
|
||||
NewRequest("GET", gomock.Any(), nil).
|
||||
Return(nil, testErr)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Download("", "", true)
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrCreateRequest.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("request fails", func() {
|
||||
BeforeEach(func() {
|
||||
mockHTTPClient.EXPECT().
|
||||
NewRequest("GET", gomock.Any(), nil).
|
||||
Return(nil, nil)
|
||||
|
||||
mockHTTPClient.EXPECT().
|
||||
Do(gomock.Any()).
|
||||
Return(nil, testErr)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Download("", "", true)
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrRequest.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("fails to open file", func() {
|
||||
BeforeEach(func() {
|
||||
mockHTTPClient.EXPECT().
|
||||
NewRequest("GET", gomock.Any(), nil).
|
||||
Return(nil, nil)
|
||||
|
||||
mockHTTPClient.EXPECT().
|
||||
Do(gomock.Any()).
|
||||
Return(&gohttp.Response{
|
||||
Body: gohttp.NoBody,
|
||||
}, nil)
|
||||
|
||||
mockOS.EXPECT().
|
||||
OpenFile(gomock.Any(), gomock.Any(), gomock.Any()).
|
||||
Return(nil, testErr)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Download("", "", true)
|
||||
Expect(err).To(MatchError(ContainSubstring("failed to open file")))
|
||||
})
|
||||
})
|
||||
|
||||
When("fails to write data to file", func() {
|
||||
BeforeEach(func() {
|
||||
mockHTTPClient.EXPECT().
|
||||
NewRequest("GET", gomock.Any(), nil).
|
||||
Return(nil, nil)
|
||||
|
||||
mockHTTPClient.EXPECT().
|
||||
Do(gomock.Any()).
|
||||
Return(&gohttp.Response{
|
||||
Body: io.NopCloser(strings.NewReader("ping")),
|
||||
}, nil)
|
||||
|
||||
mockOS.EXPECT().
|
||||
OpenFile(gomock.Any(), gomock.Any(), gomock.Any()).
|
||||
Return(nil, nil)
|
||||
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Download("", "", true)
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrFileWrite.Error())))
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
When("successfully downloads file", func() {
|
||||
var testFile *os.File
|
||||
|
||||
BeforeEach(func() {
|
||||
var err error
|
||||
testFile, err = os.CreateTemp("", "test_file")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
|
||||
|
||||
mockSearchClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[SearchResult]{
|
||||
StatusCode: 200,
|
||||
Data: SearchResult{
|
||||
Count: 1,
|
||||
Results: []App{{}},
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("", nil)
|
||||
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil).
|
||||
Times(2)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[DownloadResult]{
|
||||
Data: DownloadResult{
|
||||
Items: []DownloadItemResult{
|
||||
{
|
||||
Metadata: map[string]interface{}{},
|
||||
Sinfs: []DownloadSinfResult{
|
||||
{
|
||||
ID: 0,
|
||||
Data: []byte("test-sinf-data"),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockOS.EXPECT().
|
||||
OpenFile(gomock.Any(), gomock.Any(), gomock.Any()).
|
||||
Return(testFile, nil)
|
||||
|
||||
mockHTTPClient.EXPECT().
|
||||
NewRequest("GET", gomock.Any(), nil).
|
||||
Return(nil, nil)
|
||||
|
||||
mockHTTPClient.EXPECT().
|
||||
Do(gomock.Any()).
|
||||
Return(&gohttp.Response{
|
||||
Body: io.NopCloser(strings.NewReader("ping")),
|
||||
}, nil)
|
||||
})
|
||||
|
||||
AfterEach(func() {
|
||||
err := os.Remove(testFile.Name())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
|
||||
It("writes data to file", func() {
|
||||
mockOS.EXPECT().
|
||||
Getwd().
|
||||
Return("", nil)
|
||||
|
||||
mockOS.EXPECT().
|
||||
OpenFile(gomock.Any(), gomock.Any(), gomock.Any()).
|
||||
Return(nil, testErr)
|
||||
|
||||
err := as.Download("", "", true)
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrOpenFile.Error())))
|
||||
|
||||
testData, err := os.ReadFile(testFile.Name())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(string(testData)).To(Equal("ping"))
|
||||
})
|
||||
|
||||
When("successfully applies patches", func() {
|
||||
var tmpFile *os.File
|
||||
var zipFile *zip.Writer
|
||||
var outputPath string
|
||||
|
||||
BeforeEach(func() {
|
||||
var err error
|
||||
tmpFile, err = os.OpenFile(fmt.Sprintf("%s.tmp", testFile.Name()), os.O_CREATE|os.O_WRONLY, 0644)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
outputPath = strings.TrimSuffix(tmpFile.Name(), ".tmp")
|
||||
|
||||
mockOS.EXPECT().
|
||||
OpenFile(gomock.Any(), gomock.Any(), gomock.Any()).
|
||||
DoAndReturn(func(name string, flag int, perm os.FileMode) (*os.File, error) {
|
||||
return os.OpenFile(name, flag, perm)
|
||||
})
|
||||
|
||||
mockLogger.EXPECT().
|
||||
Log().
|
||||
Return(nil)
|
||||
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil)
|
||||
|
||||
mockOS.EXPECT().
|
||||
Stat(gomock.Any()).
|
||||
Return(nil, nil)
|
||||
|
||||
mockOS.EXPECT().
|
||||
Remove(tmpFile.Name()).
|
||||
Return(nil)
|
||||
})
|
||||
|
||||
AfterEach(func() {
|
||||
err := os.Remove(tmpFile.Name())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
|
||||
When("app uses legacy FairPlay protection", func() {
|
||||
BeforeEach(func() {
|
||||
zipFile = zip.NewWriter(tmpFile)
|
||||
w, err := zipFile.Create("Payload/Test.app/Info.plist")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
info, err := plist.Marshal(map[string]interface{}{
|
||||
"CFBundleExecutable": "Test",
|
||||
}, plist.BinaryFormat)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
_, err = w.Write(info)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
err = zipFile.Close()
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil)
|
||||
})
|
||||
|
||||
It("succeeds", func() {
|
||||
err := as.Download("", outputPath, true)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("app uses modern FairPlay protection", func() {
|
||||
BeforeEach(func() {
|
||||
zipFile = zip.NewWriter(tmpFile)
|
||||
w, err := zipFile.Create("Payload/Test.app/SC_Info/Manifest.plist")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
manifest, err := plist.Marshal(PackageManifest{
|
||||
SinfPaths: []string{
|
||||
"SC_Info/TestApp.sinf",
|
||||
},
|
||||
}, plist.BinaryFormat)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
_, err = w.Write(manifest)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
w, err = zipFile.Create("Payload/Test.app/Info.plist")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
info, err := plist.Marshal(map[string]interface{}{
|
||||
"CFBundleExecutable": "Test",
|
||||
}, plist.BinaryFormat)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
_, err = w.Write(info)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
err = zipFile.Close()
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
|
||||
It("succeeds", func() {
|
||||
outputPath := strings.TrimSuffix(tmpFile.Name(), ".tmp")
|
||||
err := as.Download("", outputPath, true)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("app uses modern FairPlay protection and has Watch app", func() {
|
||||
BeforeEach(func() {
|
||||
zipFile = zip.NewWriter(tmpFile)
|
||||
w, err := zipFile.Create("Payload/Test.app/SC_Info/Manifest.plist")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
manifest, err := plist.Marshal(PackageManifest{
|
||||
SinfPaths: []string{
|
||||
"SC_Info/TestApp.sinf",
|
||||
},
|
||||
}, plist.BinaryFormat)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
_, err = w.Write(manifest)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
w, err = zipFile.Create("Payload/Test.app/Info.plist")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
info, err := plist.Marshal(map[string]interface{}{
|
||||
"CFBundleExecutable": "Test",
|
||||
}, plist.BinaryFormat)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
_, err = w.Write(info)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
w, err = zipFile.Create("Payload/Test.app/Watch/Test Watch App.app/Info.plist")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
watchInfo, err := plist.Marshal(map[string]interface{}{
|
||||
"WKWatchKitApp": true,
|
||||
}, plist.BinaryFormat)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
_, err = w.Write(watchInfo)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
err = zipFile.Close()
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
|
||||
It("sinf is in the correct path", func() {
|
||||
outputPath := strings.TrimSuffix(tmpFile.Name(), ".tmp")
|
||||
err := as.Download("", outputPath, true)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
r, err := zip.OpenReader(outputPath)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
defer r.Close()
|
||||
|
||||
found := false
|
||||
for _, f := range r.File {
|
||||
if f.Name == "Payload/Test Watch App.app/SC_Info/TestApp.sinf" {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
Expect(found).To(BeFalse())
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,36 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
func (a *appstore) Info() error {
|
||||
acc, err := a.account()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrGetAccount.Error())
|
||||
}
|
||||
|
||||
a.logger.Log().
|
||||
Str("name", acc.Name).
|
||||
Str("email", acc.Email).
|
||||
Bool("success", true).
|
||||
Send()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *appstore) account() (Account, error) {
|
||||
data, err := a.keychain.Get("account")
|
||||
if err != nil {
|
||||
return Account{}, errors.Wrap(err, ErrGetKeychainItem.Error())
|
||||
}
|
||||
|
||||
var acc Account
|
||||
err = json.Unmarshal(data, &acc)
|
||||
if err != nil {
|
||||
return Account{}, errors.Wrap(err, ErrUnmarshal.Error())
|
||||
}
|
||||
|
||||
return acc, err
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"github.com/golang/mock/gomock"
|
||||
"github.com/majd/ipatool/pkg/keychain"
|
||||
"github.com/majd/ipatool/pkg/log"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
var _ = Describe("AppStore (Info)", func() {
|
||||
var (
|
||||
ctrl *gomock.Controller
|
||||
appstore AppStore
|
||||
mockKeychain *keychain.MockKeychain
|
||||
mockLogger *log.MockLogger
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctrl = gomock.NewController(GinkgoT())
|
||||
mockKeychain = keychain.NewMockKeychain(ctrl)
|
||||
mockLogger = log.NewMockLogger(ctrl)
|
||||
appstore = NewAppStore(AppStoreArgs{
|
||||
Keychain: mockKeychain,
|
||||
Logger: mockLogger,
|
||||
})
|
||||
})
|
||||
|
||||
AfterEach(func() {
|
||||
ctrl.Finish()
|
||||
})
|
||||
|
||||
When("keychain returns error", func() {
|
||||
var testErr = errors.New("test error")
|
||||
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte{}, testErr)
|
||||
})
|
||||
|
||||
It("returns wrapped error", func() {
|
||||
err := appstore.Info()
|
||||
Expect(err).To(MatchError(ContainSubstring(testErr.Error())))
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrGetAccount.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("keychain returns invalid data", func() {
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte("..."), nil)
|
||||
})
|
||||
|
||||
It("fails to unmarshall JSON data", func() {
|
||||
err := appstore.Info()
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrUnmarshal.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("keychain returns valid data", func() {
|
||||
BeforeEach(func() {
|
||||
mockLogger.EXPECT().
|
||||
Log().
|
||||
Return(nil)
|
||||
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte("{}"), nil)
|
||||
})
|
||||
|
||||
It("returns nil", func() {
|
||||
err := appstore.Info()
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,196 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/majd/ipatool/pkg/http"
|
||||
"github.com/majd/ipatool/pkg/util"
|
||||
"github.com/pkg/errors"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type LoginAddressResult struct {
|
||||
FirstName string `plist:"firstName,omitempty"`
|
||||
LastName string `plist:"lastName,omitempty"`
|
||||
}
|
||||
|
||||
type LoginAccountResult struct {
|
||||
Email string `plist:"appleId,omitempty"`
|
||||
Address LoginAddressResult `plist:"address,omitempty"`
|
||||
}
|
||||
|
||||
type LoginResult struct {
|
||||
FailureType string `plist:"failureType,omitempty"`
|
||||
CustomerMessage string `plist:"customerMessage,omitempty"`
|
||||
Account LoginAccountResult `plist:"accountInfo,omitempty"`
|
||||
DirectoryServicesID string `plist:"dsPersonId,omitempty"`
|
||||
PasswordToken string `plist:"passwordToken,omitempty"`
|
||||
}
|
||||
|
||||
func (a *appstore) Login(email, password, authCode string) error {
|
||||
if password == "" && !a.interactive {
|
||||
return ErrPasswordRequired
|
||||
}
|
||||
|
||||
if password == "" && a.interactive {
|
||||
a.logger.Log().Msg("enter password:")
|
||||
|
||||
var err error
|
||||
password, err = a.promptForPassword()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrGetData.Error())
|
||||
}
|
||||
}
|
||||
|
||||
macAddr, err := a.machine.MacAddress()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrGetMAC.Error())
|
||||
}
|
||||
|
||||
guid := strings.ReplaceAll(strings.ToUpper(macAddr), ":", "")
|
||||
a.logger.Verbose().Str("mac", macAddr).Str("guid", guid).Send()
|
||||
|
||||
acc, err := a.login(email, password, authCode, guid, 0, false)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrLogin.Error())
|
||||
}
|
||||
|
||||
a.logger.Log().
|
||||
Str("name", acc.Name).
|
||||
Str("email", acc.Email).
|
||||
Bool("success", true).
|
||||
Send()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *appstore) login(email, password, authCode, guid string, attempt int, failOnAuthCodeRequirement bool) (Account, error) {
|
||||
a.logger.Verbose().
|
||||
Int("attempt", attempt).
|
||||
Str("password", password).
|
||||
Str("email", email).
|
||||
Str("authCode", util.IfEmpty(authCode, "<nil>")).
|
||||
Msg("sending login request")
|
||||
|
||||
request := a.loginRequest(email, password, authCode, guid)
|
||||
res, err := a.loginClient.Send(request)
|
||||
if err != nil {
|
||||
return Account{}, errors.Wrap(err, ErrRequest.Error())
|
||||
}
|
||||
|
||||
if attempt == 0 && res.Data.FailureType == FailureTypeInvalidCredentials {
|
||||
return a.login(email, password, authCode, guid, 1, failOnAuthCodeRequirement)
|
||||
}
|
||||
|
||||
if res.Data.FailureType != "" && res.Data.CustomerMessage != "" {
|
||||
a.logger.Verbose().Interface("response", res).Send()
|
||||
return Account{}, errors.New(res.Data.CustomerMessage)
|
||||
}
|
||||
|
||||
if res.Data.FailureType != "" {
|
||||
a.logger.Verbose().Interface("response", res).Send()
|
||||
return Account{}, ErrGeneric
|
||||
}
|
||||
|
||||
if res.Data.FailureType == "" && authCode == "" && res.Data.CustomerMessage == CustomerMessageBadLogin {
|
||||
if failOnAuthCodeRequirement {
|
||||
return Account{}, ErrAuthCodeRequired
|
||||
}
|
||||
|
||||
if a.interactive {
|
||||
a.logger.Log().Msg("enter 2FA code:")
|
||||
authCode, err = a.promptForAuthCode()
|
||||
if err != nil {
|
||||
return Account{}, errors.Wrap(err, ErrGetData.Error())
|
||||
}
|
||||
|
||||
return a.login(email, password, authCode, guid, 0, failOnAuthCodeRequirement)
|
||||
} else {
|
||||
a.logger.Log().Msg("2FA code is required; run the command again and supply a code using the `--auth-code` flag")
|
||||
return Account{}, nil
|
||||
}
|
||||
}
|
||||
|
||||
addr := res.Data.Account.Address
|
||||
acc := Account{
|
||||
Name: strings.Join([]string{addr.FirstName, addr.LastName}, " "),
|
||||
Email: res.Data.Account.Email,
|
||||
PasswordToken: res.Data.PasswordToken,
|
||||
DirectoryServicesID: res.Data.DirectoryServicesID,
|
||||
StoreFront: res.Headers[HTTPHeaderStoreFront],
|
||||
Password: password,
|
||||
}
|
||||
|
||||
data, err := json.Marshal(acc)
|
||||
if err != nil {
|
||||
return Account{}, errors.Wrap(err, ErrMarshal.Error())
|
||||
}
|
||||
|
||||
err = a.keychain.Set("account", data)
|
||||
if err != nil {
|
||||
return Account{}, errors.Wrap(err, ErrSetKeychainItem.Error())
|
||||
}
|
||||
|
||||
return acc, nil
|
||||
}
|
||||
|
||||
func (a *appstore) loginRequest(email, password, authCode, guid string) http.Request {
|
||||
attempt := "4"
|
||||
if authCode != "" {
|
||||
attempt = "2"
|
||||
}
|
||||
|
||||
return http.Request{
|
||||
Method: http.MethodPOST,
|
||||
URL: a.authDomain(authCode, guid),
|
||||
ResponseFormat: http.ResponseFormatXML,
|
||||
Headers: map[string]string{
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
},
|
||||
Payload: &http.XMLPayload{
|
||||
Content: map[string]interface{}{
|
||||
"appleId": email,
|
||||
"attempt": attempt,
|
||||
"createSession": "true",
|
||||
"guid": guid,
|
||||
"password": fmt.Sprintf("%s%s", password, authCode),
|
||||
"rmp": "0",
|
||||
"why": "signIn",
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (a *appstore) promptForAuthCode() (string, error) {
|
||||
reader := bufio.NewReader(a.ioReader)
|
||||
authCode, err := reader.ReadString('\n')
|
||||
if err != nil {
|
||||
return "", errors.Wrap(err, ErrGetData.Error())
|
||||
}
|
||||
|
||||
authCode = strings.Trim(authCode, "\n")
|
||||
authCode = strings.Trim(authCode, "\r")
|
||||
|
||||
return authCode, nil
|
||||
}
|
||||
|
||||
func (*appstore) authDomain(authCode, guid string) string {
|
||||
prefix := PriavteAppStoreAPIDomainPrefixWithoutAuthCode
|
||||
if authCode != "" {
|
||||
prefix = PriavteAppStoreAPIDomainPrefixWithAuthCode
|
||||
}
|
||||
|
||||
return fmt.Sprintf(
|
||||
"https://%s-%s%s?guid=%s", prefix, PrivateAppStoreAPIDomain, PrivateAppStoreAPIPathAuthenticate, guid)
|
||||
}
|
||||
|
||||
func (a *appstore) promptForPassword() (string, error) {
|
||||
password, err := a.machine.ReadPassword(int(os.Stdin.Fd()))
|
||||
if err != nil {
|
||||
return "", errors.Wrap(err, ErrGetData.Error())
|
||||
}
|
||||
|
||||
return string(password), nil
|
||||
}
|
||||
@@ -0,0 +1,348 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/golang/mock/gomock"
|
||||
"github.com/majd/ipatool/pkg/http"
|
||||
"github.com/majd/ipatool/pkg/keychain"
|
||||
"github.com/majd/ipatool/pkg/log"
|
||||
"github.com/majd/ipatool/pkg/util"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"github.com/pkg/errors"
|
||||
"os"
|
||||
"strings"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
var _ = Describe("AppStore (Login)", func() {
|
||||
const (
|
||||
testPassword = "test-password"
|
||||
)
|
||||
|
||||
var (
|
||||
ctrl *gomock.Controller
|
||||
as AppStore
|
||||
mockKeychain *keychain.MockKeychain
|
||||
mockClient *http.MockClient[LoginResult]
|
||||
mockMachine *util.MockMachine
|
||||
mockLogger *log.MockLogger
|
||||
testErr = errors.New("test")
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctrl = gomock.NewController(GinkgoT())
|
||||
mockKeychain = keychain.NewMockKeychain(ctrl)
|
||||
mockClient = http.NewMockClient[LoginResult](ctrl)
|
||||
mockMachine = util.NewMockMachine(ctrl)
|
||||
mockLogger = log.NewMockLogger(ctrl)
|
||||
as = &appstore{
|
||||
keychain: mockKeychain,
|
||||
loginClient: mockClient,
|
||||
ioReader: os.Stdin,
|
||||
machine: mockMachine,
|
||||
logger: mockLogger,
|
||||
interactive: true,
|
||||
}
|
||||
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil).
|
||||
MaxTimes(4)
|
||||
})
|
||||
|
||||
AfterEach(func() {
|
||||
ctrl.Finish()
|
||||
})
|
||||
|
||||
When("not running in interactive mode and password is not supplied", func() {
|
||||
BeforeEach(func() {
|
||||
as.(*appstore).interactive = false
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Login("", "", "")
|
||||
Expect(err).To(MatchError(ContainSubstring("password is required")))
|
||||
})
|
||||
})
|
||||
|
||||
When("prompts user for password", func() {
|
||||
BeforeEach(func() {
|
||||
mockLogger.EXPECT().
|
||||
Log().
|
||||
Return(nil)
|
||||
})
|
||||
|
||||
When("user enters password", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("", errors.New("success"))
|
||||
|
||||
mockMachine.EXPECT().
|
||||
ReadPassword(syscall.Stdin).
|
||||
Return([]byte(testPassword), nil)
|
||||
})
|
||||
|
||||
It("succeeds", func() {
|
||||
err := as.Login("", "", "")
|
||||
Expect(err).To(MatchError(ContainSubstring("success")))
|
||||
})
|
||||
})
|
||||
|
||||
When("fails to read password from stdin", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
ReadPassword(syscall.Stdin).
|
||||
Return(nil, testErr)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Login("", "", "")
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrGetData.Error())))
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
When("fails to read Machine's MAC address", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("", testErr)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Login("", testPassword, "")
|
||||
Expect(err).To(MatchError(ContainSubstring(testErr.Error())))
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrGetMAC.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("sucessfully reads Machine's MAC address", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
})
|
||||
|
||||
When("client returns error", func() {
|
||||
BeforeEach(func() {
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[LoginResult]{}, testErr)
|
||||
})
|
||||
|
||||
It("returns wrapped error", func() {
|
||||
err := as.Login("", testPassword, "")
|
||||
Expect(err).To(MatchError(ContainSubstring(testErr.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("store API returns invalid first response", func() {
|
||||
const testCustomerMessage = "test"
|
||||
|
||||
BeforeEach(func() {
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[LoginResult]{
|
||||
Data: LoginResult{
|
||||
FailureType: FailureTypeInvalidCredentials,
|
||||
CustomerMessage: "test",
|
||||
},
|
||||
}, nil).
|
||||
Times(2)
|
||||
})
|
||||
|
||||
It("retries one more time", func() {
|
||||
err := as.Login("", testPassword, "")
|
||||
Expect(err).To(MatchError(ContainSubstring(testCustomerMessage)))
|
||||
})
|
||||
})
|
||||
|
||||
When("store API returns error", func() {
|
||||
BeforeEach(func() {
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[LoginResult]{
|
||||
Data: LoginResult{
|
||||
FailureType: "random-error",
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Login("", testPassword, "")
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrGeneric.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("store API requires 2FA code", func() {
|
||||
When("not running in interactive mode", func() {
|
||||
BeforeEach(func() {
|
||||
as.(*appstore).interactive = false
|
||||
|
||||
mockLogger.EXPECT().
|
||||
Log().
|
||||
Return(nil).
|
||||
Times(2)
|
||||
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[LoginResult]{
|
||||
Data: LoginResult{
|
||||
FailureType: "",
|
||||
CustomerMessage: CustomerMessageBadLogin,
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("prints message", func() {
|
||||
err := as.Login("", testPassword, "")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("user enters 2FA code", func() {
|
||||
BeforeEach(func() {
|
||||
mockLogger.EXPECT().
|
||||
Log().
|
||||
Return(nil).
|
||||
Times(2)
|
||||
|
||||
mockKeychain.EXPECT().
|
||||
Set("account", gomock.Any()).
|
||||
Return(nil)
|
||||
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[LoginResult]{
|
||||
Data: LoginResult{
|
||||
FailureType: "",
|
||||
CustomerMessage: CustomerMessageBadLogin,
|
||||
},
|
||||
}, nil).
|
||||
Times(2)
|
||||
|
||||
as.(*appstore).ioReader = strings.NewReader("123456\n")
|
||||
})
|
||||
|
||||
It("successfully authenticates", func() {
|
||||
err := as.Login("", testPassword, "")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("prompts user for 2FA code", func() {
|
||||
BeforeEach(func() {
|
||||
mockLogger.EXPECT().
|
||||
Log().
|
||||
Return(nil)
|
||||
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[LoginResult]{
|
||||
Data: LoginResult{
|
||||
FailureType: "",
|
||||
CustomerMessage: CustomerMessageBadLogin,
|
||||
},
|
||||
}, nil)
|
||||
|
||||
as.(*appstore).ioReader = strings.NewReader("123456")
|
||||
})
|
||||
|
||||
It("fails to read 2FA code from stdin", func() {
|
||||
err := as.Login("", testPassword, "")
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrGetData.Error())))
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
When("store API returns valid response", func() {
|
||||
const (
|
||||
testEmail = "test-email"
|
||||
testFirstName = "test-first-name"
|
||||
testLastName = "test-last-name"
|
||||
testPasswordToken = "test-password-token"
|
||||
testDirectoryServicesID = "directory-services-id"
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[LoginResult]{
|
||||
Data: LoginResult{
|
||||
PasswordToken: testPasswordToken,
|
||||
DirectoryServicesID: testDirectoryServicesID,
|
||||
Account: LoginAccountResult{
|
||||
Email: testEmail,
|
||||
Address: LoginAddressResult{
|
||||
FirstName: testFirstName,
|
||||
LastName: testLastName,
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
When("fails to save account in keychain", func() {
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Set("account", gomock.Any()).
|
||||
Do(func(key string, data []byte) {
|
||||
want := Account{
|
||||
Name: fmt.Sprintf("%s %s", testFirstName, testLastName),
|
||||
Email: testEmail,
|
||||
PasswordToken: testPasswordToken,
|
||||
Password: testPassword,
|
||||
DirectoryServicesID: testDirectoryServicesID,
|
||||
}
|
||||
|
||||
var got Account
|
||||
err := json.Unmarshal(data, &got)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(got).To(Equal(want))
|
||||
}).
|
||||
Return(testErr)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Login("", testPassword, "")
|
||||
Expect(err).To(MatchError(ContainSubstring(testErr.Error())))
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrSetKeychainItem.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("sucessfully saves account in keychain", func() {
|
||||
BeforeEach(func() {
|
||||
mockLogger.EXPECT().
|
||||
Log().
|
||||
Return(nil)
|
||||
|
||||
mockKeychain.EXPECT().
|
||||
Set("account", gomock.Any()).
|
||||
Do(func(key string, data []byte) {
|
||||
want := Account{
|
||||
Name: fmt.Sprintf("%s %s", testFirstName, testLastName),
|
||||
Email: testEmail,
|
||||
PasswordToken: testPasswordToken,
|
||||
Password: testPassword,
|
||||
DirectoryServicesID: testDirectoryServicesID,
|
||||
}
|
||||
|
||||
var got Account
|
||||
err := json.Unmarshal(data, &got)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(got).To(Equal(want))
|
||||
}).
|
||||
Return(nil)
|
||||
})
|
||||
|
||||
It("returns nil", func() {
|
||||
err := as.Login("", testPassword, "")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,51 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/majd/ipatool/pkg/http"
|
||||
"github.com/pkg/errors"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
func (a *appstore) lookup(bundleID, countryCode string) (App, error) {
|
||||
if StoreFronts[countryCode] == "" {
|
||||
return App{}, ErrInvalidCountryCode
|
||||
}
|
||||
|
||||
request := a.lookupRequest(bundleID, countryCode)
|
||||
|
||||
res, err := a.searchClient.Send(request)
|
||||
if err != nil {
|
||||
return App{}, errors.Wrap(err, ErrRequest.Error())
|
||||
}
|
||||
|
||||
if res.StatusCode != 200 {
|
||||
a.logger.Verbose().Interface("data", res.Data).Int("status", res.StatusCode).Send()
|
||||
return App{}, ErrRequest
|
||||
}
|
||||
|
||||
if len(res.Data.Results) == 0 {
|
||||
return App{}, ErrAppNotFound
|
||||
}
|
||||
|
||||
return res.Data.Results[0], nil
|
||||
}
|
||||
|
||||
func (a *appstore) lookupRequest(bundleID, countryCode string) http.Request {
|
||||
return http.Request{
|
||||
URL: a.lookupURL(bundleID, countryCode),
|
||||
Method: http.MethodGET,
|
||||
ResponseFormat: http.ResponseFormatJSON,
|
||||
}
|
||||
}
|
||||
|
||||
func (a *appstore) lookupURL(bundleID, countryCode string) string {
|
||||
params := url.Values{}
|
||||
params.Add("entity", "software,iPadSoftware")
|
||||
params.Add("limit", "1")
|
||||
params.Add("media", "software")
|
||||
params.Add("bundleId", bundleID)
|
||||
params.Add("country", countryCode)
|
||||
|
||||
return fmt.Sprintf("https://%s%s?%s", iTunesAPIDomain, iTunesAPIPathLookup, params.Encode())
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"github.com/golang/mock/gomock"
|
||||
"github.com/majd/ipatool/pkg/http"
|
||||
"github.com/majd/ipatool/pkg/log"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"github.com/pkg/errors"
|
||||
"os"
|
||||
)
|
||||
|
||||
var _ = Describe("AppStore (Lookup)", func() {
|
||||
var (
|
||||
ctrl *gomock.Controller
|
||||
mockClient *http.MockClient[SearchResult]
|
||||
mockLogger *log.MockLogger
|
||||
as *appstore
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctrl = gomock.NewController(GinkgoT())
|
||||
mockClient = http.NewMockClient[SearchResult](ctrl)
|
||||
mockLogger = log.NewMockLogger(ctrl)
|
||||
as = &appstore{
|
||||
searchClient: mockClient,
|
||||
ioReader: os.Stdin,
|
||||
logger: mockLogger,
|
||||
}
|
||||
})
|
||||
|
||||
AfterEach(func() {
|
||||
ctrl.Finish()
|
||||
})
|
||||
|
||||
When("country code is invalid", func() {
|
||||
It("returns error", func() {
|
||||
_, err := as.lookup("", "XYZ")
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrInvalidCountryCode.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("request fails", func() {
|
||||
var testErr = errors.New("test")
|
||||
|
||||
BeforeEach(func() {
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[SearchResult]{}, testErr)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.lookup("", "US")
|
||||
Expect(err).To(MatchError(ContainSubstring(testErr.Error())))
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrRequest.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("request returns bad status code", func() {
|
||||
BeforeEach(func() {
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil)
|
||||
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[SearchResult]{
|
||||
StatusCode: 400,
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.lookup("", "US")
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrRequest.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("request is successful", func() {
|
||||
When("does not find app", func() {
|
||||
BeforeEach(func() {
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[SearchResult]{
|
||||
StatusCode: 200,
|
||||
Data: SearchResult{
|
||||
Count: 0,
|
||||
Results: []App{},
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.lookup("", "US")
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrAppNotFound.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("finds app", func() {
|
||||
var testApp = App{
|
||||
ID: 1,
|
||||
BundleID: "app.bundle.id",
|
||||
Name: "app name",
|
||||
Version: "1.0",
|
||||
Price: 0.99,
|
||||
}
|
||||
|
||||
BeforeEach(func() {
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[SearchResult]{
|
||||
StatusCode: 200,
|
||||
Data: SearchResult{
|
||||
Count: 1,
|
||||
Results: []App{testApp},
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns app", func() {
|
||||
app, err := as.lookup("", "US")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(app).To(Equal(testApp))
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,163 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/majd/ipatool/pkg/http"
|
||||
"github.com/pkg/errors"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type PurchaseResult struct {
|
||||
FailureType string `plist:"failureType,omitempty"`
|
||||
CustomerMessage string `plist:"customerMessage,omitempty"`
|
||||
JingleDocType string `plist:"jingleDocType,omitempty"`
|
||||
Status int `plist:"status,omitempty"`
|
||||
}
|
||||
|
||||
func (a *appstore) Purchase(bundleID string) error {
|
||||
macAddr, err := a.machine.MacAddress()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrGetMAC.Error())
|
||||
}
|
||||
|
||||
guid := strings.ReplaceAll(strings.ToUpper(macAddr), ":", "")
|
||||
a.logger.Verbose().Str("mac", macAddr).Str("guid", guid).Send()
|
||||
|
||||
err = a.purchase(bundleID, guid, true)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrPurchase.Error())
|
||||
}
|
||||
|
||||
a.logger.Log().Bool("success", true).Send()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *appstore) purchase(bundleID string, guid string, attemptToRenewCredentials bool) error {
|
||||
acc, err := a.account()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrGetAccount.Error())
|
||||
}
|
||||
|
||||
countryCode, err := a.countryCodeFromStoreFront(acc.StoreFront)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrInvalidCountryCode.Error())
|
||||
}
|
||||
|
||||
app, err := a.lookup(bundleID, countryCode)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrAppLookup.Error())
|
||||
}
|
||||
|
||||
if app.Price > 0 {
|
||||
return ErrPaidApp
|
||||
}
|
||||
|
||||
err = a.purchaseWithParams(acc, app, bundleID, guid, attemptToRenewCredentials, PricingParameterAppStore)
|
||||
if err != nil {
|
||||
if err == ErrTemporarilyUnavailable {
|
||||
err = a.purchaseWithParams(acc, app, bundleID, guid, attemptToRenewCredentials, PricingParameterAppleArcade)
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "failed to purchase item with param '%s'", PricingParameterAppleArcade)
|
||||
}
|
||||
}
|
||||
|
||||
return errors.Wrapf(err, "failed to purchase item with param '%s'", PricingParameterAppStore)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *appstore) purchaseWithParams(acc Account, app App, bundleID string, guid string, attemptToRenewCredentials bool, pricingParameters string) error {
|
||||
req := a.purchaseRequest(acc, app, acc.StoreFront, guid, pricingParameters)
|
||||
res, err := a.purchaseClient.Send(req)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrRequest.Error())
|
||||
}
|
||||
|
||||
if res.Data.FailureType == FailureTypeTemporarilyUnavailable {
|
||||
return ErrTemporarilyUnavailable
|
||||
}
|
||||
|
||||
if res.Data.CustomerMessage == CustomerMessageSubscriptionRequired {
|
||||
a.logger.Verbose().Interface("response", res).Send()
|
||||
return ErrSubscriptionRequired
|
||||
}
|
||||
|
||||
if res.Data.FailureType == FailureTypePasswordTokenExpired {
|
||||
if attemptToRenewCredentials {
|
||||
a.logger.Verbose().Msg("retrieving new password token")
|
||||
acc, err = a.login(acc.Email, acc.Password, "", guid, 0, true)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrPasswordTokenExpired.Error())
|
||||
}
|
||||
|
||||
return a.purchaseWithParams(acc, app, bundleID, guid, false, pricingParameters)
|
||||
}
|
||||
|
||||
return ErrPasswordTokenExpired
|
||||
}
|
||||
|
||||
if res.Data.FailureType != "" && res.Data.CustomerMessage != "" {
|
||||
a.logger.Verbose().Interface("response", res).Send()
|
||||
return errors.New(res.Data.CustomerMessage)
|
||||
}
|
||||
|
||||
if res.Data.FailureType != "" {
|
||||
a.logger.Verbose().Interface("response", res).Send()
|
||||
return ErrGeneric
|
||||
}
|
||||
|
||||
if res.StatusCode == 500 {
|
||||
return ErrLicenseExists
|
||||
}
|
||||
|
||||
if res.Data.JingleDocType != "purchaseSuccess" || res.Data.Status != 0 {
|
||||
a.logger.Verbose().Interface("response", res).Send()
|
||||
return errors.New(ErrPurchase.Error())
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (*appstore) countryCodeFromStoreFront(storeFront string) (string, error) {
|
||||
for key, val := range StoreFronts {
|
||||
parts := strings.Split(storeFront, "-")
|
||||
|
||||
if len(parts) >= 1 && parts[0] == val {
|
||||
return key, nil
|
||||
}
|
||||
}
|
||||
|
||||
return "", errors.New(ErrInvalidStoreFront.Error())
|
||||
}
|
||||
|
||||
func (a *appstore) purchaseRequest(acc Account, app App, storeFront, guid string, pricingParameters string) http.Request {
|
||||
return http.Request{
|
||||
URL: fmt.Sprintf("https://%s%s", PrivateAppStoreAPIDomain, PrivateAppStoreAPIPathPurchase),
|
||||
Method: http.MethodPOST,
|
||||
ResponseFormat: http.ResponseFormatXML,
|
||||
Headers: map[string]string{
|
||||
"Content-Type": "application/x-apple-plist",
|
||||
"iCloud-DSID": acc.DirectoryServicesID,
|
||||
"X-Dsid": acc.DirectoryServicesID,
|
||||
"X-Apple-Store-Front": storeFront,
|
||||
"X-Token": acc.PasswordToken,
|
||||
},
|
||||
Payload: &http.XMLPayload{
|
||||
Content: map[string]interface{}{
|
||||
"appExtVrsId": "0",
|
||||
"hasAskedToFulfillPreorder": "true",
|
||||
"buyWithoutAuthorization": "true",
|
||||
"hasDoneAgeCheck": "true",
|
||||
"guid": guid,
|
||||
"needDiv": "0",
|
||||
"origPage": fmt.Sprintf("Software-%d", app.ID),
|
||||
"origPageLocation": "Buy",
|
||||
"price": "0",
|
||||
"pricingParameters": pricingParameters,
|
||||
"productType": "C",
|
||||
"salableAdamId": app.ID,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,631 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"github.com/golang/mock/gomock"
|
||||
"github.com/majd/ipatool/pkg/http"
|
||||
"github.com/majd/ipatool/pkg/keychain"
|
||||
"github.com/majd/ipatool/pkg/log"
|
||||
"github.com/majd/ipatool/pkg/util"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("AppStore (Purchase)", func() {
|
||||
var (
|
||||
ctrl *gomock.Controller
|
||||
mockKeychain *keychain.MockKeychain
|
||||
mockMachine *util.MockMachine
|
||||
mockLogger *log.MockLogger
|
||||
mockPurchaseClient *http.MockClient[PurchaseResult]
|
||||
mockSearchClient *http.MockClient[SearchResult]
|
||||
mockLoginClient *http.MockClient[LoginResult]
|
||||
as *appstore
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctrl = gomock.NewController(GinkgoT())
|
||||
mockKeychain = keychain.NewMockKeychain(ctrl)
|
||||
mockPurchaseClient = http.NewMockClient[PurchaseResult](ctrl)
|
||||
mockSearchClient = http.NewMockClient[SearchResult](ctrl)
|
||||
mockLoginClient = http.NewMockClient[LoginResult](ctrl)
|
||||
mockMachine = util.NewMockMachine(ctrl)
|
||||
mockLogger = log.NewMockLogger(ctrl)
|
||||
as = &appstore{
|
||||
keychain: mockKeychain,
|
||||
purchaseClient: mockPurchaseClient,
|
||||
searchClient: mockSearchClient,
|
||||
loginClient: mockLoginClient,
|
||||
machine: mockMachine,
|
||||
logger: mockLogger,
|
||||
}
|
||||
})
|
||||
|
||||
AfterEach(func() {
|
||||
ctrl.Finish()
|
||||
})
|
||||
|
||||
When("fails to read MAC address", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("", ErrGetMAC)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Purchase("")
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrGetMAC.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("not logged in", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil)
|
||||
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return(nil, ErrGetKeychainItem)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Purchase("")
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrGetKeychainItem.Error())))
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrGetAccount.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("country code is invalid", func() {
|
||||
BeforeEach(func() {
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil)
|
||||
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte("{}"), nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Purchase("")
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrInvalidCountryCode.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("app lookup fails", func() {
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
|
||||
|
||||
mockSearchClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[SearchResult]{}, ErrRequest)
|
||||
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Purchase("")
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrAppLookup.Error())))
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrRequest.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("app is paid", func() {
|
||||
BeforeEach(func() {
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil)
|
||||
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
|
||||
|
||||
mockSearchClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[SearchResult]{
|
||||
StatusCode: 200,
|
||||
Data: SearchResult{
|
||||
Count: 1,
|
||||
Results: []App{
|
||||
{
|
||||
Price: 0.99,
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Purchase("")
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrPaidApp.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("purchase request fails", func() {
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
|
||||
|
||||
mockSearchClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[SearchResult]{
|
||||
StatusCode: 200,
|
||||
Data: SearchResult{
|
||||
Count: 1,
|
||||
Results: []App{
|
||||
{
|
||||
ID: 0,
|
||||
BundleID: "",
|
||||
Name: "",
|
||||
Version: "",
|
||||
Price: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[PurchaseResult]{}, ErrRequest)
|
||||
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Purchase("")
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrRequest.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("password token is expired", func() {
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
|
||||
|
||||
mockSearchClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[SearchResult]{
|
||||
StatusCode: 200,
|
||||
Data: SearchResult{
|
||||
Count: 1,
|
||||
Results: []App{
|
||||
{
|
||||
ID: 0,
|
||||
BundleID: "",
|
||||
Name: "",
|
||||
Version: "",
|
||||
Price: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[PurchaseResult]{
|
||||
Data: PurchaseResult{
|
||||
FailureType: FailureTypePasswordTokenExpired,
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil)
|
||||
})
|
||||
|
||||
When("renewing credentials fails", func() {
|
||||
BeforeEach(func() {
|
||||
mockLoginClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[LoginResult]{
|
||||
Data: LoginResult{
|
||||
FailureType: "",
|
||||
CustomerMessage: CustomerMessageBadLogin,
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil).
|
||||
Times(2)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Purchase("")
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrPasswordTokenExpired.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("renewing credentials succeeds", func() {
|
||||
BeforeEach(func() {
|
||||
mockLoginClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[LoginResult]{
|
||||
Data: LoginResult{},
|
||||
}, nil)
|
||||
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil).
|
||||
Times(2)
|
||||
|
||||
mockKeychain.EXPECT().
|
||||
Set("account", gomock.Any()).
|
||||
Return(nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[PurchaseResult]{
|
||||
Data: PurchaseResult{
|
||||
FailureType: FailureTypePasswordTokenExpired,
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("attempts to purchase app", func() {
|
||||
err := as.Purchase("")
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrPasswordTokenExpired.Error())))
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
When("store API returns customer error message", func() {
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
|
||||
|
||||
mockSearchClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[SearchResult]{
|
||||
StatusCode: 200,
|
||||
Data: SearchResult{
|
||||
Count: 1,
|
||||
Results: []App{
|
||||
{
|
||||
ID: 0,
|
||||
BundleID: "",
|
||||
Name: "",
|
||||
Version: "",
|
||||
Price: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[PurchaseResult]{
|
||||
Data: PurchaseResult{
|
||||
FailureType: "failure",
|
||||
CustomerMessage: CustomerMessageBadLogin,
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil).
|
||||
Times(2)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Purchase("")
|
||||
Expect(err).To(MatchError(ContainSubstring(CustomerMessageBadLogin)))
|
||||
})
|
||||
})
|
||||
|
||||
When("store API returns unknown error", func() {
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
|
||||
|
||||
mockSearchClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[SearchResult]{
|
||||
StatusCode: 200,
|
||||
Data: SearchResult{
|
||||
Count: 1,
|
||||
Results: []App{
|
||||
{
|
||||
ID: 0,
|
||||
BundleID: "",
|
||||
Name: "",
|
||||
Version: "",
|
||||
Price: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[PurchaseResult]{
|
||||
Data: PurchaseResult{
|
||||
FailureType: "failure",
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil).
|
||||
Times(2)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Purchase("")
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrGeneric.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("account already has a license for the app", func() {
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
|
||||
|
||||
mockSearchClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[SearchResult]{
|
||||
StatusCode: 200,
|
||||
Data: SearchResult{
|
||||
Count: 1,
|
||||
Results: []App{
|
||||
{
|
||||
ID: 0,
|
||||
BundleID: "",
|
||||
Name: "",
|
||||
Version: "",
|
||||
Price: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[PurchaseResult]{
|
||||
StatusCode: 500,
|
||||
Data: PurchaseResult{},
|
||||
}, nil)
|
||||
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Purchase("")
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrLicenseExists.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("subscription is required", func() {
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
|
||||
|
||||
mockSearchClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[SearchResult]{
|
||||
StatusCode: 200,
|
||||
Data: SearchResult{
|
||||
Count: 1,
|
||||
Results: []App{
|
||||
{
|
||||
ID: 0,
|
||||
BundleID: "",
|
||||
Name: "",
|
||||
Version: "",
|
||||
Price: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(pricingParametersMatcher{"STDQ"}).
|
||||
Return(http.Result[PurchaseResult]{
|
||||
StatusCode: 200,
|
||||
Data: PurchaseResult{
|
||||
CustomerMessage: "This item is temporarily unavailable.",
|
||||
FailureType: FailureTypeTemporarilyUnavailable,
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(pricingParametersMatcher{"GAME"}).
|
||||
Return(http.Result[PurchaseResult]{
|
||||
StatusCode: 200,
|
||||
Data: PurchaseResult{
|
||||
CustomerMessage: CustomerMessageSubscriptionRequired,
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil).
|
||||
Times(2)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Purchase("")
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrSubscriptionRequired.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("successfully purchases the app", func() {
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
|
||||
|
||||
mockSearchClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[SearchResult]{
|
||||
StatusCode: 200,
|
||||
Data: SearchResult{
|
||||
Count: 1,
|
||||
Results: []App{
|
||||
{
|
||||
ID: 0,
|
||||
BundleID: "",
|
||||
Name: "",
|
||||
Version: "",
|
||||
Price: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(pricingParametersMatcher{"STDQ"}).
|
||||
Return(http.Result[PurchaseResult]{
|
||||
StatusCode: 200,
|
||||
Data: PurchaseResult{
|
||||
CustomerMessage: "This item is temporarily unavailable.",
|
||||
FailureType: FailureTypeTemporarilyUnavailable,
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(pricingParametersMatcher{"GAME"}).
|
||||
Return(http.Result[PurchaseResult]{
|
||||
StatusCode: 200,
|
||||
Data: PurchaseResult{
|
||||
JingleDocType: "purchaseSuccess",
|
||||
Status: 0,
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil)
|
||||
|
||||
mockLogger.EXPECT().
|
||||
Log().
|
||||
Return(nil)
|
||||
})
|
||||
|
||||
It("returns nil", func() {
|
||||
err := as.Purchase("")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("purchasing the app fails", func() {
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
|
||||
|
||||
mockSearchClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[SearchResult]{
|
||||
StatusCode: 200,
|
||||
Data: SearchResult{
|
||||
Count: 1,
|
||||
Results: []App{
|
||||
{
|
||||
ID: 0,
|
||||
BundleID: "",
|
||||
Name: "",
|
||||
Version: "",
|
||||
Price: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[PurchaseResult]{
|
||||
StatusCode: 200,
|
||||
Data: PurchaseResult{
|
||||
JingleDocType: "failure",
|
||||
Status: -1,
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil).
|
||||
Times(2)
|
||||
})
|
||||
|
||||
It("returns nil", func() {
|
||||
err := as.Purchase("")
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrPurchase.Error())))
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
type pricingParametersMatcher struct {
|
||||
pricingParameters string
|
||||
}
|
||||
|
||||
func (p pricingParametersMatcher) Matches(in interface{}) bool {
|
||||
request := in.(http.Request)
|
||||
return request.Payload.(*http.XMLPayload).Content["pricingParameters"] == p.pricingParameters
|
||||
}
|
||||
|
||||
func (p pricingParametersMatcher) String() string {
|
||||
return "payload pricingParameters is " + p.pricingParameters
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
func (a *appstore) Revoke() error {
|
||||
err := a.keychain.Remove("account")
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrRemoveKeychainItem.Error())
|
||||
}
|
||||
|
||||
a.logger.Log().Bool("success", true).Send()
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"github.com/golang/mock/gomock"
|
||||
"github.com/majd/ipatool/pkg/keychain"
|
||||
"github.com/majd/ipatool/pkg/log"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
var _ = Describe("AppStore (Revoke)", func() {
|
||||
var (
|
||||
ctrl *gomock.Controller
|
||||
appstore AppStore
|
||||
mockKeychain *keychain.MockKeychain
|
||||
mockLogger *log.MockLogger
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctrl = gomock.NewController(GinkgoT())
|
||||
mockKeychain = keychain.NewMockKeychain(ctrl)
|
||||
mockLogger = log.NewMockLogger(ctrl)
|
||||
appstore = NewAppStore(AppStoreArgs{
|
||||
Keychain: mockKeychain,
|
||||
Logger: mockLogger,
|
||||
})
|
||||
})
|
||||
|
||||
AfterEach(func() {
|
||||
ctrl.Finish()
|
||||
})
|
||||
|
||||
When("keychain returns error", func() {
|
||||
var testErr = errors.New("test error")
|
||||
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Remove("account").
|
||||
Return(testErr)
|
||||
})
|
||||
|
||||
It("returns wrapped error", func() {
|
||||
err := appstore.Revoke()
|
||||
Expect(err).To(MatchError(ContainSubstring(testErr.Error())))
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrRemoveKeychainItem.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("keychain removes item", func() {
|
||||
BeforeEach(func() {
|
||||
mockLogger.EXPECT().
|
||||
Log().
|
||||
Return(nil)
|
||||
|
||||
mockKeychain.EXPECT().
|
||||
Remove("account").
|
||||
Return(nil)
|
||||
})
|
||||
|
||||
It("returns data", func() {
|
||||
err := appstore.Revoke()
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,60 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/majd/ipatool/pkg/http"
|
||||
"github.com/pkg/errors"
|
||||
"net/url"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type SearchResult struct {
|
||||
Count int `json:"resultCount,omitempty"`
|
||||
Results []App `json:"results,omitempty"`
|
||||
}
|
||||
|
||||
func (a *appstore) Search(term string, limit int64) error {
|
||||
acc, err := a.account()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrGetAccount.Error())
|
||||
}
|
||||
|
||||
countryCode, err := a.countryCodeFromStoreFront(acc.StoreFront)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrInvalidCountryCode.Error())
|
||||
}
|
||||
|
||||
request := a.searchRequest(term, countryCode, limit)
|
||||
|
||||
res, err := a.searchClient.Send(request)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrRequest.Error())
|
||||
}
|
||||
|
||||
if res.StatusCode != 200 {
|
||||
a.logger.Verbose().Interface("data", res.Data).Int("status", res.StatusCode).Send()
|
||||
return ErrRequest
|
||||
}
|
||||
|
||||
a.logger.Log().Int("count", res.Data.Count).Array("apps", Apps(res.Data.Results)).Send()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *appstore) searchRequest(term, countryCode string, limit int64) http.Request {
|
||||
return http.Request{
|
||||
URL: a.searchURL(term, countryCode, limit),
|
||||
Method: http.MethodGET,
|
||||
ResponseFormat: http.ResponseFormatJSON,
|
||||
}
|
||||
}
|
||||
|
||||
func (a *appstore) searchURL(term, countryCode string, limit int64) string {
|
||||
params := url.Values{}
|
||||
params.Add("entity", "software,iPadSoftware")
|
||||
params.Add("limit", strconv.Itoa(int(limit)))
|
||||
params.Add("media", "software")
|
||||
params.Add("term", term)
|
||||
params.Add("country", countryCode)
|
||||
|
||||
return fmt.Sprintf("https://%s%s?%s", iTunesAPIDomain, iTunesAPIPathSearch, params.Encode())
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"github.com/golang/mock/gomock"
|
||||
"github.com/majd/ipatool/pkg/http"
|
||||
"github.com/majd/ipatool/pkg/keychain"
|
||||
"github.com/majd/ipatool/pkg/log"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"github.com/pkg/errors"
|
||||
"os"
|
||||
)
|
||||
|
||||
var _ = Describe("AppStore (Search)", func() {
|
||||
var (
|
||||
ctrl *gomock.Controller
|
||||
mockClient *http.MockClient[SearchResult]
|
||||
mockLogger *log.MockLogger
|
||||
mockKeychain *keychain.MockKeychain
|
||||
as AppStore
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctrl = gomock.NewController(GinkgoT())
|
||||
mockClient = http.NewMockClient[SearchResult](ctrl)
|
||||
mockLogger = log.NewMockLogger(ctrl)
|
||||
mockKeychain = keychain.NewMockKeychain(ctrl)
|
||||
as = &appstore{
|
||||
searchClient: mockClient,
|
||||
ioReader: os.Stdin,
|
||||
logger: mockLogger,
|
||||
keychain: mockKeychain,
|
||||
}
|
||||
})
|
||||
|
||||
AfterEach(func() {
|
||||
ctrl.Finish()
|
||||
})
|
||||
|
||||
When("user is not logged in", func() {
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return(nil, ErrGetKeychainItem)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Search("", 0)
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrGetAccount.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("country code is invalid", func() {
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte("{}"), nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Search("", 0)
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrInvalidCountryCode.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("request fails", func() {
|
||||
var testErr = errors.New("test")
|
||||
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
|
||||
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[SearchResult]{}, testErr)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Search("", 0)
|
||||
Expect(err).To(MatchError(ContainSubstring(testErr.Error())))
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrRequest.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("request returns bad status code", func() {
|
||||
BeforeEach(func() {
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil)
|
||||
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[SearchResult]{
|
||||
StatusCode: 400,
|
||||
}, nil)
|
||||
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Search("", 0)
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrRequest.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("request is successful", func() {
|
||||
BeforeEach(func() {
|
||||
mockLogger.EXPECT().
|
||||
Log().
|
||||
Return(nil)
|
||||
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[SearchResult]{
|
||||
StatusCode: 200,
|
||||
Data: SearchResult{
|
||||
Count: 0,
|
||||
Results: []App{},
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
|
||||
})
|
||||
|
||||
It("returns nil", func() {
|
||||
err := as.Search("", 0)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,12 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAppStore(t *testing.T) {
|
||||
RegisterFailHandler(Fail)
|
||||
RunSpecs(t, "App Store Suite")
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package appstore
|
||||
|
||||
const (
|
||||
FailureTypeInvalidCredentials = "-5000"
|
||||
FailureTypePasswordTokenExpired = "2034"
|
||||
FailureTypeLicenseNotFound = "9610"
|
||||
FailureTypeTemporarilyUnavailable = "2059"
|
||||
|
||||
CustomerMessageBadLogin = "MZFinance.BadLogin.Configurator_message"
|
||||
CustomerMessageSubscriptionRequired = "Subscription Required"
|
||||
|
||||
iTunesAPIDomain = "itunes.apple.com"
|
||||
iTunesAPIPathSearch = "/search"
|
||||
iTunesAPIPathLookup = "/lookup"
|
||||
|
||||
PriavteAppStoreAPIDomainPrefixWithoutAuthCode = "p25"
|
||||
PriavteAppStoreAPIDomainPrefixWithAuthCode = "p71"
|
||||
PrivateAppStoreAPIDomain = "buy." + iTunesAPIDomain
|
||||
PrivateAppStoreAPIPathAuthenticate = "/WebObjects/MZFinance.woa/wa/authenticate"
|
||||
PrivateAppStoreAPIPathPurchase = "/WebObjects/MZBuy.woa/wa/buyProduct"
|
||||
PrivateAppStoreAPIPathDownload = "/WebObjects/MZFinance.woa/wa/volumeStoreDownloadProduct"
|
||||
|
||||
HTTPHeaderStoreFront = "X-Set-Apple-Store-Front"
|
||||
|
||||
PricingParameterAppStore = "STDQ"
|
||||
PricingParameterAppleArcade = "GAME"
|
||||
)
|
||||
@@ -0,0 +1,58 @@
|
||||
package appstore
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrAppLookup = errors.New("failed to find app")
|
||||
ErrAppNotFound = errors.New("failed to find app on the App Store")
|
||||
ErrApplyLegacyPatches = errors.New("failed to apply legacy patches")
|
||||
ErrApplyPatches = errors.New("failed to apply patches")
|
||||
ErrAuthCodeRequired = errors.New("auth code is required")
|
||||
ErrCheckDirectory = errors.New("failed to determine if the supplied path is a directory")
|
||||
ErrCreateDestinationFile = errors.New("failed to create destination file")
|
||||
ErrCreateMetadataFile = errors.New("failed to create metadata file")
|
||||
ErrCreateRequest = errors.New("failed to create HTTP request")
|
||||
ErrCreateSinfFile = errors.New("failed to create sinf file")
|
||||
ErrDecompressInfoFile = errors.New("failed to open decompressed info file")
|
||||
ErrDecompressManifestFile = errors.New("failed to open decompressed manifest file")
|
||||
ErrDownloadFile = errors.New("failed to download file")
|
||||
ErrEncodeMetadataFile = errors.New("failed to encode metadata")
|
||||
ErrFileWrite = errors.New("failed to write file")
|
||||
ErrGeneric = errors.New("failed due to an unknown error")
|
||||
ErrGetAccount = errors.New("failed to get account")
|
||||
ErrGetBundleName = errors.New("failed to determine name of app bundle")
|
||||
ErrGetCurrentDirectory = errors.New("failed to get current directory path")
|
||||
ErrGetData = errors.New("failed to get data")
|
||||
ErrGetExecutablePath = errors.New("failed to get executable path")
|
||||
ErrGetFileMetadata = errors.New("failed to get file metadata")
|
||||
ErrGetInfoFile = errors.New("failed to read info file")
|
||||
ErrGetKeychainItem = errors.New("failed to read item from keychain")
|
||||
ErrGetMAC = errors.New("failed to get MAC address")
|
||||
ErrGetManifestFile = errors.New("failed to read manifest file")
|
||||
ErrInvalidCountryCode = errors.New("invalid country code")
|
||||
ErrInvalidResponse = errors.New("received 0 items from the App Store; expected 1 or more")
|
||||
ErrInvalidStoreFront = errors.New("could not infer country code from store front")
|
||||
ErrLicenseExists = errors.New("account already has a license for this app")
|
||||
ErrLicenseRequired = errors.New("license is required")
|
||||
ErrLogin = errors.New("failed to log in")
|
||||
ErrMarshal = errors.New("failed to marshal data")
|
||||
ErrOpenFile = errors.New("failed to open file")
|
||||
ErrOpenZipFile = errors.New("failed to open zip file")
|
||||
ErrPaidApp = errors.New("paid apps cannot be purchased")
|
||||
ErrPasswordRequired = errors.New("password is required when not running in interactive mode; use the \"--password\" flag")
|
||||
ErrPasswordTokenExpired = errors.New("password token is expired")
|
||||
ErrPatchApp = errors.New("failed to patch app package")
|
||||
ErrPurchase = errors.New("failed to purchase app")
|
||||
ErrRemoveKeychainItem = errors.New("failed to remove item from keychain")
|
||||
ErrRemoveTempFile = errors.New("failed to remove temporary file")
|
||||
ErrReplicateZip = errors.New("failed to replicate zip")
|
||||
ErrRequest = errors.New("failed to send request")
|
||||
ErrResolveDestinationPath = errors.New("failed to resolve destination path")
|
||||
ErrSetKeychainItem = errors.New("failed to save item in keychain")
|
||||
ErrSubscriptionRequired = errors.New("subscription required")
|
||||
ErrTemporarilyUnavailable = errors.New("item is temporarily unavailable")
|
||||
ErrUnmarshal = errors.New("failed to unmarshal data")
|
||||
ErrWriteMetadataFile = errors.New("failed to write metadata")
|
||||
ErrWriteSinfData = errors.New("failed to write sinf data")
|
||||
ErrZipSinfs = errors.New("failed to zip sinfs and sinf paths")
|
||||
)
|
||||
@@ -0,0 +1,136 @@
|
||||
package appstore
|
||||
|
||||
var StoreFronts = map[string]string{
|
||||
"AE": "143481",
|
||||
"AG": "143540",
|
||||
"AI": "143538",
|
||||
"AL": "143575",
|
||||
"AM": "143524",
|
||||
"AO": "143564",
|
||||
"AR": "143505",
|
||||
"AT": "143445",
|
||||
"AU": "143460",
|
||||
"AZ": "143568",
|
||||
"BB": "143541",
|
||||
"BD": "143490",
|
||||
"BE": "143446",
|
||||
"BG": "143526",
|
||||
"BH": "143559",
|
||||
"BM": "143542",
|
||||
"BN": "143560",
|
||||
"BO": "143556",
|
||||
"BR": "143503",
|
||||
"BS": "143539",
|
||||
"BW": "143525",
|
||||
"BY": "143565",
|
||||
"BZ": "143555",
|
||||
"CA": "143455",
|
||||
"CH": "143459",
|
||||
"CI": "143527",
|
||||
"CL": "143483",
|
||||
"CN": "143465",
|
||||
"CO": "143501",
|
||||
"CR": "143495",
|
||||
"CY": "143557",
|
||||
"CZ": "143489",
|
||||
"DE": "143443",
|
||||
"DK": "143458",
|
||||
"DM": "143545",
|
||||
"DO": "143508",
|
||||
"DZ": "143563",
|
||||
"EC": "143509",
|
||||
"EE": "143518",
|
||||
"EG": "143516",
|
||||
"ES": "143454",
|
||||
"FI": "143447",
|
||||
"FR": "143442",
|
||||
"GB": "143444",
|
||||
"GD": "143546",
|
||||
"GH": "143573",
|
||||
"GR": "143448",
|
||||
"GT": "143504",
|
||||
"GY": "143553",
|
||||
"HK": "143463",
|
||||
"HN": "143510",
|
||||
"HR": "143494",
|
||||
"HU": "143482",
|
||||
"ID": "143476",
|
||||
"IE": "143449",
|
||||
"IL": "143491",
|
||||
"IN": "143467",
|
||||
"IS": "143558",
|
||||
"IT": "143450",
|
||||
"JM": "143511",
|
||||
"JO": "143528",
|
||||
"JP": "143462",
|
||||
"KE": "143529",
|
||||
"KN": "143548",
|
||||
"KR": "143466",
|
||||
"KW": "143493",
|
||||
"KY": "143544",
|
||||
"KZ": "143517",
|
||||
"LB": "143497",
|
||||
"LC": "143549",
|
||||
"LI": "143522",
|
||||
"LK": "143486",
|
||||
"LT": "143520",
|
||||
"LU": "143451",
|
||||
"LV": "143519",
|
||||
"MD": "143523",
|
||||
"MG": "143531",
|
||||
"MK": "143530",
|
||||
"ML": "143532",
|
||||
"MN": "143592",
|
||||
"MO": "143515",
|
||||
"MS": "143547",
|
||||
"MT": "143521",
|
||||
"MU": "143533",
|
||||
"MV": "143488",
|
||||
"MX": "143468",
|
||||
"MY": "143473",
|
||||
"NE": "143534",
|
||||
"NG": "143561",
|
||||
"NI": "143512",
|
||||
"NL": "143452",
|
||||
"NO": "143457",
|
||||
"NP": "143484",
|
||||
"NZ": "143461",
|
||||
"OM": "143562",
|
||||
"PA": "143485",
|
||||
"PE": "143507",
|
||||
"PH": "143474",
|
||||
"PK": "143477",
|
||||
"PL": "143478",
|
||||
"PT": "143453",
|
||||
"PY": "143513",
|
||||
"QA": "143498",
|
||||
"RO": "143487",
|
||||
"RS": "143500",
|
||||
"RU": "143469",
|
||||
"SA": "143479",
|
||||
"SE": "143456",
|
||||
"SG": "143464",
|
||||
"SI": "143499",
|
||||
"SK": "143496",
|
||||
"SN": "143535",
|
||||
"SR": "143554",
|
||||
"SV": "143506",
|
||||
"TC": "143552",
|
||||
"TH": "143475",
|
||||
"TN": "143536",
|
||||
"TR": "143480",
|
||||
"TT": "143551",
|
||||
"TW": "143470",
|
||||
"TZ": "143572",
|
||||
"UA": "143492",
|
||||
"UG": "143537",
|
||||
"US": "143441",
|
||||
"UY": "143514",
|
||||
"UZ": "143566",
|
||||
"VC": "143550",
|
||||
"VE": "143502",
|
||||
"VG": "143543",
|
||||
"VN": "143471",
|
||||
"YE": "143571",
|
||||
"ZA": "143472",
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"github.com/pkg/errors"
|
||||
"howett.net/plist"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
//go:generate mockgen -source=client.go -destination=client_mock.go -package=http
|
||||
type Client[R interface{}] interface {
|
||||
Send(request Request) (Result[R], error)
|
||||
Do(req *http.Request) (*http.Response, error)
|
||||
NewRequest(method, url string, body io.Reader) (*http.Request, error)
|
||||
}
|
||||
|
||||
type client[R interface{}] struct {
|
||||
internalClient http.Client
|
||||
cookieJar CookieJar
|
||||
}
|
||||
|
||||
type ClientArgs struct {
|
||||
CookieJar CookieJar
|
||||
}
|
||||
|
||||
type AddHeaderTransport struct {
|
||||
T http.RoundTripper
|
||||
}
|
||||
|
||||
func (adt *AddHeaderTransport) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
if req.Header.Get("User-Agent") == "" {
|
||||
req.Header.Set("User-Agent", DefaultUserAgent)
|
||||
}
|
||||
return adt.T.RoundTrip(req)
|
||||
}
|
||||
|
||||
func NewClient[R interface{}](args ClientArgs) Client[R] {
|
||||
return &client[R]{
|
||||
internalClient: http.Client{
|
||||
Timeout: 0,
|
||||
Jar: args.CookieJar,
|
||||
Transport: &AddHeaderTransport{http.DefaultTransport},
|
||||
},
|
||||
cookieJar: args.CookieJar,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *client[R]) Send(req Request) (Result[R], error) {
|
||||
var data []byte
|
||||
var err error
|
||||
|
||||
if req.Payload != nil {
|
||||
data, err = req.Payload.data()
|
||||
if err != nil {
|
||||
return Result[R]{}, errors.Wrap(err, ErrGetPayloadData.Error())
|
||||
}
|
||||
}
|
||||
|
||||
request, err := http.NewRequest(req.Method, req.URL, bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return Result[R]{}, errors.Wrap(err, ErrCreateRequest.Error())
|
||||
}
|
||||
|
||||
for key, val := range req.Headers {
|
||||
request.Header.Set(key, val)
|
||||
}
|
||||
|
||||
res, err := c.internalClient.Do(request)
|
||||
if err != nil {
|
||||
return Result[R]{}, errors.Wrap(err, ErrRequest.Error())
|
||||
}
|
||||
|
||||
err = c.cookieJar.Save()
|
||||
if err != nil {
|
||||
return Result[R]{}, errors.Wrap(err, ErrSaveCookie.Error())
|
||||
}
|
||||
|
||||
if req.ResponseFormat == ResponseFormatJSON {
|
||||
return c.handleJSONResponse(res)
|
||||
}
|
||||
if req.ResponseFormat == ResponseFormatXML {
|
||||
return c.handleXMLResponse(res)
|
||||
}
|
||||
|
||||
return Result[R]{}, errors.Errorf("%s: %s", ErrUnsupportedContentType.Error(), req.ResponseFormat)
|
||||
}
|
||||
|
||||
func (c *client[R]) Do(req *http.Request) (*http.Response, error) {
|
||||
return c.internalClient.Do(req)
|
||||
}
|
||||
|
||||
func (*client[R]) NewRequest(method, url string, body io.Reader) (*http.Request, error) {
|
||||
return http.NewRequest(method, url, body)
|
||||
}
|
||||
|
||||
func (c *client[R]) handleJSONResponse(res *http.Response) (Result[R], error) {
|
||||
body, err := io.ReadAll(res.Body)
|
||||
if err != nil {
|
||||
return Result[R]{}, errors.Wrap(err, ErrGetResponseBody.Error())
|
||||
}
|
||||
|
||||
var data R
|
||||
err = json.Unmarshal(body, &data)
|
||||
if err != nil {
|
||||
return Result[R]{}, errors.Wrap(err, ErrUnmarshalJSON.Error())
|
||||
}
|
||||
|
||||
return Result[R]{
|
||||
StatusCode: res.StatusCode,
|
||||
Data: data,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *client[R]) handleXMLResponse(res *http.Response) (Result[R], error) {
|
||||
body, err := io.ReadAll(res.Body)
|
||||
if err != nil {
|
||||
return Result[R]{}, errors.Wrap(err, ErrGetResponseBody.Error())
|
||||
}
|
||||
|
||||
var data R
|
||||
_, err = plist.Unmarshal(body, &data)
|
||||
if err != nil {
|
||||
return Result[R]{}, errors.Wrap(err, ErrUnmarshalXML.Error())
|
||||
}
|
||||
|
||||
headers := map[string]string{}
|
||||
for key, val := range res.Header {
|
||||
headers[key] = strings.Join(val, "; ")
|
||||
}
|
||||
|
||||
return Result[R]{
|
||||
StatusCode: res.StatusCode,
|
||||
Headers: headers,
|
||||
Data: data,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
// Code generated by MockGen. DO NOT EDIT.
|
||||
// Source: client.go
|
||||
|
||||
// Package http is a generated GoMock package.
|
||||
package http
|
||||
|
||||
import (
|
||||
io "io"
|
||||
http "net/http"
|
||||
reflect "reflect"
|
||||
|
||||
gomock "github.com/golang/mock/gomock"
|
||||
)
|
||||
|
||||
// MockClient is a mock of Client interface.
|
||||
type MockClient[R interface{}] struct {
|
||||
ctrl *gomock.Controller
|
||||
recorder *MockClientMockRecorder[R]
|
||||
}
|
||||
|
||||
// MockClientMockRecorder is the mock recorder for MockClient.
|
||||
type MockClientMockRecorder[R interface{}] struct {
|
||||
mock *MockClient[R]
|
||||
}
|
||||
|
||||
// NewMockClient creates a new mock instance.
|
||||
func NewMockClient[R interface{}](ctrl *gomock.Controller) *MockClient[R] {
|
||||
mock := &MockClient[R]{ctrl: ctrl}
|
||||
mock.recorder = &MockClientMockRecorder[R]{mock}
|
||||
return mock
|
||||
}
|
||||
|
||||
// EXPECT returns an object that allows the caller to indicate expected use.
|
||||
func (m *MockClient[R]) EXPECT() *MockClientMockRecorder[R] {
|
||||
return m.recorder
|
||||
}
|
||||
|
||||
// Do mocks base method.
|
||||
func (m *MockClient[R]) Do(req *http.Request) (*http.Response, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "Do", req)
|
||||
ret0, _ := ret[0].(*http.Response)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// Do indicates an expected call of Do.
|
||||
func (mr *MockClientMockRecorder[R]) Do(req interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Do", reflect.TypeOf((*MockClient[R])(nil).Do), req)
|
||||
}
|
||||
|
||||
// NewRequest mocks base method.
|
||||
func (m *MockClient[R]) NewRequest(method, url string, body io.Reader) (*http.Request, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "NewRequest", method, url, body)
|
||||
ret0, _ := ret[0].(*http.Request)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// NewRequest indicates an expected call of NewRequest.
|
||||
func (mr *MockClientMockRecorder[R]) NewRequest(method, url, body interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NewRequest", reflect.TypeOf((*MockClient[R])(nil).NewRequest), method, url, body)
|
||||
}
|
||||
|
||||
// Send mocks base method.
|
||||
func (m *MockClient[R]) Send(request Request) (Result[R], error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "Send", request)
|
||||
ret0, _ := ret[0].(Result[R])
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// Send indicates an expected call of Send.
|
||||
func (mr *MockClientMockRecorder[R]) Send(request interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Send", reflect.TypeOf((*MockClient[R])(nil).Send), request)
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/golang/mock/gomock"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type JSONResult struct {
|
||||
Foo string `json:"foo"`
|
||||
}
|
||||
|
||||
type XMLResult struct {
|
||||
Foo string `plist:"foo"`
|
||||
}
|
||||
|
||||
var _ = Describe("Client", Ordered, func() {
|
||||
var (
|
||||
port int
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
ctrl *gomock.Controller
|
||||
mockCookieJar *MockCookieJar
|
||||
)
|
||||
|
||||
BeforeAll(func() {
|
||||
ctrl = gomock.NewController(GinkgoT())
|
||||
port = rand.Intn(59_999-50_000) + 50_000
|
||||
ctx, cancel = context.WithCancel(context.Background())
|
||||
mockCookieJar = NewMockCookieJar(ctrl)
|
||||
|
||||
http.HandleFunc("/json", func(w http.ResponseWriter, r *http.Request) {
|
||||
res := []byte("{\"foo\":\"bar\"}")
|
||||
w.Header().Add("Content-Type", "application/json")
|
||||
_, err := w.Write(res)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
|
||||
http.HandleFunc("/xml", func(w http.ResponseWriter, r *http.Request) {
|
||||
res := []byte("<dict><key>foo</key><string>bar</string></dict>")
|
||||
w.Header().Add("Content-Type", "application/xml")
|
||||
_, err := w.Write(res)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
|
||||
http.HandleFunc("/error", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Add("Content-Type", "application/random-type")
|
||||
})
|
||||
|
||||
http.HandleFunc("/headers", func(w http.ResponseWriter, r *http.Request) {
|
||||
err := json.NewEncoder(w).Encode(r.Header)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
|
||||
go func() {
|
||||
err := http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
<-ctx.Done()
|
||||
}()
|
||||
})
|
||||
|
||||
AfterAll(func() {
|
||||
cancel()
|
||||
})
|
||||
|
||||
BeforeEach(func() {
|
||||
mockCookieJar.EXPECT().
|
||||
Cookies(gomock.Any()).
|
||||
Return(nil).
|
||||
MaxTimes(1)
|
||||
})
|
||||
|
||||
It("returns request", func() {
|
||||
sut := NewClient[XMLResult](ClientArgs{})
|
||||
|
||||
req, err := sut.NewRequest("GET", fmt.Sprintf("http://localhost:%d/json", port), nil)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(req).ToNot(BeNil())
|
||||
})
|
||||
|
||||
It("returns response", func() {
|
||||
sut := NewClient[XMLResult](ClientArgs{})
|
||||
|
||||
req, err := sut.NewRequest("GET", fmt.Sprintf("http://localhost:%d/json", port), nil)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(req).ToNot(BeNil())
|
||||
|
||||
res, err := sut.Do(req)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(res).ToNot(BeNil())
|
||||
})
|
||||
|
||||
When("payload decodes successfully", func() {
|
||||
When("cookie jar fails to save", func() {
|
||||
var testErr = errors.New("test")
|
||||
|
||||
BeforeEach(func() {
|
||||
mockCookieJar.EXPECT().
|
||||
Save().
|
||||
Return(testErr)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
sut := NewClient[JSONResult](ClientArgs{
|
||||
CookieJar: mockCookieJar,
|
||||
})
|
||||
_, err := sut.Send(Request{
|
||||
URL: fmt.Sprintf("http://localhost:%d/json", port),
|
||||
Method: MethodGET,
|
||||
})
|
||||
|
||||
Expect(err).To(MatchError(ContainSubstring(testErr.Error())))
|
||||
Expect(err).To(MatchError(ContainSubstring("failed to save cookies")))
|
||||
})
|
||||
})
|
||||
|
||||
When("cookie jar saves new cookies", func() {
|
||||
BeforeEach(func() {
|
||||
mockCookieJar.EXPECT().
|
||||
Save().
|
||||
Return(nil)
|
||||
})
|
||||
|
||||
It("decodes JSON response", func() {
|
||||
sut := NewClient[JSONResult](ClientArgs{
|
||||
CookieJar: mockCookieJar,
|
||||
})
|
||||
res, err := sut.Send(Request{
|
||||
URL: fmt.Sprintf("http://localhost:%d/json", port),
|
||||
Method: MethodGET,
|
||||
ResponseFormat: ResponseFormatJSON,
|
||||
Headers: map[string]string{
|
||||
"foo": "bar",
|
||||
},
|
||||
Payload: &URLPayload{
|
||||
Content: map[string]interface{}{
|
||||
"data": "test",
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(res.Data.Foo).To(Equal("bar"))
|
||||
})
|
||||
|
||||
It("decodes XML response", func() {
|
||||
sut := NewClient[XMLResult](ClientArgs{
|
||||
CookieJar: mockCookieJar,
|
||||
})
|
||||
res, err := sut.Send(Request{
|
||||
URL: fmt.Sprintf("http://localhost:%d/xml", port),
|
||||
Method: MethodPOST,
|
||||
ResponseFormat: ResponseFormatXML,
|
||||
})
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(res.Data.Foo).To(Equal("bar"))
|
||||
})
|
||||
|
||||
It("returns error when content type is not supported", func() {
|
||||
sut := NewClient[XMLResult](ClientArgs{
|
||||
CookieJar: mockCookieJar,
|
||||
})
|
||||
_, err := sut.Send(Request{
|
||||
URL: fmt.Sprintf("http://localhost:%d/error", port),
|
||||
Method: MethodPOST,
|
||||
ResponseFormat: "random",
|
||||
})
|
||||
|
||||
Expect(err).To(MatchError(ContainSubstring("unsupported response body content type: random")))
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
When("payload fails to decode", func() {
|
||||
It("returns error", func() {
|
||||
sut := NewClient[XMLResult](ClientArgs{
|
||||
CookieJar: mockCookieJar,
|
||||
})
|
||||
_, err := sut.Send(Request{
|
||||
URL: fmt.Sprintf("http://localhost:%d/error", port),
|
||||
Method: MethodPOST,
|
||||
ResponseFormat: ResponseFormatXML,
|
||||
Payload: &URLPayload{
|
||||
Content: map[string]interface{}{
|
||||
"data": func() {},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrGetPayloadData.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
It("uses default headers", func() {
|
||||
sut := NewClient[XMLResult](ClientArgs{})
|
||||
|
||||
req, err := sut.NewRequest("GET", fmt.Sprintf("http://localhost:%d/headers", port), nil)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(req).ToNot(BeNil())
|
||||
|
||||
res, err := sut.Do(req)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(res).ToNot(BeNil())
|
||||
|
||||
headers := http.Header{}
|
||||
err = json.NewDecoder(res.Body).Decode(&headers)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(headers.Get("User-Agent")).To(Equal(DefaultUserAgent))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,9 @@
|
||||
package http
|
||||
|
||||
type ResponseFormat string
|
||||
|
||||
const (
|
||||
ResponseFormatJSON ResponseFormat = "json"
|
||||
ResponseFormatXML ResponseFormat = "xml"
|
||||
DefaultUserAgent = "Configurator/2.15 (Macintosh; OperatingSystem X 11.0.0; 16G29) AppleWebKit/2603.3.8"
|
||||
)
|
||||
@@ -0,0 +1,10 @@
|
||||
package http
|
||||
|
||||
import "net/http"
|
||||
|
||||
//go:generate mockgen -source=cookiejar.go -destination=cookiejar_mock.go -package=http
|
||||
type CookieJar interface {
|
||||
http.CookieJar
|
||||
|
||||
Save() error
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
// Code generated by MockGen. DO NOT EDIT.
|
||||
// Source: cookiejar.go
|
||||
|
||||
// Package http is a generated GoMock package.
|
||||
package http
|
||||
|
||||
import (
|
||||
http "net/http"
|
||||
url "net/url"
|
||||
reflect "reflect"
|
||||
|
||||
gomock "github.com/golang/mock/gomock"
|
||||
)
|
||||
|
||||
// MockCookieJar is a mock of CookieJar interface.
|
||||
type MockCookieJar struct {
|
||||
ctrl *gomock.Controller
|
||||
recorder *MockCookieJarMockRecorder
|
||||
}
|
||||
|
||||
// MockCookieJarMockRecorder is the mock recorder for MockCookieJar.
|
||||
type MockCookieJarMockRecorder struct {
|
||||
mock *MockCookieJar
|
||||
}
|
||||
|
||||
// NewMockCookieJar creates a new mock instance.
|
||||
func NewMockCookieJar(ctrl *gomock.Controller) *MockCookieJar {
|
||||
mock := &MockCookieJar{ctrl: ctrl}
|
||||
mock.recorder = &MockCookieJarMockRecorder{mock}
|
||||
return mock
|
||||
}
|
||||
|
||||
// EXPECT returns an object that allows the caller to indicate expected use.
|
||||
func (m *MockCookieJar) EXPECT() *MockCookieJarMockRecorder {
|
||||
return m.recorder
|
||||
}
|
||||
|
||||
// Cookies mocks base method.
|
||||
func (m *MockCookieJar) Cookies(u *url.URL) []*http.Cookie {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "Cookies", u)
|
||||
ret0, _ := ret[0].([]*http.Cookie)
|
||||
return ret0
|
||||
}
|
||||
|
||||
// Cookies indicates an expected call of Cookies.
|
||||
func (mr *MockCookieJarMockRecorder) Cookies(u interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Cookies", reflect.TypeOf((*MockCookieJar)(nil).Cookies), u)
|
||||
}
|
||||
|
||||
// Save mocks base method.
|
||||
func (m *MockCookieJar) Save() error {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "Save")
|
||||
ret0, _ := ret[0].(error)
|
||||
return ret0
|
||||
}
|
||||
|
||||
// Save indicates an expected call of Save.
|
||||
func (mr *MockCookieJarMockRecorder) Save() *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Save", reflect.TypeOf((*MockCookieJar)(nil).Save))
|
||||
}
|
||||
|
||||
// SetCookies mocks base method.
|
||||
func (m *MockCookieJar) SetCookies(u *url.URL, cookies []*http.Cookie) {
|
||||
m.ctrl.T.Helper()
|
||||
m.ctrl.Call(m, "SetCookies", u, cookies)
|
||||
}
|
||||
|
||||
// SetCookies indicates an expected call of SetCookies.
|
||||
func (mr *MockCookieJarMockRecorder) SetCookies(u, cookies interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetCookies", reflect.TypeOf((*MockCookieJar)(nil).SetCookies), u, cookies)
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package http
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrCreateRequest = errors.New("failed to create HTTP request")
|
||||
ErrEncodePayloadXML = errors.New("failed to encode XML object")
|
||||
ErrGetPayloadData = errors.New("failed to get payload data")
|
||||
ErrGetResponseBody = errors.New("failed to get response body")
|
||||
ErrRequest = errors.New("failed to send request")
|
||||
ErrSaveCookie = errors.New("failed to save cookies")
|
||||
ErrUnmarshalJSON = errors.New("failed to unmarshal JSON data")
|
||||
ErrUnmarshalXML = errors.New("failed to unmarshal XML data")
|
||||
ErrUnsupportedContentType = errors.New("unsupported response body content type")
|
||||
ErrUnsupportedValueType = errors.New("unsupported value type")
|
||||
)
|
||||
@@ -0,0 +1,12 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHTTP(t *testing.T) {
|
||||
RegisterFailHandler(Fail)
|
||||
RunSpecs(t, "HTTP Suite")
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package http
|
||||
|
||||
const (
|
||||
MethodGET = "GET"
|
||||
MethodPOST = "POST"
|
||||
)
|
||||
@@ -0,0 +1,49 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"github.com/pkg/errors"
|
||||
"howett.net/plist"
|
||||
"net/url"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type Payload interface {
|
||||
data() ([]byte, error)
|
||||
}
|
||||
|
||||
type XMLPayload struct {
|
||||
Content map[string]interface{}
|
||||
}
|
||||
|
||||
type URLPayload struct {
|
||||
Content map[string]interface{}
|
||||
}
|
||||
|
||||
func (p *XMLPayload) data() ([]byte, error) {
|
||||
buffer := new(bytes.Buffer)
|
||||
|
||||
err := plist.NewEncoder(buffer).Encode(p.Content)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, ErrEncodePayloadXML.Error())
|
||||
}
|
||||
|
||||
return buffer.Bytes(), nil
|
||||
}
|
||||
|
||||
func (p *URLPayload) data() ([]byte, error) {
|
||||
params := url.Values{}
|
||||
|
||||
for key, val := range p.Content {
|
||||
switch t := val.(type) {
|
||||
case string:
|
||||
params.Add(key, val.(string))
|
||||
case int:
|
||||
params.Add(key, strconv.Itoa(val.(int)))
|
||||
default:
|
||||
return nil, errors.Errorf("%s: %s", ErrUnsupportedValueType.Error(), t)
|
||||
}
|
||||
}
|
||||
|
||||
return []byte(params.Encode()), nil
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("Payload", func() {
|
||||
var sut Payload
|
||||
|
||||
Context("URL Payload", func() {
|
||||
It("returns encoded URL data", func() {
|
||||
sut = &URLPayload{
|
||||
Content: map[string]interface{}{
|
||||
"foo": "bar",
|
||||
"num": 3,
|
||||
},
|
||||
}
|
||||
|
||||
data, err := sut.data()
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(data).To(Equal([]byte("foo=bar&num=3")))
|
||||
})
|
||||
|
||||
It("returns error if URL data is invalid", func() {
|
||||
sut = &URLPayload{
|
||||
Content: map[string]interface{}{
|
||||
"foo": func() {},
|
||||
},
|
||||
}
|
||||
|
||||
data, err := sut.data()
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrUnsupportedValueType.Error())))
|
||||
Expect(data).To(BeNil())
|
||||
})
|
||||
})
|
||||
|
||||
Context("XML Payload", func() {
|
||||
It("returns encoded XML data", func() {
|
||||
sut = &XMLPayload{
|
||||
Content: map[string]interface{}{
|
||||
"foo": "bar",
|
||||
"lorem": "ipsum",
|
||||
},
|
||||
}
|
||||
|
||||
data, err := sut.data()
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(data).To(ContainSubstring("<dict><key>foo</key><string>bar</string><key>lorem</key><string>ipsum</string></dict>"))
|
||||
})
|
||||
|
||||
It("returns error if XML data is invalid", func() {
|
||||
sut = &XMLPayload{
|
||||
Content: map[string]interface{}{
|
||||
"foo": func() {},
|
||||
},
|
||||
}
|
||||
|
||||
data, err := sut.data()
|
||||
Expect(err).To(MatchError(ContainSubstring("failed to encode XML object")))
|
||||
Expect(data).To(BeNil())
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,9 @@
|
||||
package http
|
||||
|
||||
type Request struct {
|
||||
Method string
|
||||
URL string
|
||||
Headers map[string]string
|
||||
Payload Payload
|
||||
ResponseFormat ResponseFormat
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package http
|
||||
|
||||
type Result[R interface{}] struct {
|
||||
StatusCode int
|
||||
Headers map[string]string
|
||||
Data R
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package keychain
|
||||
|
||||
import "github.com/pkg/errors"
|
||||
|
||||
var (
|
||||
ErrGetKeychainItem = errors.New("failed to get item from keyring")
|
||||
ErrRemoveKeychainItem = errors.New("failed to remove item from keyring")
|
||||
ErrSetKeychainItem = errors.New("failed to set item in keyring")
|
||||
)
|
||||
@@ -0,0 +1,22 @@
|
||||
package keychain
|
||||
|
||||
//go:generate mockgen -source=keychain.go -destination=keychain_mock.go -package keychain
|
||||
type Keychain interface {
|
||||
Get(key string) ([]byte, error)
|
||||
Set(key string, data []byte) error
|
||||
Remove(key string) error
|
||||
}
|
||||
|
||||
type keychain struct {
|
||||
keyring Keyring
|
||||
}
|
||||
|
||||
type KeychainArgs struct {
|
||||
Keyring Keyring
|
||||
}
|
||||
|
||||
func NewKeychain(args KeychainArgs) Keychain {
|
||||
return &keychain{
|
||||
keyring: args.Keyring,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package keychain
|
||||
|
||||
import (
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
func (k *keychain) Get(key string) ([]byte, error) {
|
||||
item, err := k.keyring.Get(key)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, ErrGetKeychainItem.Error())
|
||||
}
|
||||
|
||||
return item.Data, nil
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package keychain
|
||||
|
||||
import (
|
||||
"github.com/99designs/keyring"
|
||||
"github.com/golang/mock/gomock"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
var _ = Describe("Keychain (Get)", func() {
|
||||
var (
|
||||
ctrl *gomock.Controller
|
||||
keychain Keychain
|
||||
mockKeyring *MockKeyring
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctrl = gomock.NewController(GinkgoT())
|
||||
mockKeyring = NewMockKeyring(ctrl)
|
||||
keychain = NewKeychain(KeychainArgs{
|
||||
Keyring: mockKeyring,
|
||||
})
|
||||
})
|
||||
|
||||
AfterEach(func() {
|
||||
ctrl.Finish()
|
||||
})
|
||||
|
||||
When("keyring returns error", func() {
|
||||
const testKey = "test-key"
|
||||
var testErr = errors.New("test error")
|
||||
|
||||
BeforeEach(func() {
|
||||
mockKeyring.EXPECT().
|
||||
Get(testKey).
|
||||
Return(keyring.Item{}, testErr)
|
||||
})
|
||||
|
||||
It("returns wrapped error", func() {
|
||||
data, err := keychain.Get(testKey)
|
||||
Expect(err).To(MatchError(ContainSubstring(testErr.Error())))
|
||||
Expect(err).To(MatchError(ContainSubstring("failed to get item from keyring")))
|
||||
Expect(data).To(BeNil())
|
||||
})
|
||||
})
|
||||
|
||||
When("keyring returns item", func() {
|
||||
const testKey = "test-key"
|
||||
var testData = []byte("test")
|
||||
|
||||
BeforeEach(func() {
|
||||
mockKeyring.EXPECT().
|
||||
Get(testKey).
|
||||
Return(keyring.Item{
|
||||
Data: testData,
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns data", func() {
|
||||
data, err := keychain.Get(testKey)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(data).To(Equal(testData))
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,77 @@
|
||||
// Code generated by MockGen. DO NOT EDIT.
|
||||
// Source: keychain.go
|
||||
|
||||
// Package keychain is a generated GoMock package.
|
||||
package keychain
|
||||
|
||||
import (
|
||||
reflect "reflect"
|
||||
|
||||
gomock "github.com/golang/mock/gomock"
|
||||
)
|
||||
|
||||
// MockKeychain is a mock of Keychain interface.
|
||||
type MockKeychain struct {
|
||||
ctrl *gomock.Controller
|
||||
recorder *MockKeychainMockRecorder
|
||||
}
|
||||
|
||||
// MockKeychainMockRecorder is the mock recorder for MockKeychain.
|
||||
type MockKeychainMockRecorder struct {
|
||||
mock *MockKeychain
|
||||
}
|
||||
|
||||
// NewMockKeychain creates a new mock instance.
|
||||
func NewMockKeychain(ctrl *gomock.Controller) *MockKeychain {
|
||||
mock := &MockKeychain{ctrl: ctrl}
|
||||
mock.recorder = &MockKeychainMockRecorder{mock}
|
||||
return mock
|
||||
}
|
||||
|
||||
// EXPECT returns an object that allows the caller to indicate expected use.
|
||||
func (m *MockKeychain) EXPECT() *MockKeychainMockRecorder {
|
||||
return m.recorder
|
||||
}
|
||||
|
||||
// Get mocks base method.
|
||||
func (m *MockKeychain) Get(key string) ([]byte, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "Get", key)
|
||||
ret0, _ := ret[0].([]byte)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// Get indicates an expected call of Get.
|
||||
func (mr *MockKeychainMockRecorder) Get(key interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockKeychain)(nil).Get), key)
|
||||
}
|
||||
|
||||
// Remove mocks base method.
|
||||
func (m *MockKeychain) Remove(key string) error {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "Remove", key)
|
||||
ret0, _ := ret[0].(error)
|
||||
return ret0
|
||||
}
|
||||
|
||||
// Remove indicates an expected call of Remove.
|
||||
func (mr *MockKeychainMockRecorder) Remove(key interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Remove", reflect.TypeOf((*MockKeychain)(nil).Remove), key)
|
||||
}
|
||||
|
||||
// Set mocks base method.
|
||||
func (m *MockKeychain) Set(key string, data []byte) error {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "Set", key, data)
|
||||
ret0, _ := ret[0].(error)
|
||||
return ret0
|
||||
}
|
||||
|
||||
// Set indicates an expected call of Set.
|
||||
func (mr *MockKeychainMockRecorder) Set(key, data interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Set", reflect.TypeOf((*MockKeychain)(nil).Set), key, data)
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package keychain
|
||||
|
||||
import "github.com/pkg/errors"
|
||||
|
||||
func (k *keychain) Remove(key string) error {
|
||||
err := k.keyring.Remove(key)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrRemoveKeychainItem.Error())
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package keychain
|
||||
|
||||
import (
|
||||
"github.com/golang/mock/gomock"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
var _ = Describe("Keychain (Remove)", func() {
|
||||
var (
|
||||
ctrl *gomock.Controller
|
||||
keychain Keychain
|
||||
mockKeyring *MockKeyring
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctrl = gomock.NewController(GinkgoT())
|
||||
mockKeyring = NewMockKeyring(ctrl)
|
||||
keychain = NewKeychain(KeychainArgs{
|
||||
Keyring: mockKeyring,
|
||||
})
|
||||
})
|
||||
|
||||
AfterEach(func() {
|
||||
ctrl.Finish()
|
||||
})
|
||||
|
||||
When("keyring returns error", func() {
|
||||
const testKey = "test-key"
|
||||
var testErr = errors.New("test error")
|
||||
|
||||
BeforeEach(func() {
|
||||
mockKeyring.EXPECT().
|
||||
Remove(testKey).
|
||||
Return(testErr)
|
||||
})
|
||||
|
||||
It("returns wrapped error", func() {
|
||||
err := keychain.Remove(testKey)
|
||||
Expect(err).To(MatchError(ContainSubstring(testErr.Error())))
|
||||
Expect(err).To(MatchError(ContainSubstring("failed to remove item from keyring")))
|
||||
})
|
||||
})
|
||||
|
||||
When("keyring does not return error", func() {
|
||||
const testKey = "test-key"
|
||||
|
||||
BeforeEach(func() {
|
||||
mockKeyring.EXPECT().
|
||||
Remove(testKey).
|
||||
Return(nil)
|
||||
})
|
||||
|
||||
It("returns data", func() {
|
||||
err := keychain.Remove(testKey)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,18 @@
|
||||
package keychain
|
||||
|
||||
import (
|
||||
"github.com/99designs/keyring"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
func (k *keychain) Set(key string, data []byte) error {
|
||||
err := k.keyring.Set(keyring.Item{
|
||||
Key: key,
|
||||
Data: data,
|
||||
})
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrSetKeychainItem.Error())
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package keychain
|
||||
|
||||
import (
|
||||
"github.com/99designs/keyring"
|
||||
"github.com/golang/mock/gomock"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
var _ = Describe("Keychain (Set)", func() {
|
||||
var (
|
||||
ctrl *gomock.Controller
|
||||
keychain Keychain
|
||||
mockKeyring *MockKeyring
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctrl = gomock.NewController(GinkgoT())
|
||||
mockKeyring = NewMockKeyring(ctrl)
|
||||
keychain = NewKeychain(KeychainArgs{
|
||||
Keyring: mockKeyring,
|
||||
})
|
||||
})
|
||||
|
||||
AfterEach(func() {
|
||||
ctrl.Finish()
|
||||
})
|
||||
|
||||
When("keyring returns error", func() {
|
||||
const testKey = "test-key"
|
||||
var (
|
||||
testData = []byte("test")
|
||||
testErr = errors.New("test error")
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
mockKeyring.EXPECT().
|
||||
Set(keyring.Item{
|
||||
Key: testKey,
|
||||
Data: testData,
|
||||
}).
|
||||
Return(testErr)
|
||||
})
|
||||
|
||||
It("returns wrapped error", func() {
|
||||
err := keychain.Set(testKey, testData)
|
||||
Expect(err).To(MatchError(ContainSubstring(testErr.Error())))
|
||||
Expect(err).To(MatchError(ContainSubstring("failed to set item in keyring")))
|
||||
})
|
||||
})
|
||||
|
||||
When("keyring does not return error", func() {
|
||||
const testKey = "test-key"
|
||||
var testData = []byte("test")
|
||||
|
||||
BeforeEach(func() {
|
||||
mockKeyring.EXPECT().
|
||||
Set(keyring.Item{
|
||||
Key: testKey,
|
||||
Data: testData,
|
||||
}).
|
||||
Return(nil)
|
||||
})
|
||||
|
||||
It("returns nil", func() {
|
||||
err := keychain.Set(testKey, testData)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,12 @@
|
||||
package keychain
|
||||
|
||||
import (
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestKeychain(t *testing.T) {
|
||||
RegisterFailHandler(Fail)
|
||||
RunSpecs(t, "Keychain Suite")
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package keychain
|
||||
|
||||
import "github.com/99designs/keyring"
|
||||
|
||||
//go:generate mockgen -source=keyring.go -destination=keyring_mock.go -package keychain
|
||||
type Keyring interface {
|
||||
Get(key string) (keyring.Item, error)
|
||||
Set(item keyring.Item) error
|
||||
Remove(key string) error
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
// Code generated by MockGen. DO NOT EDIT.
|
||||
// Source: keyring.go
|
||||
|
||||
// Package keychain is a generated GoMock package.
|
||||
package keychain
|
||||
|
||||
import (
|
||||
reflect "reflect"
|
||||
|
||||
keyring "github.com/99designs/keyring"
|
||||
gomock "github.com/golang/mock/gomock"
|
||||
)
|
||||
|
||||
// MockKeyring is a mock of Keyring interface.
|
||||
type MockKeyring struct {
|
||||
ctrl *gomock.Controller
|
||||
recorder *MockKeyringMockRecorder
|
||||
}
|
||||
|
||||
// MockKeyringMockRecorder is the mock recorder for MockKeyring.
|
||||
type MockKeyringMockRecorder struct {
|
||||
mock *MockKeyring
|
||||
}
|
||||
|
||||
// NewMockKeyring creates a new mock instance.
|
||||
func NewMockKeyring(ctrl *gomock.Controller) *MockKeyring {
|
||||
mock := &MockKeyring{ctrl: ctrl}
|
||||
mock.recorder = &MockKeyringMockRecorder{mock}
|
||||
return mock
|
||||
}
|
||||
|
||||
// EXPECT returns an object that allows the caller to indicate expected use.
|
||||
func (m *MockKeyring) EXPECT() *MockKeyringMockRecorder {
|
||||
return m.recorder
|
||||
}
|
||||
|
||||
// Get mocks base method.
|
||||
func (m *MockKeyring) Get(key string) (keyring.Item, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "Get", key)
|
||||
ret0, _ := ret[0].(keyring.Item)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// Get indicates an expected call of Get.
|
||||
func (mr *MockKeyringMockRecorder) Get(key interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockKeyring)(nil).Get), key)
|
||||
}
|
||||
|
||||
// Remove mocks base method.
|
||||
func (m *MockKeyring) Remove(key string) error {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "Remove", key)
|
||||
ret0, _ := ret[0].(error)
|
||||
return ret0
|
||||
}
|
||||
|
||||
// Remove indicates an expected call of Remove.
|
||||
func (mr *MockKeyringMockRecorder) Remove(key interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Remove", reflect.TypeOf((*MockKeyring)(nil).Remove), key)
|
||||
}
|
||||
|
||||
// Set mocks base method.
|
||||
func (m *MockKeyring) Set(item keyring.Item) error {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "Set", item)
|
||||
ret0, _ := ret[0].(error)
|
||||
return ret0
|
||||
}
|
||||
|
||||
// Set indicates an expected call of Set.
|
||||
func (mr *MockKeyringMockRecorder) Set(item interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Set", reflect.TypeOf((*MockKeyring)(nil).Set), item)
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLog(t *testing.T) {
|
||||
RegisterFailHandler(Fail)
|
||||
RunSpecs(t, "Log Suite")
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/rs/zerolog/pkgerrors"
|
||||
"io"
|
||||
)
|
||||
|
||||
//go:generate mockgen -source=logger.go -destination=logger_mock.go -package log
|
||||
type Logger interface {
|
||||
Verbose() *zerolog.Event
|
||||
Log() *zerolog.Event
|
||||
Error() *zerolog.Event
|
||||
}
|
||||
|
||||
type logger struct {
|
||||
internalLogger zerolog.Logger
|
||||
verbose bool
|
||||
}
|
||||
|
||||
type LoggerArgs struct {
|
||||
Verbose bool
|
||||
Writer io.Writer
|
||||
}
|
||||
|
||||
func NewLogger(args LoggerArgs) Logger {
|
||||
internalLogger := log.Logger
|
||||
level := zerolog.InfoLevel
|
||||
|
||||
if args.Verbose {
|
||||
level = zerolog.DebugLevel
|
||||
zerolog.ErrorStackMarshaler = pkgerrors.MarshalStack
|
||||
}
|
||||
|
||||
internalLogger = internalLogger.Output(args.Writer).Level(level)
|
||||
|
||||
return &logger{
|
||||
verbose: args.Verbose,
|
||||
internalLogger: internalLogger,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *logger) Log() *zerolog.Event {
|
||||
return l.internalLogger.Info()
|
||||
}
|
||||
|
||||
func (l *logger) Verbose() *zerolog.Event {
|
||||
if !l.verbose {
|
||||
return nil
|
||||
}
|
||||
|
||||
return l.internalLogger.Debug()
|
||||
}
|
||||
|
||||
func (l *logger) Error() *zerolog.Event {
|
||||
return l.internalLogger.Error()
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
// Code generated by MockGen. DO NOT EDIT.
|
||||
// Source: logger.go
|
||||
|
||||
// Package log is a generated GoMock package.
|
||||
package log
|
||||
|
||||
import (
|
||||
reflect "reflect"
|
||||
|
||||
gomock "github.com/golang/mock/gomock"
|
||||
zerolog "github.com/rs/zerolog"
|
||||
)
|
||||
|
||||
// MockLogger is a mock of Logger interface.
|
||||
type MockLogger struct {
|
||||
ctrl *gomock.Controller
|
||||
recorder *MockLoggerMockRecorder
|
||||
}
|
||||
|
||||
// MockLoggerMockRecorder is the mock recorder for MockLogger.
|
||||
type MockLoggerMockRecorder struct {
|
||||
mock *MockLogger
|
||||
}
|
||||
|
||||
// NewMockLogger creates a new mock instance.
|
||||
func NewMockLogger(ctrl *gomock.Controller) *MockLogger {
|
||||
mock := &MockLogger{ctrl: ctrl}
|
||||
mock.recorder = &MockLoggerMockRecorder{mock}
|
||||
return mock
|
||||
}
|
||||
|
||||
// EXPECT returns an object that allows the caller to indicate expected use.
|
||||
func (m *MockLogger) EXPECT() *MockLoggerMockRecorder {
|
||||
return m.recorder
|
||||
}
|
||||
|
||||
// Error mocks base method.
|
||||
func (m *MockLogger) Error() *zerolog.Event {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "Error")
|
||||
ret0, _ := ret[0].(*zerolog.Event)
|
||||
return ret0
|
||||
}
|
||||
|
||||
// Error indicates an expected call of Error.
|
||||
func (mr *MockLoggerMockRecorder) Error() *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Error", reflect.TypeOf((*MockLogger)(nil).Error))
|
||||
}
|
||||
|
||||
// Log mocks base method.
|
||||
func (m *MockLogger) Log() *zerolog.Event {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "Log")
|
||||
ret0, _ := ret[0].(*zerolog.Event)
|
||||
return ret0
|
||||
}
|
||||
|
||||
// Log indicates an expected call of Log.
|
||||
func (mr *MockLoggerMockRecorder) Log() *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Log", reflect.TypeOf((*MockLogger)(nil).Log))
|
||||
}
|
||||
|
||||
// Verbose mocks base method.
|
||||
func (m *MockLogger) Verbose() *zerolog.Event {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "Verbose")
|
||||
ret0, _ := ret[0].(*zerolog.Event)
|
||||
return ret0
|
||||
}
|
||||
|
||||
// Verbose indicates an expected call of Verbose.
|
||||
func (mr *MockLoggerMockRecorder) Verbose() *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Verbose", reflect.TypeOf((*MockLogger)(nil).Verbose))
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
|
||||
"github.com/golang/mock/gomock"
|
||||
"github.com/rs/zerolog"
|
||||
)
|
||||
|
||||
var _ = Describe("Logger", func() {
|
||||
var (
|
||||
ctrl *gomock.Controller
|
||||
mockWriter *MockWriter
|
||||
logger Logger
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctrl = gomock.NewController(GinkgoT())
|
||||
mockWriter = NewMockWriter(ctrl)
|
||||
})
|
||||
|
||||
Context("Verbose logger", func() {
|
||||
BeforeEach(func() {
|
||||
logger = NewLogger(LoggerArgs{
|
||||
Verbose: true,
|
||||
Writer: mockWriter,
|
||||
})
|
||||
})
|
||||
|
||||
When("logging with verbose level", func() {
|
||||
It("writes output", func() {
|
||||
mockWriter.EXPECT().
|
||||
WriteLevel(zerolog.DebugLevel, gomock.Any()).
|
||||
Do(func(level zerolog.Level, p []byte) {
|
||||
Expect(p).To(ContainSubstring("\"message\":\"verbose\""))
|
||||
}).
|
||||
Return(0, nil)
|
||||
|
||||
logger.Verbose().Msg("verbose")
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
Context("Non-verbose logger", func() {
|
||||
BeforeEach(func() {
|
||||
logger = NewLogger(LoggerArgs{
|
||||
Verbose: false,
|
||||
Writer: mockWriter,
|
||||
})
|
||||
})
|
||||
|
||||
When("logging messsage", func() {
|
||||
It("writes output", func() {
|
||||
mockWriter.EXPECT().
|
||||
WriteLevel(zerolog.InfoLevel, gomock.Any()).
|
||||
Do(func(level zerolog.Level, p []byte) {
|
||||
Expect(p).To(ContainSubstring("\"message\":\"info\""))
|
||||
}).
|
||||
Return(0, nil)
|
||||
|
||||
logger.Log().Msg("info")
|
||||
})
|
||||
})
|
||||
|
||||
When("logging error", func() {
|
||||
It("writes output", func() {
|
||||
mockWriter.EXPECT().
|
||||
WriteLevel(zerolog.ErrorLevel, gomock.Any()).
|
||||
Do(func(level zerolog.Level, p []byte) {
|
||||
Expect(p).To(ContainSubstring("\"message\":\"error\""))
|
||||
}).
|
||||
Return(0, nil)
|
||||
|
||||
logger.Error().Msg("error")
|
||||
})
|
||||
})
|
||||
|
||||
When("logging with verbose level", func() {
|
||||
It("returns nil", func() {
|
||||
res := logger.Verbose()
|
||||
Expect(res).To(BeNil())
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,40 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"github.com/rs/zerolog"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
//go:generate mockgen -source=writer.go -destination=writer_mock.go -package log
|
||||
type Writer interface {
|
||||
Write(p []byte) (n int, err error)
|
||||
WriteLevel(level zerolog.Level, p []byte) (n int, err error)
|
||||
}
|
||||
|
||||
type writer struct {
|
||||
stdOutWriter io.Writer
|
||||
stdErrWriter io.Writer
|
||||
}
|
||||
|
||||
func NewWriter() Writer {
|
||||
return &writer{
|
||||
stdOutWriter: zerolog.ConsoleWriter{Out: os.Stdout},
|
||||
stdErrWriter: zerolog.ConsoleWriter{Out: os.Stderr},
|
||||
}
|
||||
}
|
||||
|
||||
func (l *writer) Write(p []byte) (n int, err error) {
|
||||
return l.stdOutWriter.Write(p)
|
||||
}
|
||||
|
||||
func (l *writer) WriteLevel(level zerolog.Level, p []byte) (n int, err error) {
|
||||
switch level {
|
||||
case zerolog.DebugLevel, zerolog.InfoLevel, zerolog.WarnLevel:
|
||||
return l.stdOutWriter.Write(p)
|
||||
case zerolog.ErrorLevel:
|
||||
return l.stdErrWriter.Write(p)
|
||||
default:
|
||||
return len(p), nil
|
||||
}
|
||||
}
|
||||
Loaded 100 of 116 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user