wangrong
2024-12-10 62a7ff352d506398c6ac8824b2d3fe7c08dee8fb
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
package com.shsening.autouploadvideos.action
 
 
import android.app.Instrumentation
import android.os.SystemClock
import android.os.Handler
import android.util.Log
import com.shsening.autouploadvideos.UploadSessionActivity
import com.shsening.autouploadvideos.utils.Utils
import com.shsening.autouploadvideos.WebviewUtils
 
class ActionDouyin (private var activity: UploadSessionActivity, private var threadHandler: Handler, private var videoInfo: Utils.VideoUploadTaskInfo) :PlatformActionInterface{
 
 
    private var webView = activity.sessionProfileWebView
    private var TAG = "ActionDouyin"
 
 
    var jsCode_CheckContentLoaded = """
        document.querySelector('input[type="file"][name="upload-btn"]') !== null
    """.trimIndent()
    var jsCode_CheckVideoUploadFinished = """
        document.querySelector('#root > div > div > div.content-body-v8tuJQ > div.preview-MNjmIb > section > section > section > section.mainPanelWrapper-uThET4.unfold-rUr6x0 > div > section:nth-child(3)') !==null
    """.trimIndent()
    var jsCode_PublishVideo_Finished ="document.querySelector('#root > div > div > div.title-UUrMOP > div > div:nth-child(1)') !== null"
 
    var jsPath_PublishVideo ="#root > div > div > div.content-body-v8tuJQ > div.form-kSES6A > div.content-confirm-container-Wp91G7 > button.button-dhlUZE.primary-cECiOJ.fixed-J9O8Yw"
 
 
 
    private fun updatePostDescription(){
        WebviewUtils.addValueToInput(webView,"#root > div > div > div.content-body-v8tuJQ > div.form-kSES6A > div.publish-mention-wrapper-LWv5ed > div.editor-container-zRPSAi > div > div > div > div:nth-child(1) > div > div > input",videoInfo.title)
 
        WebviewUtils.addValueToDiv(webView,"#root > div > div > div.content-body-v8tuJQ > div.form-kSES6A > div.publish-mention-wrapper-LWv5ed > div.editor-container-zRPSAi > div > div > div > div.outerdocbody.editor-kit-outer-container > div",videoInfo.description)
 
        WebviewUtils.simpleElementClick(webView,"#root > div > div > div.content-body-v8tuJQ > div.form-kSES6A > div.publish-mention-wrapper-LWv5ed > div:nth-child(3) > div > div.activity-list-container-AZzfdV > div:nth-child(1)")
        WebviewUtils.simpleElementClick(webView,"#root > div > div > div.content-body-v8tuJQ > div.form-kSES6A > div.publish-mention-wrapper-LWv5ed > div:nth-child(3) > div > div.activity-list-container-AZzfdV > div:nth-child(2)")
 
        WebviewUtils.simpleElementClick(webView,"#root > div > div > div.content-body-v8tuJQ > div.form-kSES6A > div.content-upload-new > div > div.recommendContainer-HXvL9W > div.recommendDisplay-ifUYki > div > div:nth-child(1) > div")
        WebviewUtils.simpleElementClick(webView,"#root > div > div > div.content-body-v8tuJQ > div.form-kSES6A > div.download-content-Lci5tL > div > label:nth-child(2)")
        WebviewUtils.simpleElementClick(webView,"#root > div > div > div.content-body-v8tuJQ > div.form-kSES6A > div.publish-settings-WtW_ZW > div.schedule-part-V615Zn > div.row-suTOx_ > label:nth-child(2)")
 
        addValueToDatePickerInput(true,"#root > div > div > div.content-body-v8tuJQ > div.form-kSES6A > div.publish-settings-WtW_ZW > div.schedule-part-V615Zn > div.row-suTOx_ > div.date-picker-ioPchj > div > div",videoInfo.datetime)
 
        // 在主线程中设置延迟执行
        threadHandler.postDelayed(Runnable {
            startToPublishVideo()
        }, 5000)
    }
 
 
    override fun checkIfContentLoaded() {
        webView.postDelayed({
            webView.evaluateJavascript(jsCode_CheckContentLoaded) { result ->
                if (result == "true") {
                    simulateSwipeAndUploadVideo()
                } else {
                    webView.postDelayed({
                        checkIfContentLoaded()
                    }, 1000) // 1秒后再次检查
                }
            }
        }, 1000) // 每秒检查一次
    }
 
    private fun startToPublishVideo(){
        WebviewUtils.simpleElementClick(webView,jsPath_PublishVideo)
 
        checkVideoPublishFinished()
    }
 
    private fun checkVideoUploadFinished(){
        webView.postDelayed({
            webView.evaluateJavascript(jsCode_CheckVideoUploadFinished) { result ->
                if (result == "true") {
                    // 等待视频检测和生成封面
                    threadHandler.postDelayed({updatePostDescription()},3000)
 
                } else {
                    // 元素不存在,1秒后再次检查
                    webView.postDelayed({
                        checkVideoUploadFinished()
                    }, 1000) // 1秒后再次检查
                }
            }
        }, 1000) // 每秒检查一次
    }
 
    private fun checkVideoPublishFinished(){
        webView.postDelayed({
            webView.evaluateJavascript(jsCode_PublishVideo_Finished) { result ->
                if (result == "true") {
                    // video published successfully!!!
                    activity.checkAndStartNextTask()
                } else {
                    // 元素不存在,1秒后再次检查
                    webView.postDelayed({
                        checkVideoPublishFinished()
                    }, 1000) // 1秒后再次检查
                }
            }
        }, 1000) // 每秒检查一次
    }
 
 
    private fun addValueToDatePickerInput(first:Boolean, jsPath: String, targetValue: String) {
 
        var datetimes = Utils.validateAndReturnDateTime(targetValue) ?: return
 
        var dpPanelText = datetimes[0].toString()+"年 "+datetimes[1].toString()+"月";
 
        var dateRowColum = Utils.getDatePosition(datetimes[0],datetimes[1],datetimes[2])?:return;
 
        val jsCode = """
       try {
           var dp = document.querySelector('${jsPath}');
           dp.focus(); // 确保输入框获得焦点
           dp.click();
           
           // need time to popup date-picker
           setTimeout(() => {
               var dpPanel = document.querySelector('.semi-popover-content');
               var dpPanelSpan = document.querySelectorAll(".semi-datepicker")[1].querySelector(".semi-datepicker-navigation-month");
               if (dpPanelSpan && dpPanelSpan.textContent != '${dpPanelText}'){
                  document.querySelectorAll(".semi-datepicker")[1].querySelectorAll(".semi-button-content")[2].click();               
               }
               document.querySelectorAll(".semi-datepicker-month")[0].querySelectorAll(".semi-datepicker-weeks")[0].querySelector("div:nth-child(${dateRowColum[0]}) > div:nth-child(${dateRowColum[1]})").click();
               
               //switch to time selection
               document.querySelectorAll(".semi-datepicker-switch-time")[0].click()
               setTimeout(() => {
                  document.querySelectorAll('.semi-scrolllist-body')[0].querySelectorAll('.semi-scrolllist-item-wheel')[0].querySelector('div.semi-scrolllist-list-outer > ul > li:nth-child(${(datetimes[3]+1)})').click();
                  document.querySelectorAll('.semi-scrolllist-body')[0].querySelectorAll('.semi-scrolllist-item-wheel')[1].querySelector('div.semi-scrolllist-list-outer > ul > li:nth-child(${(datetimes[4]+1)})').click();
               }, 500);
           }, 500);
       } catch (error) {
        console.error('发生错误:', error);
       }
    """
        webView.evaluateJavascript(jsCode,null)
 
 
    }
 
 
    private fun simulateSwipeAndUploadVideo() {
        val instrumentation = Instrumentation()
        val displayMetrics = activity.resources.displayMetrics
        val width = displayMetrics.widthPixels
        val height = displayMetrics.heightPixels
 
        val startX = width.toFloat() * 0.9f // 从右侧滑动
        val endX = width.toFloat() * 0.1f // 滑动到左侧
        val y = height / 3f // Y 坐标在屏幕中间
 
        Thread {
            try {
                Utils.instrumentationSwipe(instrumentation, startX, y, endX, y)
                SystemClock.sleep(500)
                Utils.instrumentationSwipe(instrumentation, startX, y, endX, y)
                SystemClock.sleep(500)
                Utils.instrumentationClick(instrumentation, width / 2f, height * 2 / 4f)
                // back to main thread
 
            } catch (e: Exception) {
                Log.e(TAG, "滑动操作失败:应用可能在后台", e)
            }
            threadHandler.post {
                checkVideoUploadFinished()
            }
        }.start()
    }
 
}