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

[android] sync date with server date #65

Merged
merged 2 commits into from
Nov 22, 2024
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 @@ -18,7 +18,7 @@ internal class ExperimentRepositoryImpl(private val config: Config): ExperimentR
): Result<ExperimentConfigs> {
return withContext(Dispatchers.IO) {
val url = config.endpoint.cdn + "/projects/" + config.projectId + "/experiments/id/" + id
val response: String = getRequest(url).getOrElse {
val response: String = getRequest(url, syncDateTime = true).getOrElse {
return@withContext Result.failure(it)
}
val json = Json.decodeFromString<JsonElement>(response)
Expand All @@ -30,7 +30,7 @@ internal class ExperimentRepositoryImpl(private val config: Config): ExperimentR
override suspend fun fetchTriggerExperimentConfigs(name: String): Result<ExperimentConfigs> {
return withContext(Dispatchers.IO) {
val url = config.endpoint.cdn + "/projects/" + config.projectId + "/experiments/trigger/" + name
val response: String = getRequest(url).getOrElse {
val response: String = getRequest(url, syncDateTime = true).getOrElse {
return@withContext Result.failure(it)
}
val json = Json.decodeFromString<JsonElement>(response)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.nativebrik.sdk.data

import com.nativebrik.sdk.data.user.syncDateFromHttpResponse
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
Expand All @@ -9,9 +10,10 @@ import java.net.URL
internal const val CONNECT_TIMEOUT = 10 * 1000
internal const val READ_TIMEOUT = 5 * 1000

internal fun getRequest(endpoint: String): Result<String> {
internal fun getRequest(endpoint: String, syncDateTime: Boolean = false): Result<String> {
var connection: HttpURLConnection? = null
try {
val t0 = System.currentTimeMillis()
val url = URL(endpoint)
connection = url.openConnection() as HttpURLConnection
connection.connectTimeout = CONNECT_TIMEOUT
Expand All @@ -23,6 +25,10 @@ internal fun getRequest(endpoint: String): Result<String> {
connection.connect()
val responseCode = connection.responseCode

if (syncDateTime) {
syncDateFromHttpResponse(t0, connection)
}

if (responseCode == HttpURLConnection.HTTP_OK) {
val sb = StringBuilder()
var line: String?
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,15 @@ import android.content.SharedPreferences
import android.os.Build
import com.nativebrik.sdk.VERSION
import com.nativebrik.sdk.schema.BuiltinUserProperty
import java.net.HttpURLConnection
import java.text.SimpleDateFormat
import java.time.Instant
import java.time.ZoneId
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit
import java.util.Locale
import java.util.TimeZone
import java.util.UUID
import kotlin.random.Random

Expand All @@ -22,8 +27,32 @@ internal fun getNativebrikUserSharedPreferences(context: Context): SharedPrefere
internal const val USER_SEED_MAX = 100000000
internal const val USER_SEED_KEY = "NATIVEBRIK_USER_SEED"

internal var DATETIME_OFFSET: Long = 0
internal fun getCurrentDate(): ZonedDateTime {
return ZonedDateTime.now()
val currentMillis = ZonedDateTime.now().toInstant().toEpochMilli()
return ZonedDateTime.ofInstant(
Instant.ofEpochMilli(currentMillis + DATETIME_OFFSET),
ZoneId.systemDefault()
)
}

internal fun syncDateFromHttpResponse(t0: Long, connection: HttpURLConnection) {
val t1 = System.currentTimeMillis()

val serverDateStr = connection.headerFields["Date"]?.firstOrNull() ?: return

val serverTime = try {
val formatter = SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US)
formatter.timeZone = TimeZone.getTimeZone("GMT")
formatter.parse(serverDateStr)?.time ?: return
} catch (e: Exception) {
return
}

val networkDelay = (t1 - t0) / 2
val estimatedServerTime = serverTime + networkDelay

DATETIME_OFFSET = estimatedServerTime - t1
}

internal fun getToday(): ZonedDateTime {
Expand Down
Loading