initial project

This commit is contained in:
Meghdad committed 2026-10-15 14:32:18 +03:30
1 parent 26b198e26e
commit 6ce4f924b7
90 files changed
+2154 -349

No files matched your search

+13
View File
@@ -0,0 +1,13 @@
plugins { id("com.android.library") }
android {
namespace = "meghdad.pakkit.core"
compileSdk { version = release(36) { minorApiLevel = 1 } }
defaultConfig { minSdk = 31 }
compileOptions { sourceCompatibility = JavaVersion.VERSION_11; targetCompatibility = JavaVersion.VERSION_11 }
}
dependencies {
api("com.google.android.gms:play-services-wearable:19.0.0")
api("androidx.work:work-runtime-ktx:2.10.1")
api(libs.androidx.core.ktx)
testImplementation(libs.junit)
}
+17
View File
@@ -0,0 +1,17 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">
<!-- Transfers use normal bounded workers; no foreground worker is started. -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" tools:node="remove"/>
<application>
<service android:name="androidx.work.impl.foreground.SystemForegroundService" tools:node="remove"/>
<service android:name="meghdad.pakkit.core.LinkService" android:exported="true">
<intent-filter>
<action android:name="com.google.android.gms.wearable.DATA_CHANGED" />
<data android:scheme="wear" android:host="*" android:pathPrefix="/pakkit/" />
</intent-filter>
<intent-filter>
<action android:name="com.google.android.gms.wearable.MESSAGE_RECEIVED" />
<data android:scheme="wear" android:host="*" android:path="/pakkit/probe" />
</intent-filter>
</service>
</application>
</manifest>
@@ -0,0 +1,251 @@
package meghdad.pakkit.core
import android.animation.ValueAnimator
import android.content.Context
import android.content.res.ColorStateList
import android.content.res.Configuration
import android.graphics.*
import android.graphics.drawable.Drawable
import android.graphics.drawable.GradientDrawable
import android.graphics.drawable.RippleDrawable
import android.os.PowerManager
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.view.animation.DecelerateInterpolator
import android.widget.*
import kotlin.math.min
import kotlin.math.pow
/** Semantic colors: mint is an accent, never low-contrast body text on a light surface. */
data class BrandPalette(
val dark: Boolean, val canvas: Int, val surface: Int, val raised: Int,
val text: Int, val secondary: Int, val border: Int, val accent: Int,
val accentSoft: Int, val mint: Int, val mintSoft: Int, val error: Int, val errorSoft: Int
) {
companion object {
val Light = BrandPalette(false, 0xFFF6F5FC.toInt(), 0xFFFFFFFF.toInt(), 0xFFEEEBFA.toInt(),
0xFF19172C.toInt(), 0xFF646078.toInt(), 0xFFDCD8ED.toInt(), 0xFF6140D8.toInt(),
0xFFEAE3FF.toInt(), 0xFF09665E.toInt(), 0xFFDDF7F0.toInt(), 0xFFA32E4B.toInt(), 0xFFFCE8EE.toInt())
val Dark = BrandPalette(true, 0xFF090B17.toInt(), 0xFF141727.toInt(), 0xFF1C2035.toInt(),
0xFFF4F2FF.toInt(), 0xFFB7B6CE.toInt(), 0xFF32364E.toInt(), 0xFFBAA6FF.toInt(),
0xFF30234E.toInt(), 0xFF68E9CF.toInt(), 0xFF123931.toInt(), 0xFFFFA7BC.toInt(), 0xFF422330.toInt())
}
}
object Design {
const val PURPLE = 0xFF7150EF.toInt()
const val MIDNIGHT = 0xFF090B17.toInt()
const val MINT = 0xFF68E9CF.toInt()
const val CYAN = 0xFF37D7F2.toInt()
private const val THEME = "theme"
fun themeMode(c: Context): String = c.getSharedPreferences("appearance", Context.MODE_PRIVATE).getString(THEME, "system") ?: "system"
fun setThemeMode(c: Context, mode: String) {
require(mode in setOf("system", "light", "dark"))
c.getSharedPreferences("appearance", Context.MODE_PRIVATE).edit().putString(THEME, mode).apply()
}
fun isDark(c: Context): Boolean = when (themeMode(c)) {
"dark" -> true
"light" -> false
else -> c.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES
}
fun palette(c: Context): BrandPalette = if (Link.isWatch(c) || isDark(c)) BrandPalette.Dark else BrandPalette.Light
fun dp(c: Context, n: Int) = (n * c.resources.displayMetrics.density).toInt()
fun motionAllowed(c: Context) = ValueAnimator.areAnimatorsEnabled() && !c.getSystemService(PowerManager::class.java).isPowerSaveMode
fun shape(color: Int, radius: Float = 24f, stroke: Int? = null) = GradientDrawable().apply {
setColor(color); cornerRadius = radius; stroke?.let { setStroke(1, it) }
}
fun gradient(colors: IntArray, radius: Float) = GradientDrawable(GradientDrawable.Orientation.TL_BR, colors).apply { cornerRadius = radius }
fun column(c: Context) = LinearLayout(c).apply { orientation = LinearLayout.VERTICAL }
fun text(c: Context, value: String, size: Float, color: Int = palette(c).text, bold: Boolean = false) = TextView(c).apply {
text = value; textSize = size; setTextColor(color)
typeface = Typeface.create(Typeface.create("sans-serif", Typeface.NORMAL), if (bold) 650 else 400, false)
setLineSpacing(dp(c, 2).toFloat(), 1f)
includeFontPadding = false
}
fun button(c: Context, label: String, primary: Boolean = true, action: () -> Unit) = Button(c).apply {
val p = palette(c)
text = label; isAllCaps = false; textSize = 15f; minHeight = dp(c, 52)
typeface = Typeface.create(Typeface.create("sans-serif", Typeface.NORMAL), 600, false)
setTextColor(ColorStateList(arrayOf(intArrayOf(-android.R.attr.state_enabled), intArrayOf()),
intArrayOf(p.secondary, if (primary) Color.WHITE else p.text)))
val fill = if (primary) gradient(intArrayOf(0xFF7854EE.toInt(), 0xFF6038D6.toInt()), dp(c, 20).toFloat())
else shape(p.raised, dp(c, 20).toFloat(), p.border)
val states = android.graphics.drawable.StateListDrawable().apply {
addState(intArrayOf(-android.R.attr.state_enabled), shape(p.raised, dp(c, 20).toFloat(), p.border))
addState(intArrayOf(), fill)
}
background = RippleDrawable(ColorStateList.valueOf(if (primary) 0x33FFFFFF else 0x226F4EF0), states, null)
stateListAnimator = null
setPadding(dp(c, 18), dp(c, 12), dp(c, 18), dp(c, 12))
setOnClickListener { performHapticFeedback(android.view.HapticFeedbackConstants.CONFIRM); action() }
}
fun badge(c: Context, label: String, positive: Boolean = false, warning: Boolean = false) = text(c, label, 12f,
if (warning) palette(c).error else if (positive) palette(c).mint else palette(c).accent, true).apply {
val p = palette(c)
setPadding(dp(c, 12), dp(c, 7), dp(c, 12), dp(c, 7))
background = shape(if (warning) p.errorSoft else if (positive) p.mintSoft else p.accentSoft, dp(c, 16).toFloat())
}
fun progress(c: Context) = ProgressBar(c, null, android.R.attr.progressBarStyleHorizontal).apply {
isIndeterminate = true
indeterminateTintList = ColorStateList.valueOf(palette(c).accent)
contentDescription = c.getString(R.string.transfer_waiting)
}
fun entrance(v: View) {
if (!motionAllowed(v.context)) return
v.alpha = 0f; v.translationY = dp(v.context, 6).toFloat()
v.animate().alpha(1f).translationY(0f).setDuration(240).setInterpolator(DecelerateInterpolator()).start()
}
fun contrast(a: Int, b: Int): Double {
fun luminance(color: Int): Double {
fun channel(shift: Int): Double {
val v = ((color shr shift) and 255) / 255.0
return if (v <= 0.04045) v / 12.92 else ((v + .055) / 1.055).pow(2.4)
}
return .2126 * channel(16) + .7152 * channel(8) + .0722 * channel(0)
}
val x = luminance(a); val y = luminance(b)
return (maxOf(x, y) + .05) / (minOf(x, y) + .05)
}
}
/** Static ambient lighting; shaders are rebuilt only when bounds change. */
class AuroraDrawable(private val p: BrandPalette) : Drawable() {
private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
private var glow: Shader? = null
override fun onBoundsChange(bounds: Rect) {
glow = RadialGradient(bounds.width() * .9f, 0f, bounds.width() * 1.1f,
if (p.dark) 0xFF211738.toInt() else 0xFFEDE5FF.toInt(), p.canvas, Shader.TileMode.CLAMP)
}
override fun draw(canvas: Canvas) { paint.shader = glow; canvas.drawRect(bounds, paint) }
override fun setAlpha(alpha: Int) { paint.alpha = alpha }
override fun setColorFilter(filter: ColorFilter?) { paint.colorFilter = filter }
@Deprecated("Drawable API") override fun getOpacity() = PixelFormat.OPAQUE
}
enum class Glyph { TRANSFER, HISTORY, GUIDE, APPEARANCE, WATCH, FILE, CHECK, ALERT, SHIELD }
/** One stroke family for navigation, metadata and status. No font-dependent symbol icons. */
class GlyphDrawable(private val glyph: Glyph, private val color: Int) : Drawable() {
override fun getIntrinsicWidth() = 24
override fun getIntrinsicHeight() = 24
private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE; strokeWidth = 1.8f; strokeCap = Paint.Cap.ROUND; strokeJoin = Paint.Join.ROUND }
private val path = Path()
override fun draw(c: Canvas) {
val save = c.save(); c.translate(bounds.left.toFloat(), bounds.top.toFloat()); c.scale(bounds.width() / 24f, bounds.height() / 24f)
paint.color = color
path.rewind()
when (glyph) {
Glyph.TRANSFER -> { path.moveTo(4f, 8f); path.lineTo(19f, 8f); path.lineTo(15f, 4f); path.moveTo(20f, 16f); path.lineTo(5f, 16f); path.lineTo(9f, 20f) }
Glyph.HISTORY -> { c.drawCircle(12f, 12f, 8f, paint); path.moveTo(12f, 7f); path.lineTo(12f, 12f); path.lineTo(16f, 14f) }
Glyph.GUIDE -> { c.drawRoundRect(4f, 3f, 20f, 21f, 4f, 4f, paint); path.moveTo(9f, 8f); path.lineTo(15f, 8f); path.moveTo(9f, 12f); path.lineTo(15f, 12f); path.moveTo(9f, 16f); path.lineTo(12f, 16f) }
Glyph.APPEARANCE -> { c.drawCircle(12f, 12f, 8f, paint); paint.style = Paint.Style.FILL; c.drawArc(4f, 4f, 20f, 20f, 90f, 180f, true, paint); paint.style = Paint.Style.STROKE }
Glyph.WATCH -> { c.drawRoundRect(5f, 6f, 19f, 18f, 5f, 5f, paint); path.moveTo(8f, 6f); path.lineTo(9f, 2f); path.lineTo(15f, 2f); path.lineTo(16f, 6f); path.moveTo(8f, 18f); path.lineTo(9f, 22f); path.lineTo(15f, 22f); path.lineTo(16f, 18f) }
Glyph.FILE -> { path.moveTo(14f, 3f); path.lineTo(5f, 3f); path.lineTo(5f, 21f); path.lineTo(19f, 21f); path.lineTo(19f, 8f); path.close(); path.moveTo(14f, 3f); path.lineTo(14f, 8f); path.lineTo(19f, 8f); path.moveTo(9f, 13f); path.lineTo(15f, 13f); path.moveTo(9f, 17f); path.lineTo(13f, 17f) }
Glyph.CHECK -> { path.moveTo(5f, 12f); path.lineTo(10f, 17f); path.lineTo(19f, 7f) }
Glyph.ALERT -> { path.moveTo(12f, 3f); path.lineTo(22f, 20f); path.lineTo(2f, 20f); path.close(); path.moveTo(12f, 9f); path.lineTo(12f, 13f); path.moveTo(12f, 16f); path.lineTo(12f, 16.2f) }
Glyph.SHIELD -> { path.moveTo(12f, 2f); path.lineTo(20f, 6f); path.lineTo(19f, 15f); path.quadTo(16f, 20f, 12f, 22f); path.quadTo(8f, 20f, 5f, 15f); path.lineTo(4f, 6f); path.close(); path.moveTo(8f, 12f); path.lineTo(11f, 15f); path.lineTo(16f, 9f) }
}
c.drawPath(path, paint); c.restoreToCount(save)
}
override fun setAlpha(alpha: Int) { paint.alpha = alpha }
override fun setColorFilter(filter: ColorFilter?) { paint.colorFilter = filter }
@Deprecated("Drawable API") override fun getOpacity() = PixelFormat.TRANSLUCENT
}
/** A reusable parcel illustration. Geometry and shaders are allocated once, never per frame. */
class ParcelSceneView(c: Context, private val compact: Boolean = false) : View(c) {
private val p = Design.palette(c)
private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
private val left = polygon(106f, 111f, 180f, 140f, 180f, 211f, 106f, 180f)
private val right = polygon(180f, 140f, 254f, 111f, 254f, 180f, 180f, 211f)
private val inside = polygon(106f, 111f, 180f, 81f, 254f, 111f, 180f, 143f)
private val flapLeft = polygon(106f, 111f, 180f, 143f, 137f, 166f, 63f, 132f)
private val flapRight = polygon(180f, 143f, 254f, 111f, 297f, 132f, 223f, 166f)
private val flapBack = polygon(106f, 111f, 180f, 81f, 153f, 61f, 82f, 92f)
private val flapBackRight = polygon(180f, 81f, 254f, 111f, 278f, 92f, 207f, 61f)
private val faceLeft = LinearGradient(106f, 111f, 186f, 213f, intArrayOf(0xFF36D5F4.toInt(), 0xFF7762FA.toInt(), 0xFFA66CF2.toInt()), null, Shader.TileMode.CLAMP)
private val faceRight = LinearGradient(180f, 140f, 260f, 190f, intArrayOf(0xFF6845EC.toInt(), 0xFF8D52F5.toInt(), 0xFFE79BD3.toInt()), null, Shader.TileMode.CLAMP)
private val mintFlap = LinearGradient(63f, 112f, 180f, 157f, 0xFF8EF7E2.toInt(), 0xFF6B80FF.toInt(), Shader.TileMode.CLAMP)
private val violetFlap = LinearGradient(180f, 133f, 284f, 148f, 0xFFE3CAFF.toInt(), 0xFFA98CFF.toInt(), Shader.TileMode.CLAMP)
private val tile = LinearGradient(-23f, -23f, 24f, 23f, intArrayOf(0xFF6EEFD8.toInt(), 0xFF56CCF4.toInt(), 0xFF8554F3.toInt()), null, Shader.TileMode.CLAMP)
private val glow = RadialGradient(180f, 126f, 135f, if (p.dark) 0x665D3ACF else 0x335F3BE2, Color.TRANSPARENT, Shader.TileMode.CLAMP)
private val ground = RadialGradient(180f, 211f, 100f, if (p.dark) 0x55533DA7 else 0x22715AC1, Color.TRANSPARENT, Shader.TileMode.CLAMP)
private var lift = 0f
private var played = false
var active = false
set(value) { if (field != value) { field = value; play() } }
private val animator = ValueAnimator.ofFloat(0f, 1f).apply {
duration = 1100
interpolator = DecelerateInterpolator()
addUpdateListener { lift = it.animatedValue as Float; invalidate() }
}
init { importantForAccessibility = IMPORTANT_FOR_ACCESSIBILITY_NO }
private fun polygon(vararg xy: Float) = Path().apply { moveTo(xy[0], xy[1]); for (i in 2 until xy.size step 2) lineTo(xy[i], xy[i + 1]); close() }
override fun onAttachedToWindow() { super.onAttachedToWindow(); play() }
override fun onDetachedFromWindow() { animator.cancel(); super.onDetachedFromWindow() }
override fun onWindowVisibilityChanged(visibility: Int) { super.onWindowVisibilityChanged(visibility); if (visibility != VISIBLE) animator.cancel() else if (isAttachedToWindow) play() }
override fun onWindowFocusChanged(hasWindowFocus: Boolean) { super.onWindowFocusChanged(hasWindowFocus); if (!hasWindowFocus) animator.cancel() else play() }
private fun play() {
if (!isAttachedToWindow || compact || !hasWindowFocus() || windowVisibility != VISIBLE || played || !Design.motionAllowed(context)) { lift = 1f; return }
played = true; animator.start()
}
private fun face(c: Canvas, path: Path, shader: Shader) {
paint.style = Paint.Style.FILL; paint.alpha = 255; paint.shader = shader; c.drawPath(path, paint); paint.shader = null
paint.style = Paint.Style.STROKE; paint.strokeWidth = .8f; paint.color = 0x88FFFFFF.toInt(); c.drawPath(path, paint); paint.style = Paint.Style.FILL
}
override fun onDraw(c: Canvas) {
super.onDraw(c)
val save = c.save(); c.translate(width / 2f, height / 2f)
val scale = min(width / 350f, height / 235f)
c.scale(scale, scale); c.translate(-180f, -120f)
if (!compact) {
paint.shader = glow; c.drawCircle(180f, 126f, 135f, paint); paint.shader = ground; c.drawOval(65f, 181f, 295f, 236f, paint); paint.shader = null
paint.style = Paint.Style.STROKE; paint.strokeWidth = 1f; paint.color = if (p.dark) 0x4458DCCB else 0x336749C9
c.drawOval(24f, 148f, 336f, 220f, paint); c.drawOval(42f, 137f, 318f, 231f, paint)
paint.style = Paint.Style.FILL
}
paint.color = 0xFF352355.toInt(); c.drawPath(inside, paint)
face(c, flapBack, violetFlap); face(c, flapBackRight, mintFlap)
face(c, left, faceLeft); face(c, right, faceRight); face(c, flapLeft, mintFlap); face(c, flapRight, violetFlap)
c.save(); c.translate(184f, 46f - 8f * lift); c.rotate(18f)
paint.alpha = 255; paint.shader = tile; c.drawRoundRect(-23f, -23f, 23f, 23f, 11f, 11f, paint); paint.shader = null
paint.style = Paint.Style.STROKE; paint.strokeWidth = 1.4f; paint.color = 0xDDFFFFFF.toInt(); c.drawRoundRect(-23f, -23f, 23f, 23f, 11f, 11f, paint)
paint.style = Paint.Style.FILL; paint.color = 0xCCFFFFFF.toInt(); c.drawRoundRect(-9f, -7f, 9f, 7f, 4f, 4f, paint)
c.restore()
if (!compact) {
spark(c, 70f, 65f, 4f, p.accent); spark(c, 282f, 52f, 5f, Design.MINT); spark(c, 308f, 189f, 3f, p.accent)
paint.color = Design.CYAN; c.drawCircle(44f, 186f, 3f, paint)
paint.color = 0xFFFFB980.toInt(); c.drawCircle(296f, 97f, 3f, paint)
}
c.restoreToCount(save)
}
private fun spark(c: Canvas, x: Float, y: Float, r: Float, color: Int) {
paint.color = color; paint.strokeWidth = 1.5f; paint.strokeCap = Paint.Cap.ROUND
c.drawLine(x - r, y, x + r, y, paint); c.drawLine(x, y - r, x, y + r, paint)
}
}
/** Scroll position indicator follows the circular bezel and redraws only in response to scrolling. */
class RoundScrollView(c: Context) : ScrollView(c) {
private val track = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE; strokeWidth = Design.dp(c, 2).toFloat(); strokeCap = Paint.Cap.ROUND }
init { isVerticalScrollBarEnabled = false; isFillViewport = true; clipToPadding = false }
override fun onDrawForeground(canvas: Canvas) {
super.onDrawForeground(canvas)
val range = computeVerticalScrollRange().toFloat(); val extent = height.toFloat()
if (range <= extent + 1) return
val inset = Design.dp(context, 4).toFloat()
track.color = 0x3356557F
canvas.drawArc(inset, scrollY + inset, width - inset, scrollY + height - inset, -32f, 64f, false, track)
val sweep = (64f * extent / range).coerceAtLeast(12f)
val position = (scrollY / (range - extent)).coerceIn(0f, 1f)
track.color = 0xFFBAA6FF.toInt()
canvas.drawArc(inset, scrollY + inset, width - inset, scrollY + height - inset, -32f + (64f - sweep) * position, sweep, false, track)
}
override fun onGenericMotionEvent(event: MotionEvent): Boolean {
if (event.action == MotionEvent.ACTION_SCROLL) {
scrollBy(0, (-event.getAxisValue(MotionEvent.AXIS_SCROLL) * Design.dp(context, 42)).toInt()); return true
}
return super.onGenericMotionEvent(event)
}
}
@@ -0,0 +1,65 @@
package meghdad.pakkit.core
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import com.google.android.gms.tasks.Tasks
import com.google.android.gms.wearable.*
import org.json.JSONObject
import java.util.concurrent.TimeUnit
object Link {
const val ROOT = "/pakkit/"
const val CAPABILITY = "pakkit_watch_v1"
fun isWatch(c: Context) = c.packageManager.hasSystemFeature(PackageManager.FEATURE_WATCH)
fun settings(c: Context) = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:${c.packageName}"))
fun installer(c: Context): Boolean = Intent(Intent.ACTION_INSTALL_PACKAGE)
.setDataAndType(Uri.parse("content://meghdad.pakkit/probe.apk"), "application/vnd.android.package-archive")
.resolveActivity(c.packageManager) != null
fun capability(c: Context, nonce: String = "") {
val node = Tasks.await(Wearable.getNodeClient(c).localNode, 15, TimeUnit.SECONDS)
val request = PutDataMapRequest.create("${ROOT}cap/${node.id}")
request.dataMap.apply {
putString("nonce", nonce); putLong("time", System.currentTimeMillis()); putInt("sdk", Build.VERSION.SDK_INT)
putStringArrayList("abis", ArrayList(Build.SUPPORTED_ABIS.toList()))
putLong("free", Packages.free(c)); putBoolean("installer", installer(c))
putBoolean("settings", settings(c).resolveActivity(c.packageManager) != null)
putBoolean("allowed", c.packageManager.canRequestPackageInstalls())
}
Tasks.await(Wearable.getDataClient(c).putDataItem(request.asPutDataRequest().setUrgent()), 20, TimeUnit.SECONDS)
}
@Synchronized
fun status(c: Context, job: JSONObject, state: String, detail: String, persist: Boolean = true) {
val store = Store(c)
val revision = store.prefs.getLong("statusRevision", 0) + 1
store.prefs.edit().putLong("statusRevision", revision).commit()
val updated = JSONObject(job.toString()).put("state", state).put("detail", detail).put("revision", revision)
if (persist) Store(c).write("incoming", updated)
Store(c).history(job.getString("id"), job.getJSONObject("apk").getString("label"), state, detail)
val req = PutDataMapRequest.create("${ROOT}status/${job.getString("id")}")
req.dataMap.apply {
putString("id", job.getString("id")); putString("target", job.getString("source"))
putString("state", state); putString("detail", detail.take(400)); putLong("time", System.currentTimeMillis()); putLong("revision", revision)
}
// A durable worker retries publication if connectivity or Play services is temporarily unavailable.
androidx.work.WorkManager.getInstance(c).enqueueUniqueWork("status-${job.getString("id")}",
androidx.work.ExistingWorkPolicy.REPLACE, androidx.work.OneTimeWorkRequestBuilder<StatusWorker>()
.setInputData(androidx.work.workDataOf("path" to req.uri.path, "map" to req.dataMap.toByteArray())).build())
}
fun delete(c: Context, uri: Uri) = Wearable.getDataClient(c).deleteDataItems(uri)
}
class StatusWorker(c: Context, p: androidx.work.WorkerParameters) : androidx.work.Worker(c, p) {
override fun doWork(): Result { return try {
val req = PutDataMapRequest.create(requireNotNull(inputData.getString("path")))
req.dataMap.putAll(DataMap.fromByteArray(requireNotNull(inputData.getByteArray("map"))))
val current = Store(applicationContext).read("incoming")
if (current != null && current.optString("id") == req.dataMap.getString("id") && current.optLong("revision") > req.dataMap.getLong("revision")) return Result.success()
Tasks.await(Wearable.getDataClient(applicationContext).putDataItem(req.asPutDataRequest().setUrgent()), 30, TimeUnit.SECONDS)
Result.success()
} catch (_: Exception) { if (runAttemptCount < 5) Result.retry() else Result.failure() }
}
}
@@ -0,0 +1,118 @@
package meghdad.pakkit.core
import android.net.Uri
import androidx.work.*
import com.google.android.gms.tasks.Tasks
import com.google.android.gms.wearable.*
import org.json.JSONObject
import java.io.File
import java.util.concurrent.TimeUnit
class LinkService : WearableListenerService() {
override fun onMessageReceived(event: MessageEvent) {
if (Link.isWatch(this) && event.path == "/pakkit/probe" && event.data.size <= 100) {
runCatching { Link.capability(this, event.data.toString(Charsets.UTF_8)) }
}
}
override fun onDataChanged(events: DataEventBuffer) {
for (event in events) {
if (event.type != DataEvent.TYPE_CHANGED) continue
val item = event.dataItem
when {
Link.isWatch(this) && item.uri.path?.startsWith("/pakkit/offer/") == true -> {
WorkManager.getInstance(this).enqueueUniqueWork("receive-${item.uri.lastPathSegment}", ExistingWorkPolicy.KEEP,
OneTimeWorkRequestBuilder<ReceiveWorker>().setInputData(workDataOf("uri" to item.uri.toString())).build())
}
!Link.isWatch(this) && item.uri.path?.startsWith("/pakkit/status/") == true -> acceptStatus(item)
}
}
}
private fun acceptStatus(item: DataItem) = synchronized(Store::class.java) {
runCatching {
val map = DataMapItem.fromDataItem(item).dataMap
val store = Store(this)
val job = store.read("outgoing") ?: return@runCatching
if (map.getString("id") != job.optString("id") || item.uri.host != job.optString("target")) return@runCatching
val revision = map.getLong("revision")
if (revision <= job.optLong("revision", -1)) return@runCatching
val state = map.getString("state") ?: return@runCatching
if (state !in setOf("receiving", "ready", "confirm", "installing", "installed", "failed", "declined")) return@runCatching
job.put("revision", revision).put("state", state).put("detail", map.getString("detail").orEmpty().take(400))
store.write("outgoing", job)
store.history(job.getString("id"), job.getJSONObject("apk").getString("label"), state, job.getString("detail"))
if (state in setOf("installed", "failed", "declined")) {
store.file(job.getString("id")).delete()
job.optString("offer").takeIf { it.isNotEmpty() }?.let { Link.delete(this, Uri.parse(it)) }
Link.delete(this, item.uri)
}
}
}
}
class ReceiveWorker(c: android.content.Context, p: WorkerParameters) : Worker(c, p) {
override fun doWork(): Result {
val c = applicationContext
val store = Store(c)
var job: JSONObject? = null
var part: File? = null
var itemUri: Uri? = null
return try {
if (!Link.isWatch(c)) return Result.failure()
val uri = Uri.parse(requireNotNull(inputData.getString("uri")))
itemUri = uri
val item = Tasks.await(Wearable.getDataClient(c).getDataItem(uri), 30, TimeUnit.SECONDS) ?: return Result.success()
val map = DataMapItem.fromDataItem(item).dataMap
val local = Tasks.await(Wearable.getNodeClient(c).localNode, 15, TimeUnit.SECONDS)
if (map.getString("target") != local.id) return Result.success()
val id = requireNotNull(map.getString("id"))
require(TransferRules.validId(id) && uri.lastPathSegment == id)
val expected = Apk.from(JSONObject(requireNotNull(map.getString("apk"))))
job = JSONObject().put("id", id).put("source", uri.host).put("apk", expected.json()).put("created", map.getLong("created"))
if (store.prefs.getStringSet("received", emptySet()).orEmpty().contains(id)) return Result.success()
val old = store.read("incoming")
if (old?.optString("id") == id && old.optString("state") !in setOf("receiving")) return Result.success()
if (old != null && old.optString("id") != id && old.optString("state") !in setOf("installed", "failed", "declined")) {
Link.status(c, job, "failed", "Finish or dismiss the current APK on your watch first.", persist = false)
Link.delete(c, uri)
return Result.success()
}
require(TransferRules.fresh(map.getLong("created"), System.currentTimeMillis())) { "This transfer expired. Send it again from your phone." }
require(expected.bytes in 1..TransferRules.MAX_BYTES)
require(Link.installer(c) && (c.packageManager.canRequestPackageInstalls() || Link.settings(c).resolveActivity(c.packageManager) != null)) { "This watch does not expose the system installation controls. Use Google Play on your watch." }
Packages.checkForWatch(expected, android.os.Build.VERSION.SDK_INT, android.os.Build.SUPPORTED_ABIS.toSet(), Packages.free(c))
WorkManager.getInstance(c).enqueueUniqueWork("expire-$id", ExistingWorkPolicy.KEEP,
OneTimeWorkRequestBuilder<ExpireWorker>().setInitialDelay((map.getLong("created") + TransferRules.TTL_MS - System.currentTimeMillis()).coerceAtLeast(0), TimeUnit.MILLISECONDS)
.setInputData(workDataOf("id" to id)).build())
Link.status(c, job, "receiving", "Verifying the APK on your watch")
part = File(store.directory, "$id.part")
val asset = requireNotNull(map.getAsset("file"))
val response = Tasks.await(Wearable.getDataClient(c).getFdForAsset(asset), 90, TimeUnit.SECONDS)
val result = try {
requireNotNull(response.inputStream).use { input -> part.outputStream().use { output -> TransferRules.copyBounded(input, output) } }
} finally { response.release() }
require(result.first == expected.bytes && result.second == expected.sha256) { "The file did not pass its integrity check. Send it again." }
val actual = Packages.inspect(c, part, result.second)
require(actual.packageName == expected.packageName) { "Package details did not match." }
Packages.checkForWatch(actual, android.os.Build.VERSION.SDK_INT, android.os.Build.SUPPORTED_ABIS.toSet(), Packages.free(c))
require(TransferRules.fresh(map.getLong("created"), System.currentTimeMillis())) { "This transfer expired. Send it again." }
require(part.renameTo(store.file(id))) { "Could not save this APK." }
job.put("apk", actual.json())
Link.status(c, job, "ready", "Ready. Review and install on your watch.")
store.prefs.edit().putStringSet("received", (store.prefs.getStringSet("received", emptySet()).orEmpty().toList().takeLast(99) + id).toSet()).commit()
Link.delete(c, uri)
store.clean()
Result.success()
} catch (e: Exception) {
part?.delete()
if (job != null && e !is IllegalArgumentException && e !is IllegalStateException && runAttemptCount < 3) {
Result.retry()
} else if (job != null) {
runCatching { Link.status(c, job, "failed", e.message ?: "Could not receive this APK. Try again.") }
itemUri?.let { Link.delete(c, it) }
Result.failure()
} else if (runAttemptCount < 3) Result.retry() else Result.failure()
}
}
}
@@ -0,0 +1,66 @@
package meghdad.pakkit.core
import android.content.Context
import android.content.pm.PackageManager
import android.os.StatFs
import org.json.JSONObject
import java.io.File
import java.util.zip.ZipFile
data class Apk(val label: String, val packageName: String, val version: String, val minSdk: Int,
val bytes: Long, val sha256: String, val abis: Set<String>, val wear: Boolean) {
fun json() = JSONObject().put("label", label).put("package", packageName).put("version", version)
.put("minSdk", minSdk).put("bytes", bytes).put("sha256", sha256)
.put("abis", abis.joinToString(",")).put("wear", wear)
companion object {
fun from(j: JSONObject) = Apk(j.getString("label"), j.getString("package"), j.getString("version"),
j.getInt("minSdk"), j.getLong("bytes"), j.getString("sha256"),
j.getString("abis").split(',').filter { it.isNotBlank() }.toSet(), j.getBoolean("wear"))
}
}
object Packages {
@Suppress("DEPRECATION")
fun inspect(context: Context, file: File, hash: String): Apk {
require(file.length() in 1..TransferRules.MAX_BYTES) { "Choose an APK smaller than 50 MB." }
val abis = mutableSetOf<String>()
ZipFile(file).use { zip ->
require(zip.getEntry("AndroidManifest.xml") != null) { "This file is not an Android APK." }
require(zip.size() < 100_000) { "This archive contains too many entries." }
var expanded = 0L
zip.entries().asSequence().forEach { entry ->
require(entry.size >= 0 && entry.size <= 128L * 1024 * 1024) { "This APK contains an unusually large archive entry." }
expanded += entry.size
require(expanded <= 200L * 1024 * 1024) { "This APK expands beyond Pakkit’s package limit." }
if (entry.name == "AndroidManifest.xml") require(entry.size <= 2 * 1024 * 1024) { "This APK manifest is too large." }
val parts = entry.name.split('/')
if (parts.size >= 3 && parts[0] == "lib" && entry.name.endsWith(".so")) abis += parts[1]
}
}
val info = context.packageManager.getPackageArchiveInfo(file.path,
PackageManager.GET_SIGNING_CERTIFICATES or PackageManager.GET_CONFIGURATIONS)
?: error("Android could not read this APK. Split packages and bundles are not supported.")
require(info.splitNames.isNullOrEmpty()) { "Choose a complete, single APK rather than a split package." }
require(info.signingInfo?.apkContentsSigners?.isNotEmpty() == true) { "This APK has no readable signing certificate." }
require(info.packageName != context.packageName) { "Update Pakkit through Google Play." }
val app = requireNotNull(info.applicationInfo)
app.sourceDir = file.path
app.publicSourceDir = file.path
context.packageManager.getResourcesForApplication(app).assets.openXmlResourceParser("AndroidManifest.xml").use { xml ->
while (xml.next() != org.xmlpull.v1.XmlPullParser.END_DOCUMENT) {
if (xml.eventType != org.xmlpull.v1.XmlPullParser.START_TAG) continue
require(xml.name != "uses-split") { "Choose a complete APK; this file requires other splits." }
if (xml.name == "manifest") require(xml.getAttributeValue(null, "split").isNullOrEmpty()) { "This is a split APK. Choose a complete APK." }
if (xml.name == "application") require(!xml.getAttributeBooleanValue("http://schemas.android.com/apk/res/android", "isSplitRequired", false)) { "This APK requires additional splits." }
}
}
return Apk(app.loadLabel(context.packageManager).toString().take(100), info.packageName,
info.versionName.orEmpty().take(64), app.minSdkVersion, file.length(), hash, abis,
info.reqFeatures?.any { it.name == PackageManager.FEATURE_WATCH } == true)
}
fun checkForWatch(apk: Apk, sdk: Int, abis: Set<String>, free: Long) {
require(apk.minSdk <= sdk) { "This APK needs Android API ${apk.minSdk}; your watch runs API $sdk." }
require(TransferRules.compatibleAbis(apk.abis, abis)) { "This APK was built for a different processor." }
require(free > apk.bytes * 3 + 20 * 1024 * 1024) { "Free more storage on your watch, then try again." }
}
fun free(context: Context) = StatFs(context.filesDir.path).availableBytes
}
@@ -0,0 +1,72 @@
package meghdad.pakkit.core
import android.content.Context
import android.net.Uri
import androidx.work.*
import com.google.android.gms.tasks.Tasks
import com.google.android.gms.wearable.*
import java.util.concurrent.TimeUnit
class SendWorker(c: Context, p: WorkerParameters) : Worker(c, p) {
override fun doWork(): Result {
val store = Store(applicationContext)
val job = store.read("outgoing") ?: return Result.failure()
if (job.optString("id") != inputData.getString("id") || job.optString("state") != "sending") return Result.success()
return try {
require(TransferRules.fresh(job.getLong("created"), System.currentTimeMillis())) { "This transfer expired. Choose the file again." }
val req = PutDataMapRequest.create("/pakkit/offer/${job.getString("id")}")
req.dataMap.apply {
putString("id", job.getString("id")); putString("target", job.getString("target"))
putLong("created", job.getLong("created")); putString("apk", job.getJSONObject("apk").toString())
putAsset("file", Asset.createFromUri(Uri.fromFile(store.file(job.getString("id")))))
}
val item = Tasks.await(Wearable.getDataClient(applicationContext).putDataItem(req.asPutDataRequest().setUrgent()), 45, TimeUnit.SECONDS)
// Do not overwrite an acknowledgement that arrived while publication was in flight.
synchronized(Store::class.java) {
val latest = store.read("outgoing")
if (latest?.optString("id") == job.getString("id")) {
latest.put("offer", item.uri.toString())
if (latest.optString("state") == "sending") latest.put("state", "syncing")
.put("detail", "Syncing to your watch. Open Pakkit there to continue.")
store.write("outgoing", latest)
}
}
WorkManager.getInstance(applicationContext).enqueueUniqueWork("expire-${job.getString("id")}", ExistingWorkPolicy.KEEP,
OneTimeWorkRequestBuilder<ExpireWorker>().setInitialDelay(24, TimeUnit.HOURS)
.setInputData(workDataOf("id" to job.getString("id"), "uri" to item.uri.toString())).build())
Result.success()
} catch (e: Exception) {
if (runAttemptCount < 3) Result.retry() else {
synchronized(Store::class.java) {
val latest = store.read("outgoing")
if (latest?.optString("id") == job.getString("id") && latest.optString("state") == "sending")
store.write("outgoing", latest.put("state", "failed").put("detail", "Could not sync. Check your connection and choose the file again."))
}
Result.failure()
}
}
}
}
class ExpireWorker(c: Context, p: WorkerParameters) : Worker(c, p) {
override fun doWork(): Result {
val store = Store(applicationContext)
val id = inputData.getString("id") ?: return Result.failure()
return try {
inputData.getString("uri")?.let { Tasks.await(Link.delete(applicationContext, Uri.parse(it)), 30, TimeUnit.SECONDS) }
store.file(id).delete()
for (key in listOf("incoming", "outgoing")) {
val job = store.read(key) ?: continue
if (job.optString("id") == id && job.optString("state") !in setOf("installed", "failed", "declined")) {
if (key == "incoming") {
job.optInt("session", -1).takeIf { it >= 0 }?.let { runCatching { applicationContext.packageManager.packageInstaller.abandonSession(it) } }
applicationContext.getSystemService(android.app.NotificationManager::class.java).cancel(42)
}
if (key == "incoming") Link.status(applicationContext, job, "failed", "This APK expired. Send it again from your phone.")
else store.write(key, job.put("state", "failed").put("detail", "This transfer expired. Choose the file again."))
}
}
store.clean()
Result.success()
} catch (_: Exception) { if (runAttemptCount < 3) Result.retry() else Result.failure() }
}
}
@@ -0,0 +1,29 @@
package meghdad.pakkit.core
import android.content.Context
import android.content.SharedPreferences
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
class Store(context: Context) {
val prefs: SharedPreferences = context.getSharedPreferences("pakkit", Context.MODE_PRIVATE)
val directory = File(context.filesDir, "packages").apply { mkdirs() }
fun file(id: String): File { require(TransferRules.validId(id)); return File(directory, "$id.apk") }
fun read(key: String): JSONObject? = runCatching { JSONObject(prefs.getString(key, null) ?: return null) }.getOrNull()
fun write(key: String, value: JSONObject) { check(prefs.edit().putString(key, value.toString()).commit()) }
fun clear(key: String) { prefs.edit().remove(key).commit() }
fun history(id: String, label: String, state: String, detail: String) = synchronized(Store::class.java) {
val old = runCatching { JSONArray(prefs.getString("history", "[]")) }.getOrDefault(JSONArray())
val next = JSONArray().put(JSONObject().put("id", id).put("label", label).put("state", state)
.put("detail", detail).put("time", System.currentTimeMillis()))
for (i in 0 until old.length()) if (old.getJSONObject(i).optString("id") != id && next.length() < 20) next.put(old.getJSONObject(i))
prefs.edit().putString("history", next.toString()).commit()
}
fun clean() {
val keep = listOfNotNull(read("outgoing")?.optString("id"), read("incoming")?.optString("id"))
directory.listFiles()?.forEach {
if (it.name.substringBefore('.') !in keep && System.currentTimeMillis() - it.lastModified() > TransferRules.TTL_MS) it.delete()
}
}
}
@@ -0,0 +1,29 @@
package meghdad.pakkit.core
import java.io.InputStream
import java.io.OutputStream
import java.security.MessageDigest
object TransferRules {
const val MAX_BYTES = 50L * 1024 * 1024
const val TTL_MS = 24L * 60 * 60 * 1000
fun validId(id: String) = Regex("[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}").matches(id)
fun fresh(created: Long, now: Long) = created <= now + 60_000 && now - created < TTL_MS
fun compatibleAbis(packageAbis: Set<String>, deviceAbis: Set<String>) = packageAbis.isEmpty() || packageAbis.any { it in deviceAbis }
fun copyBounded(input: InputStream, output: OutputStream, max: Long = MAX_BYTES): Pair<Long, String> {
val hash = MessageDigest.getInstance("SHA-256")
val buffer = ByteArray(64 * 1024)
var total = 0L
while (true) {
val count = input.read(buffer)
if (count < 0) break
if (count == 0) continue
total += count
require(total <= max) { "Choose an APK smaller than 50 MB." }
hash.update(buffer, 0, count)
output.write(buffer, 0, count)
}
require(total > 0) { "This file is empty." }
return total to hash.digest().joinToString("") { "%02x".format(it) }
}
}
@@ -0,0 +1,20 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android" xmlns:aapt="http://schemas.android.com/aapt" android:width="108dp" android:height="108dp" android:viewportWidth="108" android:viewportHeight="108">
<path android:pathData="M31,48L54,38L77,48L54,59Z" android:fillColor="#38265F"/>
<path android:pathData="M31,48L54,58L54,81L31,71Z">
<aapt:attr name="android:fillColor"><gradient android:startX="31" android:startY="48" android:endX="55" android:endY="81" android:startColor="#42DDF1" android:endColor="#8B5CF6" android:type="linear"/></aapt:attr>
</path>
<path android:pathData="M54,58L77,48L77,71L54,81Z">
<aapt:attr name="android:fillColor"><gradient android:startX="54" android:startY="58" android:endX="78" android:endY="76" android:startColor="#7049F2" android:endColor="#D99AE5" android:type="linear"/></aapt:attr>
</path>
<path android:pathData="M31,48L54,58L40,65L18,54Z" android:strokeColor="#C8FFF0" android:strokeWidth="0.5">
<aapt:attr name="android:fillColor"><gradient android:startX="18" android:startY="48" android:endX="54" android:endY="66" android:startColor="#8FF9E1" android:endColor="#7B94FF" android:type="linear"/></aapt:attr>
</path>
<path android:pathData="M54,58L77,48L90,54L68,65Z" android:strokeColor="#EAE1FF" android:strokeWidth="0.5">
<aapt:attr name="android:fillColor"><gradient android:startX="54" android:startY="58" android:endX="90" android:endY="54" android:startColor="#E9D5FF" android:endColor="#AD8AFF" android:type="linear"/></aapt:attr>
</path>
<path android:pathData="M31,48L54,38L45,32L23,42Z" android:fillColor="#A79BFF"/>
<path android:pathData="M54,38L77,48L85,42L63,32Z" android:fillColor="#79EBD9"/>
<path android:pathData="M49,21Q50,18 54,19L65,23Q68,24 67,28L63,39Q62,42 58,41L47,37Q44,36 45,32Z" android:strokeColor="#D8FFF8" android:strokeWidth="0.7">
<aapt:attr name="android:fillColor"><gradient android:startX="46" android:startY="20" android:endX="67" android:endY="41" android:startColor="#83F5DD" android:endColor="#8055F2" android:type="linear"/></aapt:attr>
</path>
</vector>
@@ -0,0 +1,3 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android" xmlns:aapt="http://schemas.android.com/aapt" android:width="108dp" android:height="108dp" android:viewportWidth="108" android:viewportHeight="108">
<path android:pathData="M0,0H108V108H0Z"><aapt:attr name="android:fillColor"><gradient android:type="radial" android:centerX="70" android:centerY="22" android:gradientRadius="100" android:startColor="#302052" android:endColor="#090B17"/></aapt:attr></path>
</vector>
@@ -0,0 +1,3 @@
<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="#FFFFFF" android:pathData="M30,50L52,60L52,81L30,71ZM56,60L78,50L78,71L56,81ZM30,46L52,56L40,62L18,52ZM56,56L78,46L90,52L68,62ZM31,44L52,35L44,29L23,39ZM56,35L77,44L85,39L64,29ZM49,19Q50,17 53,18L65,22Q68,23 67,26L63,37Q62,40 59,39L47,35Q44,34 45,31Z"/>
</vector>
@@ -0,0 +1 @@
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android"><background android:drawable="@drawable/pakkit_launcher_background"/><foreground android:drawable="@drawable/pakkit_icon"/><monochrome android:drawable="@drawable/pakkit_mark"/></adaptive-icon>
+7
View File
@@ -0,0 +1,7 @@
<resources>
<color name="pakkit_ink">#090B17</color>
<string name="pakkit_name">Pakkit</string>
<string name="brand_tagline">Pocket to Wrist.</string>
<string name="brand_secondary_tagline">Pack it. Send it. Wear it.</string>
<string name="transfer_waiting">Waiting for the watch to acknowledge this transfer</string>
</resources>
@@ -0,0 +1,6 @@
<data-extraction-rules>
<cloud-backup disableIfNoEncryptionCapabilities="true">
<exclude domain="root" path="."/><exclude domain="file" path="."/><exclude domain="database" path="."/><exclude domain="sharedpref" path="."/><exclude domain="external" path="."/>
</cloud-backup>
<device-transfer><exclude domain="root" path="."/><exclude domain="file" path="."/><exclude domain="database" path="."/><exclude domain="sharedpref" path="."/><exclude domain="external" path="."/></device-transfer>
</data-extraction-rules>
@@ -0,0 +1,27 @@
package meghdad.pakkit.core
import org.junit.Assert.assertTrue
import org.junit.Test
class BrandPaletteTest {
@Test fun bodyAndSecondaryCopyMeetNormalTextContrast() {
for (palette in listOf(BrandPalette.Light, BrandPalette.Dark)) {
for (surface in listOf(palette.canvas, palette.surface, palette.raised)) {
assertTrue("Body contrast", Design.contrast(palette.text, surface) >= 4.5)
assertTrue("Secondary contrast", Design.contrast(palette.secondary, surface) >= 4.5)
}
}
}
@Test fun semanticBadgesRemainReadableInBothThemes() {
for (p in listOf(BrandPalette.Light, BrandPalette.Dark)) {
assertTrue("Purple badge", Design.contrast(p.accent, p.accentSoft) >= 4.5)
assertTrue("Mint badge", Design.contrast(p.mint, p.mintSoft) >= 4.5)
assertTrue("Error badge", Design.contrast(p.error, p.errorSoft) >= 4.5)
}
}
@Test fun primaryButtonTextContrastsWithBothGradientStops() {
for (stop in listOf(0xFF7854EE.toInt(), 0xFF6038D6.toInt())) {
assertTrue(Design.contrast(0xFFFFFFFF.toInt(), stop) >= 4.5)
}
}
}
@@ -0,0 +1,37 @@
package meghdad.pakkit.core
import org.junit.Assert.*
import org.junit.Test
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
class TransferRulesTest {
@Test fun copyComputesKnownDigest() {
val output=ByteArrayOutputStream()
val result=TransferRules.copyBounded(ByteArrayInputStream("abc".toByteArray()),output)
assertEquals(3L,result.first)
assertEquals("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",result.second)
assertEquals("abc",output.toString("UTF-8"))
}
@Test(expected=IllegalArgumentException::class) fun stopsBeforeWritingOverLimit() {
TransferRules.copyBounded(ByteArrayInputStream(ByteArray(1025)),ByteArrayOutputStream(),1024)
}
@Test(expected=IllegalArgumentException::class) fun refusesEmptyFiles() {
TransferRules.copyBounded(ByteArrayInputStream(byteArrayOf()),ByteArrayOutputStream())
}
@Test fun rejectsTraversalAndInvalidIdentifiers() {
assertFalse(TransferRules.validId("../apk")); assertFalse(TransferRules.validId("file.apk"))
assertTrue(TransferRules.validId("05b414ab-a230-42f8-9a6d-1be25dcc3224"))
}
@Test fun expirationAndClockSkewAreBounded() {
val now=1_000_000_000L
assertTrue(TransferRules.fresh(now-1000,now))
assertFalse(TransferRules.fresh(now-TransferRules.TTL_MS,now))
assertFalse(TransferRules.fresh(now+120000,now))
}
@Test fun nativeLibrariesNeedMatchingProcessor() {
assertTrue(TransferRules.compatibleAbis(emptySet(),setOf("arm64-v8a")))
assertTrue(TransferRules.compatibleAbis(setOf("armeabi-v7a","arm64-v8a"),setOf("arm64-v8a")))
assertFalse(TransferRules.compatibleAbis(setOf("x86_64"),setOf("arm64-v8a")))
}
}