wangrong
2024-12-10 80fa039de88829e38be193819ffea3f4144297ad
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
package com.shsening.autouploadvideos
 
import CookieHelper
import CookieHelper2
import SessionProfile
import SessionProfileManager
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import android.webkit.CookieManager
import android.webkit.ValueCallback
import android.webkit.WebChromeClient
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import com.shsening.autouploadvideos.AppConfig.Companion.SESSION_PROFILE_PALTFORM_LISTS
import com.shsening.autouploadvideos.action.ActionDouyin
import com.shsening.autouploadvideos.action.ActionKuaishou
import com.shsening.autouploadvideos.action.ActionRedbook
import com.shsening.autouploadvideos.action.ActionShipinhao
import com.shsening.autouploadvideos.utils.DownloadHelper
import com.shsening.autouploadvideos.utils.Utils
import java.io.File
import java.util.LinkedList
import java.util.Queue
 
 
class UploadSessionActivity : AppCompatActivity() {
    private var RedbooklUrl: String? = "https://creator.xiaohongshu.com/publish/publish?from=menu"
    private var DingyuehaolUrl: String? = null
    private lateinit var sessionProfileManager: SessionProfileManager
    lateinit var sessionProfileWebView:SessionProfileWebView
 
    private lateinit var uploadSessionText :TextView
    private lateinit var downloadHelper:DownloadHelper
 
    private val uploadTaskQueue: Queue<Utils.VideoUploadTaskInfo> = LinkedList() // 存储上传任务队列
 
    private lateinit var sessionProfiles: java.util.ArrayList<SessionProfile>
 
    private var last_uploaded_task_id:String = ""
 
    private val threadHandler = Handler(Looper.getMainLooper())
 
    private lateinit var activityReference: UploadSessionActivity
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.upload_session)
 
        activityReference = this
        // 初始化 SessionProfileManager
        sessionProfileManager = SessionProfileManager(this)
        //downloadReceiver = DownloadReceiver(this,)
        uploadSessionText = findViewById(R.id.uploadSessionText)
        sessionProfileWebView = findViewById(R.id.uploadSessionWebView)
        // 获取传递的 SessionProfile 数组
        sessionProfiles =
            intent.getParcelableArrayListExtra<SessionProfile>("sessionProfiles")
                ?: arrayListOf()
        if (sessionProfiles != null) {
            for (profile in sessionProfiles) {
                processProfile(profile)
            }
        } else {
            Toast.makeText(this, "未接收到任何 Profile 数据", Toast.LENGTH_SHORT).show()
        }
        downloadHelper = DownloadHelper(this)
 
 
 
        //sessionProfileWebView.setInitialScale(75) // 初始缩放比例
 
        sessionProfileWebView.webViewClient = object : WebViewClient() {
            override fun onPageStarted(
                view: WebView?,
                url: String?,
                favicon: Bitmap?
            ) {
                super.onPageStarted(view, url, favicon)
            }
            override fun onPageFinished(view: WebView?, url: String?) {
                println("这是其他页面"+url)
                super.onPageFinished(view, url)
                view?.requestFocus() // 确保 WebView 获取焦点
                //inject action
                val currentTask = uploadTaskQueue.peek()
                when (currentTask?.platform?.name) {
                    "抖音" -> {
                        val action =
                            ActionDouyin(activityReference, threadHandler, currentTask)
                        action.checkIfContentLoaded()
                    }
                    "快手" -> {
                        val action =
                            ActionKuaishou(activityReference, threadHandler, currentTask)
                        action.checkIfContentLoaded()
                    }
                    "小红书" -> {
                        val action =
                            ActionRedbook(activityReference, threadHandler, currentTask)
                        action.checkIfContentLoaded()
                    }
                    "视频号" -> {
                        val action =
                            ActionShipinhao(activityReference, threadHandler, currentTask)
                        action.checkIfContentLoaded()
                    }
                }
                url?.let{
                    Log.e("shsening", url)
                    try {
                        val cookies = CookieManager.getInstance().getCookie(url)
                        if (cookies != null) {
                            CookieHelper.saveSessionProfileUrlCookies(
                                activityReference,
                                currentTask.sessionProfileId!!,
                                url
                            )
                        } else {
                            Log.w("shsening", "No cookies found for URL: $url")
                        }
                    } catch (e: java.lang.Exception) {
                        Log.e("CookieHelper", "Failed to get cookies: ", e)
                    }
                }
            }
        }
        sessionProfileWebView.webChromeClient = object : WebChromeClient() {
            override fun onShowFileChooser(
                webView: WebView,
                filePathCallback: ValueCallback<Array<Uri>>,
                fileChooserParams: FileChooserParams
            ): Boolean {
                try {
                    var mFilePathCallback: ValueCallback<Array<Uri>>? = filePathCallback
                    // 选择特定的文件
                    val currentTask = uploadTaskQueue.peek()
                    val download_dir = File(getExternalFilesDir(null), currentTask.sessionProfileId)
                    val file = File(download_dir, currentTask.filename + ".mp4")
                    val uri: Uri =
                        FileProvider.getUriForFile(activityReference, AppConfig.FILE_PROVIDER, file)
 
                    mFilePathCallback?.onReceiveValue(arrayOf(uri))
                    return true
                }catch(e:Exception) {
                    return false
                }
            }
            override fun onShowCustomView(view: View?, callback: CustomViewCallback?) {
                super.onShowCustomView(view, callback)
                view?.requestFocus()
            }
        }
        sessionProfileWebView.isFocusableInTouchMode = true
 
        findViewById<Button>(R.id.btn_upload_back).setOnClickListener {
            finish()
        }
    }
 
    private fun processProfile(profile:SessionProfile){
        val downloadDir = File(getExternalFilesDir(null), profile.id) // 获取应用的外部存储目录,并指定 sessionid 子目录
 
        Utils.fetchTasksBySessionProfile(profile, object:Utils.FetchTasksCallback {
            override fun onTasksFetched(uploadTaskList: MutableList<Utils.VideoUploadTaskInfo>) {
                uploadTaskList.forEach { task ->
                    downloadHelper.downloadSingleFile(task.videoUrl, File(downloadDir,task.filename+".mp4"))
                    downloadHelper.downloadSingleFile(task.coverUrl, File(downloadDir,task.filename+".png"))
                    profile.getValidProfileNames().forEach{ platform ->
                        var taskInfo = Utils.VideoUploadTaskInfo(task.taskId,
                            task.title,
                            task.description,
                            task.datetime,
                            task.videoUrl,
                            task.coverUrl,
                            task.filename,
                            profile.id,
                            profile.name,
                            SESSION_PROFILE_PALTFORM_LISTS.find { it.name == platform }
                        )
                        uploadTaskQueue.offer(taskInfo)
                    }
 
                }
                Handler(Looper.getMainLooper()).postDelayed({
                    checkAndStartNextTask() // 延时等待下载任务
                }, 3000)
            }
        })
    }
    fun checkAndStartNextTask() {
        if (uploadTaskQueue.isNotEmpty()) {
            val nextTask = uploadTaskQueue.poll()
            nextTask?.let {
                nextTask.sessionProfileId?.let { sessionId ->
                    runOnUiThread {
                        if (last_uploaded_task_id != "" && last_uploaded_task_id != nextTask.taskId) {
                                Utils.sendVideoUploadedMessage(last_uploaded_task_id) { result, error ->
                                    Handler(Looper.getMainLooper()).post {
                                        Toast.makeText(
                                            activityReference,
                                            error?.message,
                                            Toast.LENGTH_SHORT
                                        )
                                    }
                            }
                        } else {
                            last_uploaded_task_id = nextTask.taskId
                        }
                        nextTask.platform?.let {
                                sessionProfileWebView.loadSessionProfileCookies(sessionId)
                                sessionProfileWebView.loadUrl(it.url)
                                Handler(Looper.getMainLooper()).post {
                                uploadSessionText.text = "任务:${nextTask.sessionProfileName}. 剩余:${uploadTaskQueue.size+1} "
                                }
                        };
                    }
                }
            }
        }else{
            Handler(Looper.getMainLooper()).post {
                uploadSessionText.text = "任务已结束。"
            }
            Handler(Looper.getMainLooper()).postDelayed({
                if (sessionProfiles != null) {
                    for (profile in sessionProfiles) {
                        updateSessionProfileLastUploadTime(profile)
                    }
                }
                finish()
            }, 2000)
 
        }
    }
 
 
    private fun updateSessionProfileLastUploadTime(sessionProfile: SessionProfile) {
        sessionProfile.lastUploadTime = Utils.getCurrentTimeString()
        sessionProfileManager.addOrUpdateSessionProfile(sessionProfile)
        sessionProfileManager.saveToFile()
    }
 
    override fun onDestroy() {
        super.onDestroy()
    }
}