mirror of
https://github.com/amnezia-vpn/amnezia-client.git
synced 2026-11-12 07:23:19 +09:00
* Add Google Play Billing Library * Disable Qt debugger sleep * Add billing module, provide a separate build for Google Play * Add a method to detect Google Play build * Add method to get the list of offers * Add methods to verify and purchase subscriptions * refactor: modify response json * feat: add purchase to UI * feat: add test purchase android * fix: merge with new structure, fix payment flow * fix: build flow for new conan structure * fix: add build android via Win * fix: fix multi-ABI filter * fix: split payment to detect payment type * fix: add artifact apk * fix: add check purchase on restore * fix: release keystore * fix: copy apk to right path * fix: separate oss/play build * fix: simply build AAB * fix: add custom target for Play billing * fix: add logs billing * fix: add support market types, add logs * fix: revert market field, up android GP version, fix subscription plan parser * fix: add support getSubscriptionInfo and subscriptions/restore * fix: update api endpoint and pay logic * fix: add logs and rename restore func * fix: add ios logs * fix: rename restore function, fix icon resource error * fix: double purchase android * fix: update Google Play Billing Library to 8.0.0 * fix: prefer free trial subscription offer on Android purchase Bump APP version to 2137. * fix: up kotlin version compiler * fix: sync price for PlayMarket from GP * fix: add logs for Google Play price merge * fix: show App Store intro offer discount price in catalog * feat: add trial support for multi platform, redesign PageSetupWizardApiPremiumInfo * feat: add logs android * fix: tighten spacing Change plan and test period tag * fix: UI text changes * fix: upgrade existing android subscription and add renew logic * feat: add support upgrade CP plan without call subscription * fix: add billing logs for plan * fix: show upgrade success as notification * fix: call getSubscriptionInfo/importServiceFromMarket on upgrade instead of skipping * fix: restore ios prod var * fix: remove noisy debug logs * chore: up version code * fix: getSubscriptionInfo used removed GatewayRequestData after rebase * fix: aab in sep tasks * fix: warn before subscription upgrade/downgrade purchase * chore: add acknowledgePlayPurchase * refactor: add store purchase controller * feat: use same acknowledge method as appstore * fix: IOS add upgrade * fix: change QML warn message * refactor: dedupe Play purchase validation and startup billing query * chore: log purchaseToken through the Android purchase flow * fix: resolve Android active plan by base plan id * fix: remove comment * fix: subscribe to Transaction.updates before Transaction.unfinished * fix: update days values * fix: genuine restore failure when another transaction was a duplicate * fix: remove debug lines and comment * chore: cleanup logs --------- Co-authored-by: albexk <albexk@proton.me> Co-authored-by: vkamn <vk@amnezia.org>
247 lines
9.7 KiB
C++
247 lines
9.7 KiB
C++
#include "apiUtils.h"
|
|
|
|
#include "core/repositories/secureAppSettingsRepository.h"
|
|
#include "core/utils/serverConfigUtils.h"
|
|
#include "core/utils/constants/configKeys.h"
|
|
#include <QDateTime>
|
|
#include <QJsonDocument>
|
|
#include <QJsonObject>
|
|
#include <QJsonValue>
|
|
|
|
#if defined(Q_OS_ANDROID)
|
|
#include "platforms/android/android_controller.h"
|
|
#endif
|
|
|
|
using namespace amnezia;
|
|
|
|
namespace
|
|
{
|
|
const QByteArray AMNEZIA_CONFIG_SIGNATURE = QByteArray::fromHex("000000ff");
|
|
|
|
constexpr QLatin1String unprocessableSubscriptionMessage("Failed to retrieve subscription information. Is it activated?");
|
|
constexpr QLatin1String trialAlreadyUsedMessage("trial subscription already used");
|
|
|
|
QDateTime subscriptionEndUtcFromString(const QString &subscriptionEndDate)
|
|
{
|
|
if (subscriptionEndDate.isEmpty()) {
|
|
return {};
|
|
}
|
|
QDateTime endDate = QDateTime::fromString(subscriptionEndDate, Qt::ISODateWithMs).toUTC();
|
|
if (!endDate.isValid()) {
|
|
endDate = QDateTime::fromString(subscriptionEndDate, Qt::ISODate).toUTC();
|
|
}
|
|
return endDate;
|
|
}
|
|
|
|
QString apiErrorMessageFromJson(const QJsonObject &jsonObj)
|
|
{
|
|
const QJsonValue value = jsonObj.value(QStringLiteral("message"));
|
|
return value.isString() ? value.toString().trimmed() : QString();
|
|
}
|
|
|
|
QString escapeUnicode(const QString &input)
|
|
{
|
|
QString output;
|
|
for (QChar c : input) {
|
|
if (c.unicode() < 0x20 || c.unicode() > 0x7E) {
|
|
output += QString("\\u%1").arg(QString::number(c.unicode(), 16).rightJustified(4, '0'));
|
|
} else {
|
|
output += c;
|
|
}
|
|
}
|
|
return output;
|
|
}
|
|
}
|
|
|
|
QString apiUtils::getAppLanguageCode(const SecureAppSettingsRepository *appSettingsRepository)
|
|
{
|
|
if (appSettingsRepository == nullptr) {
|
|
return {};
|
|
}
|
|
return appSettingsRepository->getAppLanguage().name().split("_").first();
|
|
}
|
|
|
|
QString apiUtils::getDistributionChannel()
|
|
{
|
|
#if defined(Q_OS_ANDROID)
|
|
return AndroidController::instance()->isPlay() ? QStringLiteral("googleplay") : QString();
|
|
#elif defined(Q_OS_IOS) || defined(MACOS_NE)
|
|
return QStringLiteral("appstore");
|
|
#else
|
|
return QStringLiteral("github");
|
|
#endif
|
|
}
|
|
|
|
QString apiUtils::getCountryFlagCode(const QString &serverCountryCode)
|
|
{
|
|
return serverCountryCode.section('-', 0, 0).toUpper();
|
|
}
|
|
|
|
bool apiUtils::isSubscriptionExpired(const QString &subscriptionEndDate)
|
|
{
|
|
if (subscriptionEndDate.isEmpty()) {
|
|
return false;
|
|
}
|
|
const QDateTime endDate = subscriptionEndUtcFromString(subscriptionEndDate);
|
|
if (!endDate.isValid()) {
|
|
return false;
|
|
}
|
|
return endDate <= QDateTime::currentDateTimeUtc();
|
|
}
|
|
|
|
bool apiUtils::isSubscriptionExpiringSoon(const QString &subscriptionEndDate, int withinDays)
|
|
{
|
|
if (subscriptionEndDate.isEmpty()) {
|
|
return false;
|
|
}
|
|
const QDateTime endDate = subscriptionEndUtcFromString(subscriptionEndDate);
|
|
if (!endDate.isValid()) {
|
|
return false;
|
|
}
|
|
const QDateTime nowUtc = QDateTime::currentDateTimeUtc();
|
|
if (endDate <= nowUtc) {
|
|
return false;
|
|
}
|
|
return endDate <= nowUtc.addDays(withinDays);
|
|
}
|
|
|
|
amnezia::ErrorCode apiUtils::checkNetworkReplyErrors(const QList<QSslError> &sslErrors, const QString &replyErrorString,
|
|
const QNetworkReply::NetworkError &replyError, const int httpStatusCode,
|
|
const QByteArray &responseBody)
|
|
{
|
|
const int httpStatusCodeConflict = 409;
|
|
const int httpStatusCodeNotFound = 404;
|
|
const int httpStatusCodeNotImplemented = 501;
|
|
const int httpStatusCodePaymentRequired = 402;
|
|
const int httpStatusCodeTooManyRequests = 429;
|
|
const int httpStatusCodeRequestTimeout = 408;
|
|
const int httpStatusCodeUnprocessableEntity = 422;
|
|
|
|
if (!sslErrors.empty()) {
|
|
qDebug().noquote() << sslErrors;
|
|
return amnezia::ErrorCode::ApiConfigSslError;
|
|
}
|
|
if (replyError == QNetworkReply::NetworkError::OperationCanceledError
|
|
|| replyError == QNetworkReply::NetworkError::TimeoutError) {
|
|
qDebug() << replyError;
|
|
return amnezia::ErrorCode::ApiConfigTimeoutError;
|
|
}
|
|
if (replyError == QNetworkReply::NetworkError::OperationNotImplementedError) {
|
|
qDebug() << replyError;
|
|
return amnezia::ErrorCode::ApiUpdateRequestError;
|
|
}
|
|
|
|
QJsonDocument jsonDoc = QJsonDocument::fromJson(responseBody);
|
|
if (jsonDoc.isObject()) {
|
|
QJsonObject jsonObj = jsonDoc.object();
|
|
const int httpStatusFromBody = jsonObj.value(QStringLiteral("http_status")).toInt(-1);
|
|
|
|
if (httpStatusFromBody == httpStatusCodeTooManyRequests) {
|
|
return amnezia::ErrorCode::ApiRateLimitError;
|
|
}
|
|
if (httpStatusFromBody == httpStatusCodeConflict) {
|
|
if (apiErrorMessageFromJson(jsonObj).contains(trialAlreadyUsedMessage, Qt::CaseInsensitive)) {
|
|
return amnezia::ErrorCode::ApiTrialAlreadyUsedError;
|
|
}
|
|
return amnezia::ErrorCode::ApiConfigLimitError;
|
|
}
|
|
if (httpStatusFromBody == httpStatusCodeNotFound) {
|
|
return amnezia::ErrorCode::ApiNotFoundError;
|
|
}
|
|
if (httpStatusFromBody == httpStatusCodeRequestTimeout) {
|
|
return amnezia::ErrorCode::ApiConfigTimeoutError;
|
|
}
|
|
if (httpStatusFromBody == httpStatusCodeNotImplemented) {
|
|
return amnezia::ErrorCode::ApiUpdateRequestError;
|
|
}
|
|
if (httpStatusFromBody == httpStatusCodeUnprocessableEntity) {
|
|
if (apiErrorMessageFromJson(jsonObj) == unprocessableSubscriptionMessage) {
|
|
return amnezia::ErrorCode::ApiSubscriptionExpiredError;
|
|
}
|
|
return amnezia::ErrorCode::ApiConfigDownloadError;
|
|
}
|
|
if (httpStatusFromBody == httpStatusCodePaymentRequired) {
|
|
const QString message = apiErrorMessageFromJson(jsonObj);
|
|
if (message.contains(QLatin1String("refresh_captcha"), Qt::CaseInsensitive)) {
|
|
return amnezia::ErrorCode::ApiCaptchaRefreshError;
|
|
}
|
|
if (message.contains(QLatin1String("invalid_captcha"), Qt::CaseInsensitive)) {
|
|
return amnezia::ErrorCode::ApiCaptchaInvalidError;
|
|
}
|
|
if (jsonObj.contains(QStringLiteral("captcha_id")) || jsonObj.contains(QStringLiteral("captcha_image"))
|
|
|| message.compare(QLatin1String("rate_limit_exceeded"), Qt::CaseInsensitive) == 0
|
|
|| message.contains(QLatin1String("rate_limit_exceeded"), Qt::CaseInsensitive)) {
|
|
return amnezia::ErrorCode::ApiCaptchaRequiredError;
|
|
}
|
|
return amnezia::ErrorCode::ApiSubscriptionNotActiveError;
|
|
}
|
|
|
|
if (httpStatusFromBody >= 300) {
|
|
return amnezia::ErrorCode::ApiConfigDownloadError;
|
|
}
|
|
}
|
|
|
|
if (replyError == QNetworkReply::NoError) {
|
|
return amnezia::ErrorCode::NoError;
|
|
}
|
|
|
|
qDebug() << "something went wrong";
|
|
return amnezia::ErrorCode::ApiConfigDownloadError;
|
|
}
|
|
|
|
bool apiUtils::isPremiumServer(const QJsonObject &serverConfigObject)
|
|
{
|
|
static const QSet<serverConfigUtils::ConfigType> premiumTypes = { serverConfigUtils::ConfigType::AmneziaPremiumV1, serverConfigUtils::ConfigType::AmneziaPremiumV2,
|
|
serverConfigUtils::ConfigType::ExternalPremium };
|
|
return premiumTypes.contains(serverConfigUtils::configTypeFromJson(serverConfigObject));
|
|
}
|
|
|
|
QString apiUtils::getPremiumV2VpnKey(const QJsonObject &serverConfigObject)
|
|
{
|
|
auto configType = serverConfigUtils::configTypeFromJson(serverConfigObject);
|
|
if (configType != serverConfigUtils::ConfigType::AmneziaPremiumV2 && configType != serverConfigUtils::ConfigType::ExternalPremium) {
|
|
return {};
|
|
}
|
|
|
|
QString vpnKeyText = "";
|
|
|
|
auto apiConfig = serverConfigObject.value(apiDefs::key::apiConfig).toObject();
|
|
auto authData = serverConfigObject.value(QLatin1String("auth_data")).toObject();
|
|
|
|
const QString name = serverConfigObject.value(configKey::name).toString();
|
|
const QString description = serverConfigObject.value(configKey::description).toString();
|
|
const double configVersion = serverConfigObject.value(configKey::configVersion).toDouble();
|
|
|
|
const QString serviceType = apiConfig.value(apiDefs::key::serviceType).toString();
|
|
const QString serviceProtocol = apiConfig.value(QLatin1String("service_protocol")).toString();
|
|
const QString userCountryCode = apiConfig.value(QLatin1String("user_country_code")).toString();
|
|
|
|
const QString apiKey = authData.value(apiDefs::key::apiKey).toString();
|
|
|
|
QString vpnKeyStr = "{";
|
|
vpnKeyStr += "\"" + QString(configKey::name) + "\": \"" + name + "\", ";
|
|
vpnKeyStr += "\"" + QString(configKey::description) + "\": \"" + description + "\", ";
|
|
vpnKeyStr += "\"" + QString(configKey::configVersion) + "\": " + QString::number(static_cast<int>(configVersion)) + ", ";
|
|
|
|
vpnKeyStr += "\"" + QString(apiDefs::key::apiConfig) + "\": {";
|
|
vpnKeyStr += "\"" + QString(apiDefs::key::serviceType) + "\": \"" + serviceType + "\", ";
|
|
vpnKeyStr += "\"service_protocol\": \"" + serviceProtocol + "\", ";
|
|
vpnKeyStr += "\"user_country_code\": \"" + userCountryCode + "\"";
|
|
vpnKeyStr += "}, ";
|
|
|
|
vpnKeyStr += "\"auth_data\": {";
|
|
vpnKeyStr += "\"" + QString(apiDefs::key::apiKey) + "\": \"" + apiKey + "\"";
|
|
vpnKeyStr += "}";
|
|
|
|
vpnKeyStr += "}";
|
|
|
|
QByteArray vpnKeyCompressed = escapeUnicode(vpnKeyStr).toUtf8();
|
|
vpnKeyCompressed = qCompress(vpnKeyCompressed, 6);
|
|
vpnKeyCompressed = vpnKeyCompressed.mid(4);
|
|
|
|
QByteArray signedData = AMNEZIA_CONFIG_SIGNATURE + vpnKeyCompressed;
|
|
vpnKeyText = QString("vpn://%1").arg(QString(signedData.toBase64(QByteArray::Base64UrlEncoding)));
|
|
|
|
return vpnKeyText;
|
|
}
|