archive-97f2350/app/src/main/java/uk/orllewin/sianel/data/SianelService.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
package uk.orllewin.sianel.data
import okhttp3.FormBody
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MultipartBody
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject
import java.io.File
import java.io.InputStream
import java.util.concurrent.TimeUnit
class SianelService(
private val password: String,
private val base: String,
) {
data class Uploaded(
val hash: String,
val url: String,
val embed: String,
val thumbnail: String?,
)
data class VideoItem(
val hash: String,
val filename: String,
val size: Long,
val uploadedAtEpochSec: Long,
val url: String,
val embed: String,
val thumbnail: String?,
)
// Shared across all instances — OkHttp is designed to be reused so its thread
// pool and connection pool are shared rather than rebuilt per request.
private val client = sharedClient
private fun auth() = "Bearer $password"
/**
* Uploads via the chunked endpoints (init → put × N → finalize). Falls back
* to the same on-network behavior as the single-POST upload from the
* caller's perspective; just much friendlier to flaky links and big files.
*/
fun upload(
file: File,
mime: String,
thumbnail: File? = null,
thumbnailMime: String = "image/jpeg",
unlisted: Boolean = false,
chunkSize: Int = DEFAULT_CHUNK_SIZE,
onProgress: (fraction: Float, currentChunk: Int, totalChunks: Int) -> Unit = { _, _, _ -> },
): Uploaded {
require(file.exists()) { "file does not exist" }
val totalSize = file.length()
require(totalSize > 0L) { "file is empty" }
val init = initSession(file.name, mime, totalSize, chunkSize)
val uploadId = init.uploadId
val expectedChunks = init.expectedChunks
try {
file.inputStream().use { input ->
val buf = ByteArray(chunkSize)
var uploaded = 0L
for (index in 0 until expectedChunks) {
// Report which chunk is about to go up, with the pre-chunk byte fraction.
// (1-based for human-friendly display: "part 4 of 10".)
onProgress(uploaded.toFloat() / totalSize, index + 1, expectedChunks)
val n = readFully(input, buf, chunkSize)
check(n > 0) { "unexpected EOF at chunk $index" }
putChunk(uploadId, index, buf, n)
uploaded += n
}
onProgress(1f, expectedChunks, expectedChunks)
}
return finalizeSession(uploadId, thumbnail, thumbnailMime, unlisted)
} catch (e: Throwable) {
// Best effort — server GCs orphaned sessions after 24h anyway.
runCatching { abortSession(uploadId) }
throw e
}
}
data class Page(val items: List<VideoItem>, val total: Int, val offset: Int)
/** One page of videos. [count] <= 0 asks the server for everything from [offset]. */
fun listPage(offset: Int, count: Int): Page {
val req = Request.Builder()
.url("$base/api/list?offset=$offset&count=$count")
.header("Authorization", auth())
.get()
.build()
client.newCall(req).execute().use { res ->
val text = res.body?.string().orEmpty()
if (!res.isSuccessful) error("HTTP ${res.code}: $text")
val obj = JSONObject(text)
val arr = obj.getJSONArray("videos")
val items = List(arr.length()) { i ->
val o = arr.getJSONObject(i)
VideoItem(
hash = o.getString("hash"),
filename = o.getString("filename"),
size = o.getLong("size"),
uploadedAtEpochSec = o.getLong("uploaded"),
url = o.getString("url"),
embed = o.getString("embed"),
thumbnail = o.optStringOrNull("thumbnail"),
)
}
return Page(items = items, total = obj.optInt("total", items.size), offset = offset)
}
}
data class VerifyResult(val ok: Boolean, val code: Int, val serverError: String?)
/**
* Checks the password + base URL against the server's verify endpoint. Does NOT
* throw on a non-2xx response — the HTTP status is part of the answer (401 wrong
* password, 429 locked out, 400 plain-HTTP). Network/IO failures still throw.
*/
fun verify(): VerifyResult {
val req = Request.Builder()
.url("$base/api/verify")
.header("Authorization", auth())
.get()
.build()
client.newCall(req).execute().use { res ->
val text = res.body?.string().orEmpty()
val serverError = runCatching { JSONObject(text).optStringOrNull("error") }.getOrNull()
return VerifyResult(ok = res.isSuccessful, code = res.code, serverError = serverError)
}
}
fun delete(hash: String) {
val body = FormBody.Builder().add("hash", hash).build()
val req = Request.Builder()
.url("$base/api/delete")
.header("Authorization", auth())
.post(body)
.build()
client.newCall(req).execute().use { res ->
val text = res.body?.string().orEmpty()
if (!res.isSuccessful) error("HTTP ${res.code}: $text")
}
}
// --- chunked-upload primitives ---
private data class InitResult(val uploadId: String, val expectedChunks: Int)
private fun initSession(
filename: String,
mime: String,
totalSize: Long,
chunkSize: Int,
): InitResult {
val payload = JSONObject().apply {
put("filename", filename)
put("mime", mime)
put("total_size", totalSize)
put("chunk_size", chunkSize)
}
val body = payload.toString().toRequestBody("application/json".toMediaType())
val req = Request.Builder()
.url("$base/api/chunked/init")
.header("Authorization", auth())
.post(body)
.build()
client.newCall(req).execute().use { res ->
val text = res.body?.string().orEmpty()
if (!res.isSuccessful) error("init HTTP ${res.code}: $text")
val j = JSONObject(text)
return InitResult(
uploadId = j.getString("upload_id"),
expectedChunks = j.getInt("expected_chunks"),
)
}
}
private class PermanentHttpException(msg: String) : RuntimeException(msg)
private fun putChunk(uploadId: String, index: Int, buf: ByteArray, len: Int) {
var lastErr: Throwable? = null
for (attempt in 1..RETRY_ATTEMPTS) {
try {
val body = buf.toRequestBody(OCTET_STREAM, 0, len)
val req = Request.Builder()
.url("$base/api/chunked/put?id=$uploadId&index=$index")
.header("Authorization", auth())
.post(body)
.build()
client.newCall(req).execute().use { res ->
if (res.isSuccessful) return
val text = res.body?.string().orEmpty()
val msg = "chunk $index HTTP ${res.code}: $text"
// Most 4xx responses won't be fixed by retrying — bail immediately.
if (res.code in 400..499 && res.code != 408 && res.code != 429) {
throw PermanentHttpException(msg)
}
error(msg)
}
} catch (e: PermanentHttpException) {
throw e
} catch (e: Throwable) {
lastErr = e
if (attempt < RETRY_ATTEMPTS) {
Thread.sleep(RETRY_BACKOFF_MS_BASE * (1L shl (attempt - 1)))
}
}
}
throw IllegalStateException(
"chunk $index failed after $RETRY_ATTEMPTS attempts: ${lastErr?.message}",
lastErr,
)
}
private fun finalizeSession(
uploadId: String,
thumbnail: File?,
thumbnailMime: String,
unlisted: Boolean,
): Uploaded {
val builder = MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("upload_id", uploadId)
if (unlisted) builder.addFormDataPart("unlisted", "1")
if (thumbnail != null && thumbnail.exists()) {
builder.addFormDataPart(
"thumbnail",
thumbnail.name,
thumbnail.asRequestBody(thumbnailMime.toMediaType()),
)
}
val req = Request.Builder()
.url("$base/api/chunked/finalize")
.header("Authorization", auth())
.post(builder.build())
.build()
client.newCall(req).execute().use { res ->
val text = res.body?.string().orEmpty()
if (!res.isSuccessful) error("finalize HTTP ${res.code}: $text")
val j = JSONObject(text)
return Uploaded(
hash = j.getString("hash"),
url = j.getString("url"),
embed = j.getString("embed"),
thumbnail = j.optStringOrNull("thumbnail"),
)
}
}
private fun abortSession(uploadId: String) {
val body = FormBody.Builder().add("upload_id", uploadId).build()
val req = Request.Builder()
.url("$base/api/chunked/abort")
.header("Authorization", auth())
.post(body)
.build()
client.newCall(req).execute().close()
}
companion object {
const val DEFAULT_CHUNK_SIZE = 4 * 1024 * 1024 // 4 MB
private const val RETRY_ATTEMPTS = 3
private const val RETRY_BACKOFF_MS_BASE = 500L
private val OCTET_STREAM = "application/octet-stream".toMediaType()
private val sharedClient = OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.writeTimeout(2, TimeUnit.MINUTES) // per-chunk, not per-upload
.readTimeout(2, TimeUnit.MINUTES)
.build()
}
}
private fun JSONObject.optStringOrNull(key: String): String? =
if (has(key) && !isNull(key)) getString(key) else null
/** Read up to [len] bytes into [buf], looping past partial reads. Returns bytes actually read. */
private fun readFully(input: InputStream, buf: ByteArray, len: Int): Int {
var total = 0
while (total < len) {
val n = input.read(buf, total, len - total)
if (n < 0) break
total += n
}
return total
}