First Commit With Working app
This commit is contained in:
commit
8d2c6ca504
24 changed files with 1286 additions and 0 deletions
11
.gitignore
vendored
Normal file
11
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,11 @@
|
||||||
|
*.iml
|
||||||
|
.gradle/
|
||||||
|
/local.properties
|
||||||
|
.idea/
|
||||||
|
.DS_Store
|
||||||
|
/build
|
||||||
|
/app/build
|
||||||
|
/captures
|
||||||
|
.externalNativeBuild
|
||||||
|
.cxx
|
||||||
|
/receiver/receiver
|
||||||
56
app/build.gradle.kts
Normal file
56
app/build.gradle.kts
Normal file
|
|
@ -0,0 +1,56 @@
|
||||||
|
plugins {
|
||||||
|
alias(libs.plugins.android.application)
|
||||||
|
alias(libs.plugins.kotlin.android)
|
||||||
|
alias(libs.plugins.kotlin.compose)
|
||||||
|
}
|
||||||
|
|
||||||
|
android {
|
||||||
|
namespace = "com.example.filedrop"
|
||||||
|
compileSdk = 36
|
||||||
|
|
||||||
|
defaultConfig {
|
||||||
|
applicationId = "com.example.filedrop"
|
||||||
|
minSdk = 26
|
||||||
|
targetSdk = 36
|
||||||
|
versionCode = 1
|
||||||
|
versionName = "1.0"
|
||||||
|
}
|
||||||
|
|
||||||
|
buildTypes {
|
||||||
|
release {
|
||||||
|
isMinifyEnabled = false
|
||||||
|
proguardFiles(
|
||||||
|
getDefaultProguardFile("proguard-android-optimize.txt"),
|
||||||
|
"proguard-rules.pro",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
compileOptions {
|
||||||
|
sourceCompatibility = JavaVersion.VERSION_21
|
||||||
|
targetCompatibility = JavaVersion.VERSION_21
|
||||||
|
}
|
||||||
|
|
||||||
|
kotlin {
|
||||||
|
jvmToolchain(21)
|
||||||
|
}
|
||||||
|
|
||||||
|
buildFeatures {
|
||||||
|
compose = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
implementation(libs.androidx.core.ktx)
|
||||||
|
implementation(libs.androidx.lifecycle.runtime.ktx)
|
||||||
|
implementation(libs.androidx.lifecycle.viewmodel.compose)
|
||||||
|
implementation(libs.androidx.activity.compose)
|
||||||
|
implementation(platform(libs.androidx.compose.bom))
|
||||||
|
implementation(libs.androidx.ui)
|
||||||
|
implementation(libs.androidx.ui.graphics)
|
||||||
|
implementation(libs.androidx.ui.tooling.preview)
|
||||||
|
implementation(libs.androidx.material3)
|
||||||
|
implementation(libs.androidx.datastore.preferences)
|
||||||
|
implementation(libs.okhttp)
|
||||||
|
debugImplementation(libs.androidx.ui.tooling)
|
||||||
|
}
|
||||||
5
app/proguard-rules.pro
vendored
Normal file
5
app/proguard-rules.pro
vendored
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
# Keep OkHttp platform-specific classes referenced reflectively.
|
||||||
|
-dontwarn okhttp3.internal.platform.**
|
||||||
|
-dontwarn org.conscrypt.**
|
||||||
|
-dontwarn org.bouncycastle.**
|
||||||
|
-dontwarn org.openjsse.**
|
||||||
24
app/src/main/AndroidManifest.xml
Normal file
24
app/src/main/AndroidManifest.xml
Normal file
|
|
@ -0,0 +1,24 @@
|
||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
|
||||||
|
<uses-permission android:name="android.permission.INTERNET" />
|
||||||
|
|
||||||
|
<application
|
||||||
|
android:allowBackup="true"
|
||||||
|
android:icon="@drawable/ic_launcher"
|
||||||
|
android:label="@string/app_name"
|
||||||
|
android:networkSecurityConfig="@xml/network_security_config"
|
||||||
|
android:supportsRtl="true"
|
||||||
|
android:theme="@style/Theme.FileDrop">
|
||||||
|
|
||||||
|
<activity
|
||||||
|
android:name=".MainActivity"
|
||||||
|
android:exported="true"
|
||||||
|
android:label="@string/app_name">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.MAIN" />
|
||||||
|
<category android:name="android.intent.category.LAUNCHER" />
|
||||||
|
</intent-filter>
|
||||||
|
</activity>
|
||||||
|
</application>
|
||||||
|
</manifest>
|
||||||
197
app/src/main/java/com/example/filedrop/MainActivity.kt
Normal file
197
app/src/main/java/com/example/filedrop/MainActivity.kt
Normal file
|
|
@ -0,0 +1,197 @@
|
||||||
|
package com.example.filedrop
|
||||||
|
|
||||||
|
import android.os.Bundle
|
||||||
|
import androidx.activity.ComponentActivity
|
||||||
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
|
import androidx.activity.compose.setContent
|
||||||
|
import androidx.activity.enableEdgeToEdge
|
||||||
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.Spacer
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.foundation.lazy.items
|
||||||
|
import androidx.compose.material3.Button
|
||||||
|
import androidx.compose.material3.Card
|
||||||
|
import androidx.compose.material3.LinearProgressIndicator
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.OutlinedTextField
|
||||||
|
import androidx.compose.material3.Scaffold
|
||||||
|
import androidx.compose.material3.SnackbarHost
|
||||||
|
import androidx.compose.material3.SnackbarHostState
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.material3.dynamicDarkColorScheme
|
||||||
|
import androidx.compose.material3.dynamicLightColorScheme
|
||||||
|
import androidx.compose.material3.MaterialTheme.colorScheme
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.material3.darkColorScheme
|
||||||
|
import androidx.compose.material3.lightColorScheme
|
||||||
|
import androidx.compose.foundation.isSystemInDarkTheme
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
|
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||||
|
import android.os.Build
|
||||||
|
|
||||||
|
class MainActivity : ComponentActivity() {
|
||||||
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
super.onCreate(savedInstanceState)
|
||||||
|
enableEdgeToEdge()
|
||||||
|
setContent {
|
||||||
|
AppTheme {
|
||||||
|
FileDropScreen()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun AppTheme(content: @Composable () -> Unit) {
|
||||||
|
val dark = isSystemInDarkTheme()
|
||||||
|
val context = LocalContext.current
|
||||||
|
val scheme = when {
|
||||||
|
Build.VERSION.SDK_INT >= Build.VERSION_CODES.S ->
|
||||||
|
if (dark) dynamicDarkColorScheme(context)
|
||||||
|
else dynamicLightColorScheme(context)
|
||||||
|
dark -> darkColorScheme()
|
||||||
|
else -> lightColorScheme()
|
||||||
|
}
|
||||||
|
MaterialTheme(colorScheme = scheme, content = content)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun FileDropScreen(vm: MainViewModel = viewModel()) {
|
||||||
|
val address by vm.address.collectAsStateWithLifecycle()
|
||||||
|
val token by vm.token.collectAsStateWithLifecycle()
|
||||||
|
val items by vm.items.collectAsStateWithLifecycle()
|
||||||
|
val message by vm.message.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
|
val snackbarHostState = remember { SnackbarHostState() }
|
||||||
|
|
||||||
|
val picker = rememberLauncherForActivityResult(
|
||||||
|
ActivityResultContracts.OpenMultipleDocuments(),
|
||||||
|
) { uris -> if (uris.isNotEmpty()) vm.onFilesPicked(uris) }
|
||||||
|
|
||||||
|
LaunchedEffect(message) {
|
||||||
|
message?.let {
|
||||||
|
snackbarHostState.showSnackbar(it)
|
||||||
|
vm.messageShown()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Scaffold(
|
||||||
|
snackbarHost = { SnackbarHost(snackbarHostState) },
|
||||||
|
) { padding ->
|
||||||
|
Column(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.padding(padding)
|
||||||
|
.padding(16.dp),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
"Drop to PC",
|
||||||
|
style = MaterialTheme.typography.headlineSmall,
|
||||||
|
fontWeight = FontWeight.SemiBold,
|
||||||
|
)
|
||||||
|
|
||||||
|
OutlinedTextField(
|
||||||
|
value = address,
|
||||||
|
onValueChange = vm::setAddress,
|
||||||
|
label = { Text("PC address") },
|
||||||
|
placeholder = { Text("192.168.1.42:8787") },
|
||||||
|
singleLine = true,
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
)
|
||||||
|
|
||||||
|
OutlinedTextField(
|
||||||
|
value = token,
|
||||||
|
onValueChange = vm::setToken,
|
||||||
|
label = { Text("Auth token") },
|
||||||
|
singleLine = true,
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
)
|
||||||
|
|
||||||
|
Button(
|
||||||
|
onClick = { picker.launch(arrayOf("*/*")) },
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
) {
|
||||||
|
Text("Pick files")
|
||||||
|
}
|
||||||
|
|
||||||
|
LazyColumn(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||||
|
) {
|
||||||
|
items(items, key = { it.uri }) { item ->
|
||||||
|
UploadRow(item, onRetry = { vm.retry(item.uri) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun UploadRow(item: UploadItem, onRetry: () -> Unit) {
|
||||||
|
Card(modifier = Modifier.fillMaxWidth()) {
|
||||||
|
Column(modifier = Modifier.padding(12.dp)) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
item.name,
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
modifier = Modifier.weight(1f, fill = false),
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
when (item.status) {
|
||||||
|
UploadStatus.PENDING -> "Waiting"
|
||||||
|
UploadStatus.UPLOADING -> "${(item.progress * 100).toInt()}%"
|
||||||
|
UploadStatus.DONE -> "Done"
|
||||||
|
UploadStatus.ERROR -> "Failed"
|
||||||
|
},
|
||||||
|
style = MaterialTheme.typography.labelMedium,
|
||||||
|
color = when (item.status) {
|
||||||
|
UploadStatus.DONE -> colorScheme.primary
|
||||||
|
UploadStatus.ERROR -> colorScheme.error
|
||||||
|
else -> colorScheme.onSurfaceVariant
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (item.status == UploadStatus.UPLOADING || item.status == UploadStatus.PENDING) {
|
||||||
|
Spacer(Modifier.height(8.dp))
|
||||||
|
if (item.progress > 0f) {
|
||||||
|
LinearProgressIndicator(
|
||||||
|
progress = { item.progress },
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (item.status == UploadStatus.ERROR) {
|
||||||
|
Spacer(Modifier.height(4.dp))
|
||||||
|
item.error?.let {
|
||||||
|
Text(it, style = MaterialTheme.typography.bodySmall, color = colorScheme.error)
|
||||||
|
}
|
||||||
|
TextButton(onClick = onRetry) { Text("Retry") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
91
app/src/main/java/com/example/filedrop/MainViewModel.kt
Normal file
91
app/src/main/java/com/example/filedrop/MainViewModel.kt
Normal file
|
|
@ -0,0 +1,91 @@
|
||||||
|
package com.example.filedrop
|
||||||
|
|
||||||
|
import android.app.Application
|
||||||
|
import android.net.Uri
|
||||||
|
import androidx.lifecycle.AndroidViewModel
|
||||||
|
import androidx.lifecycle.viewModelScope
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.SharingStarted
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.flow.stateIn
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
|
enum class UploadStatus { PENDING, UPLOADING, DONE, ERROR }
|
||||||
|
|
||||||
|
data class UploadItem(
|
||||||
|
val uri: Uri,
|
||||||
|
val name: String,
|
||||||
|
val size: Long,
|
||||||
|
val progress: Float = 0f,
|
||||||
|
val status: UploadStatus = UploadStatus.PENDING,
|
||||||
|
val error: String? = null,
|
||||||
|
)
|
||||||
|
|
||||||
|
class MainViewModel(app: Application) : AndroidViewModel(app) {
|
||||||
|
|
||||||
|
private val settings = Settings(app)
|
||||||
|
private val uploader = Uploader(app.contentResolver)
|
||||||
|
|
||||||
|
val address: StateFlow<String> = settings.address
|
||||||
|
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), "")
|
||||||
|
val token: StateFlow<String> = settings.token
|
||||||
|
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), "")
|
||||||
|
|
||||||
|
private val _items = MutableStateFlow<List<UploadItem>>(emptyList())
|
||||||
|
val items: StateFlow<List<UploadItem>> = _items
|
||||||
|
|
||||||
|
private val _message = MutableStateFlow<String?>(null)
|
||||||
|
val message: StateFlow<String?> = _message
|
||||||
|
|
||||||
|
fun setAddress(value: String) = viewModelScope.launch { settings.setAddress(value) }
|
||||||
|
fun setToken(value: String) = viewModelScope.launch { settings.setToken(value) }
|
||||||
|
fun messageShown() { _message.value = null }
|
||||||
|
|
||||||
|
fun onFilesPicked(uris: List<Uri>) {
|
||||||
|
val picked = uris.map { uri ->
|
||||||
|
val meta = uploader.queryMeta(uri)
|
||||||
|
UploadItem(uri = uri, name = meta.name, size = meta.size)
|
||||||
|
}
|
||||||
|
_items.value = picked
|
||||||
|
uploadAll()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun retry(uri: Uri) = uploadOne(uri)
|
||||||
|
|
||||||
|
private fun uploadAll() {
|
||||||
|
_items.value.forEach { uploadOne(it.uri) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun uploadOne(uri: Uri) {
|
||||||
|
val addr = address.value
|
||||||
|
if (addr.isBlank()) {
|
||||||
|
_message.value = "Set the PC address first"
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val item = _items.value.firstOrNull { it.uri == uri } ?: return
|
||||||
|
update(uri) { it.copy(status = UploadStatus.UPLOADING, progress = 0f, error = null) }
|
||||||
|
|
||||||
|
viewModelScope.launch {
|
||||||
|
val result = uploader.upload(
|
||||||
|
address = addr,
|
||||||
|
token = token.value,
|
||||||
|
uri = uri,
|
||||||
|
meta = FileMeta(item.name, item.size),
|
||||||
|
onProgress = { fraction ->
|
||||||
|
if (fraction >= 0f) update(uri) { it.copy(progress = fraction) }
|
||||||
|
},
|
||||||
|
)
|
||||||
|
result.onSuccess {
|
||||||
|
update(uri) { it.copy(status = UploadStatus.DONE, progress = 1f) }
|
||||||
|
_message.value = "Sent ${item.name}"
|
||||||
|
}.onFailure { e ->
|
||||||
|
update(uri) { it.copy(status = UploadStatus.ERROR, error = e.message) }
|
||||||
|
_message.value = "Failed ${item.name}: ${e.message}"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun update(uri: Uri, transform: (UploadItem) -> UploadItem) {
|
||||||
|
_items.value = _items.value.map { if (it.uri == uri) transform(it) else it }
|
||||||
|
}
|
||||||
|
}
|
||||||
30
app/src/main/java/com/example/filedrop/Settings.kt
Normal file
30
app/src/main/java/com/example/filedrop/Settings.kt
Normal file
|
|
@ -0,0 +1,30 @@
|
||||||
|
package com.example.filedrop
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.datastore.core.DataStore
|
||||||
|
import androidx.datastore.preferences.core.Preferences
|
||||||
|
import androidx.datastore.preferences.core.edit
|
||||||
|
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||||
|
import androidx.datastore.preferences.preferencesDataStore
|
||||||
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
import kotlinx.coroutines.flow.map
|
||||||
|
|
||||||
|
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")
|
||||||
|
|
||||||
|
/** Persisted connection settings: the PC address and the shared auth token. */
|
||||||
|
class Settings(private val context: Context) {
|
||||||
|
|
||||||
|
private val addressKey = stringPreferencesKey("address")
|
||||||
|
private val tokenKey = stringPreferencesKey("token")
|
||||||
|
|
||||||
|
val address: Flow<String> = context.dataStore.data.map { it[addressKey].orEmpty() }
|
||||||
|
val token: Flow<String> = context.dataStore.data.map { it[tokenKey].orEmpty() }
|
||||||
|
|
||||||
|
suspend fun setAddress(value: String) {
|
||||||
|
context.dataStore.edit { it[addressKey] = value.trim() }
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun setToken(value: String) {
|
||||||
|
context.dataStore.edit { it[tokenKey] = value.trim() }
|
||||||
|
}
|
||||||
|
}
|
||||||
96
app/src/main/java/com/example/filedrop/Uploader.kt
Normal file
96
app/src/main/java/com/example/filedrop/Uploader.kt
Normal file
|
|
@ -0,0 +1,96 @@
|
||||||
|
package com.example.filedrop
|
||||||
|
|
||||||
|
import android.content.ContentResolver
|
||||||
|
import android.net.Uri
|
||||||
|
import android.provider.OpenableColumns
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import okhttp3.MediaType.Companion.toMediaTypeOrNull
|
||||||
|
import okhttp3.MultipartBody
|
||||||
|
import okhttp3.OkHttpClient
|
||||||
|
import okhttp3.Request
|
||||||
|
import okhttp3.RequestBody
|
||||||
|
import okio.BufferedSink
|
||||||
|
import java.io.IOException
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
|
/** Basic file metadata resolved from a content Uri. */
|
||||||
|
data class FileMeta(val name: String, val size: Long)
|
||||||
|
|
||||||
|
/** Streams a content Uri to the PC receiver as a multipart upload, one file per request. */
|
||||||
|
class Uploader(private val contentResolver: ContentResolver) {
|
||||||
|
|
||||||
|
private val client = OkHttpClient.Builder()
|
||||||
|
.connectTimeout(15, TimeUnit.SECONDS)
|
||||||
|
.writeTimeout(0, TimeUnit.SECONDS) // large files stream indefinitely
|
||||||
|
.readTimeout(30, TimeUnit.SECONDS)
|
||||||
|
.build()
|
||||||
|
|
||||||
|
fun queryMeta(uri: Uri): FileMeta {
|
||||||
|
var name = "file"
|
||||||
|
var size = -1L
|
||||||
|
contentResolver.query(uri, null, null, null, null)?.use { cursor ->
|
||||||
|
if (cursor.moveToFirst()) {
|
||||||
|
val nameIdx = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
|
||||||
|
val sizeIdx = cursor.getColumnIndex(OpenableColumns.SIZE)
|
||||||
|
if (nameIdx >= 0 && !cursor.isNull(nameIdx)) name = cursor.getString(nameIdx)
|
||||||
|
if (sizeIdx >= 0 && !cursor.isNull(sizeIdx)) size = cursor.getLong(sizeIdx)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return FileMeta(name, size)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Uploads [uri] to `http://<address>/upload`. [onProgress] receives a 0f..1f fraction
|
||||||
|
* (or -1f when the size is unknown). Returns the server's response text on success.
|
||||||
|
*/
|
||||||
|
suspend fun upload(
|
||||||
|
address: String,
|
||||||
|
token: String,
|
||||||
|
uri: Uri,
|
||||||
|
meta: FileMeta,
|
||||||
|
onProgress: (Float) -> Unit,
|
||||||
|
): Result<String> = withContext(Dispatchers.IO) {
|
||||||
|
runCatching {
|
||||||
|
val url = "http://${address.trim().trimEnd('/')}/upload"
|
||||||
|
val mediaType = contentResolver.getType(uri)?.toMediaTypeOrNull()
|
||||||
|
|
||||||
|
val fileBody = object : RequestBody() {
|
||||||
|
override fun contentType() = mediaType
|
||||||
|
override fun contentLength() = meta.size
|
||||||
|
override fun writeTo(sink: BufferedSink) {
|
||||||
|
val input = contentResolver.openInputStream(uri)
|
||||||
|
?: throw IOException("Cannot open $uri")
|
||||||
|
input.use {
|
||||||
|
val buffer = ByteArray(64 * 1024)
|
||||||
|
var uploaded = 0L
|
||||||
|
while (true) {
|
||||||
|
val read = it.read(buffer)
|
||||||
|
if (read == -1) break
|
||||||
|
sink.write(buffer, 0, read)
|
||||||
|
uploaded += read
|
||||||
|
onProgress(if (meta.size > 0) uploaded.toFloat() / meta.size else -1f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val multipart = MultipartBody.Builder()
|
||||||
|
.setType(MultipartBody.FORM)
|
||||||
|
.addFormDataPart("file", meta.name, fileBody)
|
||||||
|
.build()
|
||||||
|
|
||||||
|
val requestBuilder = Request.Builder().url(url).post(multipart)
|
||||||
|
if (token.isNotBlank()) requestBuilder.header("X-Auth", token.trim())
|
||||||
|
|
||||||
|
client.newCall(requestBuilder.build()).execute().use { response ->
|
||||||
|
val body = response.body?.string().orEmpty()
|
||||||
|
if (!response.isSuccessful) {
|
||||||
|
throw IOException("HTTP ${response.code}: ${body.ifBlank { response.message }}")
|
||||||
|
}
|
||||||
|
onProgress(1f)
|
||||||
|
body.ifBlank { "saved" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
16
app/src/main/res/drawable/ic_launcher.xml
Normal file
16
app/src/main/res/drawable/ic_launcher.xml
Normal file
|
|
@ -0,0 +1,16 @@
|
||||||
|
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
android:width="108dp"
|
||||||
|
android:height="108dp"
|
||||||
|
android:viewportWidth="108"
|
||||||
|
android:viewportHeight="108">
|
||||||
|
<path
|
||||||
|
android:fillColor="#1565C0"
|
||||||
|
android:pathData="M0,0h108v108h-108z" />
|
||||||
|
<!-- Upward arrow into a tray: "drop to PC". -->
|
||||||
|
<path
|
||||||
|
android:fillColor="#FFFFFF"
|
||||||
|
android:pathData="M54,26l16,16h-10v18h-12v-18h-10z" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#FFFFFF"
|
||||||
|
android:pathData="M34,66h40v10h-40z" />
|
||||||
|
</vector>
|
||||||
4
app/src/main/res/values/strings.xml
Normal file
4
app/src/main/res/values/strings.xml
Normal file
|
|
@ -0,0 +1,4 @@
|
||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<resources>
|
||||||
|
<string name="app_name">File Drop</string>
|
||||||
|
</resources>
|
||||||
5
app/src/main/res/values/themes.xml
Normal file
5
app/src/main/res/values/themes.xml
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<resources>
|
||||||
|
<!-- Base activity theme; Compose supplies the Material 3 look. -->
|
||||||
|
<style name="Theme.FileDrop" parent="android:Theme.Material.Light.NoActionBar" />
|
||||||
|
</resources>
|
||||||
13
app/src/main/res/xml/network_security_config.xml
Normal file
13
app/src/main/res/xml/network_security_config.xml
Normal file
|
|
@ -0,0 +1,13 @@
|
||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<!--
|
||||||
|
This app talks to a receiver on the local network over plain HTTP.
|
||||||
|
Cleartext is permitted so LAN IPs (e.g. 192.168.x.x:8787) work; TLS on
|
||||||
|
the LAN is a stretch goal (see plan.md). HTTPS is still used where offered.
|
||||||
|
-->
|
||||||
|
<network-security-config>
|
||||||
|
<base-config cleartextTrafficPermitted="true">
|
||||||
|
<trust-anchors>
|
||||||
|
<certificates src="system" />
|
||||||
|
</trust-anchors>
|
||||||
|
</base-config>
|
||||||
|
</network-security-config>
|
||||||
5
build.gradle.kts
Normal file
5
build.gradle.kts
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
plugins {
|
||||||
|
alias(libs.plugins.android.application) apply false
|
||||||
|
alias(libs.plugins.kotlin.android) apply false
|
||||||
|
alias(libs.plugins.kotlin.compose) apply false
|
||||||
|
}
|
||||||
6
gradle.properties
Normal file
6
gradle.properties
Normal file
|
|
@ -0,0 +1,6 @@
|
||||||
|
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
|
||||||
|
org.gradle.caching=true
|
||||||
|
org.gradle.configuration-cache=true
|
||||||
|
android.useAndroidX=true
|
||||||
|
android.nonTransitiveRClass=true
|
||||||
|
kotlin.code.style=official
|
||||||
28
gradle/libs.versions.toml
Normal file
28
gradle/libs.versions.toml
Normal file
|
|
@ -0,0 +1,28 @@
|
||||||
|
[versions]
|
||||||
|
agp = "8.13.2"
|
||||||
|
kotlin = "2.4.0"
|
||||||
|
coreKtx = "1.15.0"
|
||||||
|
lifecycle = "2.8.7"
|
||||||
|
activityCompose = "1.9.3"
|
||||||
|
composeBom = "2024.12.01"
|
||||||
|
datastore = "1.1.7"
|
||||||
|
okhttp = "4.12.0"
|
||||||
|
|
||||||
|
[libraries]
|
||||||
|
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
|
||||||
|
androidx-lifecycle-runtime-ktx = { group = "androidx.lifecycle", name = "lifecycle-runtime-ktx", version.ref = "lifecycle" }
|
||||||
|
androidx-lifecycle-viewmodel-compose = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-compose", version.ref = "lifecycle" }
|
||||||
|
androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" }
|
||||||
|
androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" }
|
||||||
|
androidx-ui = { group = "androidx.compose.ui", name = "ui" }
|
||||||
|
androidx-ui-graphics = { group = "androidx.compose.ui", name = "ui-graphics" }
|
||||||
|
androidx-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling" }
|
||||||
|
androidx-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview" }
|
||||||
|
androidx-material3 = { group = "androidx.compose.material3", name = "material3" }
|
||||||
|
androidx-datastore-preferences = { group = "androidx.datastore", name = "datastore-preferences", version.ref = "datastore" }
|
||||||
|
okhttp = { group = "com.squareup.okhttp3", name = "okhttp", version.ref = "okhttp" }
|
||||||
|
|
||||||
|
[plugins]
|
||||||
|
android-application = { id = "com.android.application", version.ref = "agp" }
|
||||||
|
kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
|
||||||
|
kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
|
||||||
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
Binary file not shown.
7
gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
7
gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
|
|
@ -0,0 +1,7 @@
|
||||||
|
distributionBase=GRADLE_USER_HOME
|
||||||
|
distributionPath=wrapper/dists
|
||||||
|
distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.1-bin.zip
|
||||||
|
networkTimeout=10000
|
||||||
|
validateDistributionUrl=true
|
||||||
|
zipStoreBase=GRADLE_USER_HOME
|
||||||
|
zipStorePath=wrapper/dists
|
||||||
248
gradlew
vendored
Executable file
248
gradlew
vendored
Executable file
|
|
@ -0,0 +1,248 @@
|
||||||
|
#!/bin/sh
|
||||||
|
|
||||||
|
#
|
||||||
|
# Copyright © 2015 the original authors.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
#
|
||||||
|
# SPDX-License-Identifier: Apache-2.0
|
||||||
|
#
|
||||||
|
|
||||||
|
##############################################################################
|
||||||
|
#
|
||||||
|
# Gradle start up script for POSIX generated by Gradle.
|
||||||
|
#
|
||||||
|
# Important for running:
|
||||||
|
#
|
||||||
|
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||||
|
# noncompliant, but you have some other compliant shell such as ksh or
|
||||||
|
# bash, then to run this script, type that shell name before the whole
|
||||||
|
# command line, like:
|
||||||
|
#
|
||||||
|
# ksh Gradle
|
||||||
|
#
|
||||||
|
# Busybox and similar reduced shells will NOT work, because this script
|
||||||
|
# requires all of these POSIX shell features:
|
||||||
|
# * functions;
|
||||||
|
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||||
|
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||||
|
# * compound commands having a testable exit status, especially «case»;
|
||||||
|
# * various built-in commands including «command», «set», and «ulimit».
|
||||||
|
#
|
||||||
|
# Important for patching:
|
||||||
|
#
|
||||||
|
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||||
|
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||||
|
#
|
||||||
|
# The "traditional" practice of packing multiple parameters into a
|
||||||
|
# space-separated string is a well documented source of bugs and security
|
||||||
|
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||||
|
# options in "$@", and eventually passing that to Java.
|
||||||
|
#
|
||||||
|
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||||
|
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||||
|
# see the in-line comments for details.
|
||||||
|
#
|
||||||
|
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||||
|
# Darwin, MinGW, and NonStop.
|
||||||
|
#
|
||||||
|
# (3) This script is generated from the Groovy template
|
||||||
|
# https://github.com/gradle/gradle/blob/2d6327017519d23b96af35865dc997fcb544fb40/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||||
|
# within the Gradle project.
|
||||||
|
#
|
||||||
|
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||||
|
#
|
||||||
|
##############################################################################
|
||||||
|
|
||||||
|
# Attempt to set APP_HOME
|
||||||
|
|
||||||
|
# Resolve links: $0 may be a link
|
||||||
|
app_path=$0
|
||||||
|
|
||||||
|
# Need this for daisy-chained symlinks.
|
||||||
|
while
|
||||||
|
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||||
|
[ -h "$app_path" ]
|
||||||
|
do
|
||||||
|
ls=$( ls -ld "$app_path" )
|
||||||
|
link=${ls#*' -> '}
|
||||||
|
case $link in #(
|
||||||
|
/*) app_path=$link ;; #(
|
||||||
|
*) app_path=$APP_HOME$link ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
# This is normally unused
|
||||||
|
# shellcheck disable=SC2034
|
||||||
|
APP_BASE_NAME=${0##*/}
|
||||||
|
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||||
|
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
|
||||||
|
|
||||||
|
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||||
|
MAX_FD=maximum
|
||||||
|
|
||||||
|
warn () {
|
||||||
|
echo "$*"
|
||||||
|
} >&2
|
||||||
|
|
||||||
|
die () {
|
||||||
|
echo
|
||||||
|
echo "$*"
|
||||||
|
echo
|
||||||
|
exit 1
|
||||||
|
} >&2
|
||||||
|
|
||||||
|
# OS specific support (must be 'true' or 'false').
|
||||||
|
cygwin=false
|
||||||
|
msys=false
|
||||||
|
darwin=false
|
||||||
|
nonstop=false
|
||||||
|
case "$( uname )" in #(
|
||||||
|
CYGWIN* ) cygwin=true ;; #(
|
||||||
|
Darwin* ) darwin=true ;; #(
|
||||||
|
MSYS* | MINGW* ) msys=true ;; #(
|
||||||
|
NONSTOP* ) nonstop=true ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# Determine the Java command to use to start the JVM.
|
||||||
|
if [ -n "$JAVA_HOME" ] ; then
|
||||||
|
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||||
|
# IBM's JDK on AIX uses strange locations for the executables
|
||||||
|
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||||
|
else
|
||||||
|
JAVACMD=$JAVA_HOME/bin/java
|
||||||
|
fi
|
||||||
|
if [ ! -x "$JAVACMD" ] ; then
|
||||||
|
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||||
|
|
||||||
|
Please set the JAVA_HOME variable in your environment to match the
|
||||||
|
location of your Java installation."
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
JAVACMD=java
|
||||||
|
if ! command -v java >/dev/null 2>&1
|
||||||
|
then
|
||||||
|
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||||
|
|
||||||
|
Please set the JAVA_HOME variable in your environment to match the
|
||||||
|
location of your Java installation."
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Increase the maximum file descriptors if we can.
|
||||||
|
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||||
|
case $MAX_FD in #(
|
||||||
|
max*)
|
||||||
|
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||||
|
# shellcheck disable=SC2039,SC3045
|
||||||
|
MAX_FD=$( ulimit -H -n ) ||
|
||||||
|
warn "Could not query maximum file descriptor limit"
|
||||||
|
esac
|
||||||
|
case $MAX_FD in #(
|
||||||
|
'' | soft) :;; #(
|
||||||
|
*)
|
||||||
|
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||||
|
# shellcheck disable=SC2039,SC3045
|
||||||
|
ulimit -n "$MAX_FD" ||
|
||||||
|
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||||
|
esac
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Collect all arguments for the java command, stacking in reverse order:
|
||||||
|
# * args from the command line
|
||||||
|
# * the main class name
|
||||||
|
# * -classpath
|
||||||
|
# * -D...appname settings
|
||||||
|
# * --module-path (only if needed)
|
||||||
|
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||||
|
|
||||||
|
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||||
|
if "$cygwin" || "$msys" ; then
|
||||||
|
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||||
|
|
||||||
|
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||||
|
|
||||||
|
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||||
|
for arg do
|
||||||
|
if
|
||||||
|
case $arg in #(
|
||||||
|
-*) false ;; # don't mess with options #(
|
||||||
|
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||||
|
[ -e "$t" ] ;; #(
|
||||||
|
*) false ;;
|
||||||
|
esac
|
||||||
|
then
|
||||||
|
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||||
|
fi
|
||||||
|
# Roll the args list around exactly as many times as the number of
|
||||||
|
# args, so each arg winds up back in the position where it started, but
|
||||||
|
# possibly modified.
|
||||||
|
#
|
||||||
|
# NB: a `for` loop captures its iteration list before it begins, so
|
||||||
|
# changing the positional parameters here affects neither the number of
|
||||||
|
# iterations, nor the values presented in `arg`.
|
||||||
|
shift # remove old arg
|
||||||
|
set -- "$@" "$arg" # push replacement arg
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
|
||||||
|
|
||||||
|
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||||
|
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||||
|
|
||||||
|
# Collect all arguments for the java command:
|
||||||
|
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||||
|
# and any embedded shellness will be escaped.
|
||||||
|
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||||
|
# treated as '${Hostname}' itself on the command line.
|
||||||
|
|
||||||
|
set -- \
|
||||||
|
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||||
|
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
|
||||||
|
"$@"
|
||||||
|
|
||||||
|
# Stop when "xargs" is not available.
|
||||||
|
if ! command -v xargs >/dev/null 2>&1
|
||||||
|
then
|
||||||
|
die "xargs is not available"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Use "xargs" to parse quoted args.
|
||||||
|
#
|
||||||
|
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||||
|
#
|
||||||
|
# In Bash we could simply go:
|
||||||
|
#
|
||||||
|
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||||
|
# set -- "${ARGS[@]}" "$@"
|
||||||
|
#
|
||||||
|
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||||
|
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||||
|
# character that might be a shell metacharacter, then use eval to reverse
|
||||||
|
# that process (while maintaining the separation between arguments), and wrap
|
||||||
|
# the whole thing up as a single "set" statement.
|
||||||
|
#
|
||||||
|
# This will of course break if any of these variables contains a newline or
|
||||||
|
# an unmatched quote.
|
||||||
|
#
|
||||||
|
|
||||||
|
eval "set -- $(
|
||||||
|
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||||
|
xargs -n1 |
|
||||||
|
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||||
|
tr '\n' ' '
|
||||||
|
)" '"$@"'
|
||||||
|
|
||||||
|
exec "$JAVACMD" "$@"
|
||||||
93
gradlew.bat
vendored
Normal file
93
gradlew.bat
vendored
Normal file
|
|
@ -0,0 +1,93 @@
|
||||||
|
@rem
|
||||||
|
@rem Copyright 2015 the original author or authors.
|
||||||
|
@rem
|
||||||
|
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
@rem you may not use this file except in compliance with the License.
|
||||||
|
@rem You may obtain a copy of the License at
|
||||||
|
@rem
|
||||||
|
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
@rem
|
||||||
|
@rem Unless required by applicable law or agreed to in writing, software
|
||||||
|
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
@rem See the License for the specific language governing permissions and
|
||||||
|
@rem limitations under the License.
|
||||||
|
@rem
|
||||||
|
@rem SPDX-License-Identifier: Apache-2.0
|
||||||
|
@rem
|
||||||
|
|
||||||
|
@if "%DEBUG%"=="" @echo off
|
||||||
|
@rem ##########################################################################
|
||||||
|
@rem
|
||||||
|
@rem Gradle startup script for Windows
|
||||||
|
@rem
|
||||||
|
@rem ##########################################################################
|
||||||
|
|
||||||
|
@rem Set local scope for the variables with windows NT shell
|
||||||
|
if "%OS%"=="Windows_NT" setlocal
|
||||||
|
|
||||||
|
set DIRNAME=%~dp0
|
||||||
|
if "%DIRNAME%"=="" set DIRNAME=.
|
||||||
|
@rem This is normally unused
|
||||||
|
set APP_BASE_NAME=%~n0
|
||||||
|
set APP_HOME=%DIRNAME%
|
||||||
|
|
||||||
|
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||||
|
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||||
|
|
||||||
|
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||||
|
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||||
|
|
||||||
|
@rem Find java.exe
|
||||||
|
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||||
|
|
||||||
|
set JAVA_EXE=java.exe
|
||||||
|
%JAVA_EXE% -version >NUL 2>&1
|
||||||
|
if %ERRORLEVEL% equ 0 goto execute
|
||||||
|
|
||||||
|
echo. 1>&2
|
||||||
|
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
||||||
|
echo. 1>&2
|
||||||
|
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||||
|
echo location of your Java installation. 1>&2
|
||||||
|
|
||||||
|
goto fail
|
||||||
|
|
||||||
|
:findJavaFromJavaHome
|
||||||
|
set JAVA_HOME=%JAVA_HOME:"=%
|
||||||
|
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||||
|
|
||||||
|
if exist "%JAVA_EXE%" goto execute
|
||||||
|
|
||||||
|
echo. 1>&2
|
||||||
|
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
||||||
|
echo. 1>&2
|
||||||
|
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||||
|
echo location of your Java installation. 1>&2
|
||||||
|
|
||||||
|
goto fail
|
||||||
|
|
||||||
|
:execute
|
||||||
|
@rem Setup the command line
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@rem Execute Gradle
|
||||||
|
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
|
||||||
|
|
||||||
|
:end
|
||||||
|
@rem End local scope for the variables with windows NT shell
|
||||||
|
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||||
|
|
||||||
|
:fail
|
||||||
|
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||||
|
rem the _cmd.exe /c_ return code!
|
||||||
|
set EXIT_CODE=%ERRORLEVEL%
|
||||||
|
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||||
|
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||||
|
exit /b %EXIT_CODE%
|
||||||
|
|
||||||
|
:mainEnd
|
||||||
|
if "%OS%"=="Windows_NT" endlocal
|
||||||
|
|
||||||
|
:omega
|
||||||
99
plan.md
Normal file
99
plan.md
Normal file
|
|
@ -0,0 +1,99 @@
|
||||||
|
# Android → PC File Drop
|
||||||
|
|
||||||
|
Minimal Kotlin Android app that picks files/images and uploads them to a folder on a PC over the local network.
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
Two pieces:
|
||||||
|
|
||||||
|
1. **PC receiver** — tiny HTTP server that accepts multipart uploads and writes files into a chosen folder.
|
||||||
|
2. **Android app** — one screen, one button: pick files → POST them to the PC.
|
||||||
|
|
||||||
|
No cloud, no accounts, no discovery protocol. You type (or QR-scan) the PC's LAN IP once and save it.
|
||||||
|
|
||||||
|
## PC Receiver
|
||||||
|
|
||||||
|
**Language:** Go (single binary). Go for "double-click and forget."
|
||||||
|
|
||||||
|
**Behavior:**
|
||||||
|
- Listen on `0.0.0.0:8787`.
|
||||||
|
- `POST /upload` accepts `multipart/form-data`, saves each part to `DROP_DIR` with its original filename.
|
||||||
|
- Collision policy: append ` (1)`, ` (2)`, etc.
|
||||||
|
- Optional shared-secret header (`X-Auth: <token>`) so randos on the same Wi-Fi can't dump files on you.
|
||||||
|
- `GET /` returns "ok" for a health check.
|
||||||
|
- Log each received file: name, size, source IP.
|
||||||
|
|
||||||
|
it is seen on the local panel so that user locally can download
|
||||||
|
|
||||||
|
**Config:**
|
||||||
|
- `DROP_DIR` — where files land (default `~/Drops`).
|
||||||
|
- `AUTH_TOKEN` — shared secret (generated on first run, printed + saved to config).
|
||||||
|
- `PORT` — default 8787.
|
||||||
|
|
||||||
|
**Firewall:** open the port on the PC's LAN profile only.
|
||||||
|
|
||||||
|
## Android App
|
||||||
|
|
||||||
|
**Stack:** Kotlin, Jetpack Compose, single Activity, minSdk 26.
|
||||||
|
|
||||||
|
**Screens:** one.
|
||||||
|
|
||||||
|
**UI:**
|
||||||
|
- Text field: PC address (e.g. `192.168.1.42:8787`), persisted in `DataStore`.
|
||||||
|
- Text field: auth token, persisted.
|
||||||
|
- Big button: "Pick files".
|
||||||
|
- Below: list of currently-selected files with progress bars during upload.
|
||||||
|
- Snackbar for success/failure per file.
|
||||||
|
|
||||||
|
**Flow:**
|
||||||
|
1. Tap button → `ActivityResultContracts.OpenMultipleDocuments()` (handles images, video, any file; no storage permission needed on modern Android).
|
||||||
|
2. For each returned `Uri`: stream it as a multipart part to `http://<address>/upload` with the auth header.
|
||||||
|
3. Show per-file progress; on 200, mark done; on error, show retry.
|
||||||
|
|
||||||
|
**Networking:** OkHttp with a `MultipartBody`, streaming from `contentResolver.openInputStream(uri)` so big videos don't OOM.
|
||||||
|
|
||||||
|
**Manifest:**
|
||||||
|
- `INTERNET` permission.
|
||||||
|
- `usesCleartextTraffic="true"` scoped to local IP ranges via `network_security_config.xml` (HTTP is fine on LAN; adding TLS is a stretch goal).
|
||||||
|
|
||||||
|
**Share target (stretch):** register as a share target so you can hit "Share → Drop to PC" from the Photos app.
|
||||||
|
|
||||||
|
## Protocol
|
||||||
|
|
||||||
|
```
|
||||||
|
POST /upload HTTP/1.1
|
||||||
|
Host: 192.168.1.42:8787
|
||||||
|
X-Auth: <token>
|
||||||
|
Content-Type: multipart/form-data; boundary=...
|
||||||
|
|
||||||
|
--boundary
|
||||||
|
Content-Disposition: form-data; name="file"; filename="IMG_1234.jpg"
|
||||||
|
Content-Type: image/jpeg
|
||||||
|
|
||||||
|
<bytes>
|
||||||
|
--boundary--
|
||||||
|
```
|
||||||
|
|
||||||
|
Response: `200 OK` with JSON `{"saved": "IMG_1234.jpg"}` or `4xx/5xx` with error text.
|
||||||
|
|
||||||
|
## Milestones
|
||||||
|
|
||||||
|
1. PC receiver in ~60 lines; test with `curl -F file=@foo.jpg http://localhost:8787/upload -H "X-Auth: ..."`.
|
||||||
|
2. Android app scaffold: Compose UI, DataStore for settings, file picker returning URIs.
|
||||||
|
3. Wire up OkHttp multipart upload from a URI stream.
|
||||||
|
4. Progress + error UI.
|
||||||
|
5. Package: PC receiver as a systemd user service (Linux) or Task Scheduler entry (Windows) so it autostarts. Android side sideload the APK.
|
||||||
|
|
||||||
|
## Stretch
|
||||||
|
|
||||||
|
- QR code on PC receiver's `GET /` page encoding `address + token` so first-time setup is scan-once.
|
||||||
|
- mDNS advertisement (`_filedrop._tcp.local`) so the app can discover the PC without typing IPs.
|
||||||
|
- TLS with a self-signed cert pinned in the app.
|
||||||
|
- Share-target intent filter.
|
||||||
|
- Resume interrupted uploads (`Content-Range`).
|
||||||
|
|
||||||
|
## Non-goals
|
||||||
|
|
||||||
|
- PC → Android direction (use MTP or a second app instance later).
|
||||||
|
- Internet / NAT traversal.
|
||||||
|
- Multiple PCs at once (one address at a time is fine).
|
||||||
3
receiver/go.mod
Normal file
3
receiver/go.mod
Normal file
|
|
@ -0,0 +1,3 @@
|
||||||
|
module file-share/receiver
|
||||||
|
|
||||||
|
go 1.22
|
||||||
225
receiver/main.go
Normal file
225
receiver/main.go
Normal file
|
|
@ -0,0 +1,225 @@
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/rand"
|
||||||
|
"encoding/hex"
|
||||||
|
"fmt"
|
||||||
|
"html"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
home, _ := os.UserHomeDir()
|
||||||
|
cfgDir := filepath.Join(home, ".file-share")
|
||||||
|
_ = os.MkdirAll(cfgDir, 0o755)
|
||||||
|
cfgPath := filepath.Join(cfgDir, "receiver.env")
|
||||||
|
|
||||||
|
dropDir := env("DROP_DIR", filepath.Join(home, "Drops"))
|
||||||
|
port := env("PORT", "8787")
|
||||||
|
host := env("HOST", lanAddress())
|
||||||
|
authToken := env("AUTH_TOKEN", "")
|
||||||
|
if authToken == "" {
|
||||||
|
authToken = loadOrGenerateToken(cfgPath)
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = os.MkdirAll(dropDir, 0o755)
|
||||||
|
log.Printf("drop dir: %s", dropDir)
|
||||||
|
log.Printf("auth token: %s", authToken)
|
||||||
|
log.Printf("listening on http://%s:%s", host, port)
|
||||||
|
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
fmt.Fprint(w, "ok")
|
||||||
|
})
|
||||||
|
mux.HandleFunc("POST /upload", handleUpload(dropDir, authToken))
|
||||||
|
mux.HandleFunc("GET /files", handleList(dropDir))
|
||||||
|
mux.HandleFunc("GET /download", handleDownload(dropDir))
|
||||||
|
|
||||||
|
log.Fatal(http.ListenAndServe(host+":"+port, mux))
|
||||||
|
}
|
||||||
|
|
||||||
|
func handleUpload(dropDir, authToken string) http.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if authToken != "" && r.Header.Get("X-Auth") != authToken {
|
||||||
|
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := r.ParseMultipartForm(32 << 20); err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
files := r.MultipartForm.File["file"]
|
||||||
|
if len(files) == 0 {
|
||||||
|
http.Error(w, "no file", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
type savedFile struct {
|
||||||
|
Saved string `json:"saved"`
|
||||||
|
}
|
||||||
|
saved := make([]savedFile, 0, len(files))
|
||||||
|
for _, fh := range files {
|
||||||
|
src, err := fh.Open()
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
dest := uniquePath(dropDir, filepath.Base(fh.Filename))
|
||||||
|
dst, err := os.Create(dest)
|
||||||
|
if err != nil {
|
||||||
|
_ = src.Close()
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
n, err := io.Copy(dst, src)
|
||||||
|
_ = src.Close()
|
||||||
|
_ = dst.Close()
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
name := filepath.Base(dest)
|
||||||
|
log.Printf("saved %s (%d bytes) from %s", name, n, r.RemoteAddr)
|
||||||
|
saved = append(saved, savedFile{Saved: name})
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
if len(saved) == 1 {
|
||||||
|
fmt.Fprintf(w, `{"saved":%q}`, saved[0].Saved)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
fmt.Fprint(w, "[")
|
||||||
|
for i, s := range saved {
|
||||||
|
if i > 0 {
|
||||||
|
fmt.Fprint(w, ",")
|
||||||
|
}
|
||||||
|
fmt.Fprintf(w, `{"saved":%q}`, s.Saved)
|
||||||
|
}
|
||||||
|
fmt.Fprint(w, "]")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func handleList(dropDir string) http.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
entries, err := os.ReadDir(dropDir)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
|
fmt.Fprint(w, `<!doctype html><html><head><meta name="viewport" content="width=device-width, initial-scale=1"><title>Drops</title></head><body><h1>Drops</h1><ul>`)
|
||||||
|
for _, e := range entries {
|
||||||
|
if e.IsDir() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
info, _ := e.Info()
|
||||||
|
name := e.Name()
|
||||||
|
fmt.Fprintf(w, `<li><a href="/download?name=%s">%s</a> (%s)</li>`,
|
||||||
|
url.QueryEscape(name), html.EscapeString(name), formatBytes(info.Size()))
|
||||||
|
}
|
||||||
|
fmt.Fprint(w, `</ul></body></html>`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func handleDownload(dropDir string) http.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
name := r.URL.Query().Get("name")
|
||||||
|
if name == "" {
|
||||||
|
http.Error(w, "missing name", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
path := filepath.Join(dropDir, filepath.Base(name))
|
||||||
|
http.ServeFile(w, r, path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func uniquePath(dir, filename string) string {
|
||||||
|
if filename == "" {
|
||||||
|
filename = "unnamed"
|
||||||
|
}
|
||||||
|
ext := filepath.Ext(filename)
|
||||||
|
base := strings.TrimSuffix(filename, ext)
|
||||||
|
dest := filepath.Join(dir, filename)
|
||||||
|
if _, err := os.Stat(dest); os.IsNotExist(err) {
|
||||||
|
return dest
|
||||||
|
}
|
||||||
|
for i := 1; ; i++ {
|
||||||
|
candidate := filepath.Join(dir, base+" ("+strconv.Itoa(i)+")"+ext)
|
||||||
|
if _, err := os.Stat(candidate); os.IsNotExist(err) {
|
||||||
|
return candidate
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func loadOrGenerateToken(path string) string {
|
||||||
|
if data, err := os.ReadFile(path); err == nil {
|
||||||
|
for _, line := range strings.Split(string(data), "\n") {
|
||||||
|
if strings.HasPrefix(line, "AUTH_TOKEN=") {
|
||||||
|
return strings.TrimPrefix(line, "AUTH_TOKEN=")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
b := make([]byte, 4)
|
||||||
|
if _, err := rand.Read(b); err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
token := hex.EncodeToString(b)
|
||||||
|
_ = os.WriteFile(path, []byte("AUTH_TOKEN="+token+"\n"), 0o600)
|
||||||
|
log.Printf("generated token, saved to %s", path)
|
||||||
|
return token
|
||||||
|
}
|
||||||
|
|
||||||
|
func lanAddress() string {
|
||||||
|
addrs, err := net.InterfaceAddrs()
|
||||||
|
if err != nil {
|
||||||
|
return "127.0.0.1"
|
||||||
|
}
|
||||||
|
var fallback string
|
||||||
|
for _, a := range addrs {
|
||||||
|
ipnet, ok := a.(*net.IPNet)
|
||||||
|
if !ok || ipnet.IP.IsLoopback() || ipnet.IP.To4() == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
ip := ipnet.IP.To4()
|
||||||
|
if ip[0] == 192 && ip[1] == 168 {
|
||||||
|
return ip.String()
|
||||||
|
}
|
||||||
|
if fallback == "" && (ip[0] == 10 || (ip[0] == 172 && ip[1] >= 16 && ip[1] <= 31)) {
|
||||||
|
fallback = ip.String()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if fallback != "" {
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
return "127.0.0.1"
|
||||||
|
}
|
||||||
|
|
||||||
|
func env(key, def string) string {
|
||||||
|
if v := os.Getenv(key); v != "" {
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
|
||||||
|
func formatBytes(n int64) string {
|
||||||
|
if n < 1024 {
|
||||||
|
return strconv.FormatInt(n, 10) + " B"
|
||||||
|
}
|
||||||
|
units := []string{"KB", "MB", "GB", "TB"}
|
||||||
|
f := float64(n) / 1024
|
||||||
|
for _, u := range units {
|
||||||
|
if f < 1024 || u == units[len(units)-1] {
|
||||||
|
return fmt.Sprintf("%.1f %s", f, u)
|
||||||
|
}
|
||||||
|
f /= 1024
|
||||||
|
}
|
||||||
|
return strconv.FormatInt(n, 10) + " B"
|
||||||
|
}
|
||||||
BIN
receiver/reciever
Executable file
BIN
receiver/reciever
Executable file
Binary file not shown.
24
settings.gradle.kts
Normal file
24
settings.gradle.kts
Normal file
|
|
@ -0,0 +1,24 @@
|
||||||
|
pluginManagement {
|
||||||
|
repositories {
|
||||||
|
google {
|
||||||
|
content {
|
||||||
|
includeGroupByRegex("com\\.android.*")
|
||||||
|
includeGroupByRegex("com\\.google.*")
|
||||||
|
includeGroupByRegex("androidx.*")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
mavenCentral()
|
||||||
|
gradlePluginPortal()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencyResolutionManagement {
|
||||||
|
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
|
||||||
|
repositories {
|
||||||
|
google()
|
||||||
|
mavenCentral()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
rootProject.name = "FileDrop"
|
||||||
|
include(":app")
|
||||||
Loading…
Add table
Reference in a new issue