Create sub project
This commit is contained in:
3
.idea/.gitignore
generated
vendored
Normal file
3
.idea/.gitignore
generated
vendored
Normal file
@ -0,0 +1,3 @@
|
||||
# Default ignored files
|
||||
/shelf/
|
||||
/workspace.xml
|
13
.idea/compiler.xml
generated
Normal file
13
.idea/compiler.xml
generated
Normal file
@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="CompilerConfiguration">
|
||||
<annotationProcessing>
|
||||
<profile name="Maven default annotation processors profile" enabled="true">
|
||||
<sourceOutputDir name="target/generated-sources/annotations" />
|
||||
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
|
||||
<outputRelativeToContentRoot value="true" />
|
||||
<module name="cookieGenerator" />
|
||||
</profile>
|
||||
</annotationProcessing>
|
||||
</component>
|
||||
</project>
|
7
.idea/encodings.xml
generated
Normal file
7
.idea/encodings.xml
generated
Normal file
@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="Encoding">
|
||||
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/src/main/resources" charset="UTF-8" />
|
||||
</component>
|
||||
</project>
|
20
.idea/jarRepositories.xml
generated
Normal file
20
.idea/jarRepositories.xml
generated
Normal file
@ -0,0 +1,20 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="RemoteRepositoriesConfiguration">
|
||||
<remote-repository>
|
||||
<option name="id" value="central" />
|
||||
<option name="name" value="Central Repository" />
|
||||
<option name="url" value="https://repo.maven.apache.org/maven2" />
|
||||
</remote-repository>
|
||||
<remote-repository>
|
||||
<option name="id" value="central" />
|
||||
<option name="name" value="Maven Central repository" />
|
||||
<option name="url" value="https://repo1.maven.org/maven2" />
|
||||
</remote-repository>
|
||||
<remote-repository>
|
||||
<option name="id" value="jboss.community" />
|
||||
<option name="name" value="JBoss Community repository" />
|
||||
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
|
||||
</remote-repository>
|
||||
</component>
|
||||
</project>
|
13
.idea/misc.xml
generated
Normal file
13
.idea/misc.xml
generated
Normal file
@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ExternalStorageConfigurationManager" enabled="true" />
|
||||
<component name="MavenProjectsManager">
|
||||
<option name="originalFiles">
|
||||
<list>
|
||||
<option value="$PROJECT_DIR$/pom.xml" />
|
||||
</list>
|
||||
</option>
|
||||
<option name="workspaceImportForciblyTurnedOn" value="true" />
|
||||
</component>
|
||||
<component name="ProjectRootManager" version="2" languageLevel="JDK_21" default="true" project-jdk-name="openjdk-21" project-jdk-type="JavaSDK" />
|
||||
</project>
|
88
Dockerfile
Normal file
88
Dockerfile
Normal file
@ -0,0 +1,88 @@
|
||||
# Stage 1: build jar
|
||||
FROM ubuntu:22.04 AS build
|
||||
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
# Установка Maven
|
||||
RUN apt-get update && \
|
||||
apt-get install -y maven && \
|
||||
apt-get clean && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
RUN apt-get update && \
|
||||
apt-get install -y openjdk-21-jdk && \
|
||||
apt-get clean && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY pom.xml ./
|
||||
|
||||
RUN mvn dependency:go-offline -B
|
||||
|
||||
COPY src src
|
||||
|
||||
RUN mvn clean package -X -DskipTests
|
||||
|
||||
# Stage 2: deploy jar
|
||||
FROM ubuntu:22.04
|
||||
WORKDIR /app
|
||||
|
||||
# Аргумент для версии Chrome (можно переопределить при сборке)
|
||||
ARG CHROME_VERSION="google-chrome-stable"
|
||||
|
||||
# Устанавливаем зависимости и Chrome
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
wget \
|
||||
gnupg \
|
||||
grep \
|
||||
openjdk-21-jdk \
|
||||
libgbm1 \
|
||||
unzip \
|
||||
jq \
|
||||
ca-certificates \
|
||||
fonts-liberation \
|
||||
libu2f-udev \
|
||||
xdg-utils \
|
||||
# Добавляем репозиторий Google Chrome
|
||||
&& wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \
|
||||
&& sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list' \
|
||||
# Устанавливаем Chrome
|
||||
&& apt-get update \
|
||||
&& apt-get install -y --no-install-recommends ${CHROME_VERSION} \
|
||||
# Очищаем кеш apt
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Устанавливаем ChromeDriver, используя jq для парсинга JSON
|
||||
RUN set -e \
|
||||
&& JSON_URL="https://googlechromelabs.github.io/chrome-for-testing/last-known-good-versions-with-downloads.json" \
|
||||
# Выбираем URL для стабильного канала и linux64
|
||||
&& CHROMEDRIVER_URL=$(wget -qO- "${JSON_URL}" | jq -r '.channels.Stable.downloads.chromedriver[] | select(.platform=="linux64") | .url') \
|
||||
&& if [ -z "${CHROMEDRIVER_URL}" ]; then echo "Ошибка: Не удалось получить URL для ChromeDriver из JSON."; exit 1; fi \
|
||||
&& echo "Скачиваем ChromeDriver по адресу: ${CHROMEDRIVER_URL}" \
|
||||
&& wget -q --continue -P /tmp "${CHROMEDRIVER_URL}" \
|
||||
# Распаковываем архив (имя может содержать версию, используем *)
|
||||
&& unzip -q /tmp/*chromedriver-linux64.zip -d /usr/local/bin/ \
|
||||
&& rm -rf /tmp/chromedriver* \
|
||||
# Перемещаем chromedriver из возможной подпапки
|
||||
&& mv /usr/local/bin/chromedriver-linux64/chromedriver /usr/local/bin/chromedriver || true \
|
||||
&& rm -rf /usr/local/bin/chromedriver-linux64 \
|
||||
&& chmod +x /usr/local/bin/chromedriver
|
||||
|
||||
RUN apt-get update && \
|
||||
DEBIAN_FRONTEND=noninteractive apt-get install -y locales && \
|
||||
sed -i '/ru_RU.UTF-8/s/^# //g' /etc/locale.gen && \
|
||||
locale-gen
|
||||
|
||||
ENV LANG=ru_RU.UTF-8 \
|
||||
LC_ALL=ru_RU.UTF-8
|
||||
|
||||
COPY --from=build /app/target/cookieGenerator.jar ./cookieGenerator.jar
|
||||
|
||||
EXPOSE 8080
|
||||
|
||||
# Путь к ChromeDriver уже должен быть найден автоматически в /usr/local/bin
|
||||
|
||||
# Запускаем генератор
|
||||
ENTRYPOINT ["java", "-jar", "cookieGenerator.jar"]
|
4
goodbyedpi/0_russia_update_blacklist_file.cmd
Normal file
4
goodbyedpi/0_russia_update_blacklist_file.cmd
Normal file
@ -0,0 +1,4 @@
|
||||
@ECHO OFF
|
||||
PUSHD "%~dp0"
|
||||
bitsadmin /transfer blacklist https://p.thenewone.lol/domains-export.txt "%CD%\russia-blacklist.txt"
|
||||
POPD
|
11
goodbyedpi/1_russia_blacklist.cmd
Normal file
11
goodbyedpi/1_russia_blacklist.cmd
Normal file
@ -0,0 +1,11 @@
|
||||
@ECHO OFF
|
||||
PUSHD "%~dp0"
|
||||
set _arch=x86
|
||||
IF "%PROCESSOR_ARCHITECTURE%"=="AMD64" (set _arch=x86_64)
|
||||
IF DEFINED PROCESSOR_ARCHITEW6432 (set _arch=x86_64)
|
||||
PUSHD "%_arch%"
|
||||
|
||||
start "" goodbyedpi.exe -9 --blacklist ..\russia-blacklist.txt --blacklist ..\russia-youtube.txt
|
||||
|
||||
POPD
|
||||
POPD
|
11
goodbyedpi/1_russia_blacklist_YOUTUBE.cmd
Normal file
11
goodbyedpi/1_russia_blacklist_YOUTUBE.cmd
Normal file
@ -0,0 +1,11 @@
|
||||
@ECHO OFF
|
||||
PUSHD "%~dp0"
|
||||
set _arch=x86
|
||||
IF "%PROCESSOR_ARCHITECTURE%"=="AMD64" (set _arch=x86_64)
|
||||
IF DEFINED PROCESSOR_ARCHITEW6432 (set _arch=x86_64)
|
||||
PUSHD "%_arch%"
|
||||
|
||||
start "" goodbyedpi.exe -9 --fake-gen 5 --blacklist ..\russia-blacklist.txt --blacklist ..\russia-youtube.txt
|
||||
|
||||
POPD
|
||||
POPD
|
11
goodbyedpi/1_russia_blacklist_YOUTUBE_ALT.cmd
Normal file
11
goodbyedpi/1_russia_blacklist_YOUTUBE_ALT.cmd
Normal file
@ -0,0 +1,11 @@
|
||||
@ECHO OFF
|
||||
PUSHD "%~dp0"
|
||||
set _arch=x86
|
||||
IF "%PROCESSOR_ARCHITECTURE%"=="AMD64" (set _arch=x86_64)
|
||||
IF DEFINED PROCESSOR_ARCHITEW6432 (set _arch=x86_64)
|
||||
PUSHD "%_arch%"
|
||||
|
||||
start "" goodbyedpi.exe -5 -e1 -q --fake-gen 5 --blacklist ..\russia-blacklist.txt --blacklist ..\russia-youtube.txt
|
||||
|
||||
POPD
|
||||
POPD
|
11
goodbyedpi/1_russia_blacklist_dnsredir.cmd
Normal file
11
goodbyedpi/1_russia_blacklist_dnsredir.cmd
Normal file
@ -0,0 +1,11 @@
|
||||
@ECHO OFF
|
||||
PUSHD "%~dp0"
|
||||
set _arch=x86
|
||||
IF "%PROCESSOR_ARCHITECTURE%"=="AMD64" (set _arch=x86_64)
|
||||
IF DEFINED PROCESSOR_ARCHITEW6432 (set _arch=x86_64)
|
||||
PUSHD "%_arch%"
|
||||
|
||||
start "" goodbyedpi.exe -9 --dns-addr 77.88.8.8 --dns-port 1253 --dnsv6-addr 2a02:6b8::feed:0ff --dnsv6-port 1253 --blacklist ..\russia-blacklist.txt --blacklist ..\russia-youtube.txt
|
||||
|
||||
POPD
|
||||
POPD
|
11
goodbyedpi/2_any_country.cmd
Normal file
11
goodbyedpi/2_any_country.cmd
Normal file
@ -0,0 +1,11 @@
|
||||
@ECHO OFF
|
||||
PUSHD "%~dp0"
|
||||
set _arch=x86
|
||||
IF "%PROCESSOR_ARCHITECTURE%"=="AMD64" (set _arch=x86_64)
|
||||
IF DEFINED PROCESSOR_ARCHITEW6432 (set _arch=x86_64)
|
||||
PUSHD "%_arch%"
|
||||
|
||||
start "" goodbyedpi.exe -9
|
||||
|
||||
POPD
|
||||
POPD
|
11
goodbyedpi/2_any_country_dnsredir.cmd
Normal file
11
goodbyedpi/2_any_country_dnsredir.cmd
Normal file
@ -0,0 +1,11 @@
|
||||
@ECHO OFF
|
||||
PUSHD "%~dp0"
|
||||
set _arch=x86
|
||||
IF "%PROCESSOR_ARCHITECTURE%"=="AMD64" (set _arch=x86_64)
|
||||
IF DEFINED PROCESSOR_ARCHITEW6432 (set _arch=x86_64)
|
||||
PUSHD "%_arch%"
|
||||
|
||||
start "" goodbyedpi.exe -9 --dns-addr 77.88.8.8 --dns-port 1253 --dnsv6-addr 2a02:6b8::feed:0ff --dnsv6-port 1253
|
||||
|
||||
POPD
|
||||
POPD
|
28
goodbyedpi/licenses/LICENSE-getline.txt
Normal file
28
goodbyedpi/licenses/LICENSE-getline.txt
Normal file
@ -0,0 +1,28 @@
|
||||
/*-
|
||||
* Copyright (c) 2011 The NetBSD Foundation, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This code is derived from software contributed to The NetBSD Foundation
|
||||
* by Christos Zoulas.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
|
||||
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
|
||||
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
|
||||
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
201
goodbyedpi/licenses/LICENSE-goodbyedpi.txt
Normal file
201
goodbyedpi/licenses/LICENSE-goodbyedpi.txt
Normal file
@ -0,0 +1,201 @@
|
||||
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 {yyyy} {name of copyright owner}
|
||||
|
||||
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.
|
21
goodbyedpi/licenses/LICENSE-uthash.txt
Normal file
21
goodbyedpi/licenses/LICENSE-uthash.txt
Normal file
@ -0,0 +1,21 @@
|
||||
Copyright (c) 2005-2014, Troy D. Hanson http://troydhanson.github.com/uthash/
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
|
||||
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
|
||||
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
|
||||
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
|
||||
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
||||
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
||||
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
787
goodbyedpi/licenses/LICENSE-windivert.txt
Normal file
787
goodbyedpi/licenses/LICENSE-windivert.txt
Normal file
@ -0,0 +1,787 @@
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
|
||||
This version of the GNU Lesser General Public License incorporates
|
||||
the terms and conditions of version 3 of the GNU General Public
|
||||
License, supplemented by the additional permissions listed below.
|
||||
|
||||
0. Additional Definitions.
|
||||
|
||||
As used herein, "this License" refers to version 3 of the GNU Lesser
|
||||
General Public License, and the "GNU GPL" refers to version 3 of the GNU
|
||||
General Public License.
|
||||
|
||||
"The Library" refers to a covered work governed by this License,
|
||||
other than an Application or a Combined Work as defined below.
|
||||
|
||||
An "Application" is any work that makes use of an interface provided
|
||||
by the Library, but which is not otherwise based on the Library.
|
||||
Defining a subclass of a class defined by the Library is deemed a mode
|
||||
of using an interface provided by the Library.
|
||||
|
||||
A "Combined Work" is a work produced by combining or linking an
|
||||
Application with the Library. The particular version of the Library
|
||||
with which the Combined Work was made is also called the "Linked
|
||||
Version".
|
||||
|
||||
The "Minimal Corresponding Source" for a Combined Work means the
|
||||
Corresponding Source for the Combined Work, excluding any source code
|
||||
for portions of the Combined Work that, considered in isolation, are
|
||||
based on the Application, and not on the Linked Version.
|
||||
|
||||
The "Corresponding Application Code" for a Combined Work means the
|
||||
object code and/or source code for the Application, including any data
|
||||
and utility programs needed for reproducing the Combined Work from the
|
||||
Application, but excluding the System Libraries of the Combined Work.
|
||||
|
||||
1. Exception to Section 3 of the GNU GPL.
|
||||
|
||||
You may convey a covered work under sections 3 and 4 of this License
|
||||
without being bound by section 3 of the GNU GPL.
|
||||
|
||||
2. Conveying Modified Versions.
|
||||
|
||||
If you modify a copy of the Library, and, in your modifications, a
|
||||
facility refers to a function or data to be supplied by an Application
|
||||
that uses the facility (other than as an argument passed when the
|
||||
facility is invoked), then you may convey a copy of the modified
|
||||
version:
|
||||
|
||||
a) under this License, provided that you make a good faith effort to
|
||||
ensure that, in the event an Application does not supply the
|
||||
function or data, the facility still operates, and performs
|
||||
whatever part of its purpose remains meaningful, or
|
||||
|
||||
b) under the GNU GPL, with none of the additional permissions of
|
||||
this License applicable to that copy.
|
||||
|
||||
3. Object Code Incorporating Material from Library Header Files.
|
||||
|
||||
The object code form of an Application may incorporate material from
|
||||
a header file that is part of the Library. You may convey such object
|
||||
code under terms of your choice, provided that, if the incorporated
|
||||
material is not limited to numerical parameters, data structure
|
||||
layouts and accessors, or small macros, inline functions and templates
|
||||
(ten or fewer lines in length), you do both of the following:
|
||||
|
||||
a) Give prominent notice with each copy of the object code that the
|
||||
Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
|
||||
b) Accompany the object code with a copy of the GNU GPL and this license
|
||||
document.
|
||||
|
||||
4. Combined Works.
|
||||
|
||||
You may convey a Combined Work under terms of your choice that,
|
||||
taken together, effectively do not restrict modification of the
|
||||
portions of the Library contained in the Combined Work and reverse
|
||||
engineering for debugging such modifications, if you also do each of
|
||||
the following:
|
||||
|
||||
a) Give prominent notice with each copy of the Combined Work that
|
||||
the Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
|
||||
b) Accompany the Combined Work with a copy of the GNU GPL and this license
|
||||
document.
|
||||
|
||||
c) For a Combined Work that displays copyright notices during
|
||||
execution, include the copyright notice for the Library among
|
||||
these notices, as well as a reference directing the user to the
|
||||
copies of the GNU GPL and this license document.
|
||||
|
||||
d) Do one of the following:
|
||||
|
||||
0) Convey the Minimal Corresponding Source under the terms of this
|
||||
License, and the Corresponding Application Code in a form
|
||||
suitable for, and under terms that permit, the user to
|
||||
recombine or relink the Application with a modified version of
|
||||
the Linked Version to produce a modified Combined Work, in the
|
||||
manner specified by section 6 of the GNU GPL for conveying
|
||||
Corresponding Source.
|
||||
|
||||
1) Use a suitable shared library mechanism for linking with the
|
||||
Library. A suitable mechanism is one that (a) uses at run time
|
||||
a copy of the Library already present on the user's computer
|
||||
system, and (b) will operate properly with a modified version
|
||||
of the Library that is interface-compatible with the Linked
|
||||
Version.
|
||||
|
||||
e) Provide Installation Information, but only if you would otherwise
|
||||
be required to provide such information under section 6 of the
|
||||
GNU GPL, and only to the extent that such information is
|
||||
necessary to install and execute a modified version of the
|
||||
Combined Work produced by recombining or relinking the
|
||||
Application with a modified version of the Linked Version. (If
|
||||
you use option 4d0, the Installation Information must accompany
|
||||
the Minimal Corresponding Source and Corresponding Application
|
||||
Code. If you use option 4d1, you must provide the Installation
|
||||
Information in the manner specified by section 6 of the GNU GPL
|
||||
for conveying Corresponding Source.)
|
||||
|
||||
5. Combined Libraries.
|
||||
|
||||
You may place library facilities that are a work based on the
|
||||
Library side by side in a single library together with other library
|
||||
facilities that are not Applications and are not covered by this
|
||||
License, and convey such a combined library under terms of your
|
||||
choice, if you do both of the following:
|
||||
|
||||
a) Accompany the combined library with a copy of the same work based
|
||||
on the Library, uncombined with any other library facilities,
|
||||
conveyed under the terms of this License.
|
||||
|
||||
b) Give prominent notice with the combined library that part of it
|
||||
is a work based on the Library, and explaining where to find the
|
||||
accompanying uncombined form of the same work.
|
||||
|
||||
6. Revised Versions of the GNU Lesser General Public License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions
|
||||
of the GNU Lesser General Public License from time to time. Such new
|
||||
versions will be similar in spirit to the present version, but may
|
||||
differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Library as you received it specifies that a certain numbered version
|
||||
of the GNU Lesser General Public License "or any later version"
|
||||
applies to it, you have the option of following the terms and
|
||||
conditions either of that published version or of any later version
|
||||
published by the Free Software Foundation. If the Library as you
|
||||
received it does not specify a version number of the GNU Lesser
|
||||
General Public License, you may choose any version of the GNU Lesser
|
||||
General Public License ever published by the Free Software Foundation.
|
||||
|
||||
If the Library as you received it specifies that a proxy can decide
|
||||
whether future versions of the GNU Lesser General Public License shall
|
||||
apply, that proxy's public statement of acceptance of any version is
|
||||
permanent authorization for you to choose that version for the
|
||||
Library.
|
||||
|
||||
------------------------------------------------------------------------------
|
||||
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
154038
goodbyedpi/russia-blacklist.txt
Normal file
154038
goodbyedpi/russia-blacklist.txt
Normal file
File diff suppressed because it is too large
Load Diff
14
goodbyedpi/russia-youtube.txt
Normal file
14
goodbyedpi/russia-youtube.txt
Normal file
@ -0,0 +1,14 @@
|
||||
youtube.com
|
||||
youtu.be
|
||||
yt.be
|
||||
googlevideo.com
|
||||
ytimg.com
|
||||
ggpht.com
|
||||
gvt1.com
|
||||
youtube-nocookie.com
|
||||
youtube-ui.l.google.com
|
||||
youtubeembeddedplayer.googleapis.com
|
||||
youtube.googleapis.com
|
||||
youtubei.googleapis.com
|
||||
yt-video-upload.l.google.com
|
||||
wide-youtube.l.google.com
|
17
goodbyedpi/service_install_russia_blacklist.cmd
Normal file
17
goodbyedpi/service_install_russia_blacklist.cmd
Normal file
@ -0,0 +1,17 @@
|
||||
@ECHO OFF
|
||||
PUSHD "%~dp0"
|
||||
set _arch=x86
|
||||
IF "%PROCESSOR_ARCHITECTURE%"=="AMD64" (set _arch=x86_64)
|
||||
IF DEFINED PROCESSOR_ARCHITEW6432 (set _arch=x86_64)
|
||||
|
||||
echo This script should be run with administrator privileges.
|
||||
echo Right click - run as administrator.
|
||||
echo Press any key if you're running it as administrator.
|
||||
pause
|
||||
sc stop "GoodbyeDPI"
|
||||
sc delete "GoodbyeDPI"
|
||||
sc create "GoodbyeDPI" binPath= "\"%CD%\%_arch%\goodbyedpi.exe\" -9 --blacklist \"%CD%\russia-blacklist.txt\" --blacklist \"%CD%\russia-youtube.txt\"" start= "auto"
|
||||
sc description "GoodbyeDPI" "Passive Deep Packet Inspection blocker and Active DPI circumvention utility"
|
||||
sc start "GoodbyeDPI"
|
||||
|
||||
POPD
|
17
goodbyedpi/service_install_russia_blacklist_YOUTUBE.cmd
Normal file
17
goodbyedpi/service_install_russia_blacklist_YOUTUBE.cmd
Normal file
@ -0,0 +1,17 @@
|
||||
@ECHO OFF
|
||||
PUSHD "%~dp0"
|
||||
set _arch=x86
|
||||
IF "%PROCESSOR_ARCHITECTURE%"=="AMD64" (set _arch=x86_64)
|
||||
IF DEFINED PROCESSOR_ARCHITEW6432 (set _arch=x86_64)
|
||||
|
||||
echo This script should be run with administrator privileges.
|
||||
echo Right click - run as administrator.
|
||||
echo Press any key if you're running it as administrator.
|
||||
pause
|
||||
sc stop "GoodbyeDPI"
|
||||
sc delete "GoodbyeDPI"
|
||||
sc create "GoodbyeDPI" binPath= "\"%CD%\%_arch%\goodbyedpi.exe\" -9 --fake-gen 5 --blacklist \"%CD%\russia-blacklist.txt\" --blacklist \"%CD%\russia-youtube.txt\"" start= "auto"
|
||||
sc description "GoodbyeDPI" "Passive Deep Packet Inspection blocker and Active DPI circumvention utility"
|
||||
sc start "GoodbyeDPI"
|
||||
|
||||
POPD
|
17
goodbyedpi/service_install_russia_blacklist_YOUTUBE_ALT.cmd
Normal file
17
goodbyedpi/service_install_russia_blacklist_YOUTUBE_ALT.cmd
Normal file
@ -0,0 +1,17 @@
|
||||
@ECHO OFF
|
||||
PUSHD "%~dp0"
|
||||
set _arch=x86
|
||||
IF "%PROCESSOR_ARCHITECTURE%"=="AMD64" (set _arch=x86_64)
|
||||
IF DEFINED PROCESSOR_ARCHITEW6432 (set _arch=x86_64)
|
||||
|
||||
echo This script should be run with administrator privileges.
|
||||
echo Right click - run as administrator.
|
||||
echo Press any key if you're running it as administrator.
|
||||
pause
|
||||
sc stop "GoodbyeDPI"
|
||||
sc delete "GoodbyeDPI"
|
||||
sc create "GoodbyeDPI" binPath= "\"%CD%\%_arch%\goodbyedpi.exe\" -5 -e1 -q --fake-gen 5 --blacklist \"%CD%\russia-blacklist.txt\" --blacklist \"%CD%\russia-youtube.txt\"" start= "auto"
|
||||
sc description "GoodbyeDPI" "Passive Deep Packet Inspection blocker and Active DPI circumvention utility"
|
||||
sc start "GoodbyeDPI"
|
||||
|
||||
POPD
|
17
goodbyedpi/service_install_russia_blacklist_dnsredir.cmd
Normal file
17
goodbyedpi/service_install_russia_blacklist_dnsredir.cmd
Normal file
@ -0,0 +1,17 @@
|
||||
@ECHO OFF
|
||||
PUSHD "%~dp0"
|
||||
set _arch=x86
|
||||
IF "%PROCESSOR_ARCHITECTURE%"=="AMD64" (set _arch=x86_64)
|
||||
IF DEFINED PROCESSOR_ARCHITEW6432 (set _arch=x86_64)
|
||||
|
||||
echo This script should be run with administrator privileges.
|
||||
echo Right click - run as administrator.
|
||||
echo Press any key if you're running it as administrator.
|
||||
pause
|
||||
sc stop "GoodbyeDPI"
|
||||
sc delete "GoodbyeDPI"
|
||||
sc create "GoodbyeDPI" binPath= "\"%CD%\%_arch%\goodbyedpi.exe\" -9 --dns-addr 77.88.8.8 --dns-port 1253 --dnsv6-addr 2a02:6b8::feed:0ff --dnsv6-port 1253 --blacklist \"%CD%\russia-blacklist.txt\" --blacklist \"%CD%\russia-youtube.txt\"" start= "auto"
|
||||
sc description "GoodbyeDPI" "Passive Deep Packet Inspection blocker and Active DPI circumvention utility"
|
||||
sc start "GoodbyeDPI"
|
||||
|
||||
POPD
|
11
goodbyedpi/service_remove.cmd
Normal file
11
goodbyedpi/service_remove.cmd
Normal file
@ -0,0 +1,11 @@
|
||||
@ECHO OFF
|
||||
echo This script should be run with administrator privileges.
|
||||
echo Right click - run as administrator.
|
||||
echo Press any key if you're running it as administrator.
|
||||
pause
|
||||
sc stop "GoodbyeDPI"
|
||||
sc delete "GoodbyeDPI"
|
||||
sc stop "WinDivert"
|
||||
sc delete "WinDivert"
|
||||
sc stop "WinDivert14"
|
||||
sc delete "WinDivert14"
|
BIN
goodbyedpi/x86/WinDivert.dll
Normal file
BIN
goodbyedpi/x86/WinDivert.dll
Normal file
Binary file not shown.
180
pom.xml
Normal file
180
pom.xml
Normal file
@ -0,0 +1,180 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.google.accountgen</groupId>
|
||||
<artifactId>cookieGenerator</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>17</maven.compiler.source>
|
||||
<maven.compiler.target>17</maven.compiler.target>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<selenium.version>4.31.0</selenium.version>
|
||||
<webdrivermanager.version>5.6.2</webdrivermanager.version>
|
||||
<okhttp.version>4.12.0</okhttp.version>
|
||||
<jackson.version>2.16.1</jackson.version>
|
||||
<slf4j.version>2.0.9</slf4j.version>
|
||||
</properties>
|
||||
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<dependencies>
|
||||
<!-- Selenium WebDriver для управления браузером -->
|
||||
<dependency>
|
||||
<groupId>org.seleniumhq.selenium</groupId>
|
||||
<artifactId>selenium-java</artifactId>
|
||||
<version>${selenium.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- WebDriverManager для автоматического управления драйверами -->
|
||||
<dependency>
|
||||
<groupId>io.github.bonigarcia</groupId>
|
||||
<artifactId>webdrivermanager</artifactId>
|
||||
<version>${webdrivermanager.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.code.gson</groupId>
|
||||
<artifactId>gson</artifactId>
|
||||
<version>2.10.1</version>
|
||||
</dependency>
|
||||
|
||||
<!-- OkHttp для HTTP запросов в CaptchaSolver и RandomUserGenerator -->
|
||||
<dependency>
|
||||
<groupId>com.squareup.okhttp3</groupId>
|
||||
<artifactId>okhttp</artifactId>
|
||||
<version>${okhttp.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- SLF4J API и Logback для логирования -->
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>${slf4j.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Jackson для работы с JSON -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- HTTP клиент для API запросов -->
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents.client5</groupId>
|
||||
<artifactId>httpclient5</artifactId>
|
||||
<version>5.2.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>1.18.30</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.json</groupId>
|
||||
<artifactId>json</artifactId>
|
||||
<version>20231013</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-simple</artifactId>
|
||||
<version>2.0.9</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-quartz</artifactId>
|
||||
<version>3.4.2</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-core</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.nats</groupId>
|
||||
<artifactId>jnats</artifactId>
|
||||
<version>2.20.5</version>
|
||||
</dependency>
|
||||
<!-- Возвращаем явную зависимость devtools v135 -->
|
||||
<dependency>
|
||||
<groupId>org.seleniumhq.selenium</groupId>
|
||||
<artifactId>selenium-devtools-v135</artifactId>
|
||||
<version>${selenium.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>cookieGenerator</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.11.0</version>
|
||||
<configuration>
|
||||
<source>${maven.compiler.source}</source>
|
||||
<target>${maven.compiler.target}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-assembly-plugin</artifactId>
|
||||
<version>3.6.0</version>
|
||||
<configuration>
|
||||
<descriptorRefs>
|
||||
<descriptorRef>jar-with-dependencies</descriptorRef>
|
||||
</descriptorRefs>
|
||||
<archive>
|
||||
<manifest>
|
||||
<mainClass>com.google.accountgen.CookieGenerator</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>make-assembly</id>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>single</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<!-- Добавляем exec-maven-plugin -->
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>3.1.0</version> <!-- Используйте актуальную версию -->
|
||||
<configuration>
|
||||
<mainClass>com.google.accountgen.CookieGenerator</mainClass>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<version>3.4.0</version>
|
||||
<configuration>
|
||||
<mainClass>com.google.accountgen.CookieGenerator</mainClass>
|
||||
<layout>JAR</layout>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>repackage</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
16
proxyLogin/Dockerfile
Normal file
16
proxyLogin/Dockerfile
Normal file
@ -0,0 +1,16 @@
|
||||
FROM node:10-buster-slim
|
||||
RUN apt-get update
|
||||
RUN apt-get install bash
|
||||
RUN apt-get clean
|
||||
RUN npm install -g proxy-login-automator
|
||||
COPY launcher.sh ./
|
||||
|
||||
EXPOSE 8080-9080
|
||||
|
||||
ENV REMOTE_HOST=pool.proxy.market:10000
|
||||
ENV REMOTE_USER=MNj9l11mZZQA
|
||||
ENV REMOTE_PASSWORD=RNW78Fm5
|
||||
ENV REMOTE_HTTPS=true
|
||||
ENV INGORE_CERT=false
|
||||
|
||||
CMD ["bash", "launcher.sh"]
|
46
proxyLogin/launcher.sh
Normal file
46
proxyLogin/launcher.sh
Normal file
@ -0,0 +1,46 @@
|
||||
#! /bin/bash
|
||||
set -euo pipefail
|
||||
|
||||
env
|
||||
|
||||
# Check environment
|
||||
if [ -n "${GET_REMOTE_HOST}" ]; then
|
||||
echo "GET_REMOTE_HOST script was supplied evaluating, and overriding REMOTE_HOST variable"
|
||||
REMOTE_HOST=$(eval ${GET_REMOTE_HOST})
|
||||
fi
|
||||
|
||||
if [ -z "${REMOTE_HOST}" ]; then
|
||||
echo "REMOTE_HOST was not set"
|
||||
fi
|
||||
|
||||
if [ -z "${REMOTE_USER}" ]; then
|
||||
echo "REMOTE_USER was not set"
|
||||
fi
|
||||
|
||||
if [ -z "${REMOTE_PASSWORD}" ]; then
|
||||
echo "REMOTE_PASSWORD was not set"
|
||||
fi
|
||||
|
||||
LOCAL_PORT=8080
|
||||
for HOST_AND_PORT in $(echo $REMOTE_HOST| sed "s/,/ /g")
|
||||
do
|
||||
if [ -z "${HOST_AND_PORT}" ]; then
|
||||
continue
|
||||
fi
|
||||
|
||||
HOST=$(echo $HOST_AND_PORT | cut -f1 -d:)
|
||||
PORT=$(echo $HOST_AND_PORT | cut -f2 -d:)
|
||||
|
||||
proxy-login-automator \
|
||||
-local_port $LOCAL_PORT \
|
||||
-local_host 0.0.0.0 \
|
||||
-remote_host $HOST \
|
||||
-remote_port $PORT \
|
||||
-usr $REMOTE_USER -pwd $REMOTE_PASSWORD \
|
||||
-is_remote_https $REMOTE_HTTPS \
|
||||
-ignore_https_cert $IGNORE_CERT &
|
||||
|
||||
LOCAL_PORT=$((LOCAL_PORT + 1))
|
||||
done
|
||||
|
||||
wait
|
25
src/main/java/com/google/accountgen/CookieGenerator.java
Normal file
25
src/main/java/com/google/accountgen/CookieGenerator.java
Normal file
@ -0,0 +1,25 @@
|
||||
package com.google.accountgen;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.scheduling.annotation.EnableAsync;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
|
||||
/**
|
||||
* Основной класс для запуска генератора Google аккаунтов
|
||||
*/
|
||||
@SpringBootApplication
|
||||
@EnableScheduling
|
||||
@EnableAsync
|
||||
public class CookieGenerator
|
||||
{
|
||||
|
||||
|
||||
public static void main(String[] args)
|
||||
{
|
||||
SpringApplication.run(CookieGenerator.class, args);
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
199
src/main/java/com/google/accountgen/Task.java
Normal file
199
src/main/java/com/google/accountgen/Task.java
Normal file
@ -0,0 +1,199 @@
|
||||
package com.google.accountgen;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.google.accountgen.account.AccountResult;
|
||||
import com.google.accountgen.account.GoogleAccountGeneratorImpl;
|
||||
import com.google.accountgen.proxy.ProxyManager;
|
||||
import io.nats.client.Connection;
|
||||
import io.nats.client.Nats;
|
||||
import io.nats.client.Options;
|
||||
import io.nats.client.impl.NatsMessage;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.scheduling.annotation.Async;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashMap;
|
||||
|
||||
@Component
|
||||
public class Task
|
||||
{
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(Task.class);
|
||||
private static final ObjectMapper mapper = new ObjectMapper();
|
||||
private static final String API_URL = "https://papaproxy.net/api/getproxy/?action=setip&login=%s&password=%s&ip=%s";
|
||||
private static final Options natsOptions = new Options.Builder().server(
|
||||
"nats://s0ig38O8yewiMyd7oHKKYO4bih6SKY4l@nats.ricktech.ru:4222").build();
|
||||
@Value("${sms_activate_api_key}")
|
||||
private String smsActivateKey;
|
||||
@Value("${captcha_api_key}")
|
||||
private String captchaKey;
|
||||
@Value("${captcha_service_type}")
|
||||
private String captchaServiceType;
|
||||
@Value("${use_goodbyedpi}")
|
||||
private String useDPI;
|
||||
@Value("${goodbyedpi_path}")
|
||||
private String dpiPath;
|
||||
@Value("${retry_count}")
|
||||
private String retryCount;
|
||||
@Value("${account_count}")
|
||||
private int accountCount;
|
||||
@Value("${delay_between_attempts}")
|
||||
private int delayMs;
|
||||
@Autowired
|
||||
private GoogleAccountGeneratorImpl generator;
|
||||
@Autowired
|
||||
private ProxyManager proxyManager;
|
||||
@Value("${proxyLogin}")
|
||||
private String proxyLogin;
|
||||
|
||||
@Value("${proxyPass}")
|
||||
private String proxypass;
|
||||
|
||||
|
||||
|
||||
@Scheduled(fixedRate = 24 * 60 * 60 * 1000)
|
||||
@Async
|
||||
public void generateProfileMeta()
|
||||
{
|
||||
logger.info("Запуск генератора Google аккаунтов");
|
||||
linkProxy();
|
||||
proxyManager.init();
|
||||
|
||||
logConfiguration();
|
||||
|
||||
|
||||
// Автоматическая генерация аккаунтов с ротацией прокси
|
||||
for (int i = 0; i < accountCount; i++)
|
||||
{
|
||||
logger.info("Автоматическая генерация аккаунта {}/{}", i + 1, accountCount);
|
||||
AccountResult result = generator.generateAccount();
|
||||
if (result.isSuccess())
|
||||
{
|
||||
logger.info("Аккаунт {} успешно создан и сохранен генератором", i + 1);
|
||||
publish(result.getEmail(), result.getCookiesNetscape(), result.getPotToken());
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.error("Ошибка при создании аккаунта {}: {}", i + 1, result.getErrorMessage());
|
||||
}
|
||||
// Задержка перед следующей попыткой генерации
|
||||
try
|
||||
{
|
||||
Thread.sleep(delayMs);
|
||||
}
|
||||
catch (InterruptedException e)
|
||||
{
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static String sendRequest(String urlString) throws Exception
|
||||
{
|
||||
URL url = new URL(urlString.replace(" ", "%20")); // Кодируем пробелы на всякий случай
|
||||
HttpURLConnection con = (HttpURLConnection) url.openConnection();
|
||||
con.setRequestMethod("GET");
|
||||
con.setConnectTimeout(15000); // Таймаут соединения 15 сек
|
||||
con.setReadTimeout(15000); // Таймаут чтения 15 сек
|
||||
|
||||
int status = con.getResponseCode();
|
||||
BufferedReader in = new BufferedReader(
|
||||
new InputStreamReader((status == 200) ? con.getInputStream() : con.getErrorStream(),
|
||||
StandardCharsets.UTF_8));
|
||||
String inputLine;
|
||||
StringBuilder content = new StringBuilder();
|
||||
while ((inputLine = in.readLine()) != null)
|
||||
{
|
||||
content.append(inputLine);
|
||||
}
|
||||
in.close();
|
||||
con.disconnect();
|
||||
|
||||
if (status != 200)
|
||||
{
|
||||
logger.error("Ошибка HTTP запроса к API: статус {}, Ответ: {}", status, content);
|
||||
}
|
||||
|
||||
return content.toString();
|
||||
}
|
||||
|
||||
private void publish(String email, String cookieString, String poToken)
|
||||
{
|
||||
HashMap<String, String> data = new HashMap<>();
|
||||
data.put("cookie", cookieString);
|
||||
data.put("token", poToken);
|
||||
data.put("login", email.substring(0, email.indexOf('@')));
|
||||
|
||||
try (Connection connect = Nats.connect(natsOptions))
|
||||
{
|
||||
String dataString = mapper.writeValueAsString(data);
|
||||
|
||||
NatsMessage message = NatsMessage.builder().subject("cookies.data").data(dataString, StandardCharsets.UTF_8)
|
||||
.build();
|
||||
connect.publish(message);
|
||||
}
|
||||
catch (IOException | InterruptedException e)
|
||||
{
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private void logConfiguration()
|
||||
{
|
||||
logger.info("Конфигурация:");
|
||||
logger.info("- API ключ SMS: {}...", hideKey(smsActivateKey));
|
||||
logger.info("- API ключ CAPTCHA: {}...", hideKey(captchaKey));
|
||||
logger.info("- Сервис CAPTCHA: {}", captchaServiceType);
|
||||
logger.info("- Использовать GoodbyeDPI: {}", useDPI);
|
||||
logger.info("- Путь GoodbyeDPI: {}", dpiPath);
|
||||
logger.info("- Количество попыток верификации: {}", retryCount);
|
||||
logger.info("- Таймаут ожидания SMS: {} мс", 10000);
|
||||
}
|
||||
|
||||
private String hideKey(String key)
|
||||
{
|
||||
if (key == null || key.length() < 8)
|
||||
{
|
||||
return key;
|
||||
}
|
||||
return key.substring(0, 4) + "..." + key.substring(key.length() - 4);
|
||||
}
|
||||
|
||||
private void linkProxy()
|
||||
{
|
||||
try
|
||||
{
|
||||
String myIP = getPublicIP();
|
||||
String fullUrl = String.format(API_URL, proxyLogin, proxypass, myIP);
|
||||
sendRequest(fullUrl);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private String getPublicIP() throws IOException
|
||||
{
|
||||
String urlString = "http://checkip.amazonaws.com/";
|
||||
URL url = new URL(urlString);
|
||||
try (BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()))) {
|
||||
return br.readLine();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
171
src/main/java/com/google/accountgen/account/AccountResult.java
Normal file
171
src/main/java/com/google/accountgen/account/AccountResult.java
Normal file
@ -0,0 +1,171 @@
|
||||
package com.google.accountgen.account;
|
||||
|
||||
/**
|
||||
* Модель результата генерации аккаунта, содержащая все
|
||||
* необходимые данные и статус операции.
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
public class AccountResult
|
||||
{
|
||||
private String email;
|
||||
private String password;
|
||||
private String potToken;
|
||||
private String cookiesNetscape;
|
||||
private String proxyUsed;
|
||||
private boolean success;
|
||||
private String errorMessage;
|
||||
private String accountData;
|
||||
private String cookies;
|
||||
private String message;
|
||||
|
||||
// Конструктор по умолчанию
|
||||
public AccountResult()
|
||||
{
|
||||
this.success = false;
|
||||
}
|
||||
|
||||
// Конструктор для успешного результата
|
||||
public AccountResult(String email, String password, String potToken, String cookiesNetscape, String proxyUsed)
|
||||
{
|
||||
this.email = email;
|
||||
this.password = password;
|
||||
this.potToken = potToken;
|
||||
this.cookiesNetscape = cookiesNetscape;
|
||||
this.proxyUsed = proxyUsed;
|
||||
this.success = true;
|
||||
this.errorMessage = null;
|
||||
}
|
||||
|
||||
// Геттеры и сеттеры
|
||||
public String getEmail()
|
||||
{
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email)
|
||||
{
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public String getPassword()
|
||||
{
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password)
|
||||
{
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public String getPotToken()
|
||||
{
|
||||
return potToken;
|
||||
}
|
||||
|
||||
public void setPotToken(String potToken)
|
||||
{
|
||||
this.potToken = potToken;
|
||||
}
|
||||
|
||||
public String getCookiesNetscape()
|
||||
{
|
||||
return cookiesNetscape;
|
||||
}
|
||||
|
||||
public void setCookiesNetscape(String cookiesNetscape)
|
||||
{
|
||||
this.cookiesNetscape = cookiesNetscape;
|
||||
}
|
||||
|
||||
public String getProxyUsed()
|
||||
{
|
||||
return proxyUsed;
|
||||
}
|
||||
|
||||
public void setProxyUsed(String proxyUsed)
|
||||
{
|
||||
this.proxyUsed = proxyUsed;
|
||||
}
|
||||
|
||||
public boolean isSuccess()
|
||||
{
|
||||
return success;
|
||||
}
|
||||
|
||||
public void setSuccess(boolean success)
|
||||
{
|
||||
this.success = success;
|
||||
}
|
||||
|
||||
public String getErrorMessage()
|
||||
{
|
||||
return errorMessage;
|
||||
}
|
||||
|
||||
public void setErrorMessage(String errorMessage)
|
||||
{
|
||||
this.errorMessage = errorMessage;
|
||||
}
|
||||
|
||||
public String getAccountData()
|
||||
{
|
||||
return accountData;
|
||||
}
|
||||
|
||||
public void setAccountData(String accountData)
|
||||
{
|
||||
this.accountData = accountData;
|
||||
}
|
||||
|
||||
public String getCookies()
|
||||
{
|
||||
return cookies;
|
||||
}
|
||||
|
||||
public void setCookies(String cookies)
|
||||
{
|
||||
this.cookies = cookies;
|
||||
}
|
||||
|
||||
public String getMessage()
|
||||
{
|
||||
return message;
|
||||
}
|
||||
|
||||
public void setMessage(String message)
|
||||
{
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString()
|
||||
{
|
||||
if (success)
|
||||
{
|
||||
return "AccountResult{" + "email='" + email + '\'' + ", password='" + password + '\'' + ", potToken='" + potToken + '\'' + ", proxyUsed='" + proxyUsed + '\'' + ", success=" + true + '}';
|
||||
}
|
||||
else
|
||||
{
|
||||
return "AccountResult{" + "errorMessage='" + errorMessage + '\'' + ", success=" + false + '}';
|
||||
}
|
||||
}
|
||||
|
||||
// Статический метод для успешного результата
|
||||
public static AccountResult success(String accountData)
|
||||
{
|
||||
AccountResult result = new AccountResult();
|
||||
result.setSuccess(true);
|
||||
result.setAccountData(accountData);
|
||||
// Можно парсить email/пароль из accountData, если нужно
|
||||
return result;
|
||||
}
|
||||
|
||||
// Статический метод для неуспешного результата
|
||||
public static AccountResult failure(String errorMessage)
|
||||
{
|
||||
AccountResult result = new AccountResult();
|
||||
result.setSuccess(false);
|
||||
result.setErrorMessage(errorMessage);
|
||||
return result;
|
||||
}
|
||||
}
|
@ -0,0 +1,67 @@
|
||||
package com.google.accountgen.account;
|
||||
|
||||
/**
|
||||
* Класс, представляющий аккаунт Google
|
||||
*/
|
||||
public class GoogleAccount {
|
||||
private final String email;
|
||||
private final String password;
|
||||
private final String potToken;
|
||||
private final String cookiesNetscape;
|
||||
|
||||
/**
|
||||
* Создает новый аккаунт Google
|
||||
* @param email адрес электронной почты (Gmail)
|
||||
* @param password пароль от аккаунта
|
||||
* @param potToken POT токен аккаунта
|
||||
* @param cookiesNetscape cookies в формате Netscape
|
||||
*/
|
||||
public GoogleAccount(String email, String password, String potToken, String cookiesNetscape) {
|
||||
this.email = email;
|
||||
this.password = password;
|
||||
this.potToken = potToken;
|
||||
this.cookiesNetscape = cookiesNetscape;
|
||||
}
|
||||
|
||||
/**
|
||||
* Получает email аккаунта
|
||||
* @return email
|
||||
*/
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
/**
|
||||
* Получает пароль аккаунта
|
||||
* @return пароль
|
||||
*/
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
/**
|
||||
* Получает POT токен аккаунта
|
||||
* @return POT токен
|
||||
*/
|
||||
public String getPotToken() {
|
||||
return potToken;
|
||||
}
|
||||
|
||||
/**
|
||||
* Получает cookies аккаунта в формате Netscape
|
||||
* @return cookies в формате Netscape
|
||||
*/
|
||||
public String getCookiesNetscape() {
|
||||
return cookiesNetscape;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "GoogleAccount{" +
|
||||
"email='" + email + '\'' +
|
||||
", password='" + password + '\'' +
|
||||
", potToken='" + (potToken != null ? potToken.substring(0, Math.min(10, potToken.length())) + "..." : "null") + '\'' +
|
||||
", cookies='" + (cookiesNetscape != null ? cookiesNetscape.substring(0, Math.min(20, cookiesNetscape.length())) + "..." : "null") + '\'' +
|
||||
'}';
|
||||
}
|
||||
}
|
@ -0,0 +1,55 @@
|
||||
package com.google.accountgen.account;
|
||||
|
||||
/**
|
||||
* Класс, представляющий результат генерации аккаунта Google
|
||||
*/
|
||||
public class GoogleAccountGenerationResult {
|
||||
private final boolean success;
|
||||
private final String message;
|
||||
private final GoogleAccount account;
|
||||
|
||||
/**
|
||||
* Создает новый результат генерации аккаунта
|
||||
* @param success успешность операции
|
||||
* @param message сообщение о результате
|
||||
* @param account созданный аккаунт или null, если операция не была успешной
|
||||
*/
|
||||
public GoogleAccountGenerationResult(boolean success, String message, GoogleAccount account) {
|
||||
this.success = success;
|
||||
this.message = message;
|
||||
this.account = account;
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверяет, успешно ли завершилась операция
|
||||
* @return true, если операция успешна, false в противном случае
|
||||
*/
|
||||
public boolean isSuccess() {
|
||||
return success;
|
||||
}
|
||||
|
||||
/**
|
||||
* Получает сообщение о результате операции
|
||||
* @return сообщение о результате
|
||||
*/
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
/**
|
||||
* Получает созданный аккаунт
|
||||
* @return аккаунт или null, если операция не была успешной
|
||||
*/
|
||||
public GoogleAccount getAccount() {
|
||||
return account;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "GoogleAccountGenerationResult{" +
|
||||
"success=" + success +
|
||||
", message='" + message + '\'' +
|
||||
", account=" + (account != null ? account.getEmail() : "null") +
|
||||
'}';
|
||||
}
|
||||
}
|
@ -0,0 +1,16 @@
|
||||
package com.google.accountgen.account;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
/**
|
||||
* Интерфейс для генерации аккаунтов Google.
|
||||
* Определяет асинхронный метод для создания аккаунтов.
|
||||
*/
|
||||
public interface GoogleAccountGenerator {
|
||||
|
||||
/**
|
||||
* Асинхронно генерирует Google аккаунт, получает pot-токен и cookies.
|
||||
* @return AccountResult
|
||||
*/
|
||||
AccountResult generateAccount();
|
||||
}
|
@ -0,0 +1,875 @@
|
||||
package com.google.accountgen.account;
|
||||
|
||||
import com.google.accountgen.captcha.CaptchaSolver;
|
||||
import com.google.accountgen.cookies.CookieManager;
|
||||
import com.google.accountgen.proxy.ProxyManager;
|
||||
import com.google.accountgen.registration.GoogleRegistrationHandler;
|
||||
import com.google.accountgen.registration.GoogleRegistrationSelectors;
|
||||
import com.google.accountgen.sms.SmsActivateService;
|
||||
import com.google.accountgen.user.RandomUserGenerator;
|
||||
import com.google.accountgen.user.UserData;
|
||||
import com.google.accountgen.youtube.YouTubeMusicHandler;
|
||||
import io.github.bonigarcia.wdm.WebDriverManager;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
import org.openqa.selenium.By;
|
||||
import org.openqa.selenium.PageLoadStrategy;
|
||||
import org.openqa.selenium.TimeoutException;
|
||||
import org.openqa.selenium.WebDriver;
|
||||
import org.openqa.selenium.chrome.ChromeDriver;
|
||||
import org.openqa.selenium.chrome.ChromeOptions;
|
||||
import org.openqa.selenium.logging.LogEntry;
|
||||
import org.openqa.selenium.logging.LogType;
|
||||
import org.openqa.selenium.logging.LoggingPreferences;
|
||||
import org.openqa.selenium.remote.CapabilityType;
|
||||
import org.openqa.selenium.support.ui.ExpectedConditions;
|
||||
import org.openqa.selenium.support.ui.WebDriverWait;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* Реализация генератора аккаунтов Google
|
||||
*/
|
||||
@SuppressWarnings("ConstantValue")
|
||||
@Service
|
||||
public class GoogleAccountGeneratorImpl implements GoogleAccountGenerator
|
||||
{
|
||||
private static final Logger logger = LoggerFactory.getLogger(GoogleAccountGeneratorImpl.class);
|
||||
private static final String GOOGLE_SIGNUP_URL = "https://accounts.google.com/signup";
|
||||
private static final Random random = new Random();
|
||||
// Добавляем маппинг кодов стран к их ID в SMS-Activate
|
||||
private static final Map<String, Integer> COUNTRY_CODE_TO_ID = Map.of("gb", 16, // Великобритания (ID 16, а не 0)
|
||||
"us", 1, // США
|
||||
"id", 6, // Индонезия
|
||||
"nl", 48, // Нидерланды
|
||||
"tr", 62, // Турция
|
||||
"co", 33, // Колумбия
|
||||
"br", 73 // Бразилия
|
||||
// Добавьте другие страны по необходимости
|
||||
);
|
||||
@Autowired
|
||||
private SmsActivateService smsService;
|
||||
@Value("${sms_activate_api_key}")
|
||||
private String smsApiKey;
|
||||
@Value("${captcha_api_key}")
|
||||
private String captchaApiKey;
|
||||
@Value("${captcha_service_type}")
|
||||
private String captchaServiceType;
|
||||
@Value("${use_goodbyedpi}")
|
||||
private boolean useGoodbyeDPI;
|
||||
@Value("${goodbyedpi_path}")
|
||||
private String goodbyeDpiPath;
|
||||
@Value("${retry_count}")
|
||||
private int retryCount;
|
||||
@Value("${use_proxy}")
|
||||
private boolean useProxy;
|
||||
@Value("${proxyLogin}")
|
||||
private String proxyLogin;
|
||||
@Value("${proxyPass}")
|
||||
private String proxyPass;
|
||||
@Value("${use_vpn}")
|
||||
private boolean useVpnExtension;
|
||||
@Value("${vpn_extension_path}")
|
||||
private String vpnExtensionPath;
|
||||
@Autowired
|
||||
private ProxyManager proxyManager;
|
||||
private String chosenProxy;
|
||||
|
||||
// Вспомогательный метод для разбора параметров URL
|
||||
private static Map<String, String> splitQuery(java.net.URL url)
|
||||
{
|
||||
Map<String, String> query_pairs = new LinkedHashMap<>();
|
||||
String query = url.getQuery();
|
||||
if (query == null || query.isEmpty())
|
||||
{
|
||||
return query_pairs;
|
||||
}
|
||||
String[] pairs = query.split("&");
|
||||
for (String pair : pairs)
|
||||
{
|
||||
int idx = pair.indexOf("=");
|
||||
if (idx > 0 && idx < pair.length() - 1)
|
||||
{ // Проверяем, что есть и ключ, и значение
|
||||
query_pairs.put(URLDecoder.decode(pair.substring(0, idx), StandardCharsets.UTF_8),
|
||||
URLDecoder.decode(pair.substring(idx + 1), StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
return query_pairs;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AccountResult generateAccount()
|
||||
{
|
||||
|
||||
|
||||
WebDriver driver = null;
|
||||
Process goodbyeDpiProcess = null;
|
||||
UserData userData = createUserData();
|
||||
|
||||
try
|
||||
{
|
||||
logger.info("Сгенерированы данные пользователя: {}", userData);
|
||||
|
||||
// --- Запуск GoodbyeDPI ---
|
||||
if (useGoodbyeDPI && goodbyeDpiPath != null && !goodbyeDpiPath.isBlank())
|
||||
{
|
||||
try
|
||||
{
|
||||
File dpiScript = new File(goodbyeDpiPath);
|
||||
if (dpiScript.exists() && dpiScript.isFile() && dpiScript.getName().endsWith(".cmd"))
|
||||
{
|
||||
// Запускаем CMD файл через cmd.exe /c
|
||||
List<String> command = new ArrayList<>();
|
||||
command.add("cmd.exe");
|
||||
command.add("/c");
|
||||
// Используем start /B, чтобы cmd.exe не ждал завершения goodbyedpi
|
||||
// и чтобы окно cmd не появлялось (хотя оно и так не должно из ProcessBuilder)
|
||||
command.add("start");
|
||||
command.add("\"GoodbyeDPI Script\""); // Заголовок окна (необязательно, но полезно)
|
||||
command.add("/B"); // Запуск в фоновом режиме без нового окна
|
||||
command.add(dpiScript.getAbsolutePath()); // Передаем полный путь к скрипту
|
||||
|
||||
ProcessBuilder pb = new ProcessBuilder(command);
|
||||
// Устанавливаем рабочую директорию в папку со скриптом,
|
||||
// чтобы он мог найти свои файлы (например, goodbyedpi.exe в подпапке)
|
||||
pb.directory(dpiScript.getParentFile());
|
||||
pb.redirectErrorStream(true);
|
||||
logger.info("Запуск GoodbyeDPI скрипта: cmd.exe /c start /B {}", dpiScript.getName());
|
||||
// Запускаем cmd.exe, который запустит скрипт
|
||||
goodbyeDpiProcess = pb.start();
|
||||
// Process goodbyeDpiProcess теперь представляет сам cmd.exe,
|
||||
// который должен быстро завершиться после запуска скрипта в фоне (/B).
|
||||
// Нам не нужно получать PID, т.к. останавливать будем по имени goodbyedpi.exe
|
||||
logger.info("Команда запуска GoodbyeDPI скрипта отправлена. Ожидание инициализации...");
|
||||
sleep(5000); // Увеличим паузу, т.к. запуск через cmd может занять чуть больше времени
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.warn("Скрипт GoodbyeDPI не найден или не является .cmd файлом: {}. Пропускаем запуск.",
|
||||
goodbyeDpiPath);
|
||||
}
|
||||
}
|
||||
catch (IOException e)
|
||||
{
|
||||
logger.error("Ошибка ввода/вывода при запуске скрипта GoodbyeDPI: {}", e.getMessage(), e);
|
||||
// Не пытаемся остановить cmd
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.error("Непредвиденная ошибка при запуске скрипта GoodbyeDPI: {}", e.getMessage(), e);
|
||||
goodbyeDpiProcess = null;
|
||||
}
|
||||
}
|
||||
else if (useGoodbyeDPI)
|
||||
{
|
||||
logger.warn(
|
||||
"use_goodbyedpi=true, но goodbyedpi_path не указан или некорректен. GoodbyeDPI не будет запущен.");
|
||||
}
|
||||
// -------------------------
|
||||
|
||||
driver = setupChromeDriver();
|
||||
GoogleRegistrationHandler registrationHandler = new GoogleRegistrationHandler(driver);
|
||||
|
||||
|
||||
driver.get("https://myip.ru/");
|
||||
sleep(10000);
|
||||
|
||||
// Открываем страницу регистрации
|
||||
registrationHandler.openSignupPage();
|
||||
|
||||
// Ждем, пока страница регистрации загрузится (ждем появления поля для имени)
|
||||
try
|
||||
{
|
||||
logger.info("Ожидание загрузки страницы регистрации (поля имени)...");
|
||||
WebDriverWait pageLoadWait = new WebDriverWait(driver, Duration.ofSeconds(15)); // Ждем до 15 секунд
|
||||
pageLoadWait.until(ExpectedConditions.visibilityOfElementLocated(
|
||||
By.cssSelector(GoogleRegistrationSelectors.FIRST_NAME_INPUT)));
|
||||
logger.info("Страница регистрации загружена.");
|
||||
}
|
||||
catch (TimeoutException e)
|
||||
{
|
||||
logger.error("Страница регистрации не загрузилась вовремя (не найдено поле имени).", e);
|
||||
registrationHandler.takeScreenshot(driver, "registration_page_load_timeout"); // Делаем скриншот
|
||||
// Генерируем исключение, которое будет поймано внешним catch и завершит процесс
|
||||
throw new RuntimeException("Не удалось загрузить страницу регистрации.", e);
|
||||
}
|
||||
|
||||
// Заполняем первые этапы регистрации (имя, фамилия, дата рождения, пол, gmail, пароль)
|
||||
registrationHandler.fillNamePage(userData);
|
||||
registrationHandler.fillBirthdayAndGenderPage(userData);
|
||||
registrationHandler.selectCreateGmailOption();
|
||||
registrationHandler.createGmailAddress(userData);
|
||||
registrationHandler.createPassword(userData);
|
||||
|
||||
// Теперь обрабатываем проверку телефона
|
||||
if (!handlePhoneVerification(driver, registrationHandler, userData, smsApiKey))
|
||||
{
|
||||
logger.error("Ошибка при верификации номера телефона");
|
||||
// Генерируем исключение, чтобы перейти в блок finally для закрытия драйвера
|
||||
throw new RuntimeException("Ошибка при верификации номера телефона");
|
||||
}
|
||||
|
||||
// Добавляем пропуск шагов добавления резервной почты и телефона (если они появляются)
|
||||
try
|
||||
{
|
||||
logger.info("Пропуск шага добавления резервной почты...");
|
||||
registrationHandler.skipRecoveryEmail();
|
||||
sleep(1500);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.info("Не удалось пропустить шаг добавления резервной почты (возможно, его не было): {}",
|
||||
e.getMessage());
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
logger.info("Пропуск шага добавления номера телефона...");
|
||||
registrationHandler.skipAddPhone();
|
||||
sleep(1500);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.info("Не удалось пропустить шаг добавления номера телефона (возможно, его не было): {}",
|
||||
e.getMessage());
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
logger.info("Проверка информации об аккаунте...");
|
||||
registrationHandler.reviewAccountInfo();
|
||||
sleep(1500);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.info("Не удалось пройти шаг проверки информации (возможно, его не было): {}", e.getMessage());
|
||||
}
|
||||
|
||||
// Обработка настроек конфиденциальности и принятия условий
|
||||
registrationHandler.processPrivacySettings();
|
||||
|
||||
// Ожидание перехода на страницу аккаунта, проверяя URL каждые 3 секунды
|
||||
logger.info("Ожидание перехода на страницу аккаунта...");
|
||||
boolean accountPageReached = false;
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
String currentUrl = driver.getCurrentUrl();
|
||||
if (Objects.requireNonNull(currentUrl).startsWith("https://myaccount.google.com/"))
|
||||
{
|
||||
accountPageReached = true;
|
||||
break;
|
||||
}
|
||||
sleep(3000);
|
||||
}
|
||||
if (!accountPageReached)
|
||||
{
|
||||
logger.error("Не удалось перейти на страницу аккаунта за отведённое время.");
|
||||
// Генерируем исключение, чтобы перейти в блок finally для закрытия драйвера
|
||||
throw new RuntimeException("Ошибка: Не удалось попасть на страницу аккаунта.");
|
||||
}
|
||||
|
||||
// После успешного перехода — переходим на YouTube Music
|
||||
logger.info("Переходим на YouTube Music после завершения регистрации...");
|
||||
registrationHandler.navigateToYouTubeMusicAndEnsureLogin(userData);
|
||||
|
||||
// --- Извлечение POT через DevTools ---
|
||||
String potToken = null;
|
||||
try
|
||||
{
|
||||
YouTubeMusicHandler musicHandler = new YouTubeMusicHandler(driver);
|
||||
potToken = musicHandler.getPotToken();
|
||||
if (potToken != null)
|
||||
{
|
||||
logger.info("POT токен успешно извлечён: {}", potToken);
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.warn("POT токен не был извлечён");
|
||||
// Можно решить, считать ли это фатальной ошибкой
|
||||
// throw new RuntimeException("Не удалось извлечь POT токен");
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.error("Ошибка при извлечении POT токена: {}", e.getMessage(), e);
|
||||
// Можно решить, считать ли это фатальной ошибкой
|
||||
// throw new RuntimeException("Ошибка при извлечении POT токена", e);
|
||||
}
|
||||
|
||||
// --- Экспортируем cookies ---
|
||||
String cookiesNetscape = exportCookies(driver);
|
||||
if (cookiesNetscape == null || cookiesNetscape.isEmpty())
|
||||
{
|
||||
logger.warn("Не удалось экспортировать cookies");
|
||||
// Можно решить, считать ли это фатальной ошибкой
|
||||
// throw new RuntimeException("Не удалось экспортировать cookies");
|
||||
}
|
||||
|
||||
// --- Сохраняем результат ---
|
||||
|
||||
logger.info("Аккаунт успешно сгенерирован и сохранен: {}", userData.getUsername());
|
||||
return new AccountResult(userData.getUsername() + "@gmail.com", userData.getPassword(), potToken,
|
||||
cookiesNetscape, chosenProxy);
|
||||
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.error("Ошибка во время генерации аккаунта для {}: {}",
|
||||
(userData != null ? userData.getUsername() : "<unknown>"), e.getMessage(), e);
|
||||
return AccountResult.failure("Ошибка генерации аккаунта: " + e.getMessage());
|
||||
}
|
||||
finally
|
||||
{
|
||||
// --- Закрытие WebDriver ---
|
||||
if (driver != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
logger.info("Закрытие WebDriver...");
|
||||
driver.quit();
|
||||
logger.info("WebDriver успешно закрыт.");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.error("Ошибка при закрытии WebDriver: {}", e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
// -------------------------
|
||||
|
||||
// --- Остановка GoodbyeDPI ---
|
||||
if (useGoodbyeDPI && goodbyeDpiProcess != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Попытка остановить goodbyedpi.exe через taskkill
|
||||
// Сначала получаем PID запущенного goodbyedpi.exe (если он есть)
|
||||
// Это более надежно, чем закрывать по имени, но сложнее.
|
||||
// Альтернатива: убить процесс по имени.
|
||||
logger.info("Попытка остановить GoodbyeDPI (goodbyedpi.exe) через taskkill...");
|
||||
ProcessBuilder killPb = new ProcessBuilder("taskkill", "/F", "/IM", "goodbyedpi.exe", "/T");
|
||||
killPb.redirectErrorStream(true);
|
||||
Process killProcess = killPb.start();
|
||||
// Читаем вывод, чтобы убедиться, что команда выполнилась
|
||||
try (var reader = new java.io.BufferedReader(
|
||||
new java.io.InputStreamReader(killProcess.getInputStream())))
|
||||
{
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null)
|
||||
{
|
||||
logger.info("taskkill output: {}", line);
|
||||
}
|
||||
}
|
||||
int exitCode = killProcess.waitFor();
|
||||
if (exitCode == 0 || exitCode == 128)
|
||||
{ // 0 = успех, 128 = процесс не найден (уже завершился)
|
||||
logger.info("Команда taskkill для остановки goodbyedpi.exe выполнена (exit code {}).",
|
||||
exitCode);
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.warn("Команда taskkill для остановки goodbyedpi.exe завершилась с кодом ошибки: {}",
|
||||
exitCode);
|
||||
}
|
||||
|
||||
// Уничтожаем процесс cmd.exe, который запускал скрипт (на всякий случай, хотя он должен был завершиться)
|
||||
if (goodbyeDpiProcess.isAlive())
|
||||
{
|
||||
logger.info("Уничтожение процесса запуска cmd.exe для GoodbyeDPI...");
|
||||
goodbyeDpiProcess.destroyForcibly();
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.info("Процесс запуска cmd.exe для GoodbyeDPI уже завершен.");
|
||||
}
|
||||
}
|
||||
catch (IOException | InterruptedException e)
|
||||
{
|
||||
logger.error("Ошибка при остановке GoodbyeDPI: {}", e.getMessage(), e);
|
||||
// Все равно пытаемся уничтожить процесс cmd.exe
|
||||
if (goodbyeDpiProcess.isAlive())
|
||||
{
|
||||
goodbyeDpiProcess.destroyForcibly();
|
||||
}
|
||||
}
|
||||
}
|
||||
// -------------------------
|
||||
|
||||
// --- Отключение VPN ---
|
||||
if (useVpnExtension)
|
||||
{
|
||||
try
|
||||
{
|
||||
logger.info("Отключение VPN расширения...");
|
||||
// vpnManager.disconnect(); // Удаляем вызов, т.к. метод отсутствует
|
||||
logger.info("VPN расширение должно отключиться при закрытии браузера.");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.error("Ошибка при попытке отключения VPN расширения (хотя метод и отсутствовал): {}",
|
||||
e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
// ----------------------
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Создает данные пользователя
|
||||
*
|
||||
* @return данные пользователя
|
||||
*/
|
||||
private UserData createUserData()
|
||||
{
|
||||
RandomUserGenerator userGenerator = new RandomUserGenerator();
|
||||
return userGenerator.generateUser();
|
||||
}
|
||||
|
||||
/**
|
||||
* Настраивает и создает экземпляр ChromeDriver
|
||||
*
|
||||
* @return настроенный веб-драйвер
|
||||
*/
|
||||
private WebDriver setupChromeDriver()
|
||||
{
|
||||
logger.info("Настройка и запуск ChromeDriver");
|
||||
|
||||
try
|
||||
{
|
||||
// Явно вызываем WebDriverManager для установки/обновления ChromeDriver
|
||||
logger.info("Вызов WebDriverManager.chromedriver().setup()...");
|
||||
WebDriverManager.chromedriver().setup();
|
||||
logger.info("WebDriverManager.chromedriver().setup() завершен.");
|
||||
|
||||
// Путь к ChromeDriver уже должен быть установлен в Main.java - оставляем комментарий, но полагаемся на WDM
|
||||
// logger.info("Используем путь к ChromeDriver, установленный в Main.java");
|
||||
|
||||
ChromeOptions options = new ChromeOptions();
|
||||
// Если Chrome установлен НЕ в стандартное место, раскомментируйте и укажите путь:
|
||||
// options.setBinary("C:\\Путь\\К\\Вашему\\chrome.exe");
|
||||
|
||||
// Используем EAGER стратегию загрузки страницы, чтобы не ждать полной загрузки ресурсов
|
||||
options.setPageLoadStrategy(PageLoadStrategy.EAGER);
|
||||
|
||||
// Добавляем User-Agent
|
||||
options.addArguments(
|
||||
"--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36"); // Пример современного User-Agent
|
||||
|
||||
// Создаём уникальный временный профиль для Chrome
|
||||
Path tempProfile = Files.createTempDirectory("chrome-profile-");
|
||||
options.addArguments("--user-data-dir=" + tempProfile.toAbsolutePath());
|
||||
logger.info("Используется временный профиль Chrome: {}", tempProfile);
|
||||
|
||||
// Настройка логирования браузера для захвата консольных логов
|
||||
LoggingPreferences logPrefs = new LoggingPreferences();
|
||||
logPrefs.enable(LogType.BROWSER, java.util.logging.Level.ALL); // Захват всех консольных логов
|
||||
// Отключаем Performance лог, т.к. он был закомментирован
|
||||
logPrefs.enable(LogType.PERFORMANCE, java.util.logging.Level.OFF);
|
||||
options.setCapability("goog:loggingPrefs", logPrefs);
|
||||
logger.info("Настроено логирование браузера (консоль).");
|
||||
|
||||
// --- ВКЛЮЧАЕМ HEADLESS ---
|
||||
// logger.info("Headless режим ВЫКЛЮЧЕН."); // Комментируем это сообщение
|
||||
// options.addArguments("--headless");
|
||||
options.addArguments("--disable-gpu"); // Часто нужен с headless
|
||||
options.addArguments("--window-size=1920,1080"); // Устанавливаем размер окна для headless
|
||||
logger.info("Headless режим ВКЛЮЧЕН с разрешением 1920x1080.");
|
||||
// --- КОНЕЦ ВКЛЮЧЕНИЯ HEADLESS ---
|
||||
|
||||
// Оставляем общие опции
|
||||
options.addArguments("--no-sandbox"); // Может быть полезно и не в headless
|
||||
options.addArguments("--disable-dev-shm-usage"); // Может быть полезно и не в headless
|
||||
options.addArguments("--disable-extensions"); // Явно отключаем расширения
|
||||
options.addArguments("--disable-blink-features=AutomationControlled");
|
||||
options.addArguments("--disable-notifications");
|
||||
options.addArguments("--disable-popup-blocking");
|
||||
options.addArguments("--log-level=3");
|
||||
options.addArguments("--silent");
|
||||
|
||||
// Временно отключаем добавление расширения VPN
|
||||
logger.info("Загрузка VPN расширения временно отключена.");
|
||||
|
||||
// Proxy через Selenium Proxy capability
|
||||
if (useProxy && proxyManager.hasProxies())
|
||||
{
|
||||
chosenProxy = proxyManager.getNextProxy();
|
||||
// Парсим логин и пароль (login:pass@host:port)
|
||||
// HTTP(S)-прокси с Basic Auth
|
||||
String proxyUri = (proxyLogin + ":" + proxyPass + "@") + chosenProxy;
|
||||
String scheme = chosenProxy.startsWith("http") ? "" : "http://";
|
||||
String finalProxy = "--proxy-server=" + scheme + chosenProxy;
|
||||
options.addArguments(finalProxy);
|
||||
org.openqa.selenium.Proxy httpProxy = new org.openqa.selenium.Proxy();
|
||||
httpProxy.setHttpProxy(chosenProxy).setSslProxy(chosenProxy);
|
||||
options.setCapability(CapabilityType.PROXY, httpProxy);
|
||||
logger.info("HTTP(S) proxy настроен: {}{}", scheme, chosenProxy);
|
||||
}
|
||||
|
||||
|
||||
// Создаем и возвращаем драйвер
|
||||
logger.info("Попытка создания экземпляра ChromeDriver с опциями...");
|
||||
WebDriver driver = new ChromeDriver(options);
|
||||
logger.info("Экземпляр ChromeDriver успешно создан.");
|
||||
|
||||
return driver;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.error("Критическая ошибка при настройке или запуске ChromeDriver", e);
|
||||
throw new RuntimeException("Не удалось инициализировать ChromeDriver", e); // Пробрасываем исключение дальше
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Обрабатывает шаг верификации по номеру телефона.
|
||||
*
|
||||
* @param driver WebDriver
|
||||
* @param registrationHandler Handler для взаимодействия со страницей регистрации
|
||||
* @param userData Данные пользователя (для логирования)
|
||||
* @param apiKey API ключ SMS сервиса
|
||||
* @return true если верификация прошла успешно, иначе false
|
||||
*/
|
||||
private boolean handlePhoneVerification(WebDriver driver, GoogleRegistrationHandler registrationHandler, UserData userData, String apiKey)
|
||||
{
|
||||
|
||||
// Список поддерживаемых стран (ISO 3166-1 alpha-2 коды)
|
||||
List<String> supportedCountries = List.of("gb", "us", "id", "nl", "tr", "co", "br");
|
||||
|
||||
smsService.setApiKey(apiKey);
|
||||
int maxAttempts = 5; // Макс. попыток получения номера для *одной* регистрации
|
||||
|
||||
for (int attempt = 1; attempt <= maxAttempts; attempt++)
|
||||
{
|
||||
// Случайно выбираем страну из списка
|
||||
String selectedCountryCode = "tr";//supportedCountries.get(random.nextInt(supportedCountries.size()));
|
||||
// Получаем ID страны из маппинга
|
||||
Integer selectedCountryId = COUNTRY_CODE_TO_ID.get(selectedCountryCode.toLowerCase());
|
||||
|
||||
if (selectedCountryId == null)
|
||||
{
|
||||
logger.error("Попытка #{}: Не найден ID для выбранного кода страны '{}'. Пропускаем.", attempt,
|
||||
selectedCountryCode);
|
||||
continue;
|
||||
}
|
||||
|
||||
logger.info("Попытка #{}: Выбрана страна '{}' (ID: {}) для верификации номера телефона", attempt,
|
||||
selectedCountryCode, selectedCountryId);
|
||||
|
||||
// Используем ActivationResult вместо PhoneNumberInfo
|
||||
SmsActivateService.ActivationResult activationResult = null;
|
||||
try
|
||||
{
|
||||
// Используем getNumberFromCountry с ID страны
|
||||
activationResult = smsService.getNumberFromCountry("go", selectedCountryId);
|
||||
|
||||
// Проверяем успешность получения номера
|
||||
if (activationResult == null || !activationResult.isSuccess() || activationResult.phoneNumber == null)
|
||||
{
|
||||
String errorMsg = activationResult != null ? activationResult.getMessage() : "null result";
|
||||
logger.warn("Попытка #{}: Не удалось получить номер телефона для страны {} (ID {}). Ошибка: {}",
|
||||
attempt, selectedCountryCode, selectedCountryId, errorMsg);
|
||||
sleep(2000);
|
||||
continue;
|
||||
}
|
||||
|
||||
String fullPhoneNumber = activationResult.phoneNumber;
|
||||
String activationId = activationResult.activationId;
|
||||
|
||||
logger.info("Попытка #{}: Получен номер: {} (ID: {}) для страны {} (ID: {})", attempt, fullPhoneNumber,
|
||||
activationId, selectedCountryCode, selectedCountryId);
|
||||
|
||||
// --- Ввод номера телефона ---
|
||||
// Удаляем префикс кода страны из номера
|
||||
String numberOnly = fullPhoneNumber;
|
||||
// Обновляем логику для Великобритании (gb) с учетом префикса 44
|
||||
if (selectedCountryCode.equals("gb") && numberOnly.startsWith("44"))
|
||||
{
|
||||
numberOnly = numberOnly.substring(2);
|
||||
}
|
||||
else if (selectedCountryCode.equals("us") && numberOnly.startsWith("1"))
|
||||
{
|
||||
numberOnly = numberOnly.substring(1);
|
||||
}
|
||||
else if (selectedCountryCode.equals("id") && numberOnly.startsWith("62"))
|
||||
{
|
||||
numberOnly = numberOnly.substring(2);
|
||||
}
|
||||
else if (selectedCountryCode.equals("nl") && numberOnly.startsWith("31"))
|
||||
{ // Нидерланды
|
||||
numberOnly = numberOnly.substring(2);
|
||||
}
|
||||
else if (selectedCountryCode.equals("tr") && numberOnly.startsWith("90"))
|
||||
{ // Турция
|
||||
numberOnly = numberOnly.substring(2);
|
||||
}
|
||||
else if (selectedCountryCode.equals("co") && numberOnly.startsWith("57"))
|
||||
{ // Колумбия
|
||||
numberOnly = numberOnly.substring(2);
|
||||
}
|
||||
else if (selectedCountryCode.equals("br") && numberOnly.startsWith("55"))
|
||||
{ // Бразилия
|
||||
numberOnly = numberOnly.substring(2);
|
||||
} // Добавить другие страны по необходимости
|
||||
numberOnly = numberOnly.replaceAll("[^0-9]", ""); // Оставляем только цифры
|
||||
|
||||
logger.info("Попытка #{}: Номер для ввода (без кода): {}, Страна: {}", attempt, numberOnly,
|
||||
selectedCountryCode);
|
||||
|
||||
// Передаем номер (без кода) И КОД СТРАНЫ в обновленный метод
|
||||
if (!registrationHandler.enterPhoneNumber(numberOnly, selectedCountryCode))
|
||||
{
|
||||
logger.warn("Попытка #{}: Не удалось ввести номер {} (страна {}) или Google его отклонил.", attempt,
|
||||
numberOnly, selectedCountryCode);
|
||||
// Используем числовой код статуса 8 для отмены
|
||||
smsService.setStatus(activationId, 8);
|
||||
logger.info("Попытка #{}: Отменен номер ID {} для страны {}", attempt, activationId,
|
||||
selectedCountryCode);
|
||||
sleep(1500);
|
||||
continue;
|
||||
}
|
||||
|
||||
// --- Ожидание и ввод кода ---
|
||||
logger.info("Попытка #{}: Номер {} для страны {} введен. Ожидание SMS...", attempt, fullPhoneNumber,
|
||||
selectedCountryCode);
|
||||
|
||||
// Используем старый метод getCode, который возвращает ActivationResult с кодом или ошибкой
|
||||
SmsActivateService.ActivationResult codeResult = smsService.getCode(activationId);
|
||||
|
||||
if (codeResult != null && codeResult.isSuccess() && codeResult.smsCode != null)
|
||||
{
|
||||
String code = codeResult.smsCode;
|
||||
logger.info("Попытка #{}: Получен код: {} для номера ID {}", attempt, code, activationId);
|
||||
registrationHandler.enterVerificationCode(code);
|
||||
|
||||
sleep(5000);
|
||||
|
||||
if (registrationHandler.isVerificationSuccessful())
|
||||
{
|
||||
logger.info("Попытка #{}: Верификация по номеру {} (страна {}) успешно завершена.", attempt,
|
||||
fullPhoneNumber, selectedCountryCode);
|
||||
// Сообщаем сервису об успехе (статус 6)
|
||||
smsService.setStatus(activationId, 6);
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.warn("Попытка #{}: Код {} введен, но верификация не удалась.", attempt, code);
|
||||
// Отменяем номер (статус 8)
|
||||
smsService.setStatus(activationId, 8);
|
||||
logger.info("Попытка #{}: Отменен номер ID {} после неудачной верификации", attempt,
|
||||
activationId);
|
||||
sleep(1500);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
String errorMsg = codeResult != null ? codeResult.getMessage() : "Таймаут или null result";
|
||||
logger.warn("Попытка #{}: Не удалось получить SMS-код для номера ID {}. Ошибка: {}", attempt,
|
||||
activationId, errorMsg);
|
||||
// Отменяем номер (статус 8)
|
||||
smsService.setStatus(activationId, 8);
|
||||
logger.info("Попытка #{}: Отменен номер ID {} из-за ошибки/таймаута получения кода", attempt,
|
||||
activationId);
|
||||
sleep(1500);
|
||||
}
|
||||
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.error("Попытка #{}: Непредвиденная ошибка на этапе верификации для страны {} (ID {}): {}",
|
||||
attempt, selectedCountryCode, selectedCountryId, e.getMessage(), e);
|
||||
try
|
||||
{
|
||||
registrationHandler.takeScreenshot(driver,
|
||||
"phone_verification_unexpected_error_attempt_" + attempt);
|
||||
}
|
||||
catch (Exception screenshotEx)
|
||||
{
|
||||
logger.error("Не удалось сделать скриншот при ошибке верификации: {}", screenshotEx.getMessage());
|
||||
}
|
||||
if (activationResult != null && activationResult.activationId != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Отменяем номер (статус 8)
|
||||
smsService.setStatus(activationResult.activationId, 8);
|
||||
logger.info("Попытка #{}: Отменен номер ID {} из-за непредвиденной ошибки", attempt,
|
||||
activationResult.activationId);
|
||||
}
|
||||
catch (Exception cancelEx)
|
||||
{ // Оставляем общий catch на всякий случай
|
||||
logger.error("Непредвиденная ошибка при попытке отменить номер {} после основной ошибки: {}",
|
||||
activationResult.activationId, cancelEx.getMessage());
|
||||
}
|
||||
}
|
||||
sleep(2000);
|
||||
}
|
||||
} // Конец цикла попыток
|
||||
|
||||
logger.error("Не удалось пройти верификацию по номеру телефона после {} попыток.", maxAttempts);
|
||||
return false; // Не удалось после всех попыток
|
||||
}
|
||||
|
||||
/**
|
||||
* Извлекает POT токен через YouTube Music
|
||||
*
|
||||
* @param driver веб-драйвер
|
||||
* @return POT токен или null в случае ошибки
|
||||
*/
|
||||
private String extractPotToken(WebDriver driver)
|
||||
{
|
||||
try
|
||||
{
|
||||
logger.info("Извлечение POT токена через YouTube Music");
|
||||
YouTubeMusicHandler musicHandler = new YouTubeMusicHandler(driver);
|
||||
String potToken = musicHandler.getPotToken();
|
||||
|
||||
if (potToken != null && !potToken.isEmpty())
|
||||
{
|
||||
logger.info("POT токен успешно получен");
|
||||
return potToken;
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.warn("Не удалось получить POT токен");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.error("Ошибка при извлечении POT токена", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Экспортирует cookies в формате Netscape
|
||||
*
|
||||
* @param driver веб-драйвер
|
||||
* @return строка с cookies в формате Netscape или null в случае ошибки
|
||||
*/
|
||||
private String exportCookies(WebDriver driver)
|
||||
{
|
||||
try
|
||||
{
|
||||
logger.info("Экспорт cookies в формате Netscape");
|
||||
CookieManager cookieManager = new CookieManager();
|
||||
String cookiesNetscape = cookieManager.exportCookiesToNetscape(driver);
|
||||
|
||||
if (cookiesNetscape != null && !cookiesNetscape.isEmpty())
|
||||
{
|
||||
logger.info("Cookies успешно экспортированы");
|
||||
return cookiesNetscape;
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.warn("Не удалось экспортировать cookies");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.error("Ошибка при экспорте cookies", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Добавляет задержку выполнения
|
||||
*
|
||||
* @param millis длительность задержки в миллисекундах
|
||||
*/
|
||||
private void sleep(long millis)
|
||||
{
|
||||
try
|
||||
{
|
||||
Thread.sleep(millis);
|
||||
}
|
||||
catch (InterruptedException e)
|
||||
{
|
||||
Thread.currentThread().interrupt();
|
||||
logger.warn("Прерван сон потока", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Извлекает параметр 'pot' из последнего сетевого запроса к googlevideo.com/videoplayback.
|
||||
*
|
||||
* @param driver WebDriver
|
||||
* @return Значение параметра 'pot' или null, если не найден.
|
||||
*/
|
||||
private String extractPotFromNetworkLogs(WebDriver driver)
|
||||
{
|
||||
logger.info("Извлечение параметра 'pot' из сетевых логов...");
|
||||
String potValue = null;
|
||||
try
|
||||
{
|
||||
org.openqa.selenium.logging.Logs logs = driver.manage().logs();
|
||||
List<LogEntry> entries = logs.get(LogType.PERFORMANCE).getAll();
|
||||
logger.info("Получено {} записей в логе производительности.", entries.size());
|
||||
|
||||
for (int i = entries.size() - 1; i >= 0; i--)
|
||||
{ // Ищем с конца
|
||||
LogEntry entry = entries.get(i);
|
||||
JSONObject json = new JSONObject(entry.getMessage());
|
||||
JSONObject message = json.getJSONObject("message");
|
||||
String method = message.getString("method");
|
||||
|
||||
if ("Network.requestWillBeSent".equals(method))
|
||||
{
|
||||
JSONObject params = message.getJSONObject("params");
|
||||
JSONObject request = params.getJSONObject("request");
|
||||
String url = request.getString("url");
|
||||
|
||||
if (url.contains("googlevideo.com/videoplayback"))
|
||||
{
|
||||
logger.info("Найден запрос к googlevideo.com: {}", url);
|
||||
// Разбираем URL для поиска параметра pot
|
||||
Map<String, String> queryParams = splitQuery(new java.net.URL(url));
|
||||
if (queryParams.containsKey("pot"))
|
||||
{
|
||||
potValue = queryParams.get("pot");
|
||||
logger.info("Найден параметр pot: {}", potValue);
|
||||
break; // Нашли последний pot, выходим
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (JSONException e)
|
||||
{
|
||||
logger.error("Ошибка при разборе JSON из логов производительности: {}", e.getMessage());
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.error("Ошибка при получении или обработке сетевых логов: {}", e.getMessage(), e);
|
||||
}
|
||||
|
||||
if (potValue == null)
|
||||
{
|
||||
logger.warn("Параметр 'pot' не найден в сетевых запросах к googlevideo.com");
|
||||
}
|
||||
|
||||
return potValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Создает экземпляр CaptchaSolver на основе типа.
|
||||
*/
|
||||
private CaptchaSolver createCaptchaSolver(String apiKey, CaptchaSolver.ServiceType serviceType)
|
||||
{
|
||||
return new CaptchaSolver(apiKey, serviceType);
|
||||
}
|
||||
}
|
103
src/main/java/com/google/accountgen/account/UserData.java
Normal file
103
src/main/java/com/google/accountgen/account/UserData.java
Normal file
@ -0,0 +1,103 @@
|
||||
package com.google.accountgen.account;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
/**
|
||||
* Модель данных пользователя для создания Google аккаунта
|
||||
*/
|
||||
public class UserData {
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
private LocalDate birthDate;
|
||||
private String gender; // "1" для Male, "2" для Female, "3" для Rather not say
|
||||
private String username;
|
||||
private String password;
|
||||
private String phoneNumber;
|
||||
|
||||
public UserData() {
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public LocalDate getBirthDate() {
|
||||
return birthDate;
|
||||
}
|
||||
|
||||
public void setBirthDate(LocalDate birthDate) {
|
||||
this.birthDate = birthDate;
|
||||
}
|
||||
|
||||
public String getGender() {
|
||||
return gender;
|
||||
}
|
||||
|
||||
public void setGender(String gender) {
|
||||
this.gender = gender;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public String getPhoneNumber() {
|
||||
return phoneNumber;
|
||||
}
|
||||
|
||||
public void setPhoneNumber(String phoneNumber) {
|
||||
this.phoneNumber = phoneNumber;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return username + "@gmail.com";
|
||||
}
|
||||
|
||||
public int getBirthDay() {
|
||||
return birthDate.getDayOfMonth();
|
||||
}
|
||||
|
||||
public int getBirthMonth() {
|
||||
return birthDate.getMonthValue();
|
||||
}
|
||||
|
||||
public int getBirthYear() {
|
||||
return birthDate.getYear();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "UserData{" +
|
||||
"firstName='" + firstName + '\'' +
|
||||
", lastName='" + lastName + '\'' +
|
||||
", birthDate=" + birthDate +
|
||||
", gender='" + gender + '\'' +
|
||||
", username='" + username + '\'' +
|
||||
", email='" + getEmail() + '\'' +
|
||||
'}';
|
||||
}
|
||||
}
|
151
src/main/java/com/google/accountgen/captcha/CaptchaSolver.java
Normal file
151
src/main/java/com/google/accountgen/captcha/CaptchaSolver.java
Normal file
@ -0,0 +1,151 @@
|
||||
package com.google.accountgen.captcha;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import okhttp3.*;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* Сервис для решения капчи через внешние API сервисы
|
||||
* Поддерживает 2Captcha и CapMonster API
|
||||
*/
|
||||
public class CaptchaSolver
|
||||
{
|
||||
private static final Logger logger = LoggerFactory.getLogger(CaptchaSolver.class);
|
||||
|
||||
// API URLs
|
||||
private static final String TWOCAPTCHA_RESULT_URL = "https://2captcha.com/res.php";
|
||||
|
||||
// Тип сервиса
|
||||
public enum ServiceType
|
||||
{
|
||||
TWOCAPTCHA
|
||||
}
|
||||
|
||||
private final String apiKey;
|
||||
private final ServiceType serviceType;
|
||||
private final OkHttpClient httpClient;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
/**
|
||||
* Создает новый объект CaptchaSolver
|
||||
*
|
||||
* @param apiKey API ключ сервиса
|
||||
* @param serviceType Тип сервиса (TWOCAPTCHA или CAPMONSTER)
|
||||
*/
|
||||
public CaptchaSolver(String apiKey, ServiceType serviceType)
|
||||
{
|
||||
this.apiKey = apiKey;
|
||||
this.serviceType = serviceType;
|
||||
this.httpClient = new OkHttpClient.Builder().connectTimeout(30, TimeUnit.SECONDS)
|
||||
.readTimeout(30, TimeUnit.SECONDS).build();
|
||||
this.objectMapper = new ObjectMapper();
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверяет баланс аккаунта
|
||||
*
|
||||
* @return Баланс в долларах или -1 при ошибке
|
||||
*/
|
||||
public double getBalance()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (serviceType == ServiceType.TWOCAPTCHA)
|
||||
{
|
||||
return getBalance2Captcha();
|
||||
}
|
||||
else
|
||||
{
|
||||
return getBalanceCapMonster();
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.error("Ошибка при получении баланса", e);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверяет баланс аккаунта 2Captcha
|
||||
*
|
||||
* @return Баланс в долларах или -1 при ошибке
|
||||
* @throws IOException при ошибке HTTP-запроса
|
||||
*/
|
||||
private double getBalance2Captcha() throws IOException
|
||||
{
|
||||
HttpUrl url = Objects.requireNonNull(HttpUrl.parse(TWOCAPTCHA_RESULT_URL))
|
||||
.newBuilder().addQueryParameter("key", apiKey)
|
||||
.addQueryParameter("action", "getbalance").addQueryParameter("json", "1").build();
|
||||
|
||||
Request request = new Request.Builder().url(url).get().build();
|
||||
|
||||
try (Response response = httpClient.newCall(request).execute())
|
||||
{
|
||||
if (!response.isSuccessful())
|
||||
{
|
||||
logger.error("HTTP ошибка при получении баланса 2Captcha: {}", response.code());
|
||||
return -1;
|
||||
}
|
||||
|
||||
String responseBody = Objects.requireNonNull(response.body()).string();
|
||||
JsonNode jsonResponse = objectMapper.readTree(responseBody);
|
||||
|
||||
if (jsonResponse.has("status") && jsonResponse.get("status").asInt() == 1)
|
||||
{
|
||||
return jsonResponse.get("request").asDouble();
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.error("Ошибка при получении баланса 2Captcha: {}",
|
||||
jsonResponse.has("error_text") ? jsonResponse.get("error_text").asText() : responseBody);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверяет баланс аккаунта CapMonster
|
||||
*
|
||||
* @return Баланс в долларах или -1 при ошибке
|
||||
* @throws IOException при ошибке HTTP-запроса
|
||||
*/
|
||||
private double getBalanceCapMonster() throws IOException
|
||||
{
|
||||
String jsonBody = String.format("{\"clientKey\":\"%s\"}", apiKey);
|
||||
|
||||
RequestBody body = RequestBody.create(jsonBody, MediaType.parse("application/json"));
|
||||
|
||||
Request request = new Request.Builder().url("https://api.capmonster.cloud/getBalance").post(body).build();
|
||||
|
||||
try (Response response = httpClient.newCall(request).execute())
|
||||
{
|
||||
if (!response.isSuccessful())
|
||||
{
|
||||
logger.error("HTTP ошибка при получении баланса CapMonster: {}", response.code());
|
||||
return -1;
|
||||
}
|
||||
|
||||
String responseBody = Objects.requireNonNull(response.body()).string();
|
||||
JsonNode jsonResponse = objectMapper.readTree(responseBody);
|
||||
|
||||
if (jsonResponse.has("errorId") && jsonResponse.get("errorId").asInt() == 0)
|
||||
{
|
||||
return jsonResponse.get("balance").asDouble();
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.error("Ошибка при получении баланса CapMonster: {}",
|
||||
jsonResponse.has("errorDescription") ? jsonResponse.get("errorDescription")
|
||||
.asText() : responseBody);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,61 @@
|
||||
package com.google.accountgen.cookies;
|
||||
|
||||
import org.openqa.selenium.Cookie;
|
||||
import org.openqa.selenium.WebDriver;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Класс для управления cookies браузера
|
||||
*/
|
||||
public class CookieManager
|
||||
{
|
||||
private static final Logger logger = LoggerFactory.getLogger(CookieManager.class);
|
||||
|
||||
/**
|
||||
* Экспортирует cookies в формате Netscape
|
||||
* Формат: domain flag path secure expiry name value
|
||||
*
|
||||
* @param driver веб-драйвер
|
||||
* @return строка с cookies в формате Netscape
|
||||
*/
|
||||
public String exportCookiesToNetscape(WebDriver driver)
|
||||
{
|
||||
logger.info("Экспорт cookies в формате Netscape");
|
||||
|
||||
StringBuilder builder = new StringBuilder();
|
||||
builder.append("# Netscape HTTP Cookie File\n");
|
||||
builder.append("# HTTP Cookie File\n\n");
|
||||
Set<Cookie> cookies = driver.manage().getCookies();
|
||||
|
||||
for (Cookie cookie : cookies)
|
||||
{
|
||||
builder.append(getNetscapeCookieString(cookie));
|
||||
builder.append("\n");
|
||||
}
|
||||
|
||||
String result = builder.toString();
|
||||
logger.info("Экспортировано {} cookies", cookies.size());
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Преобразует объект Cookie в строку формата Netscape
|
||||
* Формат: domain flag path secure expiry name value
|
||||
*
|
||||
* @param cookie объект Cookie
|
||||
* @return строка с cookie в формате Netscape
|
||||
*/
|
||||
private String getNetscapeCookieString(Cookie cookie)
|
||||
{
|
||||
return String.format("%s\t%s\t%s\t%s\t%s\t%s\t%s", cookie.getDomain(),
|
||||
Objects.requireNonNull(cookie.getDomain()).startsWith(".") ? "TRUE" : "FALSE", // флаг
|
||||
cookie.getPath(), cookie.isSecure() ? "TRUE" : "FALSE",
|
||||
cookie.getExpiry() != null ? cookie.getExpiry().getTime() / 1000 : "0", cookie.getName(),
|
||||
cookie.getValue());
|
||||
}
|
||||
|
||||
}
|
115
src/main/java/com/google/accountgen/proxy/ProxyManager.java
Normal file
115
src/main/java/com/google/accountgen/proxy/ProxyManager.java
Normal file
@ -0,0 +1,115 @@
|
||||
package com.google.accountgen.proxy;
|
||||
|
||||
import com.fasterxml.jackson.databind.MappingIterator;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Random;
|
||||
|
||||
|
||||
@Service
|
||||
public class ProxyManager
|
||||
{
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(ProxyManager.class);
|
||||
|
||||
private final String API_URL = "https://papaproxy.net/api/getproxy/?format=json&type=http_ip&login=%s&password=%s";
|
||||
private final List<String> proxyList = new ArrayList<>();
|
||||
private final Random random = new Random();
|
||||
@Value("${proxyLogin}")
|
||||
private String proxyLogin;
|
||||
@Value("${proxyPass}")
|
||||
private String proxypass;
|
||||
|
||||
public void init()
|
||||
{
|
||||
String fullUrl = String.format(API_URL, proxyLogin, proxypass);
|
||||
try
|
||||
{
|
||||
String response = sendRequest(fullUrl);
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
for (MappingIterator<Map> it = mapper.readValues(mapper.createParser(response), Map.class); it.hasNext(); )
|
||||
{
|
||||
Map<String, String> jsonNode = it.next();
|
||||
String host = jsonNode.get("host");
|
||||
String port = jsonNode.get("port");
|
||||
proxyList.add(host + ":" + port);
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Проверяет, есть ли прокси в списке.
|
||||
*/
|
||||
public boolean hasProxies()
|
||||
{
|
||||
return true;
|
||||
// return !proxyList.isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает случайный прокси из списка или null, если список пуст.
|
||||
*/
|
||||
public String getNextProxy()
|
||||
{
|
||||
// if (proxyList.isEmpty())
|
||||
// {
|
||||
// return null;
|
||||
// }
|
||||
// return proxyList.get(random.nextInt(proxyList.size()));
|
||||
|
||||
String host = "pool.proxy.market";
|
||||
String port = "10000";
|
||||
// return proxyLogin + ":" + proxypass + "@" + host + ":" + port;
|
||||
|
||||
//HARDCODE TRUSTED PROXY THROUGHPUT LOCAL
|
||||
return "localhost:8080";
|
||||
}
|
||||
|
||||
|
||||
private String sendRequest(String urlString) throws Exception
|
||||
{
|
||||
URL url = new URL(urlString.replace(" ", "%20")); // Кодируем пробелы на всякий случай
|
||||
HttpURLConnection con = (HttpURLConnection) url.openConnection();
|
||||
con.setRequestMethod("GET");
|
||||
con.setConnectTimeout(15000); // Таймаут соединения 15 сек
|
||||
con.setReadTimeout(15000); // Таймаут чтения 15 сек
|
||||
|
||||
int status = con.getResponseCode();
|
||||
BufferedReader in = new BufferedReader(
|
||||
new InputStreamReader((status == 200) ? con.getInputStream() : con.getErrorStream(),
|
||||
StandardCharsets.UTF_8));
|
||||
String inputLine;
|
||||
StringBuilder content = new StringBuilder();
|
||||
while ((inputLine = in.readLine()) != null)
|
||||
{
|
||||
content.append(inputLine);
|
||||
}
|
||||
in.close();
|
||||
con.disconnect();
|
||||
|
||||
if (status != 200)
|
||||
{
|
||||
logger.error("Ошибка HTTP запроса к API: статус {}, Ответ: {}", status, content);
|
||||
}
|
||||
|
||||
return content.toString();
|
||||
}
|
||||
}
|
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,67 @@
|
||||
package com.google.accountgen.registration;
|
||||
|
||||
/**
|
||||
* Класс со всеми CSS/XPath селекторами для процесса регистрации аккаунта Google
|
||||
*/
|
||||
public class GoogleRegistrationSelectors
|
||||
{
|
||||
|
||||
// Языковые селекторы
|
||||
public static final String LANGUAGE_DROPDOWN = "div[role='combobox'][aria-haspopup='listbox']";
|
||||
public static final String LANGUAGE_LIST_ITEM_ENGLISH_UK = "li[data-value='en-GB']";
|
||||
public static final String LANGUAGE_LIST_ITEM_ENGLISH_UK_XPATH = "//li[contains(., 'English (United Kingdom)')]";
|
||||
public static final String LANGUAGE_ENGLISH_INDICATOR = "input[aria-label='First name']";
|
||||
public static final String LANGUAGE_RUSSIAN_INDICATOR = "input[aria-label='Имя']";
|
||||
|
||||
// Страница имени и фамилии
|
||||
public static final String FIRST_NAME_INPUT = "input[name='firstName']";
|
||||
public static final String LAST_NAME_INPUT = "input[name='lastName']";
|
||||
public static final String NEXT_BUTTON_NAME_PAGE = "button[jsname='LgbsSe']";
|
||||
|
||||
// Страница даты рождения и пола
|
||||
public static final String DAY_INPUT = "input[name='day']";
|
||||
public static final String MONTH_SELECT = "select#month";
|
||||
public static final String YEAR_INPUT = "input[name='year']";
|
||||
public static final String GENDER_SELECT = "select#gender";
|
||||
public static final String NEXT_BUTTON_BIRTHDAY_PAGE = "button[jsname='LgbsSe']";
|
||||
|
||||
// Страница выбора способа входа
|
||||
public static final String CREATE_GMAIL_RADIO = "div[jsname='ornU0b'][data-value='1']";
|
||||
public static final String CREATE_GMAIL_RADIO_ALT = "div[role='radio'][aria-posinset='1'][aria-setsize='2']";
|
||||
public static final String CREATE_GMAIL_RADIO_ALT2 = "div[jsname='ornU0b'][role='radio']";
|
||||
public static final String NEXT_BUTTON_SIGNIN_METHOD_PAGE = "button[jsname='LgbsSe']";
|
||||
|
||||
// Страница регистрации Gmail адреса
|
||||
public static final String CREATE_OWN_GMAIL_RADIO = "div[jsname='ornU0b'][data-value='custom']";
|
||||
public static final String GMAIL_ADDRESS_INPUT = "input[name='Username']";
|
||||
public static final String NEXT_BUTTON_GMAIL_ADDRESS_PAGE = "button[jsname='LgbsSe']";
|
||||
public static final String USERNAME_TAKEN_ERROR = "div.o3Dpx, div.dEOOab.RxsGPe";
|
||||
public static final String SUGGESTED_USERNAME = "div.aCjb5[aria-live='polite'] span.NzQipd";
|
||||
public static final String SUGGESTED_GMAIL_RADIO = "div[jsname='ornU0b'][data-value='0']";
|
||||
public static final String SUGGESTED_GMAIL_RADIO_ALT = "div.mUbCce.l9xNkf.gL67me.jbbQtc[role='radio']";
|
||||
|
||||
// Страница создания пароля
|
||||
public static final String PASSWORD_INPUT = "input[name='Passwd']";
|
||||
public static final String CONFIRM_PASSWORD_INPUT = "input[name='PasswdAgain']";
|
||||
public static final String SHOW_PASSWORD_CHECKBOX = "input[type='checkbox']";
|
||||
public static final String NEXT_BUTTON_PASSWORD_PAGE = "button[jsname='LgbsSe']";
|
||||
|
||||
public static final String NEXT_BUTTON_PHONE_PAGE = "button[jsname='LgbsSe']";
|
||||
|
||||
// Страница ввода кода подтверждения
|
||||
public static final String VERIFICATION_CODE_INPUT = "input[aria-label='Enter verification code'], input#code";
|
||||
public static final String NEXT_BUTTON_CODE_PAGE = "button[jsname='LgbsSe'] span.VfPpkd-vQzf8d";
|
||||
|
||||
// Страница добавления номера телефона
|
||||
public static final String SKIP_BUTTON_ADD_PHONE = "button.VfPpkd-LgbsSe.VfPpkd-LgbsSe-OWXEXe-INsAgc";
|
||||
|
||||
// Страница проверки информации об аккаунте
|
||||
public static final String NEXT_BUTTON_REVIEW_INFO = "button[jsname='LgbsSe']";
|
||||
|
||||
// Страница с условиями использования
|
||||
public static final String I_AGREE_BUTTON_XPATH = "//button[.//span[text()='I agree']]";
|
||||
public static final String I_AGREE_BUTTON = "button.VfPpkd-LgbsSe, button[jsname='LgbsSe']";
|
||||
|
||||
public static final String CONFIRM_PERSONALISATION_XPATH = "//button[.//span[contains(text(), 'Confirm')] or contains(@jsname, 'ssJRIf')]";
|
||||
|
||||
}
|
367
src/main/java/com/google/accountgen/sms/SmsActivateService.java
Normal file
367
src/main/java/com/google/accountgen/sms/SmsActivateService.java
Normal file
@ -0,0 +1,367 @@
|
||||
package com.google.accountgen.sms;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
/**
|
||||
* Сервис для работы с API SMS-Activate.world
|
||||
*/
|
||||
@Service
|
||||
public class SmsActivateService
|
||||
{
|
||||
|
||||
|
||||
private final String API_URL = "https://give-sms.com/stubs/handler_api.php";
|
||||
|
||||
private final String API2_URL = "https://api.sms-activate.world/v2/api/";
|
||||
|
||||
@Value("${default_country}")
|
||||
private int defaultCountry;
|
||||
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(SmsActivateService.class);
|
||||
|
||||
|
||||
// Конфигурационные параметры
|
||||
private static final int MAX_RETRY_COUNT = 30;
|
||||
private static final int ERROR_RETRY_TIMEOUT = 5000;
|
||||
|
||||
public void setApiKey(String apiKey)
|
||||
{
|
||||
this.apiKey = apiKey;
|
||||
}
|
||||
|
||||
// API ключ
|
||||
private String apiKey;
|
||||
|
||||
|
||||
/**
|
||||
* Получает номер телефона для указанного сервиса из конкретной страны
|
||||
*/
|
||||
public ActivationResult getNumberFromCountry(String service, int countryId)
|
||||
{
|
||||
try
|
||||
{
|
||||
double balance = getBalance();
|
||||
if (balance < 0.05)
|
||||
{
|
||||
logger.error("Недостаточно средств на балансе: {} USD", balance);
|
||||
return ActivationResult.error("Недостаточно средств на балансе: " + balance + " USD");
|
||||
}
|
||||
|
||||
if (countryId < 0)
|
||||
{
|
||||
|
||||
logger.warn("Передан некорректный ID страны ({}). Используем ID страны по умолчанию: {}", countryId,
|
||||
defaultCountry);
|
||||
countryId = defaultCountry;
|
||||
if (countryId < 0)
|
||||
{ // Если и по умолчанию некорректный ID, то ошибка
|
||||
logger.error("ID страны некорректен ({}) и не задан по умолчанию. Невозможно запросить номер.",
|
||||
countryId);
|
||||
return ActivationResult.error("ID страны некорректен и не задан по умолчанию.");
|
||||
}
|
||||
}
|
||||
|
||||
logger.info("Запрашиваем номер телефона из страны с ID: {}", countryId);
|
||||
|
||||
String googleService = service;
|
||||
if (service == null || service.isEmpty() || !(service.equals("go") || service.equals(
|
||||
"gv") || service.equals("gl")))
|
||||
{
|
||||
googleService = "go";
|
||||
}
|
||||
logger.info("Используем сервис: {}", googleService);
|
||||
|
||||
String url = API_URL + "?api_key=" + apiKey + "&action=getNumber" + "&service=" + googleService + "&country=" + countryId + "&forward=0";
|
||||
|
||||
logger.debug("Запрос URL (getNumberFromCountry): {}", url.replace(apiKey, "API_KEY_HIDDEN"));
|
||||
String response = sendRequest(url);
|
||||
|
||||
// ACCESS_NUMBER:activation_id:phone_number
|
||||
if (response.startsWith("ACCESS_NUMBER:"))
|
||||
{
|
||||
String[] parts = response.split(":");
|
||||
if (parts.length >= 3)
|
||||
{
|
||||
String activationId = parts[1];
|
||||
String phoneNumber = parts[2];
|
||||
logger.info("Номер получен: ID={}, Телефон={}", activationId, phoneNumber);
|
||||
return ActivationResult.success(activationId, phoneNumber);
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.error("Некорректный формат ответа ACCESS_NUMBER: {}", response);
|
||||
return ActivationResult.error("Некорректный формат ответа ACCESS_NUMBER");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Обработка ошибок (NO_NUMBERS, BAD_KEY, ERROR_SQL и т.д.)
|
||||
logger.warn("API v1 ({}) для страны {}: {}", googleService, countryId, response);
|
||||
if (response.contains("NO_NUMBERS"))
|
||||
{
|
||||
return ActivationResult.error("NO_NUMBERS");
|
||||
}
|
||||
else if (response.contains("NO_BALANCE"))
|
||||
{
|
||||
return ActivationResult.error("NO_BALANCE");
|
||||
}
|
||||
else if (response.contains("WRONG_SERVICE"))
|
||||
{
|
||||
return ActivationResult.error("WRONG_SERVICE");
|
||||
} // Добавить другие ошибки при необходимости
|
||||
else
|
||||
{
|
||||
// Неизвестная ошибка
|
||||
return ActivationResult.error(response);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.error("Исключение при запросе номера: {}", e.getMessage(), e);
|
||||
return ActivationResult.error("Исключение: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Получает статус активации и код из SMS
|
||||
*/
|
||||
public ActivationResult getCode(String activationId)
|
||||
{
|
||||
try
|
||||
{
|
||||
String url = API_URL + "?api_key=" + apiKey + "&action=getStatus&id=" + activationId;
|
||||
logger.info("Запрос кода для активации {}", activationId);
|
||||
|
||||
for (int i = 0; i < MAX_RETRY_COUNT; i++)
|
||||
{
|
||||
String response = sendRequest(url);
|
||||
|
||||
if (response.startsWith("STATUS_OK:"))
|
||||
{
|
||||
String code = response.substring("STATUS_OK:".length());
|
||||
logger.info("Получен SMS-код: {} для активации {}", code, activationId);
|
||||
return ActivationResult.code(code);
|
||||
}
|
||||
else if (response.equals("STATUS_WAIT_CODE"))
|
||||
{
|
||||
logger.info("Ожидание SMS-кода... Попытка {}/{}", i + 1, MAX_RETRY_COUNT);
|
||||
Thread.sleep(12000);
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.error("Ошибка при получении SMS-кода для активации {}: {}", activationId, response);
|
||||
if (response.equals("STATUS_CANCEL") || response.equals("STATUS_WAIT_RETRY") || response.equals(
|
||||
"BANNED") || response.contains("BAD_KEY") || response.contains("ERROR_"))
|
||||
{
|
||||
logger.error("Критическая ошибка при получении SMS-кода: {}", response);
|
||||
return ActivationResult.error("Ошибка при получении SMS-кода: " + response);
|
||||
}
|
||||
Thread.sleep(ERROR_RETRY_TIMEOUT);
|
||||
}
|
||||
}
|
||||
|
||||
logger.error("Превышено время ожидания SMS-кода для активации {}", activationId);
|
||||
return ActivationResult.error("Превышено время ожидания SMS-кода");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.error("Исключение при запросе SMS-кода для активации {}: {}", activationId, e.getMessage(), e);
|
||||
return ActivationResult.error("Исключение: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Устанавливает статус активации
|
||||
*/
|
||||
public void setStatus(String activationId, int status)
|
||||
{
|
||||
try
|
||||
{
|
||||
String url = API_URL + "?api_key=" + apiKey + "&action=setStatus&status=" + status + "&id=" + activationId;
|
||||
logger.info("Установка статуса {} для активации {}", status, activationId);
|
||||
|
||||
String response = sendRequest(url);
|
||||
|
||||
if (response.startsWith("ACCESS_READY") || response.equals("ACCESS_RETRY_GET") || response.equals(
|
||||
"ACCESS_ACTIVATION") || response.equals("ACCESS_CANCEL"))
|
||||
{
|
||||
logger.info("Статус активации {} успешно изменен на {}", activationId, status);
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.error("Ошибка при изменении статуса активации {} на {}: {}", activationId, status, response);
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.error("Исключение при изменении статуса активации {}: {}", activationId, e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Получает баланс аккаунта
|
||||
*/
|
||||
public double getBalance()
|
||||
{
|
||||
try
|
||||
{
|
||||
String url = API_URL + "?api_key=" + apiKey + "&action=getBalance";
|
||||
String response = sendRequest(url);
|
||||
|
||||
if (response.startsWith("ACCESS_BALANCE:"))
|
||||
{
|
||||
String balanceStr = response.substring("ACCESS_BALANCE:".length());
|
||||
double balance = Double.parseDouble(balanceStr);
|
||||
logger.info("Текущий баланс: {} USD", balance);
|
||||
return balance;
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.error("Ошибка при получении баланса: {}", response);
|
||||
try
|
||||
{
|
||||
String url2 = API2_URL + "getBalance?api_key=" + apiKey;
|
||||
String response2 = sendRequest(url2);
|
||||
if (response2.contains("\"balance\":"))
|
||||
{
|
||||
String balanceStr = response2.split("\"balance\":")[1].split(",")[0].trim();
|
||||
double balance = Double.parseDouble(balanceStr);
|
||||
logger.info("Текущий баланс (API2): {} USD", balance);
|
||||
return balance;
|
||||
}
|
||||
}
|
||||
catch (Exception e2)
|
||||
{
|
||||
logger.error("Ошибка при получении баланса через API2", e2);
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.error("Ошибка при запросе баланса", e);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Отправляет HTTP GET запрос к API
|
||||
*/
|
||||
private String sendRequest(String urlString) throws Exception
|
||||
{
|
||||
URL url = new URL(urlString.replace(" ", "%20")); // Кодируем пробелы на всякий случай
|
||||
HttpURLConnection con = (HttpURLConnection) url.openConnection();
|
||||
con.setRequestMethod("GET");
|
||||
con.setConnectTimeout(15000); // Таймаут соединения 15 сек
|
||||
con.setReadTimeout(15000); // Таймаут чтения 15 сек
|
||||
|
||||
int status = con.getResponseCode();
|
||||
BufferedReader in = new BufferedReader(
|
||||
new InputStreamReader((status == 200) ? con.getInputStream() : con.getErrorStream(),
|
||||
StandardCharsets.UTF_8));
|
||||
String inputLine;
|
||||
StringBuilder content = new StringBuilder();
|
||||
while ((inputLine = in.readLine()) != null)
|
||||
{
|
||||
content.append(inputLine);
|
||||
}
|
||||
in.close();
|
||||
con.disconnect();
|
||||
|
||||
if (status != 200)
|
||||
{
|
||||
logger.error("Ошибка HTTP запроса к API: статус {}, URL: {}, Ответ: {}", status,
|
||||
urlString.replace(apiKey, "API_KEY_HIDDEN"), content.toString());
|
||||
}
|
||||
|
||||
return content.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Скрывает часть API ключа для логирования
|
||||
*/
|
||||
private String hideApiKey(String key)
|
||||
{
|
||||
if (key == null || key.length() < 8)
|
||||
{
|
||||
return "(invalid key)";
|
||||
}
|
||||
return key.substring(0, 4) + "..." + key.substring(key.length() - 4);
|
||||
}
|
||||
|
||||
// -- Внутренний класс ActivationResult --
|
||||
@SuppressWarnings("unused")
|
||||
public static class ActivationResult
|
||||
{
|
||||
public boolean success; // Сделано public
|
||||
public String activationId; // Сделано public
|
||||
public String phoneNumber; // Сделано public
|
||||
public String smsCode; // Сделано public
|
||||
public String errorMessage; // Сделано public
|
||||
|
||||
// Приватный конструктор
|
||||
private ActivationResult(boolean success, String activationId, String phoneNumber, String smsCode, String errorMessage)
|
||||
{
|
||||
this.success = success;
|
||||
this.activationId = activationId;
|
||||
this.phoneNumber = phoneNumber;
|
||||
this.smsCode = smsCode;
|
||||
this.errorMessage = errorMessage;
|
||||
}
|
||||
|
||||
// Статические фабричные методы
|
||||
public static ActivationResult success(String activationId, String phoneNumber)
|
||||
{
|
||||
return new ActivationResult(true, activationId, phoneNumber, null, null);
|
||||
}
|
||||
|
||||
public static ActivationResult code(String smsCode)
|
||||
{
|
||||
// Используем этот метод, когда получаем код для уже существующей активации
|
||||
// Можно было бы передавать и ID/номер, но пока не требуется
|
||||
return new ActivationResult(true, null, null, smsCode, null);
|
||||
}
|
||||
|
||||
public static ActivationResult error(String message)
|
||||
{
|
||||
return new ActivationResult(false, null, null, null, message);
|
||||
}
|
||||
|
||||
// Геттеры (можно удалить, если поля public)
|
||||
public boolean isSuccess()
|
||||
{
|
||||
return success;
|
||||
}
|
||||
|
||||
public String getActivationId()
|
||||
{
|
||||
return activationId;
|
||||
}
|
||||
|
||||
public String getPhoneNumber()
|
||||
{
|
||||
return phoneNumber;
|
||||
}
|
||||
|
||||
public String getCode()
|
||||
{
|
||||
return smsCode;
|
||||
}
|
||||
|
||||
public String getMessage()
|
||||
{
|
||||
return errorMessage;
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,145 @@
|
||||
package com.google.accountgen.user;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.time.LocalDate;
|
||||
import java.time.Year;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Класс для генерации случайных данных пользователя
|
||||
*/
|
||||
public class RandomUserGenerator
|
||||
{
|
||||
private static final Logger logger = LoggerFactory.getLogger(RandomUserGenerator.class);
|
||||
private static final SecureRandom random = new SecureRandom();
|
||||
|
||||
// Списки имен и фамилий
|
||||
private static final List<String> MALE_FIRST_NAMES = Arrays.asList("James", "John", "Robert", "Michael", "William",
|
||||
"David", "Richard", "Joseph", "Thomas", "Charles", "Christopher", "Daniel", "Matthew", "Anthony", "Mark",
|
||||
"Donald", "Steven", "Paul", "Andrew", "Joshua", "Kenneth", "Kevin", "Brian", "George", "Timothy", "Ronald",
|
||||
"Edward", "Jason", "Jeffrey", "Ryan");
|
||||
|
||||
private static final List<String> FEMALE_FIRST_NAMES = Arrays.asList("Mary", "Patricia", "Jennifer", "Linda",
|
||||
"Elizabeth", "Barbara", "Susan", "Jessica", "Sarah", "Karen", "Lisa", "Nancy", "Betty", "Margaret",
|
||||
"Sandra", "Ashley", "Kimberly", "Emily", "Donna", "Michelle", "Carol", "Amanda", "Dorothy", "Melissa",
|
||||
"Deborah", "Stephanie", "Rebecca", "Sharon", "Laura", "Cynthia");
|
||||
|
||||
private static final List<String> LAST_NAMES = Arrays.asList("Smith", "Johnson", "Williams", "Jones", "Brown",
|
||||
"Davis", "Miller", "Wilson", "Moore", "Taylor", "Anderson", "Thomas", "Jackson", "White", "Harris",
|
||||
"Martin", "Thompson", "Garcia", "Martinez", "Robinson", "Clark", "Rodriguez", "Lewis", "Lee", "Walker",
|
||||
"Hall", "Allen", "Young", "Hernandez", "King");
|
||||
|
||||
/**
|
||||
* Генерирует случайные данные пользователя
|
||||
*
|
||||
* @return объект с данными пользователя
|
||||
*/
|
||||
public UserData generateUser()
|
||||
{
|
||||
try
|
||||
{
|
||||
// Генерируем пол случайным образом
|
||||
boolean isMale = random.nextBoolean();
|
||||
UserData.Gender gender = isMale ? UserData.Gender.MALE : UserData.Gender.FEMALE;
|
||||
|
||||
// Выбираем имя в зависимости от пола
|
||||
String firstName = isMale ? MALE_FIRST_NAMES.get(
|
||||
random.nextInt(MALE_FIRST_NAMES.size())) : FEMALE_FIRST_NAMES.get(
|
||||
random.nextInt(FEMALE_FIRST_NAMES.size()));
|
||||
|
||||
// Выбираем фамилию
|
||||
String lastName = LAST_NAMES.get(random.nextInt(LAST_NAMES.size()));
|
||||
|
||||
// Генерируем имя пользователя на основе имени и фамилии
|
||||
String username = generateUsername(firstName, lastName);
|
||||
|
||||
// Генерируем пароль
|
||||
String password = generateStrongPassword();
|
||||
|
||||
// Генерируем дату рождения (взрослый человек 18-40 лет)
|
||||
int currentYear = Year.now().getValue();
|
||||
int birthYear = currentYear - 18 - random.nextInt(23);
|
||||
int birthMonth = 1 + random.nextInt(12);
|
||||
|
||||
// Определяем максимальное количество дней в месяце
|
||||
LocalDate date = LocalDate.of(birthYear, birthMonth, 1);
|
||||
int maxDays = date.lengthOfMonth();
|
||||
int birthDay = 1 + random.nextInt(maxDays);
|
||||
|
||||
// Создаем и возвращаем объект UserData
|
||||
return new UserData(firstName, lastName, username, password, birthDay, birthMonth, birthYear, gender);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.error("Ошибка при генерации случайных данных пользователя", e);
|
||||
|
||||
// Возвращаем данные по умолчанию в случае ошибки
|
||||
return new UserData("John", "Doe", "johndoe" + random.nextInt(10000), "P@ssw0rd" + random.nextInt(10000), 1,
|
||||
1, 1990, UserData.Gender.MALE);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Генерирует имя пользователя на основе имени и фамилии
|
||||
*
|
||||
* @param firstName имя
|
||||
* @param lastName фамилия
|
||||
* @return имя пользователя для email
|
||||
*/
|
||||
private String generateUsername(String firstName, String lastName)
|
||||
{
|
||||
// Берем первую букву имени и фамилию + случайные цифры
|
||||
String base = firstName.toLowerCase().charAt(0) + lastName.toLowerCase();
|
||||
|
||||
// Добавляем случайные цифры (от 100 до 9999)
|
||||
return base + (100 + random.nextInt(9900));
|
||||
}
|
||||
|
||||
/**
|
||||
* Генерирует сильный пароль заданной длины
|
||||
*
|
||||
* @return сгенерированный пароль
|
||||
*/
|
||||
private String generateStrongPassword()
|
||||
{
|
||||
// Символы для генерации пароля
|
||||
String upperCaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
||||
String lowerCaseLetters = "abcdefghijklmnopqrstuvwxyz";
|
||||
String numbers = "0123456789";
|
||||
String specialChars = "!@#$%^&*()_-+=<>?";
|
||||
|
||||
// Объединяем все символы
|
||||
String allChars = upperCaseLetters + lowerCaseLetters + numbers + specialChars;
|
||||
|
||||
// Создаем буфер для хранения пароля
|
||||
StringBuilder password = new StringBuilder();
|
||||
|
||||
// Обязательно добавляем по одному символу каждого типа для соответствия требованиям
|
||||
password.append(upperCaseLetters.charAt(random.nextInt(upperCaseLetters.length())));
|
||||
password.append(lowerCaseLetters.charAt(random.nextInt(lowerCaseLetters.length())));
|
||||
password.append(numbers.charAt(random.nextInt(numbers.length())));
|
||||
password.append(specialChars.charAt(random.nextInt(specialChars.length())));
|
||||
|
||||
// Добавляем оставшиеся символы
|
||||
for (int i = 4; i < 12; i++)
|
||||
{
|
||||
password.append(allChars.charAt(random.nextInt(allChars.length())));
|
||||
}
|
||||
|
||||
// Перемешиваем строку для большей случайности
|
||||
char[] passwordArray = password.toString().toCharArray();
|
||||
for (int i = 0; i < passwordArray.length; i++)
|
||||
{
|
||||
int j = random.nextInt(passwordArray.length);
|
||||
char temp = passwordArray[i];
|
||||
passwordArray[i] = passwordArray[j];
|
||||
passwordArray[j] = temp;
|
||||
}
|
||||
|
||||
return new String(passwordArray);
|
||||
}
|
||||
}
|
147
src/main/java/com/google/accountgen/user/UserData.java
Normal file
147
src/main/java/com/google/accountgen/user/UserData.java
Normal file
@ -0,0 +1,147 @@
|
||||
package com.google.accountgen.user;
|
||||
|
||||
/**
|
||||
* Класс для хранения данных пользователя
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
public class UserData
|
||||
{
|
||||
|
||||
/**
|
||||
* Перечисление для пола пользователя
|
||||
*/
|
||||
public enum Gender
|
||||
{
|
||||
MALE, FEMALE
|
||||
}
|
||||
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
private String username;
|
||||
private String password;
|
||||
private int birthDay;
|
||||
private int birthMonth;
|
||||
private int birthYear;
|
||||
private Gender gender;
|
||||
|
||||
/**
|
||||
* Конструктор с параметрами
|
||||
*
|
||||
* @param firstName имя пользователя
|
||||
* @param lastName фамилия пользователя
|
||||
* @param username имя пользователя для email
|
||||
* @param password пароль
|
||||
* @param birthDay день рождения
|
||||
* @param birthMonth месяц рождения
|
||||
* @param birthYear год рождения
|
||||
* @param gender пол пользователя
|
||||
*/
|
||||
public UserData(String firstName, String lastName, String username, String password, int birthDay, int birthMonth, int birthYear, Gender gender)
|
||||
{
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
this.username = username;
|
||||
this.password = password;
|
||||
this.birthDay = birthDay;
|
||||
this.birthMonth = birthMonth;
|
||||
this.birthYear = birthYear;
|
||||
this.gender = gender;
|
||||
}
|
||||
|
||||
/**
|
||||
* Получает полный email пользователя
|
||||
*
|
||||
* @return email в формате username@gmail.com
|
||||
*/
|
||||
public String getEmail()
|
||||
{
|
||||
return username + "@gmail.com";
|
||||
}
|
||||
|
||||
// Геттеры и сеттеры
|
||||
public String getFirstName()
|
||||
{
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName)
|
||||
{
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName()
|
||||
{
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName)
|
||||
{
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public String getUsername()
|
||||
{
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username)
|
||||
{
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getPassword()
|
||||
{
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password)
|
||||
{
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public int getBirthDay()
|
||||
{
|
||||
return birthDay;
|
||||
}
|
||||
|
||||
public void setBirthDay(int birthDay)
|
||||
{
|
||||
this.birthDay = birthDay;
|
||||
}
|
||||
|
||||
public int getBirthMonth()
|
||||
{
|
||||
return birthMonth;
|
||||
}
|
||||
|
||||
public void setBirthMonth(int birthMonth)
|
||||
{
|
||||
this.birthMonth = birthMonth;
|
||||
}
|
||||
|
||||
public int getBirthYear()
|
||||
{
|
||||
return birthYear;
|
||||
}
|
||||
|
||||
public void setBirthYear(int birthYear)
|
||||
{
|
||||
this.birthYear = birthYear;
|
||||
}
|
||||
|
||||
public Gender getGender()
|
||||
{
|
||||
return gender;
|
||||
}
|
||||
|
||||
public void setGender(Gender gender)
|
||||
{
|
||||
this.gender = gender;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString()
|
||||
{
|
||||
return "UserData{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", username='" + username + '\'' + ", password='" + password + '\'' + ", birthDay=" + birthDay + ", birthMonth=" + birthMonth + ", birthYear=" + birthYear + ", gender=" + gender + '}';
|
||||
}
|
||||
}
|
@ -0,0 +1,441 @@
|
||||
package com.google.accountgen.youtube;
|
||||
|
||||
import org.openqa.selenium.*;
|
||||
import org.openqa.selenium.devtools.DevTools;
|
||||
import org.openqa.selenium.devtools.HasDevTools;
|
||||
import org.openqa.selenium.devtools.v135.network.Network;
|
||||
import org.openqa.selenium.devtools.v135.network.model.Request;
|
||||
import org.openqa.selenium.support.ui.ExpectedConditions;
|
||||
import org.openqa.selenium.support.ui.WebDriverWait;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Класс для работы с YouTube Music и получения POT токена
|
||||
*/
|
||||
public class YouTubeMusicHandler
|
||||
{
|
||||
private static final Logger logger = LoggerFactory.getLogger(YouTubeMusicHandler.class);
|
||||
private static final String YOUTUBE_MUSIC_URL = "https://music.youtube.com/";
|
||||
private static final Pattern POT_TOKEN_PATTERN = Pattern.compile("\"pot\":\"([^\"]+)\"");
|
||||
|
||||
private final WebDriver driver;
|
||||
private final WebDriverWait wait;
|
||||
|
||||
/**
|
||||
* Создает новый обработчик YouTube Music
|
||||
*
|
||||
* @param driver веб-драйвер
|
||||
*/
|
||||
public YouTubeMusicHandler(WebDriver driver)
|
||||
{
|
||||
this.driver = driver;
|
||||
this.wait = new WebDriverWait(driver, Duration.ofSeconds(15));
|
||||
}
|
||||
|
||||
/**
|
||||
* Получает POT токен через YouTube Music (DevTools)
|
||||
*
|
||||
* @return POT токен или null в случае ошибки
|
||||
*/
|
||||
public String getPotTokenViaDevTools()
|
||||
{
|
||||
DevTools devTools = null;
|
||||
try
|
||||
{
|
||||
logger.info("Открываю YouTube Music для извлечения pot через DevTools...");
|
||||
driver.get(YOUTUBE_MUSIC_URL);
|
||||
wait.until(ExpectedConditions.presenceOfElementLocated(By.tagName("body")));
|
||||
Thread.sleep(2000);
|
||||
|
||||
// Кликаем по первой ссылке внутри первого видео/трека
|
||||
try
|
||||
{
|
||||
WebElement firstTrackLink = wait.until(ExpectedConditions.elementToBeClickable(
|
||||
By.xpath("((//ytmusic-responsive-list-item-renderer)[1]//a)[1]")));
|
||||
firstTrackLink.click();
|
||||
logger.info("Первая ссылка внутри первого трека/видео кликнута для воспроизведения.");
|
||||
// Можно добавить ожидание загрузки страницы видео (например, по изменению URL или появлению кнопки play)
|
||||
Thread.sleep(2000);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.warn("Не удалось найти или кликнуть первую ссылку внутри первого трека: {}", e.getMessage());
|
||||
}
|
||||
|
||||
// После клика по видео — обработка рекламы по новым селекторам
|
||||
try
|
||||
{
|
||||
int maxAdWaitSeconds = 40;
|
||||
int checkIntervalMs = 1200;
|
||||
int waited = 0;
|
||||
boolean adDetected;
|
||||
By sponsoredBlock = By.xpath(
|
||||
"//div[contains(@class, 'ytp-ad-player-overlay-instream-info') and .//div[contains(@id, 'simple-ad-badge') and contains(., 'Sponsored')]]");
|
||||
By skipInfo = By.xpath(
|
||||
"//span[contains(@class, 'ytp-ad-preview-container') and contains(translate(normalize-space(.), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'you can skip to')]");
|
||||
By skipButton = By.xpath(
|
||||
"//button[contains(@class, 'ytp-ad-skip-button-modern') and .//div[text()='Skip']]");
|
||||
|
||||
int adCount = 0;
|
||||
while (waited < maxAdWaitSeconds * 1000)
|
||||
{
|
||||
adDetected = !driver.findElements(sponsoredBlock).isEmpty();
|
||||
if (!adDetected)
|
||||
{
|
||||
logger.info("Рекламный блок 'Sponsored...' не найден, продолжаем работу с видео.");
|
||||
break;
|
||||
}
|
||||
logger.info("Обнаружена реклама ({} раз). Ожидание возможности пропуска...", adCount + 1);
|
||||
// Ждём появления возможности пропуска
|
||||
boolean canSkip = false;
|
||||
for (int i = 0; i < 10; i++)
|
||||
{ // до 12 секунд
|
||||
if (!driver.findElements(skipInfo).isEmpty() || !driver.findElements(skipButton).isEmpty())
|
||||
{
|
||||
canSkip = true;
|
||||
break;
|
||||
}
|
||||
Thread.sleep(checkIntervalMs);
|
||||
waited += checkIntervalMs;
|
||||
}
|
||||
if (canSkip)
|
||||
{
|
||||
// Кликаем по кнопке Skip, если она появилась
|
||||
try
|
||||
{
|
||||
WebElement btn = driver.findElement(skipButton);
|
||||
btn.click();
|
||||
logger.info("Кнопка 'Skip' нажата.");
|
||||
Thread.sleep(2500);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.warn("Кнопка 'Skip' не найдена или не нажата: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.info("Возможность пропуска рекламы не появилась, ждём исчезновения рекламы...");
|
||||
// Ждём исчезновения блока Sponsored...
|
||||
for (int i = 0; i < 10; i++)
|
||||
{ // до 12 секунд
|
||||
if (driver.findElements(sponsoredBlock).isEmpty())
|
||||
{
|
||||
logger.info("Рекламный блок исчез.");
|
||||
break;
|
||||
}
|
||||
Thread.sleep(checkIntervalMs);
|
||||
waited += checkIntervalMs;
|
||||
}
|
||||
}
|
||||
// Проверяем, не появилась ли вторая реклама
|
||||
adDetected = !driver.findElements(sponsoredBlock).isEmpty();
|
||||
if (adDetected)
|
||||
{
|
||||
adCount++;
|
||||
logger.info("Обнаружена вторая реклама, повторяем обработку...");
|
||||
continue;
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.info("Рекламный блок полностью исчез, продолжаем работу с видео.");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.warn("Ошибка при обработке рекламы: {}", e.getMessage());
|
||||
}
|
||||
|
||||
// После обработки рекламы — ставим видео на паузу
|
||||
try
|
||||
{
|
||||
WebElement pauseBtn = null;
|
||||
try
|
||||
{
|
||||
pauseBtn = wait.withTimeout(Duration.ofSeconds(5))
|
||||
.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@aria-label='Pause']")));
|
||||
}
|
||||
catch (TimeoutException ignore)
|
||||
{
|
||||
}
|
||||
if (pauseBtn == null)
|
||||
{
|
||||
try
|
||||
{
|
||||
pauseBtn = wait.withTimeout(Duration.ofSeconds(3))
|
||||
.until(ExpectedConditions.elementToBeClickable(
|
||||
By.cssSelector("button#button[aria-label='Pause']")));
|
||||
}
|
||||
catch (TimeoutException ignore)
|
||||
{
|
||||
}
|
||||
}
|
||||
if (pauseBtn != null)
|
||||
{
|
||||
pauseBtn.click();
|
||||
logger.info("Видео поставлено на паузу после рекламы.");
|
||||
Thread.sleep(1000);
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.info("Кнопка паузы не найдена — возможно, видео уже на паузе.");
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.warn("Ошибка при попытке поставить видео на паузу: {}", e.getMessage());
|
||||
}
|
||||
|
||||
// --- Подключаем DevTools и настраиваем слушателя ЗАРАНЕЕ ---
|
||||
devTools = ((HasDevTools) driver).getDevTools();
|
||||
devTools.createSession();
|
||||
devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));
|
||||
|
||||
// Список для хранения URL запросов к googlevideo.com
|
||||
final List<String> videoUrls = new ArrayList<>(); // Используем final и effectively final в лямбде
|
||||
|
||||
devTools.addListener(Network.requestWillBeSent(), event ->
|
||||
{
|
||||
Request req = event.getRequest();
|
||||
String url = req.getUrl();
|
||||
// Собираем все URL, содержащие googlevideo.com
|
||||
if (url.contains("googlevideo.com"))
|
||||
{
|
||||
logger.debug("Перехвачен URL: {}", url); // Используем debug уровень
|
||||
synchronized (videoUrls)
|
||||
{ // Синхронизируем доступ к списку из другого потока
|
||||
videoUrls.add(url);
|
||||
}
|
||||
}
|
||||
});
|
||||
logger.info("DevTools сессия создана и слушатель Network.requestWillBeSent добавлен.");
|
||||
// --------------------------------------------------------------
|
||||
|
||||
// Далее — воспроизведение видео
|
||||
try
|
||||
{
|
||||
WebElement playBtn = null;
|
||||
try
|
||||
{
|
||||
playBtn = wait.withTimeout(Duration.ofSeconds(5))
|
||||
.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@aria-label='Play']")));
|
||||
}
|
||||
catch (TimeoutException ignore)
|
||||
{
|
||||
}
|
||||
if (playBtn == null)
|
||||
{
|
||||
try
|
||||
{
|
||||
playBtn = wait.withTimeout(Duration.ofSeconds(3)).until(ExpectedConditions.elementToBeClickable(
|
||||
By.cssSelector("button#button[aria-label='Play']")));
|
||||
}
|
||||
catch (TimeoutException ignore)
|
||||
{
|
||||
}
|
||||
}
|
||||
if (playBtn != null)
|
||||
{
|
||||
playBtn.click();
|
||||
logger.info("Видео запущено для генерации сетевых запросов.");
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.info("Кнопка Play не найдена — возможно, видео уже играет.");
|
||||
}
|
||||
// Ожидание, чтобы запросы успели отправиться и быть перехваченными
|
||||
// Увеличиваем ожидание до 15 секунд
|
||||
logger.info("Ожидание 15 секунд для перехвата сетевых запросов...");
|
||||
Thread.sleep(15000);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.warn("Ошибка при попытке воспроизвести видео: {}", e.getMessage());
|
||||
}
|
||||
|
||||
// --- Обработка результатов после ожидания ---
|
||||
logger.info("Сбор URL завершен. Всего перехвачено URL к googlevideo.com: {}", videoUrls.size());
|
||||
|
||||
// Отключаем DevTools
|
||||
devTools.close();
|
||||
devTools = null; // Сбрасываем, чтобы в finally не закрывать повторно
|
||||
|
||||
if (videoUrls.isEmpty())
|
||||
{
|
||||
logger.warn("Не перехвачено ни одного URL к googlevideo.com.");
|
||||
return null;
|
||||
}
|
||||
|
||||
// Берем последний URL из списка
|
||||
String lastUrl = videoUrls.get(videoUrls.size() - 1);
|
||||
logger.info("Последний перехваченный URL к googlevideo.com: {}", lastUrl);
|
||||
|
||||
// Извлекаем pot токен из последнего URL
|
||||
String potToken = extractPotFromUrl(lastUrl);
|
||||
|
||||
if (potToken != null)
|
||||
{
|
||||
logger.info("POT токен успешно извлечен из последнего URL: {}", potToken);
|
||||
return potToken;
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.warn("Не удалось извлечь POT токен из последнего URL: {}", lastUrl);
|
||||
// Можно попробовать проверить предыдущие URL на всякий случай, если последний не сработал
|
||||
// for (int i = videoUrls.size() - 2; i >= 0; i--) { ... }
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.error("Ошибка при извлечении pot через DevTools: {}", e.getMessage(), e);
|
||||
return null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Убедимся, что DevTools закрыт, если он был создан и не закрыт ранее
|
||||
if (devTools != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
devTools.close();
|
||||
logger.info("DevTools сессия закрыта в finally.");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.error("Ошибка при закрытии DevTools в finally: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Вспомогательный метод для извлечения pot из URL, используя логику split.
|
||||
*/
|
||||
private String extractPotFromUrl(String url)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Извлекаем часть URL после '?'
|
||||
String queryString = url.substring(url.indexOf('?') + 1);
|
||||
// Разбиваем на параметры
|
||||
String[] params = queryString.split("&");
|
||||
for (String param : params)
|
||||
{
|
||||
// Ищем параметр, начинающийся с "pot="
|
||||
if (param.startsWith("pot="))
|
||||
{
|
||||
// Разбиваем по '=' и берем вторую часть
|
||||
String[] keyValue = param.split("=");
|
||||
if (keyValue.length > 1)
|
||||
{
|
||||
return keyValue[1]; // Возвращаем значение токена
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.warn("Найден параметр 'pot=', но нет значения после '=': {}", param);
|
||||
return null; // Параметр есть, но пустой
|
||||
}
|
||||
}
|
||||
}
|
||||
logger.warn("Параметр 'pot=' не найден в URL: {}", url);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.error("Ошибка при разборе URL для извлечения pot: {}", url, e);
|
||||
}
|
||||
return null; // Токен не найден или ошибка
|
||||
}
|
||||
|
||||
/**
|
||||
* Получает POT токен через YouTube Music
|
||||
*
|
||||
* @return POT токен или null в случае ошибки
|
||||
*/
|
||||
public String getPotToken()
|
||||
{
|
||||
try
|
||||
{
|
||||
logger.info("Получение POT токена через YouTube Music");
|
||||
// Открываем YouTube Music и пробуем DevTools
|
||||
String pot = getPotTokenViaDevTools();
|
||||
if (pot != null && !pot.isEmpty())
|
||||
{
|
||||
logger.info("POT токен успешно получен через DevTools");
|
||||
return pot;
|
||||
}
|
||||
// Если не удалось — пробуем старые методы
|
||||
driver.get(YOUTUBE_MUSIC_URL);
|
||||
wait.until(ExpectedConditions.presenceOfElementLocated(By.tagName("body")));
|
||||
Thread.sleep(3000);
|
||||
String pageSource = driver.getPageSource();
|
||||
pot = extractPotTokenFromPage(pageSource);
|
||||
if (pot != null && !pot.isEmpty())
|
||||
{
|
||||
logger.info("POT токен успешно получен из страницы");
|
||||
return pot;
|
||||
}
|
||||
pot = extractPotTokenFromCookies();
|
||||
if (pot != null && !pot.isEmpty())
|
||||
{
|
||||
logger.info("POT токен успешно получен из cookies");
|
||||
return pot;
|
||||
}
|
||||
logger.warn("Не удалось получить POT токен");
|
||||
return null;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.error("Ошибка при получении POT токена", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Извлекает POT токен из исходного кода страницы
|
||||
*
|
||||
* @param pageSource исходный код страницы
|
||||
* @return POT токен или null, если не найден
|
||||
*/
|
||||
private String extractPotTokenFromPage(String pageSource)
|
||||
{
|
||||
Matcher matcher = POT_TOKEN_PATTERN.matcher(pageSource);
|
||||
if (matcher.find())
|
||||
{
|
||||
return matcher.group(1);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Извлекает POT токен из cookies
|
||||
*
|
||||
* @return POT токен или null, если не найден
|
||||
*/
|
||||
private String extractPotTokenFromCookies()
|
||||
{
|
||||
Set<Cookie> cookies = driver.manage().getCookies();
|
||||
|
||||
for (Cookie cookie : cookies)
|
||||
{
|
||||
if (cookie.getName().equals("VISITOR_INFO1_LIVE"))
|
||||
{
|
||||
return cookie.getValue();
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
24
src/main/resources/application.yml
Normal file
24
src/main/resources/application.yml
Normal file
@ -0,0 +1,24 @@
|
||||
#sms_activate_api_key: cd64e325c15813edc722867BB6171B94
|
||||
sms_activate_api_key: pPmJIKmh7RepulVySCPf
|
||||
|
||||
captcha_api_key: deeb0d134a47e88dffab6dc48a5a0906
|
||||
captcha_service_type: TWOCAPTCHA
|
||||
|
||||
retry_count: 3
|
||||
|
||||
use_proxy: true
|
||||
proxyLogin: MNj9l11mZZQA
|
||||
proxyPass: RNW78Fm5
|
||||
|
||||
use_vpn: false
|
||||
vpn_extension_path: extensions/vpn
|
||||
|
||||
|
||||
use_goodbyedpi: false
|
||||
goodbyedpi_path: scripts/goodbyedpi.cmd
|
||||
|
||||
sms_service: SMSACTIVATE
|
||||
account_count: 30
|
||||
delay_between_attempts: 5000
|
||||
|
||||
default_country: 0
|
21
src/main/resources/logback.xml
Normal file
21
src/main/resources/logback.xml
Normal file
@ -0,0 +1,21 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
|
||||
<file>logs/google-account-generator.log</file>
|
||||
<append>true</append>
|
||||
<encoder>
|
||||
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="CONSOLE" />
|
||||
<appender-ref ref="FILE" />
|
||||
</root>
|
||||
</configuration>
|
24
target/classes/application.yml
Normal file
24
target/classes/application.yml
Normal file
@ -0,0 +1,24 @@
|
||||
#sms_activate_api_key: cd64e325c15813edc722867BB6171B94
|
||||
sms_activate_api_key: pPmJIKmh7RepulVySCPf
|
||||
|
||||
captcha_api_key: deeb0d134a47e88dffab6dc48a5a0906
|
||||
captcha_service_type: TWOCAPTCHA
|
||||
|
||||
retry_count: 3
|
||||
|
||||
use_proxy: true
|
||||
proxyLogin: MNj9l11mZZQA
|
||||
proxyPass: RNW78Fm5
|
||||
|
||||
use_vpn: false
|
||||
vpn_extension_path: extensions/vpn
|
||||
|
||||
|
||||
use_goodbyedpi: false
|
||||
goodbyedpi_path: scripts/goodbyedpi.cmd
|
||||
|
||||
sms_service: SMSACTIVATE
|
||||
account_count: 30
|
||||
delay_between_attempts: 5000
|
||||
|
||||
default_country: 0
|
BIN
target/classes/com/google/accountgen/CookieGenerator.class
Normal file
BIN
target/classes/com/google/accountgen/CookieGenerator.class
Normal file
Binary file not shown.
BIN
target/classes/com/google/accountgen/Task.class
Normal file
BIN
target/classes/com/google/accountgen/Task.class
Normal file
Binary file not shown.
BIN
target/classes/com/google/accountgen/account/AccountResult.class
Normal file
BIN
target/classes/com/google/accountgen/account/AccountResult.class
Normal file
Binary file not shown.
BIN
target/classes/com/google/accountgen/account/GoogleAccount.class
Normal file
BIN
target/classes/com/google/accountgen/account/GoogleAccount.class
Normal file
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
target/classes/com/google/accountgen/account/UserData.class
Normal file
BIN
target/classes/com/google/accountgen/account/UserData.class
Normal file
Binary file not shown.
Binary file not shown.
BIN
target/classes/com/google/accountgen/captcha/CaptchaSolver.class
Normal file
BIN
target/classes/com/google/accountgen/captcha/CaptchaSolver.class
Normal file
Binary file not shown.
BIN
target/classes/com/google/accountgen/cookies/CookieManager.class
Normal file
BIN
target/classes/com/google/accountgen/cookies/CookieManager.class
Normal file
Binary file not shown.
BIN
target/classes/com/google/accountgen/proxy/ProxyManager.class
Normal file
BIN
target/classes/com/google/accountgen/proxy/ProxyManager.class
Normal file
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
target/classes/com/google/accountgen/user/UserData$Gender.class
Normal file
BIN
target/classes/com/google/accountgen/user/UserData$Gender.class
Normal file
Binary file not shown.
BIN
target/classes/com/google/accountgen/user/UserData.class
Normal file
BIN
target/classes/com/google/accountgen/user/UserData.class
Normal file
Binary file not shown.
Binary file not shown.
21
target/classes/logback.xml
Normal file
21
target/classes/logback.xml
Normal file
@ -0,0 +1,21 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
|
||||
<file>logs/google-account-generator.log</file>
|
||||
<append>true</append>
|
||||
<encoder>
|
||||
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="CONSOLE" />
|
||||
<appender-ref ref="FILE" />
|
||||
</root>
|
||||
</configuration>
|
BIN
target/cookieGenerator-jar-with-dependencies.jar
Normal file
BIN
target/cookieGenerator-jar-with-dependencies.jar
Normal file
Binary file not shown.
BIN
target/cookieGenerator.jar
Normal file
BIN
target/cookieGenerator.jar
Normal file
Binary file not shown.
BIN
target/cookieGenerator.jar.original
Normal file
BIN
target/cookieGenerator.jar.original
Normal file
Binary file not shown.
3
target/maven-archiver/pom.properties
Normal file
3
target/maven-archiver/pom.properties
Normal file
@ -0,0 +1,3 @@
|
||||
artifactId=cookieGenerator
|
||||
groupId=com.google.accountgen
|
||||
version=1.0-SNAPSHOT
|
@ -0,0 +1,20 @@
|
||||
com\google\accountgen\user\UserData.class
|
||||
com\google\accountgen\CookieGenerator.class
|
||||
com\google\accountgen\captcha\CaptchaSolver$ServiceType.class
|
||||
com\google\accountgen\sms\SmsActivateService$ActivationResult.class
|
||||
com\google\accountgen\registration\GoogleRegistrationSelectors.class
|
||||
com\google\accountgen\registration\GoogleRegistrationHandler.class
|
||||
com\google\accountgen\user\RandomUserGenerator.class
|
||||
com\google\accountgen\account\GoogleAccountGeneratorImpl.class
|
||||
com\google\accountgen\sms\SmsActivateService.class
|
||||
com\google\accountgen\cookies\CookieManager.class
|
||||
com\google\accountgen\captcha\CaptchaSolver.class
|
||||
com\google\accountgen\account\GoogleAccountGenerator.class
|
||||
com\google\accountgen\Task.class
|
||||
com\google\accountgen\account\GoogleAccountGenerationResult.class
|
||||
com\google\accountgen\youtube\YouTubeMusicHandler.class
|
||||
com\google\accountgen\account\AccountResult.class
|
||||
com\google\accountgen\proxy\ProxyManager.class
|
||||
com\google\accountgen\user\UserData$Gender.class
|
||||
com\google\accountgen\account\GoogleAccount.class
|
||||
com\google\accountgen\account\UserData.class
|
@ -0,0 +1,17 @@
|
||||
C:\IdeaProject\cookieGenerator\src\main\java\com\google\accountgen\Task.java
|
||||
C:\IdeaProject\cookieGenerator\src\main\java\com\google\accountgen\registration\GoogleRegistrationSelectors.java
|
||||
C:\IdeaProject\cookieGenerator\src\main\java\com\google\accountgen\youtube\YouTubeMusicHandler.java
|
||||
C:\IdeaProject\cookieGenerator\src\main\java\com\google\accountgen\user\RandomUserGenerator.java
|
||||
C:\IdeaProject\cookieGenerator\src\main\java\com\google\accountgen\cookies\CookieManager.java
|
||||
C:\IdeaProject\cookieGenerator\src\main\java\com\google\accountgen\proxy\ProxyManager.java
|
||||
C:\IdeaProject\cookieGenerator\src\main\java\com\google\accountgen\account\GoogleAccountGeneratorImpl.java
|
||||
C:\IdeaProject\cookieGenerator\src\main\java\com\google\accountgen\account\UserData.java
|
||||
C:\IdeaProject\cookieGenerator\src\main\java\com\google\accountgen\sms\SmsActivateService.java
|
||||
C:\IdeaProject\cookieGenerator\src\main\java\com\google\accountgen\user\UserData.java
|
||||
C:\IdeaProject\cookieGenerator\src\main\java\com\google\accountgen\account\GoogleAccount.java
|
||||
C:\IdeaProject\cookieGenerator\src\main\java\com\google\accountgen\account\GoogleAccountGenerator.java
|
||||
C:\IdeaProject\cookieGenerator\src\main\java\com\google\accountgen\account\AccountResult.java
|
||||
C:\IdeaProject\cookieGenerator\src\main\java\com\google\accountgen\account\GoogleAccountGenerationResult.java
|
||||
C:\IdeaProject\cookieGenerator\src\main\java\com\google\accountgen\CookieGenerator.java
|
||||
C:\IdeaProject\cookieGenerator\src\main\java\com\google\accountgen\captcha\CaptchaSolver.java
|
||||
C:\IdeaProject\cookieGenerator\src\main\java\com\google\accountgen\registration\GoogleRegistrationHandler.java
|
Reference in New Issue
Block a user