TP-51325 | zip utils non fatal crash (#88)

This commit is contained in:
Sayed Owais Ali
2023-12-29 20:26:59 +05:30
committed by GitHub
parent a63b842bd5
commit f2efc258d9
7 changed files with 79 additions and 47 deletions

View File

@@ -6,7 +6,7 @@ plugins {
id 'kotlin-parcelize'
}
def VERSION_NAME = "1.0.19"
def VERSION_NAME = "1.0.20"
android {
namespace 'com.navi.alfred'

View File

@@ -7,14 +7,23 @@
package com.navi.alfred.network
import android.content.Context
import android.content.Intent
import android.util.Log
import com.chuckerteam.chucker.api.ChuckerCollector
import com.chuckerteam.chucker.api.ChuckerInterceptor
import com.google.gson.GsonBuilder
import com.navi.alfred.AlfredManager
import com.navi.alfred.BuildConfig
import com.navi.alfred.deserializer.FailureDataDeserializer
import com.navi.alfred.model.ErrorMessage
import com.navi.alfred.model.FailureRequest
import com.navi.alfred.network.model.RequestInfo
import com.navi.alfred.utils.AlfredConstants
import com.navi.alfred.utils.handleException
import com.navi.alfred.utils.orZero
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
@@ -25,6 +34,27 @@ object AlfredFailureRetrofitProvider {
private lateinit var apiService: AlfredFailureRetrofitService
private lateinit var okHttpClient: OkHttpClient
private val headerInterceptor: Interceptor
get() = Interceptor { chain ->
val request = chain.request()
val response =
try {
chain.proceed(request).newBuilder().build()
} catch (e: Exception) {
val errorMessage = handleException(e)
setNetworkFailureBroadcast(e, errorMessage, request)
// A mocked response in case of n/w exception
Response.Builder()
.request(request)
.protocol(Protocol.HTTP_2)
.code(errorMessage.statusCode.orZero())
.body(ResponseBody.create("application/json".toMediaTypeOrNull(), "{}"))
.message(errorMessage.message.orEmpty())
.build()
}
response
}
fun init(context: Context) {
okHttpClient =
OkHttpClient.Builder()
@@ -33,6 +63,7 @@ object AlfredFailureRetrofitProvider {
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
if (BuildConfig.DEBUG && !AlfredManager.config.getDisableAlfredLogsStatus()) {
addInterceptor(loggingInterceptor())
addInterceptor(
ChuckerInterceptor.Builder(context)
.collector(ChuckerCollector(context))
@@ -40,6 +71,7 @@ object AlfredFailureRetrofitProvider {
.build()
)
}
addInterceptor(headerInterceptor)
connectionPool(ConnectionPool(0, 5, TimeUnit.MINUTES))
.protocols(listOf(Protocol.HTTP_1_1))
}
@@ -67,7 +99,24 @@ object AlfredFailureRetrofitProvider {
.build()
}
private fun setNetworkFailureBroadcast(e: Exception, errorMessage: ErrorMessage, request: Request) {
Log.d("Alfred", "AlfredRetrofitProvider setNetworkFailureBroadcast - sending Broadcast")
val intent = Intent(AlfredConstants.BROADCAST_ACTION_TYPE)
val requestInfo = RequestInfo(
request.url.toString(),
request.headers[AlfredConstants.HEADER_X_TARGET],
request.headers[AlfredConstants.HEADER_APP_REQUEST_ID]
)
intent.putExtra(AlfredConstants.BROADCAST_EXCEPTION, e)
intent.putExtra(AlfredConstants.BROADCAST_ERROR_MESSAGE, errorMessage)
intent.putExtra(AlfredConstants.BROADCAST_REQUEST, requestInfo)
AlfredManager.applicationContext.sendBroadcast(intent)
}
fun getApiService(): AlfredFailureRetrofitService {
return apiService
}
private fun loggingInterceptor() =
HttpLoggingInterceptor().apply { setLevel(HttpLoggingInterceptor.Level.BODY) }
}

View File

@@ -45,7 +45,6 @@ import kotlin.concurrent.fixedRateTimer
internal suspend fun sendEventsToServer(
clientTs: Long? = null,
snapshotPerSecond: Int? = null,
apiKey: String? = null,
workManagerFlow: Boolean? = false
): Boolean {
if (workManagerFlow == true || (AlfredManager.config.getAlfredStatus() && AlfredManager.config.getEnableRecordingStatus())) {
@@ -75,7 +74,7 @@ internal suspend fun sendEventsToServer(
)
val response = AlfredManager.networkRepository.sendEvents(
AlfredManager.config.getPostUrl(),
apiKey ?: AlfredManager.config.getApiKey(),
AlfredManager.config.getApiKey(),
request
)
return if (
@@ -137,7 +136,6 @@ internal suspend fun sendEventsToServer(
internal suspend fun sendNegativeCaseToServer(
clientTs: Long? = null,
snapshotPerSecond: Int? = null,
apiKey: String? = null,
workManagerFlow: Boolean? = false
): Boolean {
if (workManagerFlow == true || (AlfredManager.config.getAlfredStatus() && AlfredManager.config.getEnableRecordingStatus())) {
@@ -168,7 +166,7 @@ internal suspend fun sendNegativeCaseToServer(
)
val response = AlfredManager.networkRepository.sendNegativeCase(
DEFAULT_SEND_CRASH_URL,
apiKey ?: AlfredManager.config.getApiKey(),
AlfredManager.config.getApiKey(),
request
)
return if (
@@ -218,7 +216,6 @@ internal suspend fun sendNegativeCaseToServer(
}
internal suspend fun sendFailureEventsToServer(
apiKey: String? = null,
workManagerFlow: Boolean? = false
): Boolean {
if (workManagerFlow == true || (AlfredManager.config.getAlfredStatus() && AlfredManager.config.getEnableRecordingStatus())) {
@@ -246,7 +243,7 @@ internal suspend fun sendFailureEventsToServer(
)
val response = AlfredManager.networkRepository.sendFailure(
DEFAULT_SEND_FAILURE_POST_URL,
apiKey ?: AlfredManager.config.getApiKey(),
AlfredManager.config.getApiKey(),
request
)
return if (
@@ -281,8 +278,7 @@ internal fun sendAlfredSessionEvent(
dumpFlow: Boolean = false,
index: Int? = null,
currentZipName: String? = null,
latestScreenshotTimestamp: Long? = null,
apiKey: String
latestScreenshotTimestamp: Long? = null
) {
var request: SessionRequest? = null
if (dumpFlow) {
@@ -351,7 +347,7 @@ internal fun sendAlfredSessionEvent(
AlfredManager.coroutineScope.launch {
val response = AlfredManager.networkRepository.sendSession(
DEFAULT_SEND_SESSION_POST_URL,
apiKey,
AlfredManager.config.getApiKey(),
request
)
if (response.isSuccessful && response.code() == AlfredConstants.CODE_API_SUCCESS) {
@@ -389,7 +385,6 @@ internal fun sendAlfredSessionEvent(
internal suspend fun sendIngestMetric(
clientTs: Long? = null,
snapshotPerSecond: Int? = null,
apiKey: String? = null,
workManagerFlow: Boolean? = false
): Boolean {
if ((workManagerFlow == true) || (AlfredManager.config.getAlfredStatus() && AlfredManager.config.getEnableRecordingStatus())) {
@@ -421,7 +416,7 @@ internal suspend fun sendIngestMetric(
val response =
AlfredManager.networkRepository.eventMetric(
DEFAULT_INGEST_METRIC_URL,
apiKey ?: AlfredManager.config.getApiKey(),
AlfredManager.config.getApiKey(),
metricRequestBody = request
)
return if (

View File

@@ -31,8 +31,7 @@ internal suspend fun getPreSignedUrl(
index: Int? = null,
workManagerFlow: Boolean? = false,
alfredEventIdForDumpFlow: String? = null,
latestScreenshotTimestamp: Long? = null,
apiKey: String? = AlfredManager.config.getApiKey()
latestScreenshotTimestamp: Long? = null
) {
val currentZipName: String
val latestScreenshotName: Long
@@ -47,7 +46,7 @@ internal suspend fun getPreSignedUrl(
}
val bucketKey = currentZipName.plus(AlfredConstants.ZIP_FILE_EXTENSION)
val response =
AlfredManager.networkRepository.getPreSignedUrl(bucketKey, apiKey.toString())
AlfredManager.networkRepository.getPreSignedUrl(bucketKey, AlfredManager.config.getApiKey())
if (response.isSuccessful && response.code() == AlfredConstants.CODE_API_SUCCESS) {
checkFileExists(zipFileName, AlfredManager.applicationContext)?.let { file ->
response.body()?.data?.let {
@@ -59,8 +58,7 @@ internal suspend fun getPreSignedUrl(
zipFileName,
workManagerFlow = workManagerFlow,
currentZipName = currentZipName,
latestScreenshotTimestamp = latestScreenshotName,
apiKey = apiKey.toString()
latestScreenshotTimestamp = latestScreenshotName
)
}
}
@@ -115,7 +113,6 @@ internal fun checkAndInitiateFileUploadWorkManager() {
val latestScreenshotTimestamp = AlfredManager.config.getLatestScreenshotTimestamp()
val snapshotPerSecond = AlfredManager.config.getSnapshotPerSecond()
val alfredEventId = AlfredManager.config.getAlfredEventId()
val apiKey = AlfredManager.config.getApiKey()
val requestDataForZip =
Data.Builder()
@@ -125,13 +122,11 @@ internal fun checkAndInitiateFileUploadWorkManager() {
.putString(AlfredConstants.SCREENSHOT_LIST, Gson().toJson(screenShotList))
.putString(AlfredConstants.ALFRED_EVENT_ID, alfredEventId)
.putLong(AlfredConstants.LATEST_SCREENSHOT_TIMESTAMP, latestScreenshotTimestamp)
.putString(AlfredConstants.X_API_KEY, apiKey)
.build()
buildWorkManagerForZip(requestDataForZip)
val requestDataForEvents =
Data.Builder()
.putString(AlfredConstants.X_API_KEY, apiKey)
.putLong(AlfredConstants.EVENT_START_RECORDING_TIME, clientTs ?: 0L)
.putInt(AlfredConstants.SNAPSHOT_PER_SECOND, snapshotPerSecond)
.build()
@@ -206,14 +201,13 @@ internal suspend fun uploadFile(
zipFileName: String,
workManagerFlow: Boolean? = false,
currentZipName: String? = "",
latestScreenshotTimestamp: Long? = 0L,
apiKey: String
latestScreenshotTimestamp: Long? = 0L
) {
val requestBody = uploadFile.asRequestBody("application/zip".toMediaTypeOrNull())
val uploadResponse = AlfredManager.networkRepository.uploadZipToS3(url, requestBody)
if (uploadResponse.isSuccessful && uploadResponse.code() == AlfredConstants.CODE_API_SUCCESS) {
uploadFile.delete()
sendAlfredSessionEvent(dumpFlow, index, currentZipName, latestScreenshotTimestamp, apiKey)
sendAlfredSessionEvent(dumpFlow, index, currentZipName, latestScreenshotTimestamp)
} else {
val failureEvent = buildFailureEvent(
errorType = ZIP_ERROR,

View File

@@ -54,15 +54,19 @@ internal fun zip(_files: java.util.ArrayList<String>, zipFilePath: String?): Boo
val data = ByteArray(buffer)
for (i in _files.indices) {
try {
val fi = FileInputStream(_files[i])
origin = BufferedInputStream(fi, buffer)
val entry = ZipEntry(_files[i].substring(_files[i].lastIndexOf("/") + 1))
out.putNextEntry(entry)
var count: Int
while (origin.read(data, 0, buffer).also { count = it } != -1) {
out.write(data, 0, count)
val imageFile = File(_files[i])
val imageFileName = imageFile.name
if(checkFileExists(imageFileName, AlfredManager.applicationContext) != null) {
val fi = FileInputStream(_files[i])
origin = BufferedInputStream(fi, buffer)
val entry = ZipEntry(_files[i].substring(_files[i].lastIndexOf("/") + 1))
out.putNextEntry(entry)
var count: Int
while (origin.read(data, 0, buffer).also { count = it } != -1) {
out.write(data, 0, count)
}
origin.close()
}
origin.close()
} catch (e: Exception) {
e.log()
}
@@ -75,7 +79,7 @@ internal fun zip(_files: java.util.ArrayList<String>, zipFilePath: String?): Boo
return null
}
internal fun checkDbBeforeStartRecording(apiKey: String? = AlfredManager.config.getApiKey()) {
internal fun checkDbBeforeStartRecording() {
AlfredManager.coroutineScope.launch(Dispatchers.IO) {
if (AlfredManager.screenShotDao.getScreenShotCount() > 0) {
AlfredManager.screenShotDao.deleteAllScreenShot()
@@ -95,8 +99,7 @@ internal fun checkDbBeforeStartRecording(apiKey: String? = AlfredManager.config.
dumpFlow = true,
index = index,
alfredEventIdForDumpFlow = DumpZipDetailsHelper.alfredEventId,
latestScreenshotTimestamp = DumpZipDetailsHelper.latestScreenshotTimestamp,
apiKey = apiKey
latestScreenshotTimestamp = DumpZipDetailsHelper.latestScreenshotTimestamp
)
} else {
AlfredManager.zipDetailsDao.deleteZipFileDetail(DumpZipDetailsHelper.id)
@@ -126,8 +129,7 @@ internal suspend fun toZipForWorkManager(
eventStartRecordingTime: Long? = null,
index: Int? = null,
alfredEventId: String,
latestScreenshotTimestamp: Long,
apiKey: String
latestScreenshotTimestamp: Long
) {
AlfredManager.sessionIdForCrash = alfredSessionId
AlfredManager.sessionStartRecordingTimeForCrash = sessionStartRecordingTime
@@ -149,8 +151,7 @@ internal suspend fun toZipForWorkManager(
workManagerFlow = true,
dumpFlow = true,
alfredEventIdForDumpFlow = alfredEventId,
latestScreenshotTimestamp = latestScreenshotTimestamp,
apiKey = apiKey
latestScreenshotTimestamp = latestScreenshotTimestamp
)
}
}

View File

@@ -25,35 +25,30 @@ class UploadEventsWorker(context: Context, workerParams: WorkerParameters) :
override suspend fun doWork(): Result =
withContext(Dispatchers.IO) {
val apiKey = inputData.getString(AlfredConstants.X_API_KEY)
val clientTs = inputData.getLong(AlfredConstants.EVENT_START_RECORDING_TIME, 0L)
val snapshotPerSecond = inputData.getInt(AlfredConstants.SNAPSHOT_PER_SECOND, 1)
try {
if (apiKey == null) {
if (clientTs == 0L) {
Result.failure()
} else {
AlfredManager.alfredDataBase = AlfredDatabaseHelper.getAnalyticsDatabase(AlfredManager.applicationContext)
sendEventsToServer(
clientTs = clientTs,
snapshotPerSecond = snapshotPerSecond,
apiKey = apiKey,
workManagerFlow = true
)
sendIngestMetric(
clientTs = clientTs,
snapshotPerSecond = snapshotPerSecond,
apiKey = apiKey,
workManagerFlow = true
)
sendNegativeCaseToServer(
clientTs = clientTs,
snapshotPerSecond = snapshotPerSecond,
apiKey = apiKey,
workManagerFlow = true
)
sendFailureEventsToServer(
apiKey = apiKey,
workManagerFlow = true
)
Result.success()

View File

@@ -45,7 +45,6 @@ class UploadFileWorker(context: Context, workerParams: WorkerParameters) :
.plus(AlfredConstants.ALFRED_EVENT_ID)
val latestScreenshotTimestamp =
inputData.getLong(AlfredConstants.LATEST_SCREENSHOT_TIMESTAMP, 0L)
val apiKey = inputData.getString(AlfredConstants.X_API_KEY).toString()
workFailureData.add(
WorkManagerFailureInputData(
alfredSessionId = alfredSessionId,
@@ -73,8 +72,7 @@ class UploadFileWorker(context: Context, workerParams: WorkerParameters) :
alfredSessionId = alfredSessionId,
eventStartRecordingTime = eventStartRecordingTime,
alfredEventId = alfredEventId,
latestScreenshotTimestamp = latestScreenshotTimestamp,
apiKey = apiKey
latestScreenshotTimestamp = latestScreenshotTimestamp
)
Result.success()
}