wangzhibo
2024-11-29 e381baaeebc5b34b8c21f0f6d509b37e195af183
app/src/main/java/com/shsening/autouploadvideos/utils/Utils.kt
File was renamed from app/src/main/java/com/shsening/autouploadvideos/Utils.kt
@@ -1,13 +1,17 @@
package com.shsening.autouploadvideos
package com.shsening.autouploadvideos.utils
import SessionProfile
import android.app.Instrumentation
import android.content.Context
import android.content.Intent
import android.os.SystemClock
import android.view.MotionEvent
import android.webkit.CookieManager
import android.widget.Toast
import androidx.core.content.FileProvider
import com.shsening.autouploadvideos.AppConfig
import com.shsening.autouploadvideos.PlatformItem
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
@@ -16,11 +20,15 @@
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.io.IOException
import java.io.Serializable
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale
object Utils {
    data class AppUpdateInfo(
@@ -37,7 +45,10 @@
        val datetime: String,
        val videoUrl: String,
        val coverUrl: String,
        var filename: String = generateFilename(datetime)
        var filename: String = generateFilename(datetime),
        var sessionProfileId: String? =null,
        var sessionProfileName: String? =null,
        var platform: PlatformItem? =null
    ) : Serializable {
        companion object {
@@ -150,26 +161,37 @@
        return arrayOf(row, column) // 返回数组
    }
    suspend fun sendVideoUploadedMessage(context: Context,taskId: String): Boolean {
    fun sendVideoUploadedMessage(taskId: String, callback: (Boolean, Exception?) -> Unit) {
        try {
            val client = OkHttpClient()
            val request = Request.Builder()
                .url(AppConfig.URL_CONFIRM_TASK_UPLOADED + taskId)
                .build()
            // 异步执行网络请求
            client.newCall(request).enqueue(object : okhttp3.Callback {
                override fun onFailure(call: okhttp3.Call, e: IOException) {
                    // 请求失败,返回错误
                    callback(false, e)
                }
            return withContext(Dispatchers.IO) {
                val response = client.newCall(request).execute()
                if (!response.isSuccessful) throw IOException("Unexpected code $response")
                val json = JSONObject(response.body?.string() ?: "")
                json.getBoolean("result")
            }
        }catch(e:Exception){
                override fun onResponse(call: okhttp3.Call, response: okhttp3.Response) {
                    try {
                        val json = JSONObject(response.body?.string() ?: "")
                        val result = json.getString("msg")
                        // 成功回调
                        callback(true, Exception(result))
                    } catch (e: Exception) {
                        // 处理解析错误
                        callback(false, e)
                    } finally {
                        response.close()
                    }
                }
            })
        } catch (e: Exception) {
            e.printStackTrace()
            return false
            // 处理其他异常
            callback(false, e)
        }
    }
@@ -203,6 +225,56 @@
        }
    }
    interface FetchTasksCallback {
        fun onTasksFetched(uploadTaskList: MutableList<Utils.VideoUploadTaskInfo>)
    }
    interface UploadCallback {
        fun onSuccess()
        fun onError()
    }
    fun fetchTasksBySessionProfile(profile: SessionProfile, callback: FetchTasksCallback) {
        val uploadTaskList: MutableList<Utils.VideoUploadTaskInfo> = mutableListOf()
        val client = OkHttpClient()
        val request = Request.Builder()
            .url(AppConfig.URL_CHECK_CLIENT_TASKS + AppConfig.CLIENT_ANDROID_ID + "&sessionprofile=" + profile.id + "&videotype=" + profile.type) // 替换为你的任务地址
            .build()
        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                e.printStackTrace()
                // 可以在这里通知调用者出错
            }
            override fun onResponse(call: Call, response: Response) {
                response.use {
                    if (!response.isSuccessful) throw IOException("Unexpected code $response")
                    val jsonArray = JSONArray(response.body?.string() ?: "")
                    if (jsonArray.length() > 0) {
                        for (i in 0 until jsonArray.length()) {
                            val jsonObject = jsonArray.getJSONObject(i)
                            try {
                                val task = Utils.VideoUploadTaskInfo(
                                    taskId = jsonObject.getString("taskId"),
                                    title = jsonObject.getString("title"),
                                    description = jsonObject.getString("description"),
                                    datetime = jsonObject.getString("datetime"),
                                    videoUrl = jsonObject.getString("videoUrl"),
                                    coverUrl = jsonObject.getString("coverUrl")
                                )
                                uploadTaskList.add(task)
                            } catch (e: Exception) {
                                e.printStackTrace()
                            }
                        }
                    }
                }
                // 在请求成功并解析完任务列表后,调用回调函数
                callback.onTasksFetched(uploadTaskList)
            }
        })
    }
    suspend fun downloadCommonFileToExternalFilesDir(context: Context, url: String, filename: String, install: Boolean) {
        val tmpFile = File(context.getExternalFilesDir(null), filename)
@@ -220,18 +292,15 @@
                    override fun onFailure(call: Call, e: IOException) {
                        deferred.completeExceptionally(e) // 下载失败时标记为异常
                    }
                    override fun onResponse(call: Call, response: Response) {
                        response.use {
                            if (!response.isSuccessful) {
                                deferred.completeExceptionally(IOException("Unexpected code $response")) // 如果响应不成功,标记为异常
                                return
                            }
                            tmpFile.outputStream().use { outputStream ->
                                outputStream.write(response.body?.bytes())
                            }
                            if (install) {
                                installApk(context,tmpFile)
                            }
@@ -272,4 +341,24 @@
        return if (month in 1..12) months[month - 1] else "Invalid"
    }
    // 获取 key 的位置
    fun getSessionProfileValuePosition(key: String): Int {
        val index = AppConfig.SESSION_PROFILE_TYPE.values.toList().indexOf(key)
        return if (index == -1) 0 else index
    }
    fun getCurrentTimeString(): String {
        val formatter = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()) // 自定义格式
        val currentDate = Date() // 获取当前时间
        return formatter.format(currentDate) // 格式化为字符串
    }
    // 根据位置获取 key
    fun getSessionProfileValueByPosition(position: Int?): String? {
        if (position==null){
            return "Unknown"
        }
        return AppConfig.SESSION_PROFILE_TYPE.values.toList().getOrElse(position) { "Unknown" }
    }
}