|
| 1 | +package com.mobitouchos.mt_audio |
| 2 | + |
| 3 | +import android.content.ContentProvider |
| 4 | +import android.content.ContentValues |
| 5 | +import android.database.Cursor |
| 6 | +import android.net.Uri |
| 7 | +import android.os.ParcelFileDescriptor |
| 8 | +import android.webkit.MimeTypeMap |
| 9 | +import java.io.File |
| 10 | + |
| 11 | +/** |
| 12 | + * Read-only [ContentProvider] that serves cached artwork files to Android Auto. |
| 13 | + * |
| 14 | + * Android Auto runs in a separate process and cannot access `file://` URIs in the |
| 15 | + * app's private cache. This provider exposes the cached artwork via `content://` |
| 16 | + * URIs that Android Auto can resolve. |
| 17 | + * |
| 18 | + * URI format: `content://{applicationId}.mt_audio.artwork/{asset_key}` |
| 19 | + * Maps to: `{cacheDir}/mt_audio_assets/{asset_key}` |
| 20 | + */ |
| 21 | +class MtAudioArtworkProvider : ContentProvider() { |
| 22 | + |
| 23 | + override fun onCreate(): Boolean = true |
| 24 | + |
| 25 | + override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor? { |
| 26 | + if (mode != "r") return null |
| 27 | + |
| 28 | + val assetKey = uri.path?.removePrefix("/") ?: return null |
| 29 | + val context = context ?: return null |
| 30 | + val file = File(context.cacheDir, "mt_audio_assets/$assetKey") |
| 31 | + |
| 32 | + // Prevent path traversal by ensuring the resolved path stays within the cache. |
| 33 | + // The trailing separator stops prefixes like `${cacheBase}_evil/...` slipping past. |
| 34 | + val cacheBase = File(context.cacheDir, "mt_audio_assets").canonicalPath + File.separator |
| 35 | + if (!file.canonicalPath.startsWith(cacheBase)) return null |
| 36 | + |
| 37 | + if (!file.exists()) return null |
| 38 | + |
| 39 | + return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY) |
| 40 | + } |
| 41 | + |
| 42 | + override fun getType(uri: Uri): String? { |
| 43 | + val path = uri.path ?: return null |
| 44 | + val ext = MimeTypeMap.getFileExtensionFromUrl(path) |
| 45 | + return MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext) |
| 46 | + ?: "application/octet-stream" |
| 47 | + } |
| 48 | + |
| 49 | + // This is a read-only provider — write operations are not supported. |
| 50 | + |
| 51 | + override fun query( |
| 52 | + uri: Uri, |
| 53 | + projection: Array<out String>?, |
| 54 | + selection: String?, |
| 55 | + selectionArgs: Array<out String>?, |
| 56 | + sortOrder: String?, |
| 57 | + ): Cursor? = null |
| 58 | + |
| 59 | + override fun insert(uri: Uri, values: ContentValues?): Uri? = null |
| 60 | + |
| 61 | + override fun update( |
| 62 | + uri: Uri, |
| 63 | + values: ContentValues?, |
| 64 | + selection: String?, |
| 65 | + selectionArgs: Array<out String>?, |
| 66 | + ): Int = 0 |
| 67 | + |
| 68 | + override fun delete( |
| 69 | + uri: Uri, |
| 70 | + selection: String?, |
| 71 | + selectionArgs: Array<out String>?, |
| 72 | + ): Int = 0 |
| 73 | +} |
0 commit comments