mirror of
https://github.com/amnezia-vpn/amnezia-client.git
synced 2026-12-04 06:01:26 +09:00
Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
41fed9f94f | ||
|
|
6a9dc041a7 | ||
|
|
d43f6e9184 | ||
|
|
d10d8f93d2 | ||
|
|
2b59de5d30 | ||
|
|
01721aa7c6 | ||
|
|
af28f03bd1 | ||
|
|
819f517b1a | ||
|
|
bac31c7c89 | ||
|
|
3c96e399f7 | ||
|
|
0e61ef4e46 | ||
|
|
9fbd35b3f1 |
No files matched your search
@@ -658,6 +658,64 @@ ErrorCode StorePurchaseController::finalizePlayPurchase(const QString &userCount
|
||||
}
|
||||
#endif
|
||||
|
||||
ErrorCode StorePurchaseController::resolveOtpLoginProof(QString &proof)
|
||||
{
|
||||
#if defined(Q_OS_ANDROID)
|
||||
QJsonObject newestPurchase;
|
||||
bool hasPendingPurchase = false;
|
||||
for (const QJsonValue &purchaseValue : queryPlayPurchases()) {
|
||||
const QJsonObject purchaseObj = purchaseValue.toObject();
|
||||
const int purchaseState = purchaseObj.value("purchaseState").toInt(-1);
|
||||
if (purchaseState == purchaseStatePending) {
|
||||
hasPendingPurchase = true;
|
||||
continue;
|
||||
}
|
||||
if (purchaseState != purchaseStatePurchased || purchaseObj.value("purchaseToken").toString().isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
if (newestPurchase.isEmpty()
|
||||
|| purchaseObj.value("purchaseTime").toDouble() > newestPurchase.value("purchaseTime").toDouble()) {
|
||||
newestPurchase = purchaseObj;
|
||||
}
|
||||
}
|
||||
if (newestPurchase.isEmpty()) {
|
||||
return hasPendingPurchase ? ErrorCode::ApiPurchasePendingError : ErrorCode::ApiNoPurchasesToRestore;
|
||||
}
|
||||
proof = newestPurchase.value("purchaseToken").toString();
|
||||
return ErrorCode::NoError;
|
||||
#elif defined(Q_OS_IOS) || defined(MACOS_NE)
|
||||
bool fetchSuccess = false;
|
||||
QList<QVariantMap> entitlements;
|
||||
QString fetchError;
|
||||
QEventLoop waitEntitlements;
|
||||
|
||||
IosController::Instance()->fetchLocalEntitlements([&](bool success, const QList<QVariantMap> &transactions, const QString &errorString) {
|
||||
fetchSuccess = success;
|
||||
entitlements = transactions;
|
||||
fetchError = errorString;
|
||||
waitEntitlements.quit();
|
||||
});
|
||||
waitEntitlements.exec();
|
||||
|
||||
if (!fetchSuccess) {
|
||||
qWarning().noquote() << "[IAP] fetchLocalEntitlements failed:" << fetchError;
|
||||
return ErrorCode::ApiPurchaseError;
|
||||
}
|
||||
|
||||
for (const QVariantMap &transaction : entitlements) {
|
||||
const QString jws = transaction.value(QStringLiteral("jwsRepresentation")).toString();
|
||||
if (!jws.isEmpty()) {
|
||||
proof = jws;
|
||||
return ErrorCode::NoError;
|
||||
}
|
||||
}
|
||||
return ErrorCode::ApiNoPurchasesToRestore;
|
||||
#else
|
||||
Q_UNUSED(proof);
|
||||
return ErrorCode::ApiPurchaseError;
|
||||
#endif
|
||||
}
|
||||
|
||||
QJsonArray StorePurchaseController::findUnacknowledgedPlayPurchases()
|
||||
{
|
||||
#if defined(Q_OS_ANDROID)
|
||||
|
||||
@@ -51,6 +51,8 @@ public:
|
||||
|
||||
QStringList resolveActiveStoreProductIds();
|
||||
|
||||
ErrorCode resolveOtpLoginProof(QString &proof);
|
||||
|
||||
// Android counterpart of the iOS Transaction.updates listener: purchases that were
|
||||
// paid but never acknowledged (validation failed earlier, or a PENDING purchase was
|
||||
// completed outside the app). Query once with findUnacknowledgedPlayPurchases(), then
|
||||
|
||||
@@ -35,6 +35,36 @@ using namespace amnezia;
|
||||
|
||||
namespace
|
||||
{
|
||||
constexpr int httpStatusCodeBadRequest = 400;
|
||||
constexpr int httpStatusCodeNotFound = 404;
|
||||
constexpr int httpStatusCodeTooManyRequests = 429;
|
||||
|
||||
int httpStatusFromResponse(const QByteArray &responseBody)
|
||||
{
|
||||
const QJsonObject errorObject = QJsonDocument::fromJson(responseBody).object();
|
||||
return errorObject.value(apiDefs::key::httpStatus).toInt(errorObject.value(QLatin1String("status")).toInt(0));
|
||||
}
|
||||
|
||||
SubscriptionController::OtpLoginError classifyOtpLoginError(int httpStatus, ErrorCode errorCode)
|
||||
{
|
||||
switch (httpStatus) {
|
||||
case httpStatusCodeBadRequest: return SubscriptionController::OtpLoginError::ReceiptRejected;
|
||||
case httpStatusCodeNotFound: return SubscriptionController::OtpLoginError::PurchaseNotFound;
|
||||
case httpStatusCodeTooManyRequests: return SubscriptionController::OtpLoginError::RateLimited;
|
||||
default: break;
|
||||
}
|
||||
if (httpStatus > 0) {
|
||||
return SubscriptionController::OtpLoginError::Failed;
|
||||
}
|
||||
|
||||
switch (errorCode) {
|
||||
case ErrorCode::ApiConfigTimeoutError:
|
||||
case ErrorCode::ApiConfigSslError:
|
||||
case ErrorCode::ApiConfigDownloadError: return SubscriptionController::OtpLoginError::NoNetwork;
|
||||
default: return SubscriptionController::OtpLoginError::Failed;
|
||||
}
|
||||
}
|
||||
|
||||
QString getSubscriptionStatusForRenewal(const ApiConfig &apiConfig)
|
||||
{
|
||||
if (apiConfig.subscriptionExpiredByServer) {
|
||||
@@ -605,6 +635,90 @@ ErrorCode SubscriptionController::revokeNativeConfig(const QString &serverId, co
|
||||
return ErrorCode::NoError;
|
||||
}
|
||||
|
||||
ErrorCode SubscriptionController::otpLogin(const QString &transactionId, OtpData &otpData, OtpLoginError &loginError, bool isTestPurchase)
|
||||
{
|
||||
loginError = OtpLoginError::None;
|
||||
|
||||
QJsonObject apiPayload = GatewayPayloadBuilder(m_appSettingsRepository)
|
||||
.addField(apiDefs::key::transactionId, transactionId)
|
||||
.build();
|
||||
|
||||
QByteArray responseBody;
|
||||
ErrorCode errorCode = executeRequest(QString("%1v1/get_otp_code"), apiPayload, responseBody, isTestPurchase);
|
||||
if (errorCode != ErrorCode::NoError) {
|
||||
const int httpStatus = httpStatusFromResponse(responseBody);
|
||||
loginError = classifyOtpLoginError(httpStatus, errorCode);
|
||||
qWarning().noquote() << "[OTP] Code request failed, errorCode =" << static_cast<int>(errorCode)
|
||||
<< "http status =" << httpStatus;
|
||||
return errorCode;
|
||||
}
|
||||
|
||||
const QJsonObject responseObject = QJsonDocument::fromJson(responseBody).object();
|
||||
otpData.code = responseObject.value(apiDefs::key::otpCode).toString();
|
||||
otpData.otpRequestId = responseObject.value(apiDefs::key::otpRequestId).toString();
|
||||
otpData.expiresAt = QDateTime::fromString(responseObject.value(apiDefs::key::expiresAt).toString(), Qt::ISODateWithMs);
|
||||
if (otpData.code.isEmpty() || otpData.otpRequestId.isEmpty()) {
|
||||
qWarning().noquote() << "[OTP] Response does not contain an otp code or request id";
|
||||
loginError = OtpLoginError::Failed;
|
||||
return ErrorCode::ApiOtpLoginError;
|
||||
}
|
||||
qDebug().noquote() << "[OTP] Code issued, request id =" << otpData.otpRequestId
|
||||
<< "expires at =" << otpData.expiresAt.toString(Qt::ISODate);
|
||||
return ErrorCode::NoError;
|
||||
}
|
||||
|
||||
QFuture<QPair<ErrorCode, SubscriptionController::OtpStatus>> SubscriptionController::otpStatus(const QString &requestId,
|
||||
bool isTestPurchase)
|
||||
{
|
||||
auto promise = QSharedPointer<QPromise<QPair<ErrorCode, OtpStatus>>>::create();
|
||||
promise->start();
|
||||
|
||||
QJsonObject apiPayload = GatewayPayloadBuilder(m_appSettingsRepository)
|
||||
.addField(apiDefs::key::otpRequestId, requestId)
|
||||
.build();
|
||||
|
||||
auto gatewayController = QSharedPointer<GatewayController>::create(
|
||||
m_appSettingsRepository->gatewayEnvironment(isTestPurchase), apiDefs::requestTimeoutMsecs,
|
||||
m_appSettingsRepository->isStrictKillSwitchEnabled(), m_appSettingsRepository);
|
||||
auto postFuture = gatewayController->postAsync(QString("%1v1/otp_status"), apiPayload);
|
||||
auto *watcher = new QFutureWatcher<QPair<ErrorCode, QByteArray>>();
|
||||
QObject::connect(watcher, &QFutureWatcher<QPair<ErrorCode, QByteArray>>::finished,
|
||||
[promise, watcher, gatewayController]() {
|
||||
const auto [errorCode, responseBody] = watcher->result();
|
||||
watcher->deleteLater();
|
||||
if (errorCode != ErrorCode::NoError) {
|
||||
const QJsonObject errorObject = QJsonDocument::fromJson(responseBody).object();
|
||||
const int httpStatus = httpStatusFromResponse(responseBody);
|
||||
qWarning().noquote() << "[OTP] Status request failed, errorCode =" << static_cast<int>(errorCode)
|
||||
<< "http status =" << httpStatus
|
||||
<< "message =" << errorObject.value(QLatin1String("message")).toString()
|
||||
<< errorObject.value(QLatin1String("title")).toString()
|
||||
<< errorObject.value(QLatin1String("detail")).toString();
|
||||
if (httpStatus == httpStatusCodeNotFound) {
|
||||
promise->addResult(qMakePair(ErrorCode::NoError, OtpStatus::Expired));
|
||||
} else {
|
||||
promise->addResult(qMakePair(errorCode, OtpStatus::Pending));
|
||||
}
|
||||
promise->finish();
|
||||
return;
|
||||
}
|
||||
|
||||
const QString status = QJsonDocument::fromJson(responseBody).object().value(apiDefs::key::otpStatus).toString();
|
||||
OtpStatus parsedStatus = OtpStatus::Pending;
|
||||
if (status == QLatin1String("consumed")) {
|
||||
parsedStatus = OtpStatus::Confirmed;
|
||||
} else if (status == QLatin1String("expired")) {
|
||||
parsedStatus = OtpStatus::Expired;
|
||||
} else if (status != QLatin1String("pending")) {
|
||||
qWarning().noquote() << "[OTP] Unknown otp_status value:" << status;
|
||||
}
|
||||
promise->addResult(qMakePair(ErrorCode::NoError, parsedStatus));
|
||||
promise->finish();
|
||||
});
|
||||
watcher->setFuture(postFuture);
|
||||
return promise->future();
|
||||
}
|
||||
|
||||
ErrorCode SubscriptionController::prepareVpnKeyExport(const QString &serverId, QString &vpnKey)
|
||||
{
|
||||
auto apiV2 = m_serversRepository->apiV2Config(serverId);
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
#ifndef SUBSCRIPTIONCONTROLLER_H
|
||||
#define SUBSCRIPTIONCONTROLLER_H
|
||||
|
||||
#include <QDateTime>
|
||||
|
||||
#include <QJsonObject>
|
||||
#include <QByteArray>
|
||||
#include <QFuture>
|
||||
@@ -32,6 +34,27 @@ public:
|
||||
bool isRequired = false;
|
||||
};
|
||||
|
||||
struct OtpData {
|
||||
QString code;
|
||||
QString otpRequestId;
|
||||
QDateTime expiresAt;
|
||||
};
|
||||
|
||||
enum class OtpStatus {
|
||||
Pending,
|
||||
Confirmed,
|
||||
Expired
|
||||
};
|
||||
|
||||
enum class OtpLoginError {
|
||||
None,
|
||||
NoNetwork,
|
||||
PurchaseNotFound,
|
||||
RateLimited,
|
||||
ReceiptRejected,
|
||||
Failed
|
||||
};
|
||||
|
||||
explicit SubscriptionController(SecureServersRepository* serversRepository,
|
||||
SecureAppSettingsRepository* appSettingsRepository);
|
||||
|
||||
@@ -79,6 +102,9 @@ public:
|
||||
ErrorCode getAccountInfo(const QString &serverId, QJsonObject &accountInfo);
|
||||
QFuture<QPair<ErrorCode, QString>> getRenewalLink(const QString &serverId);
|
||||
|
||||
ErrorCode otpLogin(const QString &transactionId, OtpData &otpData, OtpLoginError &loginError, bool isTestPurchase = false);
|
||||
QFuture<QPair<ErrorCode, OtpStatus>> otpStatus(const QString &requestId, bool isTestPurchase);
|
||||
|
||||
ErrorCode resolveImportServiceCaptcha(const QString &userCountryCode, const QString &serviceType,
|
||||
const QString &serviceProtocol, const ProtocolData &protocolData,
|
||||
const QString &captchaId, const QString &captchaSolution,
|
||||
|
||||
@@ -97,6 +97,9 @@ namespace apiDefs
|
||||
constexpr QLatin1String publicKeyInfo("public_key");
|
||||
constexpr QLatin1String publicKey("public_key");
|
||||
constexpr QLatin1String expiresAt("expires_at");
|
||||
constexpr QLatin1String otpCode("otp_code");
|
||||
constexpr QLatin1String otpStatus("otp_status");
|
||||
constexpr QLatin1String otpRequestId("otp_request_id");
|
||||
constexpr QLatin1String isConnectEvent("is_connect_event");
|
||||
constexpr QLatin1String certificate("certificate");
|
||||
} // namespace key
|
||||
|
||||
@@ -120,6 +120,7 @@ namespace amnezia
|
||||
ApiRateLimitError = 1120,
|
||||
ApiNoPurchasesToRestore = 1121,
|
||||
ApiPurchasePendingError = 1122,
|
||||
ApiOtpLoginError = 1123,
|
||||
|
||||
// QFile errors
|
||||
OpenError = 1200,
|
||||
|
||||
@@ -147,6 +147,7 @@ QString errorString(ErrorCode code) {
|
||||
errorMessage = QObject::tr("Your payment is pending confirmation. Please complete the payment and then restore your subscription.");
|
||||
#endif
|
||||
break;
|
||||
case (ErrorCode::ApiOtpLoginError): errorMessage = QObject::tr("Unable to get the login code. Please try again in a minute"); break;
|
||||
case (ErrorCode::ApiNoPurchasesToRestore):
|
||||
#if defined(Q_OS_ANDROID)
|
||||
errorMessage = QObject::tr("No purchases to restore. If you have an active subscription, make sure you're signed in with the same Google account used for the purchase.");
|
||||
|
||||
@@ -20,13 +20,15 @@ public class StoreKit2Helper: NSObject {
|
||||
let productId: String
|
||||
let purchaseDate: Date
|
||||
let environment: String
|
||||
var jwsRepresentation: String = ""
|
||||
|
||||
var dictionary: NSDictionary {
|
||||
[
|
||||
"transactionId": String(transactionId),
|
||||
"originalTransactionId": String(originalTransactionId),
|
||||
"productId": productId,
|
||||
"environment": environment
|
||||
"environment": environment,
|
||||
"jwsRepresentation": jwsRepresentation
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -53,7 +55,8 @@ public class StoreKit2Helper: NSObject {
|
||||
originalTransactionId: transaction.originalID,
|
||||
productId: transaction.productID,
|
||||
purchaseDate: transaction.purchaseDate,
|
||||
environment: environmentString(for: transaction)))
|
||||
environment: environmentString(for: transaction),
|
||||
jwsRepresentation: result.jwsRepresentation))
|
||||
case .unverified(_, let error):
|
||||
print("[IAP][StoreKit2] Unverified transaction skipped: \(error.localizedDescription)")
|
||||
}
|
||||
|
||||
@@ -1035,7 +1035,7 @@ IosController::StorePurchaseFailure storePurchaseFailureFromError(NSError *error
|
||||
QVariantMap toTransactionMap(NSDictionary *dict)
|
||||
{
|
||||
QVariantMap transaction;
|
||||
for (NSString *key in @[@"transactionId", @"originalTransactionId", @"productId", @"environment"]) {
|
||||
for (NSString *key in @[@"transactionId", @"originalTransactionId", @"productId", @"environment", @"jwsRepresentation"]) {
|
||||
NSString *value = dict[key];
|
||||
if (value) {
|
||||
transaction.insert(QString::fromUtf8(key.UTF8String), QString::fromUtf8(value.UTF8String));
|
||||
|
||||
@@ -3790,6 +3790,14 @@ Create one from the current settings.</source>
|
||||
</context>
|
||||
<context>
|
||||
<name>PageSettingsApiServerInfo</name>
|
||||
<message>
|
||||
<source>Code for the web account</source>
|
||||
<translation>Код для кабинета на сайте</translation>
|
||||
</message>
|
||||
<message>
|
||||
<source>To sign in or add a subscription</source>
|
||||
<translation>Для входа или чтобы добавить подписку</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../ui/qml/Pages2/PageSettingsApiServerInfo.qml" line="170"/>
|
||||
<source>Subscription Status</source>
|
||||
@@ -6532,6 +6540,10 @@ Only one can be active at a time: VPN or local proxy</source>
|
||||
<source>Unable to process purchase</source>
|
||||
<translation>Не удалось обработать покупку</translation>
|
||||
</message>
|
||||
<message>
|
||||
<source>Unable to get the login code. Please try again in a minute</source>
|
||||
<translation>Не удалось получить код для входа. Попробуйте через минуту</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../core/utils/errorStrings.cpp" line="134"/>
|
||||
<source>No active subscription found</source>
|
||||
@@ -7669,4 +7681,99 @@ Remove the server from the app to continue.</source>
|
||||
<translation>Невозможно удалить сервер во время активного соединения</translation>
|
||||
</message>
|
||||
</context>
|
||||
<context>
|
||||
<name>OtpLoginDialog</name>
|
||||
<message>
|
||||
<source>Code for your account</source>
|
||||
<translation>Код для кабинета</translation>
|
||||
</message>
|
||||
<message>
|
||||
<source>Enter it at cp.amnezia.org to confirm the subscription is yours</source>
|
||||
<translation>Введите его на cp.amnezia.org, чтобы подтвердить, что подписка ваша</translation>
|
||||
</message>
|
||||
<message>
|
||||
<source>%1 left</source>
|
||||
<translation>Осталось %1</translation>
|
||||
</message>
|
||||
<message>
|
||||
<source>Don't share this code with anyone, even support</source>
|
||||
<translation>Никому не сообщайте код, даже поддержке</translation>
|
||||
</message>
|
||||
<message>
|
||||
<source>Close</source>
|
||||
<translation>Закрыть</translation>
|
||||
</message>
|
||||
<message>
|
||||
<source>Open account</source>
|
||||
<translation>Открыть кабинет</translation>
|
||||
</message>
|
||||
<message>
|
||||
<source>Code copied</source>
|
||||
<translation>Код скопирован</translation>
|
||||
</message>
|
||||
<message>
|
||||
<source>Code accepted</source>
|
||||
<translation>Код принят</translation>
|
||||
</message>
|
||||
<message>
|
||||
<source>Code expired</source>
|
||||
<translation>Код устарел</translation>
|
||||
</message>
|
||||
<message>
|
||||
<source>Request a new code</source>
|
||||
<translation>Запросите новый код</translation>
|
||||
</message>
|
||||
<message>
|
||||
<source>Get a new code</source>
|
||||
<translation>Получить новый код</translation>
|
||||
</message>
|
||||
<message>
|
||||
<source>Retry</source>
|
||||
<translation>Повторить</translation>
|
||||
</message>
|
||||
<message>
|
||||
<source>Contact support</source>
|
||||
<translation>Написать в поддержку</translation>
|
||||
</message>
|
||||
<message>
|
||||
<source>No connection</source>
|
||||
<translation>Нет соединения</translation>
|
||||
</message>
|
||||
<message>
|
||||
<source>Check your connection and retry</source>
|
||||
<translation>Проверьте интернет и повторите</translation>
|
||||
</message>
|
||||
<message>
|
||||
<source>Purchase hasn't reached us yet</source>
|
||||
<translation>Покупка еще не дошла</translation>
|
||||
</message>
|
||||
<message>
|
||||
<source>This happens right after payment or a plan change. Retry in a minute</source>
|
||||
<translation>Так бывает сразу после оплаты или смены тарифа. Повторите через минуту</translation>
|
||||
</message>
|
||||
<message>
|
||||
<source>Service is busy</source>
|
||||
<translation>Сервис занят</translation>
|
||||
</message>
|
||||
<message>
|
||||
<source>Try again later</source>
|
||||
<translation>Повторите позже</translation>
|
||||
</message>
|
||||
<message>
|
||||
<source>Couldn't verify the purchase</source>
|
||||
<translation>Не удалось проверить покупку</translation>
|
||||
</message>
|
||||
<message>
|
||||
<source>Try again</source>
|
||||
<translation>Повторите</translation>
|
||||
</message>
|
||||
<message>
|
||||
<source>Contact support and we'll help you sort it out</source>
|
||||
<translation>Напишите в поддержку, поможем разобраться</translation>
|
||||
</message>
|
||||
<message>
|
||||
<source>Couldn't get a code</source>
|
||||
<translation>Не удалось получить код</translation>
|
||||
</message>
|
||||
</context>
|
||||
</TS>
|
||||
@@ -10,6 +10,7 @@
|
||||
#include "ui/controllers/systemController.h"
|
||||
#include "version.h"
|
||||
#include <QClipboard>
|
||||
#include <QDateTime>
|
||||
#include <QDebug>
|
||||
#include <QSet>
|
||||
#include <QEventLoop>
|
||||
@@ -25,6 +26,7 @@
|
||||
namespace
|
||||
{
|
||||
constexpr char premiumServiceType[] = "amnezia-premium";
|
||||
constexpr int otpDefaultTtlSec = 600;
|
||||
}
|
||||
|
||||
SubscriptionUiController::SubscriptionUiController(ServersController* serversController,
|
||||
@@ -294,6 +296,92 @@ bool SubscriptionUiController::restoreServiceFromStore()
|
||||
return true;
|
||||
}
|
||||
|
||||
void SubscriptionUiController::otpLogin(const QString &serverId)
|
||||
{
|
||||
const auto apiV2 = m_serversController->apiV2Config(serverId);
|
||||
if (!apiV2.has_value()) {
|
||||
emit errorOccurred(ErrorCode::InternalError);
|
||||
emit otpLoginFailed(QString());
|
||||
return;
|
||||
}
|
||||
const bool isTestPurchase = apiV2->apiConfig.isTestPurchase;
|
||||
|
||||
QString proof;
|
||||
ErrorCode errorCode = m_storePurchaseController->resolveOtpLoginProof(proof);
|
||||
if (errorCode != ErrorCode::NoError) {
|
||||
if (errorCode == ErrorCode::ApiPurchasePendingError) {
|
||||
emit otpLoginFailed(QStringLiteral("purchaseNotFound"));
|
||||
} else {
|
||||
emit errorOccurred(errorCode);
|
||||
emit otpLoginFailed(QString());
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
SubscriptionController::OtpData otpData;
|
||||
SubscriptionController::OtpLoginError loginError = SubscriptionController::OtpLoginError::None;
|
||||
errorCode = m_subscriptionController->otpLogin(proof, otpData, loginError, isTestPurchase);
|
||||
if (errorCode != ErrorCode::NoError) {
|
||||
emit otpLoginFailed(otpLoginErrorKind(loginError));
|
||||
return;
|
||||
}
|
||||
|
||||
m_otpReceiptRejectedCount = 0;
|
||||
m_otpRequestId = otpData.otpRequestId;
|
||||
m_otpIsTestPurchase = isTestPurchase;
|
||||
|
||||
int expiresInSec = otpDefaultTtlSec;
|
||||
if (otpData.expiresAt.isValid()) {
|
||||
expiresInSec = static_cast<int>(qMax<qint64>(0, QDateTime::currentDateTimeUtc().secsTo(otpData.expiresAt)));
|
||||
}
|
||||
emit otpCodeReceived(otpData.code, expiresInSec);
|
||||
}
|
||||
|
||||
QString SubscriptionUiController::otpLoginErrorKind(SubscriptionController::OtpLoginError loginError)
|
||||
{
|
||||
using OtpLoginError = SubscriptionController::OtpLoginError;
|
||||
switch (loginError) {
|
||||
case OtpLoginError::NoNetwork: return QStringLiteral("noNetwork");
|
||||
case OtpLoginError::PurchaseNotFound: return QStringLiteral("purchaseNotFound");
|
||||
case OtpLoginError::RateLimited: return QStringLiteral("rateLimited");
|
||||
case OtpLoginError::ReceiptRejected:
|
||||
++m_otpReceiptRejectedCount;
|
||||
return m_otpReceiptRejectedCount > 1 ? QStringLiteral("receiptRejectedAgain") : QStringLiteral("receiptRejected");
|
||||
default: return QStringLiteral("failed");
|
||||
}
|
||||
}
|
||||
|
||||
void SubscriptionUiController::checkOtpStatus()
|
||||
{
|
||||
if (m_otpRequestId.isEmpty() || m_otpStatusCheckInProgress) {
|
||||
return;
|
||||
}
|
||||
m_otpStatusCheckInProgress = true;
|
||||
|
||||
using OtpStatusResult = QPair<ErrorCode, SubscriptionController::OtpStatus>;
|
||||
auto *watcher = new QFutureWatcher<OtpStatusResult>(this);
|
||||
connect(watcher, &QFutureWatcher<OtpStatusResult>::finished, this, [this, watcher]() {
|
||||
const auto [errorCode, status] = watcher->result();
|
||||
watcher->deleteLater();
|
||||
m_otpStatusCheckInProgress = false;
|
||||
|
||||
// Poll failures are silent: the drawer keeps polling on its timer
|
||||
if (errorCode != ErrorCode::NoError) {
|
||||
return;
|
||||
}
|
||||
if (status == SubscriptionController::OtpStatus::Confirmed) {
|
||||
qDebug().noquote() << "[OTP] Code confirmed";
|
||||
m_otpRequestId.clear();
|
||||
emit otpConfirmed();
|
||||
} else if (status == SubscriptionController::OtpStatus::Expired) {
|
||||
qDebug().noquote() << "[OTP] Code expired";
|
||||
m_otpRequestId.clear();
|
||||
emit otpExpired();
|
||||
}
|
||||
});
|
||||
watcher->setFuture(m_subscriptionController->otpStatus(m_otpRequestId, m_otpIsTestPurchase));
|
||||
}
|
||||
|
||||
#if defined(Q_OS_IOS) || defined(MACOS_NE)
|
||||
void SubscriptionUiController::onStoreTransactionUpdated(const QVariantMap &transaction)
|
||||
{
|
||||
|
||||
@@ -76,6 +76,8 @@ public slots:
|
||||
|
||||
bool getAccountInfo(const QString &serverId, bool reload);
|
||||
void getRenewalLink(const QString &serverId);
|
||||
void otpLogin(const QString &serverId);
|
||||
void checkOtpStatus();
|
||||
|
||||
void updateApiCountryModel(const QString &serverId);
|
||||
void updateApiDevicesModel();
|
||||
@@ -86,6 +88,10 @@ signals:
|
||||
void trialEmailError(const QString &message);
|
||||
void subscriptionExpiredOnServer();
|
||||
void renewalLinkReceived(const QString &url);
|
||||
void otpCodeReceived(const QString &code, int expiresInSec);
|
||||
void otpLoginFailed(const QString &kind);
|
||||
void otpConfirmed();
|
||||
void otpExpired();
|
||||
|
||||
void installServerFromApiFinished(const QString &message, int preferredDefaultServerIndex = -1);
|
||||
void backgroundPurchaseCompleted(const QString &message);
|
||||
@@ -159,6 +165,13 @@ private:
|
||||
QString getVpnKey();
|
||||
|
||||
QList<QString> m_qrCodes;
|
||||
|
||||
QString otpLoginErrorKind(SubscriptionController::OtpLoginError loginError);
|
||||
|
||||
QString m_otpRequestId;
|
||||
bool m_otpIsTestPurchase = false;
|
||||
bool m_otpStatusCheckInProgress = false;
|
||||
int m_otpReceiptRejectedCount = 0;
|
||||
QString m_vpnKey;
|
||||
|
||||
ServersController* m_serversController;
|
||||
|
||||
@@ -0,0 +1,371 @@
|
||||
pragma ComponentBehavior: Bound
|
||||
|
||||
import QtQuick
|
||||
import QtQuick.Controls
|
||||
import QtQuick.Layouts
|
||||
|
||||
import PageEnum 1.0
|
||||
import Style 1.0
|
||||
|
||||
import "../Controls2"
|
||||
import "../Controls2/TextTypes"
|
||||
import "../Config"
|
||||
|
||||
Popup {
|
||||
id: root
|
||||
|
||||
property string serverId: ""
|
||||
property string otpCode: ""
|
||||
property int secondsLeft: 0
|
||||
property string errorKind: ""
|
||||
property int retryCooldownSec: 0
|
||||
|
||||
// loading | code | expired | error
|
||||
property string dialogState: "loading"
|
||||
|
||||
readonly property string accountUrl: "https://cp.amnezia.org"
|
||||
readonly property bool showsCode: dialogState === "loading" || dialogState === "code"
|
||||
|
||||
function requestCode(serverId) {
|
||||
root.serverId = serverId
|
||||
root.otpCode = ""
|
||||
root.errorKind = ""
|
||||
root.dialogState = "loading"
|
||||
countdown.stop()
|
||||
statusPoll.stop()
|
||||
if (!root.opened) {
|
||||
root.open()
|
||||
}
|
||||
Qt.callLater(function() {
|
||||
SubscriptionUiController.otpLogin(root.serverId)
|
||||
})
|
||||
}
|
||||
|
||||
function formattedCode() {
|
||||
var half = Math.ceil(root.otpCode.length / 2)
|
||||
return root.otpCode.length > 4
|
||||
? root.otpCode.substring(0, half) + " " + root.otpCode.substring(half)
|
||||
: root.otpCode
|
||||
}
|
||||
|
||||
function formattedTime() {
|
||||
var minutes = Math.floor(root.secondsLeft / 60)
|
||||
var seconds = root.secondsLeft % 60
|
||||
return minutes + ":" + (seconds < 10 ? "0" : "") + seconds
|
||||
}
|
||||
|
||||
function titleText() {
|
||||
if (root.dialogState === "expired") {
|
||||
return qsTr("Code expired")
|
||||
}
|
||||
if (root.dialogState === "error") {
|
||||
switch (root.errorKind) {
|
||||
case "noNetwork": return qsTr("No connection")
|
||||
case "purchaseNotFound": return qsTr("Purchase hasn't reached us yet")
|
||||
case "rateLimited": return qsTr("Service is busy")
|
||||
case "receiptRejected":
|
||||
case "receiptRejectedAgain": return qsTr("Couldn't verify the purchase")
|
||||
default: return qsTr("Couldn't get a code")
|
||||
}
|
||||
}
|
||||
return qsTr("Code for your account")
|
||||
}
|
||||
|
||||
function subtitleText() {
|
||||
if (root.dialogState === "expired") {
|
||||
return qsTr("Request a new code")
|
||||
}
|
||||
if (root.dialogState === "error") {
|
||||
switch (root.errorKind) {
|
||||
case "noNetwork": return qsTr("Check your connection and retry")
|
||||
case "purchaseNotFound": return qsTr("This happens right after payment or a plan change. Retry in a minute")
|
||||
case "receiptRejected": return qsTr("Try again")
|
||||
case "receiptRejectedAgain": return qsTr("Contact support and we'll help you sort it out")
|
||||
default: return qsTr("Try again later")
|
||||
}
|
||||
}
|
||||
return qsTr("Enter it at cp.amnezia.org to confirm the subscription is yours")
|
||||
}
|
||||
|
||||
function primaryButtonText() {
|
||||
if (root.dialogState === "expired") {
|
||||
return qsTr("Get a new code")
|
||||
}
|
||||
if (root.dialogState === "error") {
|
||||
return root.errorKind === "receiptRejectedAgain" ? qsTr("Contact support") : qsTr("Retry")
|
||||
}
|
||||
return qsTr("Open account")
|
||||
}
|
||||
|
||||
function primaryButtonEnabled() {
|
||||
if (root.dialogState === "loading") {
|
||||
return false
|
||||
}
|
||||
if (root.dialogState === "error" && root.errorKind === "rateLimited") {
|
||||
return root.retryCooldownSec <= 0
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
function primaryButtonClicked() {
|
||||
if (root.dialogState === "code") {
|
||||
Qt.openUrlExternally(root.accountUrl)
|
||||
} else if (root.dialogState === "error" && root.errorKind === "receiptRejectedAgain") {
|
||||
root.close()
|
||||
PageController.goToPage(PageEnum.PageSettingsApiSupport)
|
||||
} else {
|
||||
root.requestCode(root.serverId)
|
||||
}
|
||||
}
|
||||
|
||||
parent: Overlay.overlay
|
||||
|
||||
x: Math.round((parent.width - width) / 2)
|
||||
y: Math.round((parent.height - height) / 2)
|
||||
width: Math.min(parent.width - 32, 400)
|
||||
|
||||
padding: 0
|
||||
|
||||
modal: true
|
||||
focus: true
|
||||
closePolicy: Popup.CloseOnEscape
|
||||
|
||||
Overlay.modal: Rectangle {
|
||||
color: AmneziaStyle.color.bgOverlay
|
||||
}
|
||||
|
||||
background: Rectangle {
|
||||
color: AmneziaStyle.color.bgSurfaceAlt
|
||||
radius: 16
|
||||
}
|
||||
|
||||
onClosed: {
|
||||
countdown.stop()
|
||||
statusPoll.stop()
|
||||
retryCooldown.stop()
|
||||
}
|
||||
|
||||
Timer {
|
||||
id: countdown
|
||||
|
||||
interval: 1000
|
||||
repeat: true
|
||||
|
||||
onTriggered: {
|
||||
if (root.secondsLeft > 0) {
|
||||
root.secondsLeft -= 1
|
||||
} else {
|
||||
stop()
|
||||
statusPoll.stop()
|
||||
root.dialogState = "expired"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Timer {
|
||||
id: statusPoll
|
||||
|
||||
interval: 3000
|
||||
repeat: true
|
||||
|
||||
onTriggered: {
|
||||
SubscriptionUiController.checkOtpStatus()
|
||||
}
|
||||
}
|
||||
|
||||
Timer {
|
||||
id: retryCooldown
|
||||
|
||||
interval: 1000
|
||||
repeat: true
|
||||
|
||||
onTriggered: {
|
||||
if (root.retryCooldownSec > 0) {
|
||||
root.retryCooldownSec -= 1
|
||||
} else {
|
||||
stop()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Connections {
|
||||
target: SubscriptionUiController
|
||||
|
||||
function onOtpCodeReceived(code, expiresInSec) {
|
||||
if (!root.opened) {
|
||||
return
|
||||
}
|
||||
root.otpCode = code
|
||||
root.secondsLeft = expiresInSec
|
||||
root.dialogState = "code"
|
||||
countdown.restart()
|
||||
statusPoll.restart()
|
||||
}
|
||||
|
||||
function onOtpLoginFailed(kind) {
|
||||
if (!root.opened) {
|
||||
return
|
||||
}
|
||||
if (kind === "") {
|
||||
root.close()
|
||||
return
|
||||
}
|
||||
root.errorKind = kind
|
||||
root.dialogState = "error"
|
||||
if (kind === "rateLimited") {
|
||||
root.retryCooldownSec = 30
|
||||
retryCooldown.restart()
|
||||
}
|
||||
}
|
||||
|
||||
function onOtpConfirmed() {
|
||||
countdown.stop()
|
||||
statusPoll.stop()
|
||||
root.close()
|
||||
PageController.showNotificationMessage(qsTr("Code accepted"))
|
||||
}
|
||||
|
||||
function onOtpExpired() {
|
||||
root.secondsLeft = 0
|
||||
countdown.stop()
|
||||
statusPoll.stop()
|
||||
root.dialogState = "expired"
|
||||
}
|
||||
}
|
||||
|
||||
contentItem: ColumnLayout {
|
||||
spacing: 0
|
||||
|
||||
H3TextType {
|
||||
Layout.fillWidth: true
|
||||
Layout.topMargin: 16
|
||||
Layout.leftMargin: 16
|
||||
Layout.rightMargin: 16
|
||||
|
||||
text: root.titleText()
|
||||
}
|
||||
|
||||
BodyTextType {
|
||||
Layout.fillWidth: true
|
||||
Layout.topMargin: 8
|
||||
Layout.leftMargin: 16
|
||||
Layout.rightMargin: 16
|
||||
|
||||
color: AmneziaStyle.color.textTertiary
|
||||
text: root.subtitleText()
|
||||
}
|
||||
|
||||
Rectangle {
|
||||
id: codeBox
|
||||
|
||||
Layout.fillWidth: true
|
||||
Layout.topMargin: 16
|
||||
Layout.leftMargin: 16
|
||||
Layout.rightMargin: 16
|
||||
implicitHeight: 96
|
||||
|
||||
visible: root.showsCode
|
||||
radius: 16
|
||||
color: AmneziaStyle.color.bgBase
|
||||
|
||||
Rectangle {
|
||||
anchors.centerIn: parent
|
||||
width: parent.width * 0.6
|
||||
height: 48
|
||||
radius: 12
|
||||
|
||||
visible: root.dialogState === "loading"
|
||||
color: AmneziaStyle.color.bgSurface
|
||||
}
|
||||
|
||||
ColumnLayout {
|
||||
anchors.fill: parent
|
||||
anchors.leftMargin: 16
|
||||
anchors.rightMargin: 16
|
||||
spacing: 4
|
||||
|
||||
visible: root.dialogState === "code"
|
||||
|
||||
Item {
|
||||
Layout.fillWidth: true
|
||||
Layout.fillHeight: true
|
||||
|
||||
H1TextType {
|
||||
anchors.centerIn: parent
|
||||
|
||||
horizontalAlignment: Text.AlignHCenter
|
||||
font.letterSpacing: 2
|
||||
text: root.formattedCode()
|
||||
}
|
||||
|
||||
IconButtonType {
|
||||
id: copyButton
|
||||
|
||||
anchors.right: parent.right
|
||||
anchors.verticalCenter: parent.verticalCenter
|
||||
|
||||
size: IconButtonType.Small
|
||||
|
||||
icon.source: "qrc:/images/controls/copy.svg"
|
||||
|
||||
onClicked: {
|
||||
GC.copyToClipBoard(root.otpCode)
|
||||
PageController.showNotificationMessage(qsTr("Code copied"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SmallTextType {
|
||||
Layout.fillWidth: true
|
||||
Layout.bottomMargin: 12
|
||||
|
||||
horizontalAlignment: Text.AlignHCenter
|
||||
color: AmneziaStyle.color.textTertiary
|
||||
text: qsTr("%1 left").arg(root.formattedTime())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
CaptionTextType {
|
||||
Layout.fillWidth: true
|
||||
Layout.topMargin: 12
|
||||
Layout.leftMargin: 16
|
||||
Layout.rightMargin: 16
|
||||
|
||||
visible: root.showsCode
|
||||
horizontalAlignment: Text.AlignHCenter
|
||||
color: AmneziaStyle.color.textTertiary
|
||||
text: qsTr("Don't share this code with anyone, even support")
|
||||
}
|
||||
|
||||
RowLayout {
|
||||
Layout.fillWidth: true
|
||||
Layout.topMargin: 16
|
||||
Layout.bottomMargin: 8
|
||||
Layout.leftMargin: 8
|
||||
Layout.rightMargin: 8
|
||||
|
||||
DialogButtonType {
|
||||
Layout.fillWidth: true
|
||||
Layout.preferredWidth: 1
|
||||
|
||||
text: qsTr("Close")
|
||||
|
||||
onClicked: root.close()
|
||||
}
|
||||
|
||||
DialogButtonType {
|
||||
Layout.fillWidth: true
|
||||
Layout.preferredWidth: 1
|
||||
|
||||
enabled: root.primaryButtonEnabled()
|
||||
|
||||
text: root.primaryButtonText()
|
||||
emphasized: true
|
||||
textColor: AmneziaStyle.color.textAccent
|
||||
|
||||
onClicked: root.primaryButtonClicked()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -35,6 +35,8 @@ PageType {
|
||||
readonly property bool showRenewLink: !root.showSubscriptionNote
|
||||
&& root.isSubscriptionRenewalAvailable && !root.isInAppPurchase
|
||||
|
||||
readonly property bool isStorePlatform: Qt.platform.os === "ios" || Qt.platform.os === "android" || Qt.platform.os === "osx"
|
||||
|
||||
function updateSubscriptionState() {
|
||||
root.isSubscriptionExpired = ApiAccountInfoModel.data("isSubscriptionExpired")
|
||||
root.isSubscriptionExpiringSoon = ApiAccountInfoModel.data("isSubscriptionExpiringSoon")
|
||||
@@ -268,6 +270,22 @@ PageType {
|
||||
|
||||
spacing: 0
|
||||
|
||||
ListItemType {
|
||||
id: otpLoginEntry
|
||||
|
||||
Layout.fillWidth: true
|
||||
|
||||
visible: root.isStorePlatform
|
||||
|
||||
text: qsTr("Code for the web account")
|
||||
subtitle: qsTr("To sign in or add a subscription")
|
||||
trailingIconSource: "qrc:/images/controls/external-link.svg"
|
||||
|
||||
onClicked: {
|
||||
otpLoginDialog.requestCode(ServersUiController.processedServerId)
|
||||
}
|
||||
}
|
||||
|
||||
ListItemType {
|
||||
id: localProxyItem
|
||||
|
||||
@@ -488,4 +506,8 @@ PageType {
|
||||
|
||||
serverNameText: root.processedServer != null ? root.processedServer.name : ""
|
||||
}
|
||||
|
||||
OtpLoginDialog {
|
||||
id: otpLoginDialog
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,7 @@
|
||||
<file>Components/BenefitRow.qml</file>
|
||||
<file>Components/BenefitsPanel.qml</file>
|
||||
<file>Components/SubscriptionExpiredDrawer.qml</file>
|
||||
<file>Components/OtpLoginDialog.qml</file>
|
||||
<file>Components/TermsAndPrivacyText.qml</file>
|
||||
<file>Components/TransportProtoSelector.qml</file>
|
||||
<file>Components/AddSitePanel.qml</file>
|
||||
|
||||
Reference in new issue
Block a user