Clean up: Removed all previous commits and reset commit date to the project's creation date.

Esse commit está contido em:
offici5l
2024-01-14 14:19:39 +00:00
commit 31cb35ba3a
7 arquivos alterados com 999 adições e 0 exclusões
+71
Ver Arquivo
@@ -0,0 +1,71 @@
name: Release miunlock
on:
push:
paths:
- MiUnlockTool.py
pull_request:
paths:
- MiUnlockTool.py
workflow_dispatch:
jobs:
linux:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Get version
id: get_version
run: |
version=$(grep -oP '(?<=version = ")(.*)(?=")' MiUnlockTool.py)
echo "VERSION=$version" >> $GITHUB_ENV
- name: tag
run: |
if ! git ls-remote --tags origin | grep -q "$VERSION"; then
git tag "$VERSION"
git push origin "$VERSION"
else
echo "Tag $VERSION already exists, skipping tag creation."
fi
- name: release
run: |
if ! gh release view $VERSION; then
gh release create $VERSION --title "Release $VERSION"
else
echo "Release $VERSION already exists, skipping release creation."
fi
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
VERSION: ${{ env.VERSION }}
- name: upload
run: |
if git rev-parse --verify HEAD~1 >/dev/null 2>&1; then
if git diff --name-only HEAD~1 HEAD | grep -q "MiUnlockTool.py"; then
commit_message=$(git log -1 --pretty=format:"%s" -- MiUnlockTool.py)
old_notes=$(gh release view $VERSION --json body -q '.body')
if [ -z "$old_notes" ]; then
notes="$commit_message"
else
if [ "$old_notes" = "$commit_message" ]; then
notes="$commit_message"
else
notes="${old_notes}\n$commit_message"
fi
fi
new_notes=$(echo -e "$notes")
gh release edit $VERSION --notes "$new_notes"
else
echo "MiUnlockTool.py was not modified in the last commit, skipping notes update."
fi
else
echo "No previous commit to compare with."
fi
gh release upload $VERSION ./MiUnlockTool.py --clobber
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
VERSION: ${{ env.VERSION }}
+5
Ver Arquivo
@@ -0,0 +1,5 @@
/venv
/platform-tools
/data.json
/encryptData
+172
Ver Arquivo
@@ -0,0 +1,172 @@
#!/data/data/com.termux/files/usr/bin/bash
echo
if [ ! -d "/data/data/com.termux.api" ]; then
echo -e "\ncom.termux.api app is not installed\nPlease install it first\n"
exit 1
fi
arch=$(uname -m)
if [ "$arch" = "aarch64" ]; then
arch="aarch64"
elif [ "$arch" = "armv7l" ]; then
arch="arm"
elif [ "$arch" = "armv8l" ]; then
arch="arm"
else
echo -e "\nArchitecture $arch not supported\n"
exit 1
fi
echo -ne "\rurl check ..."
main_repo=$(grep -E '^deb ' /data/data/com.termux/files/usr/etc/apt/sources.list | awk '{print $2}' | head -n 1)
curl -s --retry 4 $main_repo > /dev/null
exit_code=$?
if [ $exit_code -eq 6 ]; then
echo -e "\nRequest to $main_repo failed. Please check your internet connection.\n"
exit 6
elif [ $exit_code -eq 35 ]; then
echo -e "\nThe $main_repo is blocked in your current country.\n"
exit 35
fi
git_repo="https://raw.githubusercontent.com"
curl -s --retry 4 $git_repo > /dev/null
exit_code=$?
if [ $exit_code -eq 6 ]; then
echo -e "\nRequest to $git_repo failed. Please check your internet connection.\n"
exit 6
elif [ $exit_code -eq 35 ]; then
echo -e "\nThe $git_repo is blocked in your current country.\n"
exit 35
fi
echo -ne "\rapt update ..."
apt update > /dev/null 2> >(grep -v "apt does not have a stable CLI interface")
charit=-1
total=22
start_time=$(date +%s)
_progress() {
charit=$((charit + 1))
percentage=$((charit * 100 / total))
echo -ne "\rProgress: $charit/$total ($percentage%)"
if [ $percentage -eq 100 ]; then
end_time=$(date +%s)
elapsed_time=$((end_time - start_time))
echo -ne "\rProgress: $charit/$total ($percentage%) Took: $elapsed_time seconds"
else
echo -ne "\rProgress: $charit/$total ($percentage%)"
fi
}
_progress
url="https://raw.githubusercontent.com/nohajc/nohajc.github.io/master/dists/termux/extras/binary-${arch}"
get_version() {
package_name="$1"
local __resultvar=$2
version=$(curl -s "$url/Packages" | awk -v package="$package_name" '
$0 ~ "^Package: " package {found=1}
found && /^Version:/ {print $2; exit}
')
eval $__resultvar="'$version'"
}
libprotobuf_version_c=""
termux_adb_version_c=""
get_version "libprotobuf-tadb-core" libprotobuf_version_c
get_version "termux-adb" termux_adb_version_c
libprotobuf_version_i=$(pkg show libprotobuf-tadb-core 2>/dev/null | grep Version | cut -d ' ' -f 2)
termux_adb_version_i=$(pkg show termux-adb 2>/dev/null | grep Version | cut -d ' ' -f 2)
# Function to compare versions without printing anything if the package is already updated
compare_versions() {
package_name="$1"
available_version="$2"
installed_version="$3"
if [ "$installed_version" != "$available_version" ]; then
curl -s -O "$url/${package_name}_${available_version}_${arch}.deb"
dpkg --force-overwrite -i "${package_name}_${available_version}_${arch}.deb" >/dev/null 2>&1
rm -f "${package_name}_${available_version}_${arch}.deb"
fi
_progress
}
compare_versions "libprotobuf-tadb-core" "$libprotobuf_version_c" "$libprotobuf_version_i"
compare_versions "termux-adb" "$termux_adb_version_c" "$termux_adb_version_i"
ln -sf "$PREFIX/bin/termux-fastboot" "$PREFIX/bin/fastboot" && ln -sf "$PREFIX/bin/termux-adb" "$PREFIX/bin/adb"
packages=(
"openssl"
"libffi"
"abseil-cpp"
"termux-api"
"libusb"
"brotli"
"python"
"python-pip"
"libexpat"
"pkg-config"
"libc++"
"zlib"
"zstd"
"liblz4"
"tur-repo"
"python-pycryptodomex"
)
for package in "${packages[@]}"; do
installed=$(apt policy "$package" 2>/dev/null | grep 'Installed' | awk '{print $2}')
candidate=$(apt policy "$package" 2>/dev/null | grep 'Candidate' | awk '{print $2}')
if [ "$installed" != "$candidate" ]; then
apt download "$package" >/dev/null 2>&1
dpkg --force-overwrite -i "${package}"*.deb >/dev/null 2>&1
rm -f "${package}"*.deb
fi
_progress
done
libs=(
"urllib3"
"requests"
"colorama"
)
for lib in "${libs[@]}"; do
installed_version=$(pip show "$lib" 2>/dev/null | grep Version | awk '{print $2}')
latest_version=$(pip index versions "$lib" 2>/dev/null | grep 'LATEST:' | awk '{print $2}')
if [ -z "$installed_version" ]; then
pip install "$lib" -q
elif [ "$installed_version" != "$latest_version" ]; then
pip install --upgrade "$lib" -q
fi
_progress
done
curl -sSL -o "$PREFIX/bin/miunlock" https://github.com/offici5l/MiUnlockTool/releases/latest/download/MiUnlockTool.py && chmod +x "$PREFIX/bin/miunlock"
_progress
echo
printf "\nuse command: \e[1;32mmiunlock\e[0m\n\n"
+155
Ver Arquivo
@@ -0,0 +1,155 @@
### Version 1.4.8:
- Make the installation method easier, just download and run the file, it will take care of the rest.
- Other improvements
### Version 1.4.9:
- Improvements and fixes
### Version 1.5.0:
- un-lock has been restructured and rebuilt.
- Improved and reduced un-lock size.
- un-lock is now compatible with all operating systems.
- Resolved the "securityStatus16" issue and fixed other problems.
#### Version 1.5.0 (Update):
- Deleted `cmd getvar all` in `def CheckB` and replaced it with `getvar token` and `getvar product`.
- In case of failure to obtain `deviceToken` and `product`, added a step to enter them manually.
- Other improvements
#### Version 1.5.0 (Update):
- Simplified cookie extraction for concise code.
- Streamlined URL determination for better clarity based on the geographical region.
- Specified "https" directly in the `Url` constructor for secure communication and improved clarity.
- Deleted requests to "/api/v3/unlock/userinfo" and "/api/v2/unlock/device/clear" to reduce code size as they are not currently important.
- Adjusted message formatting for enhanced readability.
- Changed `cmd = "tfastboot"` to `cmd = "fastboot"`. Also, removed `adb`.
### Tool name update: "un-lock" is now "MiUnlockTool".
#### Version 1.5.0 (Update):
- Minor bug fix
- Add command (cmd, "oem", "get_token")
- In the event of failure to obtain the device token, the user will be asked to enter it manually
- Other improvements
#### Version 1.5.0 (Update):
- When 2 or more tokens are obtained via the festboot oem get_token ..
tool will now merge them automatically
#### Version 1.5.0 (Update):
- Updated client version to 7.6.727.43.
- Improved unlocking process.
#### Version 1.5.0 (Update):
- Save keys:values directly
#### Version 1.5.0 (Update):
- Added a step to check if the com.termux.api application is installed ..
#### Version 1.5.0 (Update):
- A few users are experiencing an issue regarding "Check if device is connected in bootloader mode..."
Due to the slow transmission with the device
So the time was increased from 1s to [6s](https://github.com/offici5l/MiUnlockTool/blob/main/MiUnlockTool.py#L112)
#### Version 1.5.0 (Update):
- get tokens(deviceToken) and merging them Automatically done. ( MTK devices )
#### Version 1.5.0 (Update):
- Add ability to choose server(host region) from terminal
#### Version 1.5.0 (Update):
- Adding some improvements
#### Version 1.5.0 (Update):
- improvements
#### Version 1.5.0 (Update):
- Skip saving device information such as token and product, so as not to cause problems during unlocking...
- improvements
#### Version 1.5.0 (Update):
- Adding some improvements
#### Version 1.5.0 (Update):
- Correct the issue of the confirmation page not opening in Linux
#### Version 1.5.0 (Update):
- fix ( For Linux( and termux ) users : the 401 issue .... during account confirmation ... )
#### Version 1.5.0 (Update):
- add colorama to handle colors instead of ANSI
- Add requests to access the region and deal with the region, to send the request to the correct server accurately
- improvements
#### Version 1.5.0 (Update):
- Adding some improvements
#### Version 1.5.0 (Update):
- Add manual mode to unlock the bootloader
#### Version 1.5.0 (Update):
- Enhanced request security and improved access to region data to fix issues "code 20033"
#### Version 1.5.0 (Update):
- Replace command "oem device-info" with "getvar unloked"
#### Version 1.5.0 (Update):
- Adding steps to deal with "security Status 4", regarding adding email to xiaomi account This will fix "Failed to get pass Token"
#### Version 1.5.0 (Update):
- Re-added request 'api/v2/unlock/device/clear' to check if the device is cleared or not After unlocking bootloader
### Version 1.5.1:
- improvements
- Simplified browser login: Confirm login instead of re-entering credentials
### Version 1.5.1 (Update):
- Simplified browser login canceled currently due to some problems. so Means »
- `fix "Invalid link"`
### Version 1.5.2:
- Fix `"device is not recognized but termux-api popup appears !"`
- Improvements
- Delete some unimportant messages ..
### Version 1.5.2 (Update):
- Add a step to verify that storage access(termux-setup-storage) is granted
### Version 1.5.3:
- A global variable connect was added to track the device connection status. the code now checks for device connection only if it hasn't been connected yet, reducing redundant checks.
This will reduce the process time by about half, and it cannot be reduced further because the problem is with termux &termux-api itself.
- Add some messages to let the user know that the process is in progress.
### Version 1.5.4:
- Edit the encryptData save path to be in /sdcard/encryptData Instead of being in /sdcard/Download/encryptData ( this will fix the issue :
FileNotFoundError: [Errno 2] No such file or directory: '/sdcard/Download/encryptData' )
### Version 1.5.5:
- Output management has been enhanced by using threads to read from stdout and stderr concurrently, which reduces verification delays and improves system responsiveness.
- The fastboot devices command has been removed from the verification process, which reduces the number of executed commands and increases process efficiency. (This will minimize waiting time for devices facing issues.)
- Manual input on failure has been removed and some unnecessary elements have been eliminated.
### Version 1.5.5 (Update):
[#L289-L323:](https://github.com/offici5l/MiUnlockTool/blob/main/MiUnlockTool.py#L289-L323)
- Retry 4 attempts, in case of failure to get phone info
- Add print the type of SoC, based on the order that gets the token.
### Version 1.5.6:
- Remove manual mode, and remove some functions that are no longer necessary.
- Some improvements, to handle jobs better.
- Fix the issue with termux (Error message: fastboot: error: cannot load /sdcard/encryptData) , due to some termux-setup-storage issues, the encryptData will now be saved in $PREFIX/bin instead of /sdcard...
- Other improvements in the installation process regarding Termux.
+204
Ver Arquivo
@@ -0,0 +1,204 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2024 offici5l
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Project: [MiUnlockTool]
Repository: [https://github.com/offici5l/MiUnlockTool]
+361
Ver Arquivo
@@ -0,0 +1,361 @@
#!/usr/bin/python
version = "1.5.6"
import os
for lib in ['Cryptodome', 'urllib3', 'requests', 'colorama']:
try:
__import__(lib)
except ImportError:
prefix = os.getenv("PREFIX", "")
if lib == 'Cryptodome':
if "com.termux" in prefix:
cmd = 'pkg install python-pycryptodomex'
else:
cmd = 'pip install pycryptodomex'
else:
cmd = f'pip install {lib}'
os.system(cmd)
import re, requests, json, hmac, random, binascii, urllib, hashlib, io, urllib.parse, time, sys, urllib.request, zipfile, webbrowser, platform, subprocess, shutil, stat, datetime, threading
from urllib3.util.url import Url
from base64 import b64encode, b64decode
from Cryptodome.Cipher import AES
from urllib.parse import urlparse, parse_qs, urlencode
from colorama import init, Fore, Style
init(autoreset=True)
cg = Style.BRIGHT + Fore.GREEN
cgg = Style.DIM
cr = Fore.RED
crr = Style.BRIGHT + Fore.RED
cres = Style.RESET_ALL
cy = Style.BRIGHT + Fore.YELLOW
p_ = cg + "\n" + "_"*56 +"\n"
session = requests.Session()
headers = {"User-Agent": "XiaomiPCSuite"}
if '1' in sys.argv:
pass
else:
print(cgg + f"\n[V{version}] For issues or feedback:\n- GitHub: github.com/offici5l/MiUnlockTool/issues\n- Telegram: t.me/Offici5l_Group\n" + cres)
print(p_)
s = platform.system()
if s == "Linux" and os.path.exists("/data/data/com.termux"):
up = os.path.join(os.getenv("PREFIX", ""), "bin", "miunlock")
try:
if "fastboot version" not in os.popen("fastboot --version").read():
raise Exception
except:
os.system("curl https://raw.githubusercontent.com/offici5l/MiUnlockTool/main/.install | bash")
exit()
if not os.path.exists(up):
shutil.copy(__file__, up)
os.system(f"chmod +x {up}")
print(f"\nuse command: {cg}miunlock{cres}\n")
exit()
if not os.path.exists("/data/data/com.termux.api"):
print("\ncom.termux.api app is not installed\nPlease install it first\n")
exit()
cmd = "fastboot"
browserp = "t"
else:
dir = os.path.dirname(__file__)
fp = os.path.join(dir, "platform-tools")
if not os.path.exists(fp):
print("\ndownload platform-tools...\n")
url = f"https://dl.google.com/android/repository/platform-tools-latest-{s}.zip"
cd = os.path.join(os.path.dirname(__file__))
fp = os.path.join(cd, os.path.basename(url))
urllib.request.urlretrieve(url, fp)
with zipfile.ZipFile(fp, 'r') as zip_ref:
zip_ref.extractall(cd)
os.remove(fp)
cmd = os.path.join(fp, "fastboot")
if s == "Linux" or s == "Darwin":
st = os.stat(cmd)
os.chmod(cmd, st.st_mode | stat.S_IEXEC)
browserp = "wlm"
datafile = os.path.join(os.path.dirname(__file__), "miunlockdata.json")
while os.path.isfile(datafile):
try:
with open(datafile, "r") as file:
data = json.load(file)
if '1' in sys.argv:
break
elif data and data.get("login") == "ok":
choice = input(f"\nYou are already logged in with account uid: {data['uid']}\n{cg}Press Enter to continue\n{cgg}(to log out, type 2 and press Enter){cres}\n").strip().lower()
if choice == "2":
os.remove(datafile)
else:
break
else:
os.remove(datafile)
except PermissionError:
os.remove(datafile)
except json.JSONDecodeError:
os.remove(datafile)
def remove(*keys):
print(f"\n{cr}invalid {keys[0] if len(keys) == 1 else ' or '.join(keys)}{cres}\n")
with open(datafile, "r+") as file:
data = json.load(file)
for key in keys:
data.pop(key, None)
file.seek(0)
json.dump(data, file, indent=2)
file.truncate()
subprocess.run(["python", __file__, "1"])
try:
with open(datafile, "r+") as file:
data = json.load(file)
except FileNotFoundError:
data = {}
with open(datafile, 'w') as file:
json.dump(data, file)
def save(data, path):
with open(path, "w") as file:
json.dump(data, file, indent=2)
if "user" not in data:
data["user"] = input("\n\n(Xiaomi Account) Id or Email or Phone (in international format): ")
save(data, datafile)
if "pwd" not in data:
data["pwd"] = input("\nEnter password: ")
save(data, datafile)
if "wb_id" not in data:
input(f"\n{Fore.CYAN}Notice:\nIf logged in with any account in your default browser,\nplease log out before pressing Enter.\n\n{cres}{cg}Press Enter{cres} to open confirmation page, \n copy link after seeing {Fore.CYAN}{Style.BRIGHT}\"R\":\"\",\"S\":\"OK\"{Style.RESET_ALL}, \n and return here\n\n")
conl = 'https://account.xiaomi.com/pass/serviceLogin?sid=unlockApi&checkSafeAddress=true&passive=false&hidden=false'
if s == "Linux":
os.system("xdg-open '" + conl + "'")
else:
webbrowser.open(conl)
time.sleep(2)
wb_id = parse_qs(urlparse(input("\nEnter Link: ")).query).get('d', [None])[0]
if wb_id is None:
print("\n\nInvalid link\n")
subprocess.run(["python", __file__, "1"])
sys.exit()
data["wb_id"] = wb_id
save(data, datafile)
user, pwd, wb_id = (data.get(key, "") for key in ["user", "pwd", "wb_id"])
datav = data
def add_email(SetEmail):
input(f"\n{cr}Failed to get passToken !{cres}\n\nThe account is not linked to an email.\n{cg}Press Enter{cres} to open the email adding page.\nAfter successfully adding your email, return here")
if s == "Linux":
os.system("xdg-open '" + SetEmail + "'")
else:
webbrowser.open(SetEmail)
time.sleep(2)
input(f"\nIf email added successfully, {cg}press Enter{cres} to continue\n")
subprocess.run(["python", __file__, "1"])
sys.exit()
def postv(sid):
return json.loads(session.post(f"https://account.xiaomi.com/pass/serviceLoginAuth2?sid={sid}&_json=true&passive=true&hidden=true", data={"user": user, "hash": hashlib.md5(pwd.encode()).hexdigest().upper()}, headers=headers, cookies={"deviceId": str(wb_id)}).text.replace("&&&START&&&", ""))
data = postv("unlockApi")
if data["code"] == 70016:
remove("user", "pwd")
sys.exit()
if data["securityStatus"] == 4 and "notificationUrl" in data and "bizType=SetEmail" in data["notificationUrl"]:
add_email(data["notificationUrl"])
if data["securityStatus"] == 16:
p = postv("passport")
if p["securityStatus"] == 4 and "notificationUrl" in p and "bizType=SetEmail" in p["notificationUrl"]:
add_email(p["notificationUrl"])
elif "passToken" not in p:
print(f"\n{cr}Failed to get passToken !{cres}\n")
exit()
data = json.loads(requests.get("https://account.xiaomi.com/pass/serviceLogin?sid=unlockApi&_json=true&passive=true&hidden=true", headers=headers, cookies={'passToken': p['passToken'], 'userId': str(p['userId']), 'deviceId': parse_qs(urlparse(p['location']).query)['d'][0]}).text.replace("&&&START&&&", ""))
ssecurity, nonce, location = data["ssecurity"], data["nonce"], data["location"]
cookies = {cookie.name: cookie.value for cookie in session.get(location + "&clientSign=" + urllib.parse.quote_plus(b64encode(hashlib.sha1(f"nonce={nonce}".encode("utf-8") + b"&" + ssecurity.encode("utf-8")).digest())), headers=headers).cookies}
if 'serviceToken' not in cookies:
print(f"\n{cr}Failed to get serviceToken.{cres}")
remove("wb_id")
sys.exit()
if "login" not in datav:
datav["login"] = "ok"
if "uid" not in datav:
datav["uid"] = data['userId']
save(datav, datafile)
print(f"\n\n{cg}Login successful! Login saved.{cres}")
region = json.loads(requests.get("https://account.xiaomi.com/pass/user/login/region?", headers=headers, cookies={'passToken': data['passToken'], 'userId': str(data['userId']), 'deviceId': parse_qs(urlparse(data['location']).query)['d'][0]}).text.replace("&&&START&&&", ""))['data']['region']
print(f"\n{cg}AccountInfo:{cres}\nid: {data['userId']}\nregion: {region}")
region_config = json.loads(requests.get("https://account.xiaomi.com/pass2/config?key=register").text.replace("&&&START&&&", ""))['regionConfig']
for key, value in region_config.items():
if 'region.codes' in value and region in value['region.codes']:
region = value['name'].lower()
break
for arg in sys.argv:
if arg.lower() in ['global', 'india', 'russia', 'china', 'europe']:
region = arg
break
g = "unlock.update.intl.miui.com"
if region == "china":
url = g.replace("intl.", "")
elif region == "india":
url = f"in-{g}"
elif region == "russia":
url = f"ru-{g}"
elif region == "europe":
url = f"eu-{g}"
else:
url = g
def read_stream(stream, output_list, process, restart_flag):
try:
for line in iter(stream.readline, ''):
line = line.strip()
output_list.append(line)
if "No permission" in line or "< waiting for any device >" in line:
process.terminate()
print(f'\r< waiting for any device >', end='', flush=True)
restart_flag[0] = True
return
finally:
stream.close()
def CheckB(cmd, var_name, *fastboot_args):
while True:
process = subprocess.Popen([cmd] + list(fastboot_args), stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1, universal_newlines=True)
stdout_lines, stderr_lines, restart_flag = [], [], [False]
threading.Thread(target=read_stream, args=(process.stdout, stdout_lines, process, restart_flag)).start()
threading.Thread(target=read_stream, args=(process.stderr, stderr_lines, process, restart_flag)).start()
try:
process.wait()
except subprocess.SubprocessError as e:
print(f"Error while executing process: {e}")
return None
if restart_flag[0]:
time.sleep(2)
sys.stdout.write('\r\033[K')
continue
print(f"\rFetching '{var_name}' — please wait...", end='', flush=True)
lines = [line.split(f"{var_name}:")[1].strip() for line in stderr_lines + stdout_lines if f"{var_name}:" in line]
if len(lines) > 1:
return "".join(lines)
return lines[0] if lines else None
[print(char, end='', flush=True) or time.sleep(0.01) for char in "\nEnsure you're in Bootloader mode (fastboot mode)\n\n"]
unlocked = None
product = None
SoC = None
token = None
while unlocked is None or product is None or SoC is None or token is None:
if unlocked is None:
unlocked = CheckB(cmd, "unlocked", "getvar", "unlocked")
if product is None:
product = CheckB(cmd, "product", "getvar", "product")
if token is None:
token = CheckB(cmd, "token", "oem", "get_token")
if token:
SoC = "Mediatek"
else:
token = CheckB(cmd, "token", "getvar", "token")
if token:
SoC = "Qualcomm"
sys.stdout.write('\r\033[K')
print(f"\n{cg}DeviceInfo:{cres}\nunlocked: {unlocked}\nSoC: {SoC}\nproduct: {product}\ntoken: {token}\n")
class RetrieveEncryptData:
def add_nonce(self):
r = RetrieveEncryptData("/api/v2/nonce", {"r":''.join(random.choices(list("abcdefghijklmnopqrstuvwxyz"), k=16)), "sid":"miui_unlocktool_client"}).run()
self.params[b"nonce"] = r["nonce"].encode("utf-8")
self.params[b"sid"] = b"miui_unlocktool_client"
return self
def __init__(self, path, params):
self.path = path
self.params = {k.encode("utf-8"): v.encode("utf-8") if isinstance(v, str) else b64encode(json.dumps(v).encode("utf-8")) if not isinstance(v, bytes) else v for k, v in params.items()}
def getp(self, sep):
return b'POST'+sep+self.path.encode("utf-8")+sep+b"&".join([k+b"="+v for k,v in self.params.items()])
def run(self):
self.params[b"sign"] = binascii.hexlify(hmac.digest(b'2tBeoEyJTunmWUGq7bQH2Abn0k2NhhurOaqBfyxCuLVgn4AVj7swcawe53uDUno', self.getp(b"\n"), "sha1"))
for k, v in self.params.items():
self.params[k] = b64encode(AES.new(b64decode(ssecurity), AES.MODE_CBC, b"0102030405060708").encrypt(v + (16 - len(v) % 16) * bytes([16 - len(v) % 16])))
self.params[b"signature"] = b64encode(hashlib.sha1(self.getp(b"&")+b"&"+ssecurity.encode("utf-8")).digest())
return json.loads(b64decode((lambda s: s[:-s[-1]])(AES.new(b64decode(ssecurity), AES.MODE_CBC, b"0102030405060708").decrypt(b64decode(session.post(Url(scheme="https", host=url, path=self.path).url, data=self.params, headers=headers, cookies=cookies).text)))))
print(p_)
c = RetrieveEncryptData("/api/v2/unlock/device/clear", {"data":{"product":product}}).add_nonce().run()
cleanOrNot = c['cleanOrNot']
if cleanOrNot == 1:
print(f"\n{crr}This device clears user data when it is unlocked{cres}\n")
elif cleanOrNot == -1:
print(f"\n{cg}Unlocking the device does not clear user data{cres}\n")
print(Style.BRIGHT + Fore.CYAN + c['notice'] + cres)
choice = input(f"\n{cg}Press Enter to Unlock\n{cgg}( or type q and press Enter to quit){cres}")
if choice.lower() == 'q':
print("\nExiting...\n")
exit()
print(p_)
r = RetrieveEncryptData("/api/v3/ahaUnlock", {"appId":"1", "data":{"clientId":"2", "clientVersion":"7.6.727.43", "language":"en", "operate":"unlock", "pcId":hashlib.md5(wb_id.encode("utf-8")).hexdigest(), "product":product, "region":"","deviceInfo":{"boardVersion":"","product":product, "socId":"","deviceName":""}, "deviceToken":token}}).add_nonce().run()
if "code" in r and r["code"] == 0:
ed = io.BytesIO(bytes.fromhex(r["encryptData"]))
with open("encryptData", "wb") as edfile:
edfile.write(ed.getvalue())
CheckB(cmd, "serialno", "getvar", "serialno")
sys.stdout.write('\r\033[K')
try:
result_stage = subprocess.run([cmd, "stage", "encryptData"], check=True, capture_output=True, text=True)
result_unlock = subprocess.run([cmd, "oem", "unlock"], check=True, capture_output=True, text=True)
print(f"\n{cg}Unlock successful{cgg}\n")
os.remove("encryptData")
except subprocess.CalledProcessError as e:
print("Error message:", e.stderr)
elif "descEN" in r:
print(f"\ncode {r['code']}\n\n{r['descEN']}")
if r["code"] == 20036:
print("\nYou can unlock on:", (datetime.datetime.now().replace(minute=0, second=0, microsecond=0) + datetime.timedelta(hours=r["data"]["waitHour"])).strftime("%Y-%m-%d %H:%M"))
if r["code"] == 10000:
print(f"\n{cr}invalid product or token")
else:
for key, value in r.items():
print(f"\n{key}: {value}")
print(p_)
browserp == "wlm" and input("\nPress Enter to exit ...")
+31
Ver Arquivo
@@ -0,0 +1,31 @@
<div align="center">
<a href="https://github.com/offici5l/MiUnlockTool/releases/latest"><img src="https://img.shields.io/badge/MiUnlockTool-%23FF6900?style=flat&logo=xiaomi&logoColor=white" alt="MiUnlockTool" style="width: 200px; vertical-align: middle;" /> </a><br>
<img src="https://img.shields.io/github/v/release/offici5l/MiUnlockTool?style=flat&label=Version&labelColor=black&color=brightgreen" alt="Version" /><br><p style="font-weight: bold;">Developed to retrieve <code>encryptData(token)</code>
<br>
for Xiaomi devices to unlock the bootloader.
<br>
Compatible with all platforms.</p>
<a href="https://github.com/offici5l/MiUnlockTool/blob/main/CHANGELOG.md"><img src="https://img.shields.io/badge/Changelog-%23000000?style=flat&logo=github&logoColor=white" alt="CHANGELOG" /></a>
<a href="./LICENSE"><img src="https://img.shields.io/badge/License-Apache%202.0-blue.svg" alt="Apache 2.0 License" /></a>
<a href="https://t.me/Offici5l_Channel"><img src="https://img.shields.io/badge/Telegram-%230077B5?style=flat&logo=telegram&logoColor=white" alt="Telegram Channel" /></a>
</div>
<h1>Installation:</h1>
<h2>For Windows, Linux, MacOS :</h2>
<ol>
<li>Install Python3</li>
<li>Download <a href="https://github.com/offici5l/MiUnlockTool/releases/latest/download/MiUnlockTool.py">MiUnlockTool</a> and run it</li>
</ol>
<h2>For Android :</h2>
<ol>
<li>Install <a href="https://github.com/termux/termux-app/releases/download/v0.118.0/termux-app_v0.118.0+github-debug_universal.apk">Termux</a></li>
<li>Install <a href="https://github.com/termux/termux-api/releases/download/v0.50.1/termux-api_v0.50.1+github-debug.apk">Termux API</a></li>
<li>From Termux command line run:</li>
</ol>
<pre><code>curl -sS https://raw.githubusercontent.com/offici5l/MiUnlockTool/main/.install | bash</code></pre>