archive-97f2350/app/src/main/java/uk/orllewin/sianel/data/UploadWorker.kt
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
package uk.orllewin.sianel.data
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.content.pm.ServiceInfo
import android.media.MediaMetadataRetriever
import android.net.Uri
import android.os.Build
import android.os.Handler
import android.os.Looper
import androidx.annotation.OptIn
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.media3.common.MediaItem
import androidx.media3.common.MimeTypes
import androidx.media3.common.util.UnstableApi
import androidx.media3.effect.Presentation
import androidx.media3.transformer.Composition
import androidx.media3.transformer.DefaultEncoderFactory
import androidx.media3.transformer.EditedMediaItem
import androidx.media3.transformer.Effects
import androidx.media3.transformer.ExportException
import androidx.media3.transformer.ExportResult
import androidx.media3.transformer.ProgressHolder
import androidx.media3.transformer.Transformer
import androidx.media3.transformer.VideoEncoderSettings
import androidx.work.CoroutineWorker
import androidx.work.ForegroundInfo
import androidx.work.WorkManager
import androidx.work.WorkerParameters
import androidx.work.workDataOf
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import java.io.File
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
/**
* Compresses (optional) then uploads a cached video file. Survives backgrounding
* because WorkManager re-runs.
* Progress is reported under [KEY_PROGRESS] and tagged with a [KEY_PHASE] of "compress" or "upload"
* so the UI can label it.
*/
class UploadWorker(
appContext: Context,
params: WorkerParameters,
) : CoroutineWorker(appContext, params) {
override suspend fun getForegroundInfo(): ForegroundInfo =
buildForegroundInfo(title = "Preparing video upload", text = null, percent = null)
override suspend fun doWork(): Result = withContext(Dispatchers.IO) {
// Promote to a foreground service so big uploads survive backgrounding.
// setExpedited on the request side means this only kicks in when the OS
// can't grant expedited quota.
runCatching { setForeground(getForegroundInfo()) }
val filePath = inputData.getString(KEY_FILE_PATH)
?: return@withContext fail("no file path")
val mime = inputData.getString(KEY_MIME) ?: "video/mp4"
val quality = runCatching {
Quality.valueOf(inputData.getString(KEY_QUALITY) ?: Quality.ORIGINAL.name)
}.getOrDefault(Quality.ORIGINAL)
val password = Prefs.getPassword(applicationContext)
if (password.isBlank()) return@withContext fail("no password set")
val baseUrl = Prefs.getBaseUrl(applicationContext)
val source = File(filePath)
if (!source.exists()) return@withContext fail("file no longer available")
val thumb = inputData.getString(KEY_THUMB_PATH)
?.let { File(it) }
?.takeIf { it.exists() }
val unlisted = inputData.getBoolean(KEY_UNLISTED, false)
fun cleanup(also: File? = null) {
source.delete()
also?.delete()
thumb?.delete()
}
val toUpload = if (quality.transcodes && shouldTranscode(source, quality)) {
try {
transcode(source, quality) { p ->
setProgressAsync(workDataOf(KEY_PROGRESS to p, KEY_PHASE to PHASE_COMPRESS))
updateNotification("Compressing video", (p * 100).toInt())
}
} catch (e: Throwable) {
cleanup()
return@withContext fail("compress failed: ${e.message}")
}
} else source
return@withContext try {
val uploadMime = if (toUpload != source) "video/mp4" else mime
val result = SianelService(password, baseUrl).upload(
file = toUpload,
mime = uploadMime,
thumbnail = thumb,
thumbnailMime = "image/jpeg",
unlisted = unlisted,
) { p, chunk, total ->
setProgressAsync(
workDataOf(
KEY_PROGRESS to p,
KEY_PHASE to PHASE_UPLOAD,
KEY_CHUNK_INDEX to chunk,
KEY_CHUNK_TOTAL to total,
)
)
val title = if (total > 1) {
"Uploading video (chunk $chunk/$total)"
} else {
"Uploading video"
}
updateNotification(title, (p * 100).toInt())
}
cleanup(also = toUpload.takeIf { it != source })
Result.success(
workDataOf(
KEY_HASH to result.hash,
KEY_URL to result.url,
KEY_EMBED to result.embed,
KEY_THUMBNAIL_URL to result.thumbnail,
)
)
} catch (e: Throwable) {
cleanup(also = toUpload.takeIf { it != source })
fail(e.message ?: e::class.java.simpleName)
}
}
private fun shouldTranscode(source: File, quality: Quality): Boolean {
val target = quality.targetHeight ?: return false
val height = probeHeight(source) ?: return true // can't probe → transcode anyway
return height > target
}
private fun probeHeight(file: File): Int? {
val r = MediaMetadataRetriever()
return try {
r.setDataSource(file.absolutePath)
r.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)?.toIntOrNull()
} catch (_: Throwable) {
null
} finally {
runCatching { r.release() }
}
}
@OptIn(UnstableApi::class)
private suspend fun transcode(
src: File,
quality: Quality,
onProgress: (Float) -> Unit,
): File {
val out = File(applicationContext.cacheDir, "trans-${System.currentTimeMillis()}.mp4")
val main = Handler(Looper.getMainLooper())
// Transformer's API must be touched from a single thread (main looper).
return suspendCancellableCoroutine { cont ->
main.post {
val transformer = Transformer.Builder(applicationContext)
.setVideoMimeType(MimeTypes.VIDEO_H264)
.setEncoderFactory(
DefaultEncoderFactory.Builder(applicationContext)
.setRequestedVideoEncoderSettings(
VideoEncoderSettings.Builder()
.setBitrate(quality.bitrate!!)
.build()
)
.build()
)
.addListener(object : Transformer.Listener {
override fun onCompleted(c: Composition, r: ExportResult) {
if (cont.isActive) cont.resume(out)
}
override fun onError(c: Composition, r: ExportResult, e: ExportException) {
if (cont.isActive) cont.resumeWithException(e)
}
})
.build()
val item = EditedMediaItem.Builder(MediaItem.fromUri(Uri.fromFile(src)))
.setEffects(
Effects(
emptyList(),
listOf(Presentation.createForHeight(quality.targetHeight!!))
)
)
.build()
transformer.start(item, out.absolutePath)
val holder = ProgressHolder()
val poll = object : Runnable {
override fun run() {
if (!cont.isActive) return
when (transformer.getProgress(holder)) {
Transformer.PROGRESS_STATE_AVAILABLE -> {
onProgress(holder.progress / 100f)
main.postDelayed(this, 200)
}
Transformer.PROGRESS_STATE_UNAVAILABLE -> {
main.postDelayed(this, 500)
}
else -> { /* NOT_STARTED or terminal */ }
}
}
}
main.postDelayed(poll, 200)
cont.invokeOnCancellation {
main.post { runCatching { transformer.cancel() } }
}
}
}
}
private fun fail(msg: String) = Result.failure(workDataOf(KEY_ERROR to msg))
private fun buildForegroundInfo(
title: String,
text: String?,
percent: Int?,
): ForegroundInfo {
ensureChannel()
val notification = buildNotification(title, text, percent)
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ForegroundInfo(
NOTIFICATION_ID,
notification,
ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC,
)
} else {
ForegroundInfo(NOTIFICATION_ID, notification)
}
}
private fun buildNotification(title: String, text: String?, percent: Int?): Notification {
val cancel = WorkManager.getInstance(applicationContext)
.createCancelPendingIntent(id)
val builder = NotificationCompat.Builder(applicationContext, CHANNEL_ID)
.setSmallIcon(android.R.drawable.stat_sys_upload)
.setContentTitle(title)
.setOngoing(true)
.setOnlyAlertOnce(true)
.setForegroundServiceBehavior(NotificationCompat.FOREGROUND_SERVICE_IMMEDIATE)
.addAction(android.R.drawable.ic_menu_close_clear_cancel, "Cancel", cancel)
if (text != null) builder.setContentText(text)
if (percent != null) {
builder.setProgress(100, percent.coerceIn(0, 100), false)
} else {
builder.setProgress(0, 0, true) // indeterminate
}
return builder.build()
}
private fun ensureChannel() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
val nm = applicationContext.getSystemService(NotificationManager::class.java) ?: return
if (nm.getNotificationChannel(CHANNEL_ID) != null) return
nm.createNotificationChannel(
NotificationChannel(
CHANNEL_ID,
"Video uploads",
NotificationManager.IMPORTANCE_LOW,
).apply { description = "Progress for video uploads" }
)
}
private fun updateNotification(title: String, percent: Int) {
val nm = NotificationManagerCompat.from(applicationContext)
if (!nm.areNotificationsEnabled()) return
runCatching {
nm.notify(NOTIFICATION_ID, buildNotification(title, "$percent%", percent))
}
}
companion object {
const val KEY_FILE_PATH = "file_path"
const val KEY_MIME = "mime"
const val KEY_QUALITY = "quality"
const val KEY_THUMB_PATH = "thumb_path"
const val KEY_UNLISTED = "unlisted"
const val KEY_PROGRESS = "progress"
const val KEY_PHASE = "phase"
const val KEY_CHUNK_INDEX = "chunk_index" // 1-based for display
const val KEY_CHUNK_TOTAL = "chunk_total"
const val KEY_HASH = "hash"
const val KEY_URL = "url"
const val KEY_EMBED = "embed"
const val KEY_THUMBNAIL_URL = "thumbnail_url"
const val KEY_ERROR = "error"
const val TAG = "video-upload"
const val PHASE_COMPRESS = "compress"
const val PHASE_UPLOAD = "upload"
private const val CHANNEL_ID = "video-upload"
private const val NOTIFICATION_ID = 0x5_1A_E1 // arbitrary stable id
}
}