Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PIA-1948: Introduce DIP signup API to get token #19

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,17 @@ public interface AccountAPI {
callback: (details: DipCountriesResponse?, error: List<AccountRequestError>) -> Unit
)

/**
* @param countryCode `String`
* @param regionName `String`
* @param callback `(details: DedicatedIPTokenDetails?, error: List<AccountRequestError>) -> Unit`
*/
fun getDedicatedIP(
countryCode: String,
regionName: String,
callback: (details: DedicatedIPTokenDetails?, error: List<AccountRequestError>) -> Unit
)

/**
* @param dipTokens `List<String>`
* @param callback `(details: DedicatedIPInformation, error: List<AccountRequestError>) -> Unit`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ package com.privateinternetaccess.account.internals

import com.privateinternetaccess.account.*
import com.privateinternetaccess.account.internals.model.request.DedicatedIPRequest
import com.privateinternetaccess.account.internals.model.request.GetDedicatedIPTokenRequest
import com.privateinternetaccess.account.internals.model.response.ApiTokenResponse
import com.privateinternetaccess.account.model.response.DipCountriesResponse
import com.privateinternetaccess.account.internals.model.response.SetEmailResponse
Expand Down Expand Up @@ -86,6 +87,7 @@ internal open class Account(
REFRESH_TOKEN("/api/client/v4/refresh"),
MESSAGES("/api/client/v2/messages"),
SUPPORTED_DEDICATED_IP_COUNTRIES("/api/client/v5/dip_regions"),
GET_DEDICATED_IP_TOKEN("/api/client/v5/redeem_dip_token"),
REDEEM_DEDICATED_IP("/api/client/v2/dedicated_ip"),
RENEW_DEDICATED_IP("/api/client/v2/check_renew_dip"),
ANDROID_ADDONS_SUBSCRIPTIONS("/api/client/v5/android_addons"),
Expand Down Expand Up @@ -121,6 +123,7 @@ internal open class Account(
Path.REFRESH_TOKEN to "apiv4",
Path.MESSAGES to "apiv2",
Path.SUPPORTED_DEDICATED_IP_COUNTRIES to "apiv5",
Path.GET_DEDICATED_IP_TOKEN to "apiv5",
Path.REDEEM_DEDICATED_IP to "apiv2",
Path.RENEW_DEDICATED_IP to "apiv2",
Path.ANDROID_ADDONS_SUBSCRIPTIONS to "apiv5",
Expand Down Expand Up @@ -218,6 +221,16 @@ internal open class Account(
}
}

override fun getDedicatedIP(
countryCode: String,
regionName: String,
callback: (details: DedicatedIPTokenDetails?, error: List<AccountRequestError>) -> Unit
) {
launch {
getDedicatedIPAsync(countryCode, regionName, endpointsProvider.accountEndpoints(), callback)
}
}

override fun redeemDedicatedIPs(
dipTokens: List<String>,
callback: (details: List<DedicatedIPInformation>, error: List<AccountRequestError>) -> Unit
Expand Down Expand Up @@ -887,6 +900,105 @@ internal open class Account(
}
}

private suspend fun getDedicatedIPAsync(
countryCode: String,
regionName: String,
endpoints: List<AccountEndpoint>,
callback: (details: DedicatedIPTokenDetails?, error: List<AccountRequestError>) -> Unit
) {
val listErrors: MutableList<AccountRequestError> = mutableListOf()
kp-juan-docal marked this conversation as resolved.
Show resolved Hide resolved
var details: DedicatedIPTokenDetails? = null
if (endpoints.isEmpty()) {
listErrors.add(
AccountRequestError(
600,
"No available endpoints to perform the request"
)
)
}

refreshTokensIfNeeded(endpoints)
for (endpoint in endpoints) {
val apiToken = persistence.apiTokenResponse()?.apiToken
if (apiToken == null) {
listErrors.add(AccountRequestError(600, "Invalid request token"))
break
}

if (endpoint.usePinnedCertificate && certificate.isNullOrEmpty()) {
listErrors.add(
AccountRequestError(
600,
"No available certificate for pinning purposes"
)
)
continue
}

val httpClientConfigResult = if (endpoint.usePinnedCertificate) {
AccountHttpClient.client(certificate, Pair(endpoint.ipOrRootDomain, endpoint.certificateCommonName!!))
} else {
AccountHttpClient.client()
}

val httpClient = httpClientConfigResult.first
val httpClientError = httpClientConfigResult.second
if (httpClientError != null) {
listErrors.add(AccountRequestError(600, httpClientError.message))
continue
}

if (httpClient == null) {
listErrors.add(AccountRequestError(600, "Invalid http client"))
continue
}

val url = AccountUtils.prepareRequestUrl(endpoint.ipOrRootDomain, Path.GET_DEDICATED_IP_TOKEN)
if (url == null) {
listErrors.add(AccountRequestError(600, "Error preparing url ${endpoint.ipOrRootDomain} - ${Path.GET_DEDICATED_IP_TOKEN.url}"))
continue
}

var succeeded = false
val response = httpClient.postCatching<Pair<HttpResponse?, Exception?>> {
url(url)
header("Authorization", "Token $apiToken")
contentType(ContentType.Application.Json)
setBody(json.encodeToString(GetDedicatedIPTokenRequest.serializer(), GetDedicatedIPTokenRequest(countryCode, regionName)))
}

response.first?.let {
if (AccountUtils.isErrorStatusCode(it.status.value)) {
listErrors.add(it.mapStatusCodeToAccountError())
} else {
try {
details = json.decodeFromString(DedicatedIPTokenDetails.serializer(), it.bodyAsText())
succeeded = true
} catch (exception: SerializationException) {
listErrors.add(AccountRequestError(600, "Decode error $exception"))
}
}
}
response.second?.let {
listErrors.add(AccountRequestError(600, it.message))
}

// Close the used client explicitly.
// We need to recreate it due to the possibility of pinning among the endpoints list.
httpClient.close()

// If there were no errors in the request for the current endpoint. No need to try the next endpoint.
if (succeeded) {
listErrors.clear()
break
}
}

withContext(Dispatchers.Main) {
callback(details, listErrors)
}
}

private suspend fun redeemDedicatedIPsAsync(
dipTokens: List<String>,
endpoints: List<AccountEndpoint>,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.privateinternetaccess.account.internals.model.request


import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable

@Serializable
data class GetDedicatedIPTokenRequest(
@SerialName("country_code")
val countryCode: String,
@SerialName("region")
val region: String
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package com.privateinternetaccess.account.model.response


import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable

@Serializable
data class DedicatedIPTokenDetails(
@SerialName("meta_data")
val metaData: List<MetaData>,
@SerialName("partners_id")
val partnersId: Int,
@SerialName("redeemed_at")
val redeemedAt: String,
@SerialName("token")
val token: String
) {
@Serializable
data class MetaData(
@SerialName("common_name")
val commonName: String,
@SerialName("region_id")
val regionId: String
)
}
Loading