path
stringlengths
4
297
contentHash
stringlengths
1
10
content
stringlengths
0
13M
WeUI/feature/media/src/main/kotlin/top/chengdongqing/weui/feature/media/imagecropper/CropperMask.kt
2130247068
package top.chengdongqing.weui.feature.media.imagecropper import androidx.compose.foundation.Canvas import androidx.compose.foundation.layout.BoxScope import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.BlendMode import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Paint import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.graphics.drawscope.drawIntoCanvas import androidx.compose.ui.unit.dp @Composable internal fun BoxScope.CropperMask(onSizeChange: (Size) -> Unit) { Canvas(modifier = Modifier.matchParentSize()) { val spacing = 25.dp.toPx() val width = size.width - spacing * 2 onSizeChange(Size(width, width)) drawIntoCanvas { canvas -> canvas.saveLayer(bounds = Rect(offset = Offset.Zero, size = size), Paint()) // 绘制遮罩 drawRect(color = Color(0f, 0f, 0f, 0.4f)) // 露出裁剪框 canvas.saveLayer( bounds = Rect( offset = Offset(x = spacing, y = (size.height - width) / 2), size = Size(width, width) ), paint = Paint().apply { blendMode = BlendMode.Clear } ) canvas.restore() } // 绘制四个角 drawCorners(spacing, width) } } private fun DrawScope.drawCorners(space: Float, width: Float) { val cornerSize = 10.dp.toPx() val strokeWidth = 2.dp.toPx() val cornerPaths = listOf( // 左上角 Path().apply { moveTo(space, size.height / 2 - width / 2 + cornerSize) lineTo(space, size.height / 2 - width / 2) lineTo(space + cornerSize, size.height / 2 - width / 2) }, // 右上角 Path().apply { moveTo(size.width - space, size.height / 2 - width / 2 + cornerSize) lineTo(size.width - space, size.height / 2 - width / 2) lineTo(size.width - space - cornerSize, size.height / 2 - width / 2) }, // 左下角 Path().apply { moveTo(space, size.height / 2 + width / 2 - cornerSize) lineTo(space, size.height / 2 + width / 2) lineTo(space + cornerSize, size.height / 2 + width / 2) }, // 右下角 Path().apply { moveTo(size.width - space, size.height / 2 + width / 2 - cornerSize) lineTo(size.width - space, size.height / 2 + width / 2) lineTo(size.width - space - cornerSize, size.height / 2 + width / 2) } ) cornerPaths.forEach { path -> drawPath(path, color = Color.White, style = Stroke(width = strokeWidth)) } }
WeUI/feature/media/src/main/kotlin/top/chengdongqing/weui/feature/media/imagecropper/ImageTransform.kt
766596832
package top.chengdongqing.weui.feature.media.imagecropper data class ImageTransform( val scale: Float = 1f, val rotation: Float = 0f, val offsetX: Float = 0f, val offsetY: Float = 0f )
WeUI/feature/media/src/main/kotlin/top/chengdongqing/weui/feature/media/imagecropper/ImageCropper.kt
2811085800
package top.chengdongqing.weui.feature.media.imagecropper import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Matrix import android.net.Uri import androidx.compose.animation.core.animateFloatAsState import androidx.compose.foundation.Canvas import androidx.compose.foundation.background import androidx.compose.foundation.gestures.rememberTransformableState import androidx.compose.foundation.gestures.transformable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.MutableState import androidx.compose.runtime.State import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.produceState import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.asAndroidBitmap import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.graphics.drawscope.rotate import androidx.compose.ui.graphics.drawscope.scale import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.center import androidx.compose.ui.unit.toOffset import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import top.chengdongqing.weui.core.ui.components.toast.ToastIcon import top.chengdongqing.weui.core.ui.components.toast.rememberToastState import top.chengdongqing.weui.core.utils.getFileProviderUri import top.chengdongqing.weui.core.utils.toIntOffset import top.chengdongqing.weui.core.utils.toIntSize import java.io.File import java.io.FileOutputStream import kotlin.math.max import kotlin.time.Duration @Composable fun WeImageCropper(uri: Uri, onCancel: () -> Unit, onConfirm: (Uri) -> Unit) { val context = LocalContext.current val imageBitmap by context.loadImageBitmap(uri) var screenSize by remember { mutableStateOf(IntSize.Zero) } var boxSize by remember { mutableStateOf(IntSize.Zero) } val transform = remember { mutableStateOf(ImageTransform()) } var initialTransform by remember { mutableStateOf<ImageTransform?>(null) } val animatedRotation by animateFloatAsState(targetValue = transform.value.rotation, label = "") val coroutineScope = rememberCoroutineScope() val toast = rememberToastState() TransformInitializeEffect( screenSize, boxSize, imageBitmap, transform ) { initialTransform = it } Box { Canvas( modifier = Modifier .fillMaxSize() .background(Color.Black) .onSizeChanged { screenSize = it } .transformable(rememberTransformableState { zoomChange, panChange, _ -> imageBitmap?.let { image -> transform.value = transform.value.createNewTransform( zoomChange, panChange, boxSize, image ) } }) ) { imageBitmap?.let { transform.value.apply { rotate(degrees = animatedRotation) { scale(scale) { drawImage( it, dstOffset = Offset(offsetX, offsetY).toIntOffset() ) } } } } } CropperMask { boxSize = it.toIntSize() } ActionBar( transform, onCancel = onCancel, onReset = { initialTransform?.let { transform.value = it } } ) { imageBitmap?.let { toast.show( "处理中...", ToastIcon.LOADING, duration = Duration.INFINITE, mask = true ) coroutineScope.launch(Dispatchers.IO) { val bitmap = it.drawToNativeCanvas(screenSize, boxSize, transform.value) context.createImageUri(bitmap).apply(onConfirm) } } } } } @Composable private fun TransformInitializeEffect( screenSize: IntSize, boxSize: IntSize, image: ImageBitmap?, transform: MutableState<ImageTransform>, onInit: (ImageTransform) -> Unit ) { LaunchedEffect(boxSize, image) { if (screenSize != IntSize.Zero && boxSize != IntSize.Zero && image != null) { val scale = max( boxSize.width / image.width.toFloat(), boxSize.height / image.height.toFloat() ) val offsetX = (screenSize.width - image.width) / 2f val offsetY = (screenSize.height - image.height) / 2f transform.value = ImageTransform( scale = scale, offsetX = offsetX, offsetY = offsetY ).also(onInit) } } } @Composable private fun Context.loadImageBitmap(uri: Uri): State<ImageBitmap?> { val context = this return produceState<ImageBitmap?>(initialValue = null) { value = withContext(Dispatchers.IO) { context.contentResolver.openInputStream(uri)?.use { inputStream -> BitmapFactory.decodeStream(inputStream).asImageBitmap() } } } } private fun ImageTransform.createNewTransform( zoomChange: Float, panChange: Offset, boxSize: IntSize, image: ImageBitmap ): ImageTransform { val minScale = max( boxSize.width / image.width.toFloat(), boxSize.height / image.height.toFloat() ) val newScale = (scale * zoomChange).coerceIn(minScale, 5f) return copy( scale = newScale, offsetX = offsetX + panChange.x, offsetY = offsetY + panChange.y ) } private fun ImageBitmap.drawToNativeCanvas( screenSize: IntSize, boxSize: IntSize, transform: ImageTransform ): Bitmap { val bitmap = Bitmap.createBitmap( screenSize.width, screenSize.height, Bitmap.Config.ARGB_8888 ) val canvas = android.graphics.Canvas(bitmap) transform.apply { val offset = screenSize.center.toOffset() val matrix = Matrix().apply { postTranslate(offsetX, offsetY) postRotate(rotation, offset.x, offset.y) postScale(scale, scale, offset.x, offset.y) } canvas.drawBitmap(asAndroidBitmap(), matrix, null) } val offset = IntSize( width = screenSize.width - boxSize.width, height = screenSize.height - boxSize.height ).center return Bitmap.createBitmap( bitmap, offset.x, offset.y, boxSize.width, boxSize.height ) } private fun Context.createImageUri(bitmap: Bitmap): Uri { val tempFile = File.createTempFile("cropped_", ".png").apply { deleteOnExit() } FileOutputStream(tempFile).use { outputStream -> bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream) } return getFileProviderUri(tempFile) }
WeUI/feature/media/src/main/kotlin/top/chengdongqing/weui/feature/media/imagecropper/ActionBar.kt
3114885375
package top.chengdongqing.weui.feature.media.imagecropper import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.BoxScope import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.Replay import androidx.compose.material.icons.outlined.Rotate90DegreesCcw import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import top.chengdongqing.weui.core.ui.components.button.ButtonSize import top.chengdongqing.weui.core.ui.components.button.WeButton @Composable internal fun BoxScope.ActionBar( transform: MutableState<ImageTransform>, onCancel: () -> Unit, onReset: () -> Unit, onConfirm: () -> Unit ) { Row( modifier = Modifier .align(Alignment.BottomCenter) .fillMaxWidth() .padding(24.dp), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Text( text = "取消", color = Color.White, fontSize = 16.sp, modifier = Modifier.clickable { onCancel() } ) IconButton(onClick = onReset) { Icon( imageVector = Icons.Outlined.Replay, contentDescription = "恢复", tint = Color.White, modifier = Modifier.size(28.dp) ) } IconButton(onClick = { transform.value = transform.value.copy( rotation = transform.value.rotation - 90f ) }) { Icon( imageVector = Icons.Outlined.Rotate90DegreesCcw, contentDescription = "旋转", tint = Color.White, modifier = Modifier.size(28.dp) ) } WeButton(text = "确定", size = ButtonSize.SMALL) { onConfirm() } } }
tensorflow-lite-samples/ai-landmark-recognition/src/main/java/com/evgeny/aiLandmarkRecognition/data/TfLiteLandmarkClassifier.kt
2332230200
package com.evgeny.aiLandmarkRecognition.data import android.graphics.Bitmap import android.view.Surface import com.evgeny.aiLandmarkRecognition.TfLiteLandmarksClassifier import com.evgeny.aiLandmarkRecognition.domain.LandmarkClassifier import com.evgeny.aiLandmarkRecognition.domain.model.Classification import org.tensorflow.lite.support.image.ImageProcessor import org.tensorflow.lite.support.image.TensorImage import org.tensorflow.lite.task.core.vision.ImageProcessingOptions import org.tensorflow.lite.task.vision.classifier.ImageClassifier import javax.inject.Inject internal class TfLiteLandmarkClassifier @Inject constructor( @TfLiteLandmarksClassifier private val classifier: ImageClassifier, private val imageProcessor: ImageProcessor, ) : LandmarkClassifier { override fun classify(bitmap: Bitmap, rotation: Int): List<Classification> { val tensorImage = imageProcessor.process(TensorImage.fromBitmap(bitmap)) val imageProcessingOptions = ImageProcessingOptions.builder() .setOrientation(getOrientationFromRotation(rotation)) .build() val results = classifier.classify(tensorImage, imageProcessingOptions) return results.asSequence() .map { it.categories.map { Classification( name = it.displayName, score = it.score, ) } } .flatten() .distinctBy { it.name } .toList() } private fun getOrientationFromRotation(rotation: Int): ImageProcessingOptions.Orientation { return when (rotation) { Surface.ROTATION_270 -> ImageProcessingOptions.Orientation.BOTTOM_RIGHT Surface.ROTATION_90 -> ImageProcessingOptions.Orientation.TOP_LEFT Surface.ROTATION_180 -> ImageProcessingOptions.Orientation.RIGHT_BOTTOM else -> ImageProcessingOptions.Orientation.RIGHT_TOP } } }
tensorflow-lite-samples/ai-landmark-recognition/src/main/java/com/evgeny/aiLandmarkRecognition/domain/LandmarkClassifier.kt
1610334792
package com.evgeny.aiLandmarkRecognition.domain import android.graphics.Bitmap import com.evgeny.aiLandmarkRecognition.domain.model.Classification internal interface LandmarkClassifier { fun classify(bitmap: Bitmap, rotation: Int): List<Classification> }
tensorflow-lite-samples/ai-landmark-recognition/src/main/java/com/evgeny/aiLandmarkRecognition/domain/model/Classification.kt
771703642
package com.evgeny.aiLandmarkRecognition.domain.model internal data class Classification( val name: String, val score: Float, )
tensorflow-lite-samples/ai-landmark-recognition/src/main/java/com/evgeny/aiLandmarkRecognition/presentation/AiLandmarkRecognitionViewModel.kt
3127445414
package com.evgeny.aiLandmarkRecognition.presentation import android.content.Context import androidx.camera.view.CameraController import androidx.camera.view.LifecycleCameraController import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.asExecutor import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.stateIn import javax.inject.Inject @HiltViewModel internal class AiLandmarkRecognitionViewModel @Inject constructor( @ApplicationContext context: Context, private val landmarkImageAnalyzer: LandmarkImageAnalyzer, ) : ViewModel() { val cameraController = LifecycleCameraController(context).apply { setEnabledUseCases(CameraController.IMAGE_ANALYSIS) setImageAnalysisAnalyzer(Dispatchers.Default.asExecutor(), landmarkImageAnalyzer) } val imageAnalyzerResults = landmarkImageAnalyzer.results.stateIn( scope = viewModelScope, initialValue = emptyList(), started = SharingStarted.Lazily ) }
tensorflow-lite-samples/ai-landmark-recognition/src/main/java/com/evgeny/aiLandmarkRecognition/presentation/AiLandmarkRecognitionPage.kt
2739138046
package com.evgeny.aiLandmarkRecognition.presentation import androidx.activity.compose.BackHandler import androidx.camera.view.PreviewView import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.width import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.compose.ui.unit.dp import androidx.compose.ui.viewinterop.AndroidView import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavController import com.evgeny.aiLandmarkRecognition.domain.model.Classification import com.evgeny.archBase.compose.DisposableEffectWithLifeCycle @Composable fun AiLandmarkRecognitionPage( navController: NavController?, ) { val viewModel = hiltViewModel<AiLandmarkRecognitionViewModel>() val lifecycleOwner = LocalLifecycleOwner.current val results by viewModel.imageAnalyzerResults.collectAsStateWithLifecycle() Box(modifier = Modifier.fillMaxSize()) { AndroidView( factory = { PreviewView(it).apply { controller = viewModel.cameraController } }, modifier = Modifier .fillMaxWidth() .aspectRatio(1f) .align(Alignment.Center) ) Column( modifier = Modifier.align(Alignment.BottomCenter) ) { results.forEach { ClassificationItem(it) } } } DisposableEffectWithLifeCycle( onCreate = { viewModel.cameraController.bindToLifecycle(lifecycleOwner) }, onDestroy = { viewModel.cameraController.unbind() } ) BackHandler { navController?.popBackStack() } } @Composable private fun ClassificationItem(item: Classification) { Row(modifier = Modifier.fillMaxWidth()) { Text(text = item.name, modifier = Modifier.weight(1f)) Spacer(modifier = Modifier.width(10.dp)) Text(text = String.format("%.2f", item.score)) } }
tensorflow-lite-samples/ai-landmark-recognition/src/main/java/com/evgeny/aiLandmarkRecognition/presentation/LandmarkImageAnalyzer.kt
215038598
package com.evgeny.aiLandmarkRecognition.presentation import androidx.camera.core.ImageAnalysis import androidx.camera.core.ImageProxy import com.evgeny.aiLandmarkRecognition.DefaultCoroutineScope import com.evgeny.aiLandmarkRecognition.domain.LandmarkClassifier import com.evgeny.aiLandmarkRecognition.domain.model.Classification import com.evgeny.archBase.graphics.centerCrop import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.launch import java.util.concurrent.atomic.AtomicLong import javax.inject.Inject internal class LandmarkImageAnalyzer @Inject constructor( private val landmarkClassifier: LandmarkClassifier, @DefaultCoroutineScope private val coroutineScope: CoroutineScope, ) : ImageAnalysis.Analyzer { private val _results = MutableSharedFlow<List<Classification>>() val results = _results.asSharedFlow() private val frameSkipCounter = AtomicLong(0) override fun analyze(image: ImageProxy) { coroutineScope.launch { if (frameSkipCounter.getAndIncrement() % 20 == 0L) { val results = landmarkClassifier.classify( bitmap = image.toBitmap().centerCrop(321, 321), rotation = image.imageInfo.rotationDegrees, ) _results.emit(results) } image.close() } } }
tensorflow-lite-samples/ai-landmark-recognition/src/main/java/com/evgeny/aiLandmarkRecognition/AiLandmarkRecognitionModule.kt
2706180829
package com.evgeny.aiLandmarkRecognition import android.content.Context import androidx.camera.core.ImageAnalysis import com.evgeny.aiLandmarkRecognition.data.TfLiteLandmarkClassifier import com.evgeny.aiLandmarkRecognition.domain.LandmarkClassifier import com.evgeny.aiLandmarkRecognition.presentation.LandmarkImageAnalyzer import dagger.Binds import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import org.tensorflow.lite.support.image.ImageProcessor import org.tensorflow.lite.task.core.BaseOptions import org.tensorflow.lite.task.vision.classifier.ImageClassifier import org.tensorflow.lite.task.vision.classifier.ImageClassifier.ImageClassifierOptions import javax.inject.Qualifier import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) internal interface AiLandmarkRecognitionModule { @Binds @Singleton fun bindLandmarkClassifier(impl: TfLiteLandmarkClassifier): LandmarkClassifier @Binds fun bindImageAnalyzer(impl: LandmarkImageAnalyzer): ImageAnalysis.Analyzer companion object { @Provides @Singleton @TfLiteLandmarksClassifier fun provideImageClassifier( @ApplicationContext context: Context, ): ImageClassifier { val baseOptions = BaseOptions.builder() .setNumThreads(2) .build() val options = ImageClassifierOptions.builder() .setBaseOptions(baseOptions) .setMaxResults(3) .setScoreThreshold(0.5f) .build() return ImageClassifier.createFromFileAndOptions( context, "landmarks.tflite", options, ) } @Provides @Singleton fun provideImageProcessor(): ImageProcessor = ImageProcessor.Builder().build() @Provides @Singleton @DefaultCoroutineScope fun provideDefaultCoroutineScope(): CoroutineScope = CoroutineScope(Dispatchers.Default) } } @Qualifier @Retention(AnnotationRetention.RUNTIME) annotation class TfLiteLandmarksClassifier @Qualifier @Retention(AnnotationRetention.RUNTIME) annotation class DefaultCoroutineScope
tensorflow-lite-samples/app/src/main/java/com/evgeny/tensorflowlitesamples/ui/theme/Color.kt
3396599453
package com.evgeny.tensorflowlitesamples.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
tensorflow-lite-samples/app/src/main/java/com/evgeny/tensorflowlitesamples/ui/theme/Theme.kt
1188667527
package com.evgeny.tensorflowlitesamples.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun TensorFlowLiteSamplesTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
tensorflow-lite-samples/app/src/main/java/com/evgeny/tensorflowlitesamples/ui/theme/Type.kt
4230523347
package com.evgeny.tensorflowlitesamples.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
tensorflow-lite-samples/app/src/main/java/com/evgeny/tensorflowlitesamples/MainActivity.kt
2909621611
package com.evgeny.tensorflowlitesamples import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.ui.Modifier import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import com.evgeny.aiLandmarkRecognition.presentation.AiLandmarkRecognitionPage import com.evgeny.tensorflowlitesamples.feature.home.MainPage import com.evgeny.tensorflowlitesamples.ui.theme.TensorFlowLiteSamplesTheme import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { TensorFlowLiteSamplesTheme { val navController = rememberNavController() Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { NavHost(navController = navController, startDestination = "main") { composable("main") { MainPage(navController = navController) } composable("aiLandmarkRecognition") { AiLandmarkRecognitionPage(navController = navController) } } } } } } }
tensorflow-lite-samples/app/src/main/java/com/evgeny/tensorflowlitesamples/app/App.kt
3982841646
package com.evgeny.tensorflowlitesamples.app import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class App : Application()
tensorflow-lite-samples/app/src/main/java/com/evgeny/tensorflowlitesamples/feature/home/MainPage.kt
3237260791
package com.evgeny.tensorflowlitesamples.feature.home import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.navigation.NavController import com.evgeny.tensorflowlitesamples.R import com.evgeny.tensorflowlitesamples.ui.theme.TensorFlowLiteSamplesTheme import com.google.accompanist.permissions.ExperimentalPermissionsApi import com.google.accompanist.permissions.isGranted import com.google.accompanist.permissions.rememberPermissionState @OptIn(ExperimentalPermissionsApi::class, ExperimentalMaterial3Api::class) @Composable internal fun MainPage( navController: NavController?, ) { val cameraPermission = rememberPermissionState(permission = "android.permission.CAMERA") if (cameraPermission.status.isGranted) { Column(modifier = Modifier.fillMaxSize()) { TopAppBar(title = { Text(text = "TensorFlowLite Samples") }) Item(title = "AI Landmark Recognition") { navController?.navigate("aiLandmarkRecognition") } } } else { Box(modifier = Modifier.fillMaxSize()) { Text( text = "Enable camera permission", modifier = Modifier.align(Alignment.Center) ) } } if (cameraPermission.status.isGranted.not()) { LaunchedEffect(Unit) { cameraPermission.launchPermissionRequest() } } } @Composable private fun Item(title: String, onClick: () -> Unit) { Row( modifier = Modifier .fillMaxWidth() .clickable { onClick() } .padding(horizontal = 16.dp, vertical = 20.dp) ) { Text(text = title, modifier = Modifier .weight(1f) .align(Alignment.CenterVertically)) Icon( painter = painterResource(id = R.drawable.ic_arrow_forward_24), contentDescription = null, modifier = Modifier .weight(0.1f) .align(Alignment.CenterVertically) ) } } @Composable @Preview internal fun MainPagePreview() { TensorFlowLiteSamplesTheme { MainPage(navController = null) } }
tensorflow-lite-samples/arch-base/src/main/java/com/evgeny/archBase/compose/Extensions.kt
2573930353
package com.evgeny.archBase.compose import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver @Composable fun DisposableEffectWithLifeCycle( onResume: () -> Unit = {}, onPause: () -> Unit = {}, onStop: () -> Unit = {}, onStart: () -> Unit = {}, onCreate: () -> Unit = {}, onDestroy: () -> Unit = {}, ) { // Safely update the current lambdas when a new one is provided val lifecycleOwner = LocalLifecycleOwner.current val currentOnResume by rememberUpdatedState(onResume) val currentOnPause by rememberUpdatedState(onPause) val currentOnStop by rememberUpdatedState(onStop) val currentOnStart by rememberUpdatedState(onStart) val currentOnCreate by rememberUpdatedState(onCreate) val currentOnDestroy by rememberUpdatedState(onDestroy) // If `lifecycleOwner` changes, dispose and reset the effect DisposableEffect(lifecycleOwner) { // Create an observer that triggers our remembered callbacks // for lifecycle events val observer = LifecycleEventObserver { _, event -> when (event) { Lifecycle.Event.ON_CREATE -> { currentOnCreate() } Lifecycle.Event.ON_START -> { currentOnStart() } Lifecycle.Event.ON_RESUME -> { currentOnResume() } Lifecycle.Event.ON_PAUSE -> { currentOnPause() } Lifecycle.Event.ON_STOP -> { currentOnStop() } Lifecycle.Event.ON_DESTROY -> { currentOnDestroy() } else -> {} } } // Add the observer to the lifecycle lifecycleOwner.lifecycle.addObserver(observer) // When the effect leaves the Composition, remove the observer onDispose { lifecycleOwner.lifecycle.removeObserver(observer) } } }
tensorflow-lite-samples/arch-base/src/main/java/com/evgeny/archBase/graphics/Extensions.kt
1476518077
package com.evgeny.archBase.graphics import android.graphics.Bitmap fun Bitmap.centerCrop(desiredWidth: Int, desiredHeight: Int): Bitmap { val xStart = (width - desiredWidth) / 2 val yStart = (height - desiredHeight) / 2 return Bitmap.createBitmap(this, xStart, yStart, desiredHeight, desiredHeight) }
HelloWorldAnyi/app/src/androidTest/java/com/example/holamundoanyi/ExampleInstrumentedTest.kt
423884862
package com.example.holamundoanyi import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.holamundoanyi", appContext.packageName) } }
HelloWorldAnyi/app/src/test/java/com/example/holamundoanyi/ExampleUnitTest.kt
2136297204
package com.example.holamundoanyi import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
HelloWorldAnyi/app/src/main/java/com/example/holamundoanyi/MainActivity.kt
1435216404
package com.example.holamundoanyi import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } }
webview_download_test/flutter_downloader/example/android/app/src/main/kotlin/vn/hunghd/example/MainActivity.kt
809020230
package vn.hunghd.example; import io.flutter.embedding.android.FlutterActivity; class MainActivity : FlutterActivity()
webview_download_test/flutter_downloader/android/src/main/kotlin/vn/hunghd/flutterdownloader/FlutterDownloaderPlugin.kt
2159191128
package vn.hunghd.flutterdownloader import android.content.ContentResolver import android.content.ContentUris import android.content.Context import android.content.Intent import android.net.Uri import android.provider.MediaStore import android.util.Log import androidx.core.app.NotificationManagerCompat import androidx.work.BackoffPolicy import androidx.work.Constraints import androidx.work.Data import androidx.work.NetworkType import androidx.work.OneTimeWorkRequest import androidx.work.WorkManager import androidx.work.WorkRequest import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.embedding.engine.plugins.FlutterPlugin.FlutterPluginBinding import io.flutter.plugin.common.BinaryMessenger import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.MethodChannel import java.io.File import java.util.UUID import java.util.concurrent.TimeUnit private const val invalidTaskId = "invalid_task_id" private const val invalidStatus = "invalid_status" private const val invalidData = "invalid_data" class FlutterDownloaderPlugin : MethodChannel.MethodCallHandler, FlutterPlugin { private var flutterChannel: MethodChannel? = null private var taskDao: TaskDao? = null private var context: Context? = null private var callbackHandle: Long = 0 private var step = 0 private var debugMode = 0 private var ignoreSsl = 0 private val initializationLock = Any() private fun onAttachedToEngine(applicationContext: Context?, messenger: BinaryMessenger) { synchronized(initializationLock) { if (flutterChannel != null) { return } context = applicationContext flutterChannel = MethodChannel(messenger, CHANNEL) flutterChannel?.setMethodCallHandler(this) val dbHelper: TaskDbHelper = TaskDbHelper.getInstance(context) taskDao = TaskDao(dbHelper) } } override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { when (call.method) { "initialize" -> initialize(call, result) "registerCallback" -> registerCallback(call, result) "enqueue" -> enqueue(call, result) "loadTasks" -> loadTasks(result) "loadTasksWithRawQuery" -> loadTasksWithRawQuery(call, result) "cancel" -> cancel(call, result) "cancelAll" -> cancelAll(result) "pause" -> pause(call, result) "resume" -> resume(call, result) "retry" -> retry(call, result) "open" -> open(call, result) "remove" -> remove(call, result) else -> result.notImplemented() } } override fun onAttachedToEngine(binding: FlutterPluginBinding) { onAttachedToEngine(binding.applicationContext, binding.binaryMessenger) } override fun onDetachedFromEngine(binding: FlutterPluginBinding) { context = null flutterChannel?.setMethodCallHandler(null) flutterChannel = null } private fun requireContext() = requireNotNull(context) private fun buildRequest( url: String?, savedDir: String?, filename: String?, headers: String?, showNotification: Boolean, openFileFromNotification: Boolean, isResume: Boolean, requiresStorageNotLow: Boolean, saveInPublicStorage: Boolean, timeout: Int, allowCellular: Boolean ): WorkRequest { return OneTimeWorkRequest.Builder(DownloadWorker::class.java) .setConstraints( Constraints.Builder() .setRequiresStorageNotLow(requiresStorageNotLow) .setRequiredNetworkType(if (allowCellular) NetworkType.CONNECTED else NetworkType.UNMETERED) .build() ) .addTag(TAG) .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 10, TimeUnit.SECONDS) .setInputData( Data.Builder() .putString(DownloadWorker.ARG_URL, url) .putString(DownloadWorker.ARG_SAVED_DIR, savedDir) .putString(DownloadWorker.ARG_FILE_NAME, filename) .putString(DownloadWorker.ARG_HEADERS, headers) .putBoolean(DownloadWorker.ARG_SHOW_NOTIFICATION, showNotification) .putBoolean( DownloadWorker.ARG_OPEN_FILE_FROM_NOTIFICATION, openFileFromNotification ) .putBoolean(DownloadWorker.ARG_IS_RESUME, isResume) .putLong(DownloadWorker.ARG_CALLBACK_HANDLE, callbackHandle) .putInt(DownloadWorker.ARG_STEP, step) .putBoolean(DownloadWorker.ARG_DEBUG, debugMode == 1) .putBoolean(DownloadWorker.ARG_IGNORESSL, ignoreSsl == 1) .putBoolean( DownloadWorker.ARG_SAVE_IN_PUBLIC_STORAGE, saveInPublicStorage ) .putInt(DownloadWorker.ARG_TIMEOUT, timeout) .build() ) .build() } private fun sendUpdateProgress(id: String, status: DownloadStatus, progress: Int) { val args: MutableMap<String, Any> = HashMap() args["task_id"] = id args["status"] = status.ordinal args["progress"] = progress flutterChannel?.invokeMethod("updateProgress", args) } private fun initialize(call: MethodCall, result: MethodChannel.Result) { val args = call.arguments as List<*> val callbackHandle = args[0].toString().toLong() debugMode = args[1].toString().toInt() ignoreSsl = args[2].toString().toInt() val pref = context?.getSharedPreferences(SHARED_PREFERENCES_KEY, Context.MODE_PRIVATE) pref?.edit()?.putLong(CALLBACK_DISPATCHER_HANDLE_KEY, callbackHandle)?.apply() result.success(null) } private fun registerCallback(call: MethodCall, result: MethodChannel.Result) { val args = call.arguments as List<*> callbackHandle = args[0].toString().toLong() step = args[1].toString().toInt() result.success(null) } private fun <T> MethodCall.requireArgument(key: String): T = requireNotNull(argument(key)) { "Required key '$key' was null" } private fun enqueue(call: MethodCall, result: MethodChannel.Result) { val url: String = call.requireArgument("url") val savedDir: String = call.requireArgument("saved_dir") val filename: String? = call.argument("file_name") val headers: String = call.requireArgument("headers") val timeout: Int = call.requireArgument("timeout") val showNotification: Boolean = call.requireArgument("show_notification") val openFileFromNotification: Boolean = call.requireArgument("open_file_from_notification") val requiresStorageNotLow: Boolean = call.requireArgument("requires_storage_not_low") val saveInPublicStorage: Boolean = call.requireArgument("save_in_public_storage") val allowCellular: Boolean = call.requireArgument("allow_cellular") val request: WorkRequest = buildRequest( url, savedDir, filename, headers, showNotification, openFileFromNotification, false, requiresStorageNotLow, saveInPublicStorage, timeout, allowCellular = allowCellular ) WorkManager.getInstance(requireContext()).enqueue(request) val taskId: String = request.id.toString() result.success(taskId) sendUpdateProgress(taskId, DownloadStatus.ENQUEUED, 0) taskDao!!.insertOrUpdateNewTask( taskId, url, DownloadStatus.ENQUEUED, 0, filename, savedDir, headers, showNotification, openFileFromNotification, saveInPublicStorage, allowCellular = allowCellular ) } private fun loadTasks(result: MethodChannel.Result) { val tasks = taskDao!!.loadAllTasks() val array: MutableList<Map<*, *>> = ArrayList() for (task in tasks) { val item: MutableMap<String, Any?> = HashMap() item["task_id"] = task.taskId item["status"] = task.status.ordinal item["progress"] = task.progress item["url"] = task.url item["file_name"] = task.filename item["saved_dir"] = task.savedDir item["time_created"] = task.timeCreated item["allow_cellular"] = task.allowCellular array.add(item) } result.success(array) } private fun loadTasksWithRawQuery(call: MethodCall, result: MethodChannel.Result) { val query: String = call.requireArgument("query") val tasks = taskDao!!.loadTasksWithRawQuery(query) val array: MutableList<Map<*, *>> = ArrayList() for (task in tasks) { val item: MutableMap<String, Any?> = HashMap() item["task_id"] = task.taskId item["status"] = task.status.ordinal item["progress"] = task.progress item["url"] = task.url item["file_name"] = task.filename item["saved_dir"] = task.savedDir item["time_created"] = task.timeCreated item["allow_cellular"] = task.allowCellular array.add(item) } result.success(array) } private fun cancel(call: MethodCall, result: MethodChannel.Result) { val taskId: String = call.requireArgument("task_id") WorkManager.getInstance(requireContext()).cancelWorkById(UUID.fromString(taskId)) result.success(null) } private fun cancelAll(result: MethodChannel.Result) { WorkManager.getInstance(requireContext()).cancelAllWorkByTag(TAG) result.success(null) } private fun pause(call: MethodCall, result: MethodChannel.Result) { val taskId: String = call.requireArgument("task_id") // mark the current task is cancelled to process pause request // the worker will depends on this flag to prepare data for resume request taskDao!!.updateTask(taskId, true) // cancel running task, this method causes WorkManager.isStopped() turning true and the download loop will be stopped WorkManager.getInstance(requireContext()).cancelWorkById(UUID.fromString(taskId)) result.success(null) } private fun resume(call: MethodCall, result: MethodChannel.Result) { val taskId: String = call.requireArgument("task_id") val task = taskDao!!.loadTask(taskId) val requiresStorageNotLow: Boolean = call.requireArgument("requires_storage_not_low") var timeout: Int = call.requireArgument("timeout") if (task != null) { if (task.status == DownloadStatus.PAUSED) { var filename = task.filename if (filename == null) { filename = task.url.substring(task.url.lastIndexOf("/") + 1, task.url.length) } val partialFilePath = task.savedDir + File.separator + filename val partialFile = File(partialFilePath) if (partialFile.exists()) { val request: WorkRequest = buildRequest( task.url, task.savedDir, task.filename, task.headers, task.showNotification, task.openFileFromNotification, true, requiresStorageNotLow, task.saveInPublicStorage, timeout, allowCellular = task.allowCellular ) val newTaskId: String = request.id.toString() result.success(newTaskId) sendUpdateProgress(newTaskId, DownloadStatus.RUNNING, task.progress) taskDao!!.updateTask( taskId, newTaskId, DownloadStatus.RUNNING, task.progress, false ) WorkManager.getInstance(requireContext()).enqueue(request) } else { taskDao!!.updateTask(taskId, false) result.error( invalidData, "not found partial downloaded data, this task cannot be resumed", null ) } } else { result.error(invalidStatus, "only paused task can be resumed", null) } } else { result.error(invalidTaskId, "not found task corresponding to given task id", null) } } private fun retry(call: MethodCall, result: MethodChannel.Result) { val taskId: String = call.requireArgument("task_id") val task = taskDao!!.loadTask(taskId) val requiresStorageNotLow: Boolean = call.requireArgument("requires_storage_not_low") var timeout: Int = call.requireArgument("timeout") if (task != null) { if (task.status == DownloadStatus.FAILED || task.status == DownloadStatus.CANCELED) { val request: WorkRequest = buildRequest( task.url, task.savedDir, task.filename, task.headers, task.showNotification, task.openFileFromNotification, false, requiresStorageNotLow, task.saveInPublicStorage, timeout, allowCellular = task.allowCellular ) val newTaskId: String = request.id.toString() result.success(newTaskId) sendUpdateProgress(newTaskId, DownloadStatus.ENQUEUED, task.progress) taskDao!!.updateTask( taskId, newTaskId, DownloadStatus.ENQUEUED, task.progress, false ) WorkManager.getInstance(requireContext()).enqueue(request) } else { result.error(invalidStatus, "only failed and canceled task can be retried", null) } } else { result.error(invalidTaskId, "not found task corresponding to given task id", null) } } private fun open(call: MethodCall, result: MethodChannel.Result) { val taskId: String = call.requireArgument("task_id") val task = taskDao!!.loadTask(taskId) if (task == null) { result.error(invalidTaskId, "not found task with id $taskId", null) return } if (task.status != DownloadStatus.COMPLETE) { result.error(invalidStatus, "only completed tasks can be opened", null) return } val fileURL = task.url val savedDir = task.savedDir var filename = task.filename if (filename == null) { filename = fileURL.substring(fileURL.lastIndexOf("/") + 1, fileURL.length) } val saveFilePath = savedDir + File.separator + filename val intent: Intent? = IntentUtils.validatedFileIntent(requireContext(), saveFilePath, task.mimeType) if (intent != null) { requireContext().startActivity(intent) result.success(true) } else { result.success(false) } } private fun remove(call: MethodCall, result: MethodChannel.Result) { val taskId: String = call.requireArgument("task_id") val shouldDeleteContent: Boolean = call.requireArgument("should_delete_content") val task = taskDao!!.loadTask(taskId) if (task != null) { if (task.status == DownloadStatus.ENQUEUED || task.status == DownloadStatus.RUNNING) { WorkManager.getInstance(requireContext()).cancelWorkById(UUID.fromString(taskId)) } if (shouldDeleteContent) { var filename = task.filename if (filename == null) { filename = task.url.substring(task.url.lastIndexOf("/") + 1, task.url.length) } val saveFilePath = task.savedDir + File.separator + filename val tempFile = File(saveFilePath) if (tempFile.exists()) { try { deleteFileInMediaStore(tempFile) } catch (e: SecurityException) { Log.d( "FlutterDownloader", "Failed to delete file in media store, will fall back to normal delete()" ) } tempFile.delete() } } taskDao!!.deleteTask(taskId) NotificationManagerCompat.from(requireContext()).cancel(task.primaryId) result.success(null) } else { result.error(invalidTaskId, "not found task corresponding to given task id", null) } } private fun deleteFileInMediaStore(file: File) { // Set up the projection (we only need the ID) val projection = arrayOf(MediaStore.Images.Media._ID) // Match on the file path val imageSelection: String = MediaStore.Images.Media.DATA + " = ?" val selectionArgs = arrayOf<String>(file.absolutePath) // Query for the ID of the media matching the file path val imageQueryUri: Uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI val contentResolver: ContentResolver = requireContext().contentResolver // search the file in image store first val imageCursor = contentResolver.query(imageQueryUri, projection, imageSelection, selectionArgs, null) if (imageCursor != null && imageCursor.moveToFirst()) { // We found the ID. Deleting the item via the content provider will also remove the file val id: Long = imageCursor.getLong(imageCursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID)) val deleteUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id) contentResolver.delete(deleteUri, null, null) } else { // File not found in image store DB, try to search in video store val videoCursor = contentResolver.query(imageQueryUri, projection, imageSelection, selectionArgs, null) if (videoCursor != null && videoCursor.moveToFirst()) { // We found the ID. Deleting the item via the content provider will also remove the file val id: Long = videoCursor.getLong(videoCursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID)) val deleteUri: Uri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id) contentResolver.delete(deleteUri, null, null) } else { // can not find the file in media store DB at all } videoCursor?.close() } imageCursor?.close() } companion object { private const val CHANNEL = "vn.hunghd/downloader" private const val TAG = "flutter_download_task" const val SHARED_PREFERENCES_KEY = "vn.hunghd.downloader.pref" const val CALLBACK_DISPATCHER_HANDLE_KEY = "callback_dispatcher_handle_key" } }
webview_download_test/flutter_downloader/android/src/main/kotlin/vn/hunghd/flutterdownloader/IntentUtils.kt
3181690995
package vn.hunghd.flutterdownloader import android.content.Context import android.content.Intent import android.net.Uri import android.os.Build import androidx.core.content.FileProvider import java.io.File import java.io.FileInputStream import java.io.IOException import java.lang.Exception import java.net.URLConnection import kotlin.jvm.Synchronized object IntentUtils { private fun buildIntent(context: Context, file: File, mime: String?): Intent { val intent = Intent(Intent.ACTION_VIEW) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { val uri = FileProvider.getUriForFile( context, context.packageName + ".flutter_downloader.provider", file ) intent.setDataAndType(uri, mime) } else { intent.setDataAndType(Uri.fromFile(file), mime) } intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) return intent } @Synchronized fun validatedFileIntent(context: Context, path: String, contentType: String?): Intent? { val file = File(path) var intent = buildIntent(context, file, contentType) if (canBeHandled(context, intent)) { return intent } var mime: String? = null var inputFile: FileInputStream? = null try { inputFile = FileInputStream(path) mime = URLConnection.guessContentTypeFromStream(inputFile) // fails sometimes } catch (e: Exception) { e.printStackTrace() } finally { if (inputFile != null) { try { inputFile.close() } catch (e: IOException) { e.printStackTrace() } } } if (mime == null) { mime = URLConnection.guessContentTypeFromName(path) // fallback to check file extension } if (mime != null) { intent = buildIntent(context, file, mime) if (canBeHandled(context, intent)) return intent } return null } private fun canBeHandled(context: Context, intent: Intent): Boolean { val manager = context.packageManager val results = manager.queryIntentActivities(intent, 0) // return if there is at least one app that can handle this intent return results.size > 0 } }
webview_download_test/flutter_downloader/android/src/main/kotlin/vn/hunghd/flutterdownloader/DownloadStatus.kt
492954288
package vn.hunghd.flutterdownloader enum class DownloadStatus { UNDEFINED, ENQUEUED, RUNNING, COMPLETE, FAILED, CANCELED, PAUSED }
webview_download_test/flutter_downloader/android/src/main/kotlin/vn/hunghd/flutterdownloader/TaskEntry.kt
3733632638
package vn.hunghd.flutterdownloader import android.provider.BaseColumns object TaskEntry : BaseColumns { const val TABLE_NAME = "task" const val COLUMN_NAME_TASK_ID = "task_id" const val COLUMN_NAME_STATUS = "status" const val COLUMN_NAME_PROGRESS = "progress" const val COLUMN_NAME_URL = "url" const val COLUMN_NAME_SAVED_DIR = "saved_dir" const val COLUMN_NAME_FILE_NAME = "file_name" const val COLUMN_NAME_MIME_TYPE = "mime_type" const val COLUMN_NAME_RESUMABLE = "resumable" const val COLUMN_NAME_HEADERS = "headers" const val COLUMN_NAME_SHOW_NOTIFICATION = "show_notification" const val COLUMN_NAME_OPEN_FILE_FROM_NOTIFICATION = "open_file_from_notification" const val COLUMN_NAME_TIME_CREATED = "time_created" const val COLUMN_SAVE_IN_PUBLIC_STORAGE = "save_in_public_storage" const val COLUMN_ALLOW_CELLULAR = "allow_cellular" }
webview_download_test/flutter_downloader/android/src/main/kotlin/vn/hunghd/flutterdownloader/FlutterDownloaderInitializer.kt
3756968175
package vn.hunghd.flutterdownloader import android.content.ComponentName import android.content.ContentProvider import android.content.ContentValues import android.content.Context import android.content.pm.PackageManager import android.content.pm.PackageManager.NameNotFoundException import android.net.Uri import android.util.Log import androidx.work.Configuration import androidx.work.WorkManager import java.util.concurrent.Executors class FlutterDownloaderInitializer : ContentProvider() { companion object { private const val TAG = "DownloaderInitializer" private const val DEFAULT_MAX_CONCURRENT_TASKS = 3 } override fun onCreate(): Boolean { val context = requireNotNull(this.context) { "Cannot find context from the provider." } val maximumConcurrentTask = getMaxConcurrentTaskMetadata(context) WorkManager.initialize( context, Configuration.Builder() .setExecutor(Executors.newFixedThreadPool(maximumConcurrentTask)) .build() ) return true } override fun query(uri: Uri, strings: Array<String>?, s: String?, strings1: Array<String>?, s1: String?): Nothing? = null override fun getType(uri: Uri): Nothing? = null override fun insert(uri: Uri, contentValues: ContentValues?): Uri? = null override fun delete(uri: Uri, s: String?, strings: Array<String>?) = 0 override fun update(uri: Uri, contentValues: ContentValues?, s: String?, strings: Array<String>?) = 0 private fun getMaxConcurrentTaskMetadata(context: Context): Int { try { val providerInfo = context.packageManager.getProviderInfo( ComponentName(context, "vn.hunghd.flutterdownloader.FlutterDownloaderInitializer"), PackageManager.GET_META_DATA ) val bundle = providerInfo.metaData val max = bundle.getInt( "vn.hunghd.flutterdownloader.MAX_CONCURRENT_TASKS", DEFAULT_MAX_CONCURRENT_TASKS ) Log.d(TAG, "MAX_CONCURRENT_TASKS = $max") return max } catch (e: NameNotFoundException) { Log.e(TAG, "Failed to load meta-data, NameNotFound: " + e.message) } catch (e: NullPointerException) { Log.e(TAG, "Failed to load meta-data, NullPointer: " + e.message) } return DEFAULT_MAX_CONCURRENT_TASKS } }
webview_download_test/flutter_downloader/android/src/main/kotlin/vn/hunghd/flutterdownloader/DownloadTask.kt
1531714841
package vn.hunghd.flutterdownloader data class DownloadTask( var primaryId: Int, var taskId: String, var status: DownloadStatus, var progress: Int, var url: String, var filename: String?, var savedDir: String, var headers: String, var mimeType: String, var resumable: Boolean, var showNotification: Boolean, var openFileFromNotification: Boolean, var timeCreated: Long, var saveInPublicStorage: Boolean, var allowCellular: Boolean )
webview_download_test/flutter_downloader/android/src/main/kotlin/vn/hunghd/flutterdownloader/TaskDbHelper.kt
3400468753
package vn.hunghd.flutterdownloader import android.content.Context import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper import android.provider.BaseColumns class TaskDbHelper private constructor(context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) { override fun onCreate(db: SQLiteDatabase) { db.execSQL(SQL_CREATE_ENTRIES) } override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { if (newVersion == 4) { db.execSQL("ALTER TABLE ${TaskEntry.TABLE_NAME} ADD COLUMN ${TaskEntry.COLUMN_ALLOW_CELLULAR} TINYINT DEFAULT 1") } else if (oldVersion == 2 && newVersion == 3) { db.execSQL("ALTER TABLE " + TaskEntry.TABLE_NAME + " ADD COLUMN " + TaskEntry.COLUMN_SAVE_IN_PUBLIC_STORAGE + " TINYINT DEFAULT 0") } else { db.execSQL(SQL_DELETE_ENTRIES) onCreate(db) } } override fun onDowngrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { onUpgrade(db, oldVersion, newVersion) } companion object { const val DATABASE_VERSION = 4 const val DATABASE_NAME = "download_tasks.db" private var instance: TaskDbHelper? = null private const val SQL_CREATE_ENTRIES = ( "CREATE TABLE " + TaskEntry.TABLE_NAME + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY," + TaskEntry.COLUMN_NAME_TASK_ID + " VARCHAR(256), " + TaskEntry.COLUMN_NAME_URL + " TEXT, " + TaskEntry.COLUMN_NAME_STATUS + " INTEGER DEFAULT 0, " + TaskEntry.COLUMN_NAME_PROGRESS + " INTEGER DEFAULT 0, " + TaskEntry.COLUMN_NAME_FILE_NAME + " TEXT, " + TaskEntry.COLUMN_NAME_SAVED_DIR + " TEXT, " + TaskEntry.COLUMN_NAME_HEADERS + " TEXT, " + TaskEntry.COLUMN_NAME_MIME_TYPE + " VARCHAR(128), " + TaskEntry.COLUMN_NAME_RESUMABLE + " TINYINT DEFAULT 0, " + TaskEntry.COLUMN_NAME_SHOW_NOTIFICATION + " TINYINT DEFAULT 0, " + TaskEntry.COLUMN_NAME_OPEN_FILE_FROM_NOTIFICATION + " TINYINT DEFAULT 0, " + TaskEntry.COLUMN_NAME_TIME_CREATED + " INTEGER DEFAULT 0, " + TaskEntry.COLUMN_SAVE_IN_PUBLIC_STORAGE + " TINYINT DEFAULT 0, " + TaskEntry.COLUMN_ALLOW_CELLULAR + " TINYINT DEFAULT 1" + ")" ) private const val SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS ${TaskEntry.TABLE_NAME}" fun getInstance(ctx: Context?): TaskDbHelper { // Use the application context, which will ensure that you // don't accidentally leak an Activity's context. // See this article for more information: http://bit.ly/6LRzfx if (instance == null) { instance = TaskDbHelper(ctx!!.applicationContext) } return instance!! } } }
webview_download_test/flutter_downloader/android/src/main/kotlin/vn/hunghd/flutterdownloader/DownloadedFileProvider.kt
949855946
package vn.hunghd.flutterdownloader import androidx.core.content.FileProvider class DownloadedFileProvider : FileProvider()
webview_download_test/flutter_downloader/android/src/main/kotlin/vn/hunghd/flutterdownloader/DownloadWorker.kt
1466250551
package vn.hunghd.flutterdownloader import android.Manifest import android.annotation.SuppressLint import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.ContentValues import android.content.Context import android.content.SharedPreferences import android.content.pm.ApplicationInfo import android.content.pm.PackageManager import android.net.Uri import android.os.Build import android.os.Environment import android.os.Handler import android.provider.MediaStore import android.util.Log import androidx.annotation.RequiresApi import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.core.content.ContextCompat import androidx.work.Worker import androidx.work.WorkerParameters import io.flutter.FlutterInjector import io.flutter.embedding.engine.FlutterEngine import io.flutter.embedding.engine.dart.DartExecutor import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.MethodChannel import io.flutter.view.FlutterCallbackInformation import org.json.JSONException import org.json.JSONObject import java.io.File import java.io.FileOutputStream import java.io.IOException import java.io.InputStream import java.io.OutputStream import java.io.UnsupportedEncodingException import java.net.HttpURLConnection import java.net.URL import java.net.URLDecoder import java.security.SecureRandom import java.security.cert.X509Certificate import java.util.ArrayDeque import java.util.Locale import java.util.concurrent.atomic.AtomicBoolean import java.util.regex.Pattern import javax.net.ssl.HostnameVerifier import javax.net.ssl.HttpsURLConnection import javax.net.ssl.SSLContext import javax.net.ssl.TrustManager import javax.net.ssl.X509TrustManager class DownloadWorker(context: Context, params: WorkerParameters) : Worker(context, params), MethodChannel.MethodCallHandler { private val charsetPattern = Pattern.compile("(?i)\\bcharset=\\s*\"?([^\\s;\"]*)") private val filenameStarPattern = Pattern.compile("(?i)\\bfilename\\*=([^']+)'([^']*)'\"?([^\"]+)\"?") private val filenamePattern = Pattern.compile("(?i)\\bfilename=\"?([^\"]+)\"?") private var backgroundChannel: MethodChannel? = null private var dbHelper: TaskDbHelper? = null private var taskDao: TaskDao? = null private var showNotification = false private var clickToOpenDownloadedFile = false private var debug = false private var ignoreSsl = false private var lastProgress = 0 private var primaryId = 0 private var msgStarted: String? = null private var msgInProgress: String? = null private var msgCanceled: String? = null private var msgFailed: String? = null private var msgPaused: String? = null private var msgComplete: String? = null private var lastCallUpdateNotification: Long = 0 private var step = 0 private var saveInPublicStorage = false private fun startBackgroundIsolate(context: Context) { synchronized(isolateStarted) { if (backgroundFlutterEngine == null) { val pref: SharedPreferences = context.getSharedPreferences( FlutterDownloaderPlugin.SHARED_PREFERENCES_KEY, Context.MODE_PRIVATE ) val callbackHandle: Long = pref.getLong( FlutterDownloaderPlugin.CALLBACK_DISPATCHER_HANDLE_KEY, 0 ) backgroundFlutterEngine = FlutterEngine(applicationContext, null, false) // We need to create an instance of `FlutterEngine` before looking up the // callback. If we don't, the callback cache won't be initialized and the // lookup will fail. val flutterCallback: FlutterCallbackInformation? = FlutterCallbackInformation.lookupCallbackInformation(callbackHandle) if (flutterCallback == null) { log("Fatal: failed to find callback") return } val appBundlePath: String = FlutterInjector.instance().flutterLoader().findAppBundlePath() val assets = applicationContext.assets backgroundFlutterEngine?.dartExecutor?.executeDartCallback( DartExecutor.DartCallback( assets, appBundlePath, flutterCallback ) ) } } backgroundChannel = MethodChannel( backgroundFlutterEngine!!.dartExecutor, "vn.hunghd/downloader_background" ) backgroundChannel?.setMethodCallHandler(this) } override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { if (call.method.equals("didInitializeDispatcher")) { synchronized(isolateStarted) { while (!isolateQueue.isEmpty()) { backgroundChannel?.invokeMethod("", isolateQueue.remove()) } isolateStarted.set(true) result.success(null) } } else { result.notImplemented() } } override fun onStopped() { val context: Context = applicationContext dbHelper = TaskDbHelper.getInstance(context) taskDao = TaskDao(dbHelper!!) val url: String? = inputData.getString(ARG_URL) val filename: String? = inputData.getString(ARG_FILE_NAME) val task = taskDao?.loadTask(id.toString()) if (task != null && task.status == DownloadStatus.ENQUEUED) { updateNotification(context, filename ?: url, DownloadStatus.CANCELED, -1, null, true) taskDao?.updateTask(id.toString(), DownloadStatus.CANCELED, lastProgress) } } override fun doWork(): Result { dbHelper = TaskDbHelper.getInstance(applicationContext) taskDao = TaskDao(dbHelper!!) val url: String = inputData.getString(ARG_URL) ?: throw IllegalArgumentException("Argument '$ARG_URL' should not be null") val filename: String? = inputData.getString(ARG_FILE_NAME) // ?: throw IllegalArgumentException("Argument '$ARG_FILE_NAME' should not be null") val savedDir: String = inputData.getString(ARG_SAVED_DIR) ?: throw IllegalArgumentException("Argument '$ARG_SAVED_DIR' should not be null") val headers: String = inputData.getString(ARG_HEADERS) ?: throw IllegalArgumentException("Argument '$ARG_HEADERS' should not be null") var isResume: Boolean = inputData.getBoolean(ARG_IS_RESUME, false) val timeout: Int = inputData.getInt(ARG_TIMEOUT, 15000) debug = inputData.getBoolean(ARG_DEBUG, false) step = inputData.getInt(ARG_STEP, 10) ignoreSsl = inputData.getBoolean(ARG_IGNORESSL, false) val res = applicationContext.resources msgStarted = res.getString(R.string.flutter_downloader_notification_started) msgInProgress = res.getString(R.string.flutter_downloader_notification_in_progress) msgCanceled = res.getString(R.string.flutter_downloader_notification_canceled) msgFailed = res.getString(R.string.flutter_downloader_notification_failed) msgPaused = res.getString(R.string.flutter_downloader_notification_paused) msgComplete = res.getString(R.string.flutter_downloader_notification_complete) val task = taskDao?.loadTask(id.toString()) log( "DownloadWorker{url=$url,filename=$filename,savedDir=$savedDir,header=$headers,isResume=$isResume,status=" + ( task?.status ?: "GONE" ) ) // Task has been deleted or cancelled if (task == null || task.status == DownloadStatus.CANCELED) { return Result.success() } showNotification = inputData.getBoolean(ARG_SHOW_NOTIFICATION, false) clickToOpenDownloadedFile = inputData.getBoolean(ARG_OPEN_FILE_FROM_NOTIFICATION, false) saveInPublicStorage = inputData.getBoolean(ARG_SAVE_IN_PUBLIC_STORAGE, false) primaryId = task.primaryId setupNotification(applicationContext) updateNotification( applicationContext, filename ?: url, DownloadStatus.RUNNING, task.progress, null, false ) taskDao?.updateTask(id.toString(), DownloadStatus.RUNNING, task.progress) // automatic resume for partial files. (if the workmanager unexpectedly quited in background) val saveFilePath = savedDir + File.separator + filename val partialFile = File(saveFilePath) if (partialFile.exists()) { isResume = true log("exists file for " + filename + "automatic resuming...") } return try { downloadFile(applicationContext, url, savedDir, filename, headers, isResume, timeout) cleanUp() dbHelper = null taskDao = null Result.success() } catch (e: Exception) { updateNotification(applicationContext, filename ?: url, DownloadStatus.FAILED, -1, null, true) taskDao?.updateTask(id.toString(), DownloadStatus.FAILED, lastProgress) e.printStackTrace() dbHelper = null taskDao = null Result.failure() } } private fun setupHeaders(conn: HttpURLConnection, headers: String) { if (headers.isNotEmpty()) { log("Headers = $headers") try { val json = JSONObject(headers) val it: Iterator<String> = json.keys() while (it.hasNext()) { val key = it.next() conn.setRequestProperty(key, json.getString(key)) } conn.doInput = true } catch (e: JSONException) { e.printStackTrace() } } } private fun setupPartialDownloadedDataHeader( conn: HttpURLConnection, filename: String?, savedDir: String ): Long { val saveFilePath = savedDir + File.separator + filename val partialFile = File(saveFilePath) val downloadedBytes: Long = partialFile.length() log("Resume download: Range: bytes=$downloadedBytes-") conn.setRequestProperty("Accept-Encoding", "identity") conn.setRequestProperty("Range", "bytes=$downloadedBytes-") conn.doInput = true return downloadedBytes } private fun downloadFile( context: Context, fileURL: String, savedDir: String, filename: String?, headers: String, isResume: Boolean, timeout: Int ) { var actualFilename = filename var url = fileURL var resourceUrl: URL var base: URL? var next: URL val visited: MutableMap<String, Int> var httpConn: HttpURLConnection? = null var inputStream: InputStream? = null var outputStream: OutputStream? = null var location: String var downloadedBytes: Long = 0 var responseCode: Int var times: Int visited = HashMap() try { val task = taskDao?.loadTask(id.toString()) if (task != null) { lastProgress = task.progress } // handle redirection logic while (true) { if (!visited.containsKey(url)) { times = 1 visited[url] = times } else { times = visited[url]!! + 1 } if (times > 3) throw IOException("Stuck in redirect loop") resourceUrl = URL(url) httpConn = if (ignoreSsl) { trustAllHosts() if (resourceUrl.protocol.lowercase(Locale.US) == "https") { val https: HttpsURLConnection = resourceUrl.openConnection() as HttpsURLConnection https.hostnameVerifier = DO_NOT_VERIFY https } else { resourceUrl.openConnection() as HttpURLConnection } } else { if (resourceUrl.protocol.lowercase(Locale.US) == "https") { resourceUrl.openConnection() as HttpsURLConnection } else { resourceUrl.openConnection() as HttpURLConnection } } log("Open connection to $url") httpConn.connectTimeout = timeout httpConn.readTimeout = timeout httpConn.instanceFollowRedirects = false // Make the logic below easier to detect redirections httpConn.setRequestProperty("User-Agent", "Mozilla/5.0...") // setup request headers if it is set setupHeaders(httpConn, headers) // try to continue downloading a file from its partial downloaded data. if (isResume) { downloadedBytes = setupPartialDownloadedDataHeader(httpConn, actualFilename, savedDir) } responseCode = httpConn.responseCode when (responseCode) { HttpURLConnection.HTTP_MOVED_PERM, HttpURLConnection.HTTP_SEE_OTHER, HttpURLConnection.HTTP_MOVED_TEMP, 307, 308 -> { log("Response with redirection code") location = httpConn.getHeaderField("Location") log("Location = $location") base = URL(url) next = URL(base, location) // Deal with relative URLs url = next.toExternalForm() log("New url: $url") continue } } break } httpConn!!.connect() val contentType: String if ((responseCode == HttpURLConnection.HTTP_OK || isResume && responseCode == HttpURLConnection.HTTP_PARTIAL) && !isStopped) { contentType = httpConn.contentType val contentLength: Long = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) httpConn.contentLengthLong else httpConn.contentLength.toLong() log("Content-Type = $contentType") log("Content-Length = $contentLength") val charset = getCharsetFromContentType(contentType) log("Charset = $charset") if (!isResume) { // try to extract filename from HTTP headers if it is not given by user if (actualFilename == null) { val disposition: String? = httpConn.getHeaderField("Content-Disposition") log("Content-Disposition = $disposition") if (!disposition.isNullOrEmpty()) { actualFilename = getFileNameFromContentDisposition(disposition, charset) } if (actualFilename.isNullOrEmpty()) { actualFilename = url.substring(url.lastIndexOf("/") + 1) try { actualFilename = URLDecoder.decode(actualFilename, "UTF-8") } catch (e: IllegalArgumentException) { /* ok, just let filename be not encoded */ e.printStackTrace() } } } } log("fileName = $actualFilename") taskDao?.updateTask(id.toString(), actualFilename, contentType) // opens input stream from the HTTP connection inputStream = httpConn.inputStream val savedFilePath: String? // opens an output stream to save into file // there are two case: if (isResume) { // 1. continue downloading (append data to partial downloaded file) savedFilePath = savedDir + File.separator + actualFilename outputStream = FileOutputStream(savedFilePath, true) } else { // 2. new download, create new file // there are two case according to Android SDK version and save path // From Android 11 onwards, file is only downloaded to app-specific directory (internal storage) // or public shared download directory (external storage). // The second option will ignore `savedDir` parameter. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && saveInPublicStorage) { val uri = createFileInPublicDownloadsDir(actualFilename, contentType) savedFilePath = getMediaStoreEntryPathApi29(uri!!) outputStream = context.contentResolver.openOutputStream(uri, "w") } else { val file = createFileInAppSpecificDir(actualFilename!!, savedDir) savedFilePath = file!!.path outputStream = FileOutputStream(file, false) } } var count = downloadedBytes var bytesRead: Int val buffer = ByteArray(BUFFER_SIZE) // using isStopped to monitor canceling task while (inputStream.read(buffer).also { bytesRead = it } != -1 && !isStopped) { count += bytesRead.toLong() val progress = (count * 100 / (contentLength + downloadedBytes)).toInt() outputStream?.write(buffer, 0, bytesRead) if ((lastProgress == 0 || progress > lastProgress + step || progress == 100) && progress != lastProgress ) { lastProgress = progress // This line possibly causes system overloaded because of accessing to DB too many ?!!! // but commenting this line causes tasks loaded from DB missing current downloading progress, // however, this missing data should be temporary and it will be updated as soon as // a new bunch of data fetched and a notification sent taskDao!!.updateTask(id.toString(), DownloadStatus.RUNNING, progress) updateNotification( context, actualFilename, DownloadStatus.RUNNING, progress, null, false ) } } val loadedTask = taskDao?.loadTask(id.toString()) val progress = if (isStopped && loadedTask!!.resumable) lastProgress else 100 val status = if (isStopped) if (loadedTask!!.resumable) DownloadStatus.PAUSED else DownloadStatus.CANCELED else DownloadStatus.COMPLETE val storage: Int = ContextCompat.checkSelfPermission( applicationContext, Manifest.permission.WRITE_EXTERNAL_STORAGE ) var pendingIntent: PendingIntent? = null if (status == DownloadStatus.COMPLETE) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) { if (isImageOrVideoFile(contentType) && isExternalStoragePath(savedFilePath)) { addImageOrVideoToGallery( actualFilename, savedFilePath, getContentTypeWithoutCharset(contentType) ) } } if (clickToOpenDownloadedFile) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q && storage != PackageManager.PERMISSION_GRANTED) return val intent = IntentUtils.validatedFileIntent( applicationContext, savedFilePath!!, contentType ) if (intent != null) { log("Setting an intent to open the file $savedFilePath") val flags: Int = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) PendingIntent.FLAG_CANCEL_CURRENT or PendingIntent.FLAG_IMMUTABLE else PendingIntent.FLAG_CANCEL_CURRENT pendingIntent = PendingIntent.getActivity(applicationContext, 0, intent, flags) } else { log("There's no application that can open the file $savedFilePath") } } } taskDao!!.updateTask(id.toString(), status, progress) updateNotification(context, actualFilename, status, progress, pendingIntent, true) log(if (isStopped) "Download canceled" else "File downloaded") } else { val loadedTask = taskDao!!.loadTask(id.toString()) val status = if (isStopped) if (loadedTask!!.resumable) DownloadStatus.PAUSED else DownloadStatus.CANCELED else DownloadStatus.FAILED taskDao!!.updateTask(id.toString(), status, lastProgress) updateNotification(context, actualFilename ?: fileURL, status, -1, null, true) log(if (isStopped) "Download canceled" else "Server replied HTTP code: $responseCode") } } catch (e: IOException) { taskDao!!.updateTask(id.toString(), DownloadStatus.FAILED, lastProgress) updateNotification(context, actualFilename ?: fileURL, DownloadStatus.FAILED, -1, null, true) e.printStackTrace() } finally { if (outputStream != null) { outputStream.flush() try { outputStream.close() } catch (e: IOException) { e.printStackTrace() } } if (inputStream != null) { try { inputStream.close() } catch (e: IOException) { e.printStackTrace() } } httpConn?.disconnect() } } /** * Create a file using java.io API */ private fun createFileInAppSpecificDir(filename: String, savedDir: String): File? { val newFile = File(savedDir, filename) try { val rs: Boolean = newFile.createNewFile() if (rs) { return newFile } else { logError("It looks like you are trying to save file in public storage but not setting 'saveInPublicStorage' to 'true'") } } catch (e: IOException) { e.printStackTrace() logError("Create a file using java.io API failed ") } return null } /** * Create a file inside the Download folder using MediaStore API */ @RequiresApi(Build.VERSION_CODES.Q) private fun createFileInPublicDownloadsDir(filename: String?, mimeType: String): Uri? { val collection: Uri = MediaStore.Downloads.EXTERNAL_CONTENT_URI val values = ContentValues() values.put(MediaStore.Downloads.DISPLAY_NAME, filename) values.put(MediaStore.Downloads.MIME_TYPE, mimeType) values.put(MediaStore.Downloads.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS) val contentResolver = applicationContext.contentResolver try { return contentResolver.insert(collection, values) } catch (e: Exception) { e.printStackTrace() logError("Create a file using MediaStore API failed.") } return null } /** * Get a path for a MediaStore entry as it's needed when calling MediaScanner */ private fun getMediaStoreEntryPathApi29(uri: Uri): String? { try { applicationContext.contentResolver.query( uri, arrayOf(MediaStore.Files.FileColumns.DATA), null, null, null ).use { cursor -> if (cursor == null) return null return if (!cursor.moveToFirst()) { null } else { cursor.getString( cursor.getColumnIndexOrThrow( MediaStore.Files.FileColumns.DATA ) ) } } } catch (e: IllegalArgumentException) { e.printStackTrace() logError("Get a path for a MediaStore failed") return null } } private fun cleanUp() { val task = taskDao!!.loadTask(id.toString()) if (task != null && task.status != DownloadStatus.COMPLETE && !task.resumable) { var filename = task.filename if (filename == null) { filename = task.url.substring(task.url.lastIndexOf("/") + 1, task.url.length) } // check and delete uncompleted file val saveFilePath = task.savedDir + File.separator + filename val tempFile = File(saveFilePath) if (tempFile.exists()) { tempFile.delete() } } } private val notificationIconRes: Int get() { try { val applicationInfo: ApplicationInfo = applicationContext.packageManager .getApplicationInfo( applicationContext.packageName, PackageManager.GET_META_DATA ) val appIconResId: Int = applicationInfo.icon return applicationInfo.metaData.getInt( "vn.hunghd.flutterdownloader.NOTIFICATION_ICON", appIconResId ) } catch (e: PackageManager.NameNotFoundException) { e.printStackTrace() } return 0 } private fun setupNotification(context: Context) { if (!showNotification) return // Make a channel if necessary if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // Create the NotificationChannel val res = applicationContext.resources val channelName: String = res.getString(R.string.flutter_downloader_notification_channel_name) val channelDescription: String = res.getString(R.string.flutter_downloader_notification_channel_description) val importance: Int = NotificationManager.IMPORTANCE_LOW val channel = NotificationChannel(CHANNEL_ID, channelName, importance) channel.description = channelDescription channel.setSound(null, null) // Add the channel val notificationManager: NotificationManagerCompat = NotificationManagerCompat.from(context) notificationManager.createNotificationChannel(channel) } } private fun updateNotification( context: Context, title: String?, status: DownloadStatus, progress: Int, intent: PendingIntent?, finalize: Boolean ) { sendUpdateProcessEvent(status, progress) // Show the notification if (showNotification) { // Create the notification val builder = NotificationCompat.Builder(context, CHANNEL_ID).setContentTitle(title) .setContentIntent(intent) .setOnlyAlertOnce(true) .setAutoCancel(true) .setPriority(NotificationCompat.PRIORITY_LOW) when (status) { DownloadStatus.RUNNING -> { if (progress <= 0) { builder.setContentText(msgStarted) .setProgress(0, 0, false) builder.setOngoing(false) .setSmallIcon(notificationIconRes) } else if (progress < 100) { builder.setContentText(msgInProgress) .setProgress(100, progress, false) builder.setOngoing(true) .setSmallIcon(android.R.drawable.stat_sys_download) } else { builder.setContentText(msgComplete).setProgress(0, 0, false) builder.setOngoing(false) .setSmallIcon(android.R.drawable.stat_sys_download_done) } } DownloadStatus.CANCELED -> { builder.setContentText(msgCanceled).setProgress(0, 0, false) builder.setOngoing(false) .setSmallIcon(android.R.drawable.stat_sys_download_done) } DownloadStatus.FAILED -> { builder.setContentText(msgFailed).setProgress(0, 0, false) builder.setOngoing(false) .setSmallIcon(android.R.drawable.stat_sys_download_done) } DownloadStatus.PAUSED -> { builder.setContentText(msgPaused).setProgress(0, 0, false) builder.setOngoing(false) .setSmallIcon(android.R.drawable.stat_sys_download_done) } DownloadStatus.COMPLETE -> { builder.setContentText(msgComplete).setProgress(0, 0, false) builder.setOngoing(false) .setSmallIcon(android.R.drawable.stat_sys_download_done) } else -> { builder.setProgress(0, 0, false) builder.setOngoing(false).setSmallIcon(notificationIconRes) } } // Note: Android applies a rate limit when updating a notification. // If you post updates to a notification too frequently (many in less than one second), // the system might drop some updates. (https://developer.android.com/training/notify-user/build-notification#Updating) // // If this is progress update, it's not much important if it is dropped because there're still incoming updates later // If this is the final update, it must be success otherwise the notification will be stuck at the processing state // In order to ensure the final one is success, we check and sleep a second if need. if (System.currentTimeMillis() - lastCallUpdateNotification < 1000) { if (finalize) { log("Update too frequently!!!!, but it is the final update, we should sleep a second to ensure the update call can be processed") try { Thread.sleep(1000) } catch (e: InterruptedException) { e.printStackTrace() } } else { log("Update too frequently!!!!, this should be dropped") return } } log("Update notification: {notificationId: $primaryId, title: $title, status: $status, progress: $progress}") NotificationManagerCompat.from(context).notify(primaryId, builder.build()) lastCallUpdateNotification = System.currentTimeMillis() } } private fun sendUpdateProcessEvent(status: DownloadStatus, progress: Int) { val args: MutableList<Any> = ArrayList() val callbackHandle: Long = inputData.getLong(ARG_CALLBACK_HANDLE, 0) args.add(callbackHandle) args.add(id.toString()) args.add(status.ordinal) args.add(progress) synchronized(isolateStarted) { if (!isolateStarted.get()) { isolateQueue.add(args) } else { Handler(applicationContext.mainLooper).post { backgroundChannel?.invokeMethod("", args) } } } } private fun getCharsetFromContentType(contentType: String?): String? { if (contentType == null) return null val m = charsetPattern.matcher(contentType) return if (m.find()) { m.group(1)?.trim { it <= ' ' }?.uppercase(Locale.US) } else { null } } @Throws(UnsupportedEncodingException::class) private fun getFileNameFromContentDisposition( disposition: String?, contentCharset: String? ): String? { if (disposition == null) return null var name: String? = null var charset = contentCharset // first, match plain filename, and then replace it with star filename, to follow the spec val plainMatcher = filenamePattern.matcher(disposition) if (plainMatcher.find()) name = plainMatcher.group(1) val starMatcher = filenameStarPattern.matcher(disposition) if (starMatcher.find()) { name = starMatcher.group(3) charset = starMatcher.group(1)?.uppercase(Locale.US) } return if (name == null) { null } else { URLDecoder.decode( name, charset ?: "ISO-8859-1" ) } } private fun getContentTypeWithoutCharset(contentType: String?): String? { return contentType?.split(";")?.toTypedArray()?.get(0)?.trim { it <= ' ' } } private fun isImageOrVideoFile(contentType: String): Boolean { val newContentType = getContentTypeWithoutCharset(contentType) return newContentType != null && (newContentType.startsWith("image/") || newContentType.startsWith("video")) } private fun isExternalStoragePath(filePath: String?): Boolean { val externalStorageDir: File = Environment.getExternalStorageDirectory() return filePath != null && filePath.startsWith( externalStorageDir.path ) } private fun addImageOrVideoToGallery( fileName: String?, filePath: String?, contentType: String? ) { if (contentType != null && filePath != null && fileName != null) { if (contentType.startsWith("image/")) { val values = ContentValues() values.put(MediaStore.Images.Media.TITLE, fileName) values.put(MediaStore.Images.Media.DISPLAY_NAME, fileName) values.put(MediaStore.Images.Media.DESCRIPTION, "") values.put(MediaStore.Images.Media.MIME_TYPE, contentType) values.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis()) values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis()) values.put(MediaStore.Images.Media.DATA, filePath) log("insert $values to MediaStore") val contentResolver = applicationContext.contentResolver contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values) } else if (contentType.startsWith("video")) { val values = ContentValues() values.put(MediaStore.Video.Media.TITLE, fileName) values.put(MediaStore.Video.Media.DISPLAY_NAME, fileName) values.put(MediaStore.Video.Media.DESCRIPTION, "") values.put(MediaStore.Video.Media.MIME_TYPE, contentType) values.put(MediaStore.Video.Media.DATE_ADDED, System.currentTimeMillis()) values.put(MediaStore.Video.Media.DATE_TAKEN, System.currentTimeMillis()) values.put(MediaStore.Video.Media.DATA, filePath) log("insert $values to MediaStore") val contentResolver = applicationContext.contentResolver contentResolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values) } } } private fun log(message: String) { if (debug) { Log.d(TAG, message) } } private fun logError(message: String) { if (debug) { Log.e(TAG, message) } } companion object { const val ARG_URL = "url" const val ARG_FILE_NAME = "file_name" const val ARG_SAVED_DIR = "saved_file" const val ARG_HEADERS = "headers" const val ARG_IS_RESUME = "is_resume" const val ARG_TIMEOUT = "timeout" const val ARG_SHOW_NOTIFICATION = "show_notification" const val ARG_OPEN_FILE_FROM_NOTIFICATION = "open_file_from_notification" const val ARG_CALLBACK_HANDLE = "callback_handle" const val ARG_DEBUG = "debug" const val ARG_STEP = "step" const val ARG_SAVE_IN_PUBLIC_STORAGE = "save_in_public_storage" const val ARG_IGNORESSL = "ignoreSsl" private val TAG = DownloadWorker::class.java.simpleName private const val BUFFER_SIZE = 4096 private const val CHANNEL_ID = "FLUTTER_DOWNLOADER_NOTIFICATION" private val isolateStarted = AtomicBoolean(false) private val isolateQueue = ArrayDeque<List<Any>>() private var backgroundFlutterEngine: FlutterEngine? = null val DO_NOT_VERIFY = HostnameVerifier { _, _ -> true } /** * Trust every server - dont check for any certificate */ private fun trustAllHosts() { val tag = "trustAllHosts" // Create a trust manager that does not validate certificate chains val trustManagers: Array<TrustManager> = arrayOf( @SuppressLint("CustomX509TrustManager") object : X509TrustManager { override fun checkClientTrusted( chain: Array<X509Certificate>, authType: String ) { Log.i(tag, "checkClientTrusted") } override fun checkServerTrusted( chain: Array<X509Certificate>, authType: String ) { Log.i(tag, "checkServerTrusted") } override fun getAcceptedIssuers(): Array<out X509Certificate> = emptyArray() } ) // Install the all-trusting trust manager try { val sslContent: SSLContext = SSLContext.getInstance("TLS") sslContent.init(null, trustManagers, SecureRandom()) HttpsURLConnection.setDefaultSSLSocketFactory(sslContent.socketFactory) } catch (e: Exception) { e.printStackTrace() } } } init { Handler(context.mainLooper).post { startBackgroundIsolate(context) } } }
webview_download_test/flutter_downloader/android/src/main/kotlin/vn/hunghd/flutterdownloader/TaskDao.kt
803343808
package vn.hunghd.flutterdownloader import android.content.ContentValues import android.database.Cursor import android.database.sqlite.SQLiteDatabase import android.provider.BaseColumns class TaskDao(private val dbHelper: TaskDbHelper) { private val projection = arrayOf( BaseColumns._ID, TaskEntry.COLUMN_NAME_TASK_ID, TaskEntry.COLUMN_NAME_PROGRESS, TaskEntry.COLUMN_NAME_STATUS, TaskEntry.COLUMN_NAME_URL, TaskEntry.COLUMN_NAME_FILE_NAME, TaskEntry.COLUMN_NAME_SAVED_DIR, TaskEntry.COLUMN_NAME_HEADERS, TaskEntry.COLUMN_NAME_MIME_TYPE, TaskEntry.COLUMN_NAME_RESUMABLE, TaskEntry.COLUMN_NAME_OPEN_FILE_FROM_NOTIFICATION, TaskEntry.COLUMN_NAME_SHOW_NOTIFICATION, TaskEntry.COLUMN_NAME_TIME_CREATED, TaskEntry.COLUMN_SAVE_IN_PUBLIC_STORAGE, TaskEntry.COLUMN_ALLOW_CELLULAR ) fun insertOrUpdateNewTask( taskId: String?, url: String?, status: DownloadStatus, progress: Int, fileName: String?, savedDir: String?, headers: String?, showNotification: Boolean, openFileFromNotification: Boolean, saveInPublicStorage: Boolean, allowCellular: Boolean ) { val db = dbHelper.writableDatabase val values = ContentValues() values.put(TaskEntry.COLUMN_NAME_TASK_ID, taskId) values.put(TaskEntry.COLUMN_NAME_URL, url) values.put(TaskEntry.COLUMN_NAME_STATUS, status.ordinal) values.put(TaskEntry.COLUMN_NAME_PROGRESS, progress) values.put(TaskEntry.COLUMN_NAME_FILE_NAME, fileName) values.put(TaskEntry.COLUMN_NAME_SAVED_DIR, savedDir) values.put(TaskEntry.COLUMN_NAME_HEADERS, headers) values.put(TaskEntry.COLUMN_NAME_MIME_TYPE, "unknown") values.put(TaskEntry.COLUMN_NAME_SHOW_NOTIFICATION, if (showNotification) 1 else 0) values.put( TaskEntry.COLUMN_NAME_OPEN_FILE_FROM_NOTIFICATION, if (openFileFromNotification) 1 else 0 ) values.put(TaskEntry.COLUMN_NAME_RESUMABLE, 0) values.put(TaskEntry.COLUMN_NAME_TIME_CREATED, System.currentTimeMillis()) values.put(TaskEntry.COLUMN_SAVE_IN_PUBLIC_STORAGE, if (saveInPublicStorage) 1 else 0) values.put(TaskEntry.COLUMN_ALLOW_CELLULAR, if (allowCellular) 1 else 0) db.beginTransaction() try { db.insertWithOnConflict( TaskEntry.TABLE_NAME, null, values, SQLiteDatabase.CONFLICT_REPLACE ) db.setTransactionSuccessful() } catch (e: Exception) { e.printStackTrace() } finally { db.endTransaction() } } fun loadAllTasks(): List<DownloadTask> { val db = dbHelper.readableDatabase val cursor = db.query( TaskEntry.TABLE_NAME, projection, null, null, null, null, null ) val result: MutableList<DownloadTask> = ArrayList() while (cursor.moveToNext()) { result.add(parseCursor(cursor)) } cursor.close() return result } fun loadTasksWithRawQuery(query: String?): List<DownloadTask> { val db = dbHelper.readableDatabase val cursor = db.rawQuery(query, null) val result: MutableList<DownloadTask> = ArrayList() while (cursor.moveToNext()) { result.add(parseCursor(cursor)) } cursor.close() return result } fun loadTask(taskId: String): DownloadTask? { val db = dbHelper.readableDatabase val whereClause = TaskEntry.COLUMN_NAME_TASK_ID + " = ?" val whereArgs = arrayOf(taskId) val cursor = db.query( TaskEntry.TABLE_NAME, projection, whereClause, whereArgs, null, null, BaseColumns._ID + " DESC", "1" ) var result: DownloadTask? = null while (cursor.moveToNext()) { result = parseCursor(cursor) } cursor.close() return result } fun updateTask(taskId: String, status: DownloadStatus, progress: Int) { val db = dbHelper.writableDatabase val values = ContentValues() values.put(TaskEntry.COLUMN_NAME_STATUS, status.ordinal) values.put(TaskEntry.COLUMN_NAME_PROGRESS, progress) db.beginTransaction() try { db.update( TaskEntry.TABLE_NAME, values, TaskEntry.COLUMN_NAME_TASK_ID + " = ?", arrayOf(taskId) ) db.setTransactionSuccessful() } catch (e: Exception) { e.printStackTrace() } finally { db.endTransaction() } } fun updateTask( currentTaskId: String, newTaskId: String?, status: DownloadStatus, progress: Int, resumable: Boolean ) { val db = dbHelper.writableDatabase val values = ContentValues() values.put(TaskEntry.COLUMN_NAME_TASK_ID, newTaskId) values.put(TaskEntry.COLUMN_NAME_STATUS, status.ordinal) values.put(TaskEntry.COLUMN_NAME_PROGRESS, progress) values.put(TaskEntry.COLUMN_NAME_RESUMABLE, if (resumable) 1 else 0) values.put(TaskEntry.COLUMN_NAME_TIME_CREATED, System.currentTimeMillis()) db.beginTransaction() try { db.update( TaskEntry.TABLE_NAME, values, TaskEntry.COLUMN_NAME_TASK_ID + " = ?", arrayOf(currentTaskId) ) db.setTransactionSuccessful() } catch (e: Exception) { e.printStackTrace() } finally { db.endTransaction() } } fun updateTask(taskId: String, resumable: Boolean) { val db = dbHelper.writableDatabase val values = ContentValues() values.put(TaskEntry.COLUMN_NAME_RESUMABLE, if (resumable) 1 else 0) db.beginTransaction() try { db.update( TaskEntry.TABLE_NAME, values, TaskEntry.COLUMN_NAME_TASK_ID + " = ?", arrayOf(taskId) ) db.setTransactionSuccessful() } catch (e: Exception) { e.printStackTrace() } finally { db.endTransaction() } } fun updateTask(taskId: String, filename: String?, mimeType: String?) { val db = dbHelper.writableDatabase val values = ContentValues() values.put(TaskEntry.COLUMN_NAME_FILE_NAME, filename) values.put(TaskEntry.COLUMN_NAME_MIME_TYPE, mimeType) db.beginTransaction() try { db.update( TaskEntry.TABLE_NAME, values, TaskEntry.COLUMN_NAME_TASK_ID + " = ?", arrayOf(taskId) ) db.setTransactionSuccessful() } catch (e: Exception) { e.printStackTrace() } finally { db.endTransaction() } } fun deleteTask(taskId: String) { val db = dbHelper.writableDatabase db.beginTransaction() try { val whereClause = TaskEntry.COLUMN_NAME_TASK_ID + " = ?" val whereArgs = arrayOf(taskId) db.delete(TaskEntry.TABLE_NAME, whereClause, whereArgs) db.setTransactionSuccessful() } catch (e: Exception) { e.printStackTrace() } finally { db.endTransaction() } } private fun parseCursor(cursor: Cursor): DownloadTask { val primaryId = cursor.getInt(cursor.getColumnIndexOrThrow(BaseColumns._ID)) val taskId = cursor.getString(cursor.getColumnIndexOrThrow(TaskEntry.COLUMN_NAME_TASK_ID)) val status = cursor.getInt(cursor.getColumnIndexOrThrow(TaskEntry.COLUMN_NAME_STATUS)) val progress = cursor.getInt(cursor.getColumnIndexOrThrow(TaskEntry.COLUMN_NAME_PROGRESS)) val url = cursor.getString(cursor.getColumnIndexOrThrow(TaskEntry.COLUMN_NAME_URL)) val filename = cursor.getString(cursor.getColumnIndexOrThrow(TaskEntry.COLUMN_NAME_FILE_NAME)) val savedDir = cursor.getString(cursor.getColumnIndexOrThrow(TaskEntry.COLUMN_NAME_SAVED_DIR)) val headers = cursor.getString(cursor.getColumnIndexOrThrow(TaskEntry.COLUMN_NAME_HEADERS)) val mimeType = cursor.getString(cursor.getColumnIndexOrThrow(TaskEntry.COLUMN_NAME_MIME_TYPE)) val resumable = cursor.getShort(cursor.getColumnIndexOrThrow(TaskEntry.COLUMN_NAME_RESUMABLE)).toInt() val showNotification = cursor.getShort(cursor.getColumnIndexOrThrow(TaskEntry.COLUMN_NAME_SHOW_NOTIFICATION)).toInt() val clickToOpenDownloadedFile = cursor.getShort(cursor.getColumnIndexOrThrow(TaskEntry.COLUMN_NAME_OPEN_FILE_FROM_NOTIFICATION)).toInt() val timeCreated = cursor.getLong(cursor.getColumnIndexOrThrow(TaskEntry.COLUMN_NAME_TIME_CREATED)) val saveInPublicStorage = cursor.getShort(cursor.getColumnIndexOrThrow(TaskEntry.COLUMN_SAVE_IN_PUBLIC_STORAGE)).toInt() val allowCelluar = cursor.getShort(cursor.getColumnIndexOrThrow(TaskEntry.COLUMN_ALLOW_CELLULAR)).toInt() return DownloadTask( primaryId, taskId, DownloadStatus.values()[status], progress, url, filename, savedDir, headers, mimeType, resumable == 1, showNotification == 1, clickToOpenDownloadedFile == 1, timeCreated, saveInPublicStorage == 1, allowCellular = allowCelluar == 1 ) } }
webview_download_test/android/app/src/main/kotlin/com/example/webview_test/MainActivity.kt
2228203775
package com.example.webview_test import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
FocusOnUnitTesting/app/src/androidTest/java/com/bacancy/focusonunittesting/ExampleInstrumentedTest.kt
1649104909
package com.bacancy.focusonunittesting import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.bacancy.focusonunittesting", appContext.packageName) } }
FocusOnUnitTesting/app/src/test/java/com/bacancy/focusonunittesting/ExampleUnitTest.kt
761966399
package com.bacancy.focusonunittesting import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
FocusOnUnitTesting/app/src/main/java/com/bacancy/focusonunittesting/MainActivity.kt
634803765
package com.bacancy.focusonunittesting import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } }
bank-app_google-assistant/app/src/androidTest/java/com/refridev/bankapp/ExampleInstrumentedTest.kt
156556775
package com.refridev.bankapp import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.bankapp", appContext.packageName) } }
bank-app_google-assistant/app/src/test/java/com/refridev/bankapp/ExampleUnitTest.kt
3346757455
package com.refridev.bankapp import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/ui/MainViewModel.kt
2493786221
package com.refridev.bankapp.ui import androidx.lifecycle.ViewModel class MainViewModel : ViewModel() { }
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/ui/MainRepository.kt
3856117416
package com.refridev.bankapp.ui class MainRepository { }
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/ui/transaction/TransactionSuccessContract.kt
2576391578
package com.refridev.bankapp.ui.transaction interface TransactionSuccessContract { }
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/ui/transaction/pin/InputPinContract.kt
3383427541
package com.refridev.bankapp.ui.transaction.pin interface InputPinContract { }
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/ui/transaction/pin/InputPinViewModel.kt
2889500703
package com.refridev.bankapp.ui.transaction.pin import androidx.lifecycle.ViewModel class InputPinViewModel : ViewModel() { }
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/ui/transaction/pin/InputPinActivity.kt
2024274632
package com.refridev.bankapp.ui.transaction.pin import android.content.Context import android.content.Intent import android.text.Editable import android.text.TextWatcher import android.view.View import android.widget.Button import android.widget.Toast import com.refridev.bankapp.R import com.refridev.bankapp.base.BaseActivity import com.refridev.bankapp.databinding.ActivityInputPinBinding import com.refridev.bankapp.ui.transaction.TransactionSuccessActivity class InputPinActivity : BaseActivity<ActivityInputPinBinding, InputPinViewModel>(ActivityInputPinBinding::inflate) { override fun initView() { setTextChangeListener() } private fun setTextChangeListener(){ getViewBinding().etPin.requestFocus() getViewBinding().etPin.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable) {} override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { if (s.isEmpty()){ getViewBinding().btnFingerPrint.visibility = View.VISIBLE getViewBinding().btnDelete.visibility = View.GONE } else { getViewBinding().btnFingerPrint.visibility = View.GONE getViewBinding().btnDelete.visibility = View.VISIBLE } setViewImageState(s.length) if (s.length == 6){ goToSuccessActivity() } } }) } fun onButtonClick(view: View) { if (view is Button) { val digit = view.text.toString() val currentText = getViewBinding().etPin.text.toString() getViewBinding().etPin.setText(currentText + digit) } } fun onFingerprintClick(view: View) { if (view.id == R.id.btn_finger_print) { val toast = Toast.makeText(this, "Fingerprint", Toast.LENGTH_SHORT) toast.show() } } fun onForgotPinClick(view: View){ if (view.id == R.id.btn_forgot_pin) { val toast = Toast.makeText(this, "Forgot PIN", Toast.LENGTH_SHORT) toast.show() } } fun onDeleteClick(view: View) { if (view.id == R.id.btn_delete) { val currentText = getViewBinding().etPin.text.toString() // Check if there is any text in the EditText if (currentText.isNotEmpty()) { // Remove the last character from the text val newText = currentText.substring(0, currentText.length - 1) getViewBinding().etPin.setText(newText) } } } private val circleViews by lazy { arrayOf( getViewBinding().circle1, getViewBinding().circle2, getViewBinding().circle3, getViewBinding().circle4, getViewBinding().circle5, getViewBinding().circle6 ) } private fun setViewImageState(input: Int) { for (i in circleViews.indices) { val backgroundResource = if (i < input) R.drawable.bg_pin_filled else R.drawable.bg_pin circleViews[i].setBackgroundResource(backgroundResource) } } private fun goToSuccessActivity(){ startActivity(TransactionSuccessActivity.getStartIntent(this)) } override fun showContent(isVisible: Boolean) {} override fun showLoading(isVisible: Boolean) {} override fun showError(isErrorEnabled: Boolean, msg: String?) {} companion object { fun getStartIntent(context: Context?): Intent { return Intent(context, InputPinActivity::class.java) } } }
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/ui/transaction/pin/InputPinRepository.kt
508171134
package com.refridev.bankapp.ui.transaction.pin class InputPinRepository { }
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/ui/transaction/amount/InputAmountActivity.kt
3374035970
package com.refridev.bankapp.ui.transaction.amount import android.content.Context import android.content.Intent import android.text.Editable import android.text.TextWatcher import android.view.inputmethod.InputMethodManager import android.widget.EditText import com.refridev.bankapp.R import com.refridev.bankapp.base.BaseActivity import com.refridev.bankapp.databinding.ActivityInputAmountBinding import com.refridev.bankapp.ui.transaction.detail.TransactionDetailActivity class InputAmountActivity : BaseActivity<ActivityInputAmountBinding, InputAmountViewModel> (ActivityInputAmountBinding::inflate) { private var name : String = "" private var account : String = "" private var amount : String = "" override fun initView() { setButtonListener() setTextWatcher() getIntentData() } private fun getIntentData(){ // Extract the data you need from the Intent extras amount = intent.getStringExtra(EXTRA_AMOUNT) ?: "0" name = intent.getStringExtra(EXTRA_NAME) ?: getString(R.string.detail_recipient_name) account = intent.getStringExtra(EXTRA_ACCOUNT) ?: getString(R.string.detail_recipient_acc) if (amount != "0") { // For example, update UI elements with the retrieved data getViewBinding().etAmount.setText(amount) getViewBinding().btnNext.isEnabled = true getViewBinding().btnNext.alpha = 1.0f }else { showKeyboard(getViewBinding().etAmount) } } private fun setButtonListener(){ getViewBinding().btnBack.setOnClickListener { finish() } getViewBinding().btnNext.setOnClickListener { val amount = getViewBinding().etAmount.text.toString() startActivity(TransactionDetailActivity.getStartIntent(this, name, account, amount)) } } private fun setTextWatcher(){ getViewBinding().etAmount.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {} override fun afterTextChanged(s: Editable?) { s?.let { val inputText = it.toString() if (inputText.startsWith("0") && inputText.length > 1) { // If input starts with '0' and has more than one character val firstNonZeroIndex = inputText.indexOfFirst { it != '0' } if (firstNonZeroIndex != -1) { // Replace '0' with the first non-zero digit val replacedText = inputText.substring(firstNonZeroIndex) // Update EditText text only if a replacement was made if (replacedText != inputText) { getViewBinding().etAmount.setText(replacedText) // Set the cursor position to the end of the EditText getViewBinding().etAmount.setSelection(replacedText.length) } } } } if (getViewBinding().etAmount.text.toString().startsWith("0") && getViewBinding().etAmount.text!!.length > 1) { getViewBinding().etAmount.setText("0") getViewBinding().etAmount.setSelection(getViewBinding().etAmount.text.toString().length) } val text = s.toString() val isEnabled = text.isNotEmpty() && text != "0" getViewBinding().btnNext.isEnabled = isEnabled getViewBinding().btnNext.alpha = if (isEnabled) 1.0f else 0.5f } }) getViewBinding().btnNext.isEnabled = false } private fun showKeyboard(editText: EditText) { editText.requestFocus() val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT) getViewBinding().btnNext.isEnabled = false getViewBinding().btnNext.alpha = 0.5f } override fun showContent(isVisible: Boolean) {} override fun showLoading(isVisible: Boolean) {} override fun showError(isErrorEnabled: Boolean, msg: String?) {} companion object { private const val EXTRA_NAME = "EXTRA_NAME" private const val EXTRA_ACCOUNT = "EXTRA_ACCOUNT" private const val EXTRA_AMOUNT = "EXTRA_AMOUNT" private const val EXTRA_VALUE = "value" fun getStartIntent(context: Context?, name: String, account: String, amount: String): Intent { return Intent(context, InputAmountActivity::class.java) .putExtra(EXTRA_NAME, name) .putExtra(EXTRA_ACCOUNT, account) .putExtra(EXTRA_AMOUNT, amount) } } }
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/ui/transaction/amount/InputAmountViewModel.kt
3786902848
package com.refridev.bankapp.ui.transaction.amount import androidx.lifecycle.ViewModel class InputAmountViewModel : ViewModel() { }
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/ui/transaction/amount/InputAmountRepository.kt
1577548642
package com.refridev.bankapp.ui.transaction.amount class InputAmountRepository { }
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/ui/transaction/amount/InputAmountContract.kt
3798618785
package com.refridev.bankapp.ui.transaction.amount interface InputAmountContract { }
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/ui/transaction/TransactionSuccessViewModel.kt
3120558110
package com.refridev.bankapp.ui.transaction import androidx.lifecycle.ViewModel class TransactionSuccessViewModel : ViewModel() { }
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/ui/transaction/TransactionSuccessRepository.kt
1309629471
package com.refridev.bankapp.ui.transaction class TransactionSuccessRepository { }
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/ui/transaction/detail/TransactionDetailRepository.kt
3337852189
package com.refridev.bankapp.ui.transaction.detail class TransactionDetailRepository { }
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/ui/transaction/detail/TransactionDetailContract.kt
951941231
package com.refridev.bankapp.ui.transaction.detail interface TransactionDetailContract { }
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/ui/transaction/detail/TransactionDetailViewModel.kt
1475948970
package com.refridev.bankapp.ui.transaction.detail import androidx.lifecycle.ViewModel class TransactionDetailViewModel : ViewModel() { }
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/ui/transaction/detail/TransactionDetailActivity.kt
2252262831
package com.refridev.bankapp.ui.transaction.detail import android.content.Context import android.content.Intent import com.refridev.bankapp.base.BaseActivity import com.refridev.bankapp.databinding.ActivityTransactionDetailBinding import com.refridev.bankapp.ui.transaction.pin.InputPinActivity class TransactionDetailActivity : BaseActivity<ActivityTransactionDetailBinding, TransactionDetailViewModel> (ActivityTransactionDetailBinding::inflate) { override fun initView() { setButtonListener() setView() } private fun setButtonListener(){ getViewBinding().btnBack.setOnClickListener { finish() } getViewBinding().btnConfirm.setOnClickListener { startActivity(InputPinActivity.getStartIntent(this)) } } private fun setView(){ val name = intent.getStringExtra(EXTRA_NAME) var account = intent.getStringExtra(EXTRA_ACCOUNT) val amount = intent.getStringExtra(EXTRA_AMOUNT) getViewBinding().tvRecipientName.text = name getViewBinding().tvRecipientAccount.text = account getViewBinding().tvTransferAmount.text = amount getViewBinding().tvTotal.text = amount getViewBinding().tvAmount.text = amount } override fun showContent(isVisible: Boolean) {} override fun showLoading(isVisible: Boolean) {} override fun showError(isErrorEnabled: Boolean, msg: String?) {} companion object { private const val EXTRA_NAME = "EXTRA_NAME" private const val EXTRA_ACCOUNT = "EXTRA_ACCOUNT" private const val EXTRA_AMOUNT = "EXTRA_AMOUNT" fun getStartIntent(context: Context?, name: String, account: String, amount: String): Intent { return Intent(context, TransactionDetailActivity::class.java) .putExtra(EXTRA_NAME, name) .putExtra(EXTRA_ACCOUNT, account) .putExtra(EXTRA_AMOUNT, amount) } } }
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/ui/transaction/TransactionSuccessActivity.kt
1258842491
package com.refridev.bankapp.ui.transaction import android.content.Context import android.content.Intent import com.refridev.bankapp.base.BaseActivity import com.refridev.bankapp.databinding.ActivityTransactionSuccessBinding import com.refridev.bankapp.ui.MainActivity class TransactionSuccessActivity : BaseActivity<ActivityTransactionSuccessBinding, TransactionSuccessViewModel> (ActivityTransactionSuccessBinding::inflate) { override fun initView() { onButtonClicked() } private fun onButtonClicked(){ getViewBinding().btnBackToApp.setOnClickListener { val intent = Intent(this, MainActivity::class.java).also { it.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP } startActivity(intent) } } override fun showContent(isVisible: Boolean) {} override fun showLoading(isVisible: Boolean) {} override fun showError(isErrorEnabled: Boolean, msg: String?) {} companion object { fun getStartIntent(context: Context?): Intent { return Intent(context, TransactionSuccessActivity::class.java) } } }
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/ui/MainActivity.kt
294521305
package com.refridev.bankapp.ui import android.content.Intent import com.refridev.bankapp.base.BaseActivity import com.refridev.bankapp.databinding.ActivityMainBinding import com.refridev.bankapp.ui.recipient.RecipientListActivity class MainActivity : BaseActivity<ActivityMainBinding, MainViewModel>( ActivityMainBinding::inflate) { override fun initView() { onLogoClicked() } private fun onLogoClicked(){ getViewBinding().ivLogo.setOnClickListener { val intent = Intent(this, RecipientListActivity::class.java) startActivity(intent) } } override fun showContent(isVisible: Boolean) {} override fun showLoading(isVisible: Boolean) {} override fun showError(isErrorEnabled: Boolean, msg: String?) {} }
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/ui/recipient/RecipientListActivity.kt
24104598
package com.refridev.bankapp.ui.recipient import android.content.Context import android.content.Intent import androidx.recyclerview.widget.LinearLayoutManager import com.refridev.bankapp.R import com.refridev.bankapp.base.BaseActivity import com.refridev.bankapp.base.Resource import com.refridev.bankapp.data.model.response.RecipientListResponse import com.refridev.bankapp.databinding.ActivityRecipientListBinding import com.refridev.bankapp.ui.recipient.adapter.RecipientListAdapter import com.refridev.bankapp.ui.transaction.amount.InputAmountActivity import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class RecipientListActivity : BaseActivity<ActivityRecipientListBinding, RecipientListViewModel> (ActivityRecipientListBinding::inflate), RecipientListAdapter.OnItemClickListener, RecipientListContract.View { private lateinit var adapter: RecipientListAdapter private var amount: String = "" override fun initView() { val intent = intent getIntentData(intent) } override fun onResume() { super.onResume() adapter = RecipientListAdapter() setRecycleView() getViewModel().getRecipientList() } override fun setRecycleView(){ getViewBinding().rvRecipient.apply { layoutManager = LinearLayoutManager(context) adapter = [email protected] } adapter.setOnItemClickListener(this) } private fun getIntentData(intent: Intent){ if (intent?.extras != null) { // Extract the data you need from the Intent extras amount = intent.getStringExtra(EXTRA_VALUE) ?: "0" } } override fun setDataAdapter(data: List<RecipientListResponse>?){ data?.let{ adapter.setItems(it)} } override fun observeData() { getViewModel().getRecipientListLiveData().observe(this) { when (it) { is Resource.Loading -> { showLoading(true) showContent(false) showError(false, null) } is Resource.Success -> { showLoading(false) it.data?.let{data -> if (data.isEmpty()) { // showError(true, getString(R.string.text_no_item)) showContent(false) } else { showContent(true) showError(false, null) setDataAdapter(it.data) } } } is Resource.Error -> { showLoading(false) showContent(false) showError(true, it.message) } else -> {} } } } override fun showContent(isVisible: Boolean) {} override fun showLoading(isVisible: Boolean) {} override fun showError(isErrorEnabled: Boolean, msg: String?) {} override fun onItemClicked(recipientListResponse: RecipientListResponse) { val name = recipientListResponse.recipientName.toString() val account = recipientListResponse.accountNumber.toString() val amount = intent.getStringExtra(EXTRA_VALUE) ?: "0" startActivity(InputAmountActivity.getStartIntent(this, name, account, amount)) } companion object { private const val EXTRA_VALUE = "value" fun getStartIntent(context: Context?): Intent { return Intent(context, RecipientListActivity::class.java) } } }
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/ui/recipient/adapter/RecipientListAdapter.kt
3619328742
package com.refridev.bankapp.ui.recipient.adapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.refridev.bankapp.data.model.response.RecipientListResponse import com.refridev.bankapp.databinding.ItemRecipientBinding class RecipientListAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() { private var items: ArrayList<RecipientListResponse> = arrayListOf() private var itemClickListener: OnItemClickListener? = null override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding = ItemRecipientBinding.inflate(LayoutInflater.from(parent.context), parent, false) return ViewHolder(binding) } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { when (holder) { is ViewHolder -> holder.bindView(items[position]) } } override fun getItemCount(): Int { return if (items != null && items.isNotEmpty()) { items.size } else { 0 } } fun setItems(items: List<RecipientListResponse>){ this.items.addAll(items) notifyDataSetChanged() } inner class ViewHolder(private val binding: ItemRecipientBinding): RecyclerView.ViewHolder(binding.root){ fun bindView(item: RecipientListResponse){ binding.llRecipientName.text = item.recipientName binding.llRecipientAccount.text = item.accountNumber binding.llRecipient.setOnClickListener { if (itemClickListener != null) { itemClickListener?.onItemClicked(item) } } } } interface OnItemClickListener { fun onItemClicked(recipientListResponse: RecipientListResponse) } fun setOnItemClickListener(listener: OnItemClickListener?) { itemClickListener = listener } }
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/ui/recipient/RecipientListContract.kt
2596692930
package com.refridev.bankapp.ui.recipient import androidx.lifecycle.LiveData import com.refridev.bankapp.base.BaseContract import com.refridev.bankapp.base.Resource import com.refridev.bankapp.data.model.response.RecipientListResponse interface RecipientListContract { interface View : BaseContract.BaseView { fun setRecycleView() fun setDataAdapter(data: List<RecipientListResponse>?) } interface ViewModel : BaseContract.BaseViewModel { fun getRecipientList() fun getRecipientListLiveData(): LiveData<Resource<List<RecipientListResponse>>> } interface Repository : BaseContract.BaseRepository { suspend fun getRecipientList(): List<RecipientListResponse> } }
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/ui/recipient/RecipientListViewModel.kt
2582484038
package com.refridev.bankapp.ui.recipient import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.refridev.bankapp.base.Resource import com.refridev.bankapp.data.model.response.RecipientListResponse import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import java.lang.Exception import javax.inject.Inject @HiltViewModel class RecipientListViewModel @Inject constructor(private val repository: RecipientListRepository) : ViewModel(), RecipientListContract.ViewModel{ private val recipientLiveData = MutableLiveData<Resource<List<RecipientListResponse>>>() override fun getRecipientList(){ recipientLiveData.value = Resource.Loading() viewModelScope.launch (Dispatchers.IO){ try{ val response = repository.getRecipientList() viewModelScope.launch (Dispatchers.Main){ recipientLiveData.value = response.let{Resource.Success(it)} } } catch (e: Exception){ Log.e("VMTest", "Exception: ${e.message}", e) viewModelScope.launch(Dispatchers.Main){ recipientLiveData.value = Resource.Error(e.message.orEmpty()) } } } } override fun getRecipientListLiveData(): LiveData<Resource<List<RecipientListResponse>>> = recipientLiveData override fun logResponse(msg: String?) {} }
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/ui/recipient/RecipientListRepository.kt
3453992977
package com.refridev.bankapp.ui.recipient import com.refridev.bankapp.data.model.response.RecipientListResponse import com.refridev.bankapp.data.network.datasource.recipient.RecipientListDataSource import javax.inject.Inject class RecipientListRepository @Inject constructor (private val recipientListDataSource: RecipientListDataSource) : RecipientListContract.Repository { override suspend fun getRecipientList(): List<RecipientListResponse> { return recipientListDataSource.getRecipientList() } override fun logResponse(msg: String?) {} }
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/ui/MainContract.kt
1077878952
package com.refridev.bankapp.ui interface MainContract { }
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/App.kt
222912817
package com.refridev.bankapp import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class App : Application() { }
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/di/NetworkModule.kt
786311086
package com.refridev.bankapp.di import com.refridev.bankapp.data.network.service.ApiServices import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object NetworkModule { @Singleton @Provides fun provideNewsApiServices(): ApiServices { return ApiServices.invoke() } }
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/di/DataSourceModule.kt
977633252
package com.refridev.bankapp.di import com.refridev.bankapp.data.network.datasource.recipient.RecipientListDataSource import com.refridev.bankapp.data.network.datasource.recipient.RecipientListDataSourceImpl import com.refridev.bankapp.data.network.service.ApiServices import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object DataSourceModule { @Singleton @Provides fun provideRecipientListDataSource(recipientApiService: ApiServices): RecipientListDataSource { return RecipientListDataSourceImpl(recipientApiService) } }
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/di/RepositoryModule.kt
3507086073
package com.refridev.bankapp.di import com.refridev.bankapp.data.network.datasource.recipient.RecipientListDataSource import com.refridev.bankapp.ui.recipient.RecipientListRepository import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object RepositoryModule { @Provides @Singleton fun provideNewsListRepository( recipientListDataSource: RecipientListDataSource ): RecipientListRepository { return RecipientListRepository(recipientListDataSource) } }
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/di/ViewModelModule.kt
748943243
package com.refridev.bankapp.di import com.refridev.bankapp.base.GenericViewModelFactory import com.refridev.bankapp.ui.recipient.RecipientListRepository import com.refridev.bankapp.ui.recipient.RecipientListViewModel import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.components.ActivityComponent import dagger.hilt.android.scopes.ActivityScoped @Module @InstallIn(ActivityComponent::class) object ViewModelModule { @Provides @ActivityScoped fun provideRecipientListViewModel( recipientListRepository: RecipientListRepository ): RecipientListViewModel { return GenericViewModelFactory(RecipientListViewModel(recipientListRepository)).create( RecipientListViewModel::class.java ) } }
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/widget/BalanceWidget.kt
2639988358
//package com.example.bankapp.widget // //import android.appwidget.AppWidgetManager //import android.content.Context //import android.text.format.DateFormat //import android.widget.RemoteViews //import java.util.Locale //import java.util.concurrent.TimeUnit // //class BalanceWidget( // private val context: Context, // private val appWidgetManager: AppWidgetManager, // private val appWidgetId: Int, // layout: Int, //) { // private val views = RemoteViews(context.packageName, layout) // private val repository = FitRepository.getInstance(context) // private val hasBii: Boolean // private val isFallbackIntent: Boolean // private val aboutExerciseName: String // private val exerciseType: FitActivity.Type // // init { // val optionsBundle = appWidgetManager.getAppWidgetOptions(appWidgetId) // val bii = optionsBundle.getString(AppActionsWidgetExtension.EXTRA_APP_ACTIONS_BII) // hasBii = !bii.isNullOrBlank() // val params = optionsBundle.getBundle(AppActionsWidgetExtension.EXTRA_APP_ACTIONS_PARAMS) // if (params != null) { // isFallbackIntent = params.isEmpty // if (isFallbackIntent) { // aboutExerciseName = context.resources.getString(R.string.activity_unknown) // } else { // aboutExerciseName = params.get("aboutExerciseName") as String // } // } else { // isFallbackIntent = false // aboutExerciseName = context.resources.getString(R.string.activity_unknown) // } // exerciseType = FitActivity.Type.find(aboutExerciseName) // } // // /** // * Checks if widget should get requested or last exercise data and updates widget // * accordingly // */ // fun updateAppWidget() { // if (hasBii && !isFallbackIntent) { // observeAndUpdateRequestedExercise() // } else observeAndUpdateLastExercise() // } // // // // /** // * Sets title, duration and distance data to widget // */ // private fun setDataToWidget( // exerciseType: String, // distanceInKm: Float, // durationInMin: Long // ) { // views.setTextViewText( // R.id.activityType, // context.getString(R.string.widget_activity_type, exerciseType) // ) // views.setTextViewText( // R.id.appwidgetDuration, // context.getString(R.string.widqet_distance, distanceInKm) // ) // views.setTextViewText( // R.id.appwidgetDistance, // context.getString(R.string.widget_duration, durationInMin) // ) // } // // /** // * Sets TTS to widget // */ // private fun setTts( // speechText: String, // displayText: String, // ) { // val appActionsWidgetExtension: AppActionsWidgetExtension = // AppActionsWidgetExtension.newBuilder(appWidgetManager) // .setResponseSpeech(speechText) // TTS to be played back to the user // .setResponseText(displayText) // Response text to be displayed in Assistant // .build() // // // Update widget with TTS // appActionsWidgetExtension.updateWidget(appWidgetId) // } // // /** // * Formats and sets activity data to Widget // */ // private fun formatDataAndSetWidget( // activityStat: FitActivity, // ) { // // formats date of activity // val datePattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), "EEEdMMMM") // val formattedDate = DateFormat.format(datePattern, activityStat.date) // // // // formats duration, distance and exercise name for widget // val durationInMin = TimeUnit.MILLISECONDS.toMinutes(activityStat.durationMs) // val distanceInKm = (activityStat.distanceMeters / 1000).toFloat() // val activityExerciseType = activityStat.type.toString() // val activityExerciseTypeFormatted = activityExerciseType.lowercase() // // // setDataToWidget(activityExerciseType, distanceInKm, durationInMin) // // if (hasBii) { // // formats speech and display text for Assistant // // https://developers.google.com/assistant/app/widgets#tts // val speechText = context.getString( // R.string.widget_activity_speech, // activityExerciseTypeFormatted, // formattedDate, // durationInMin, // distanceInKm // ) // val displayText = context.getString( // R.string.widget_activity_text, // activityExerciseTypeFormatted, // formattedDate // ) // setTts(speechText, displayText) // } // } // // /** // * Formats and sets no activity data to Widget // */ // private fun setNoActivityDataWidget() { // val appwidgetTypeTitleText = context.getString((R.string.widget_no_data)) // val distanceInKm = 0F // val durationInMin = 0L // // setDataToWidget(appwidgetTypeTitleText, distanceInKm, durationInMin) // // if (hasBii) { // // formats speech and display text for Assistant // // https://developers.google.com/assistant/app/widgets#library // val speechText = // context.getString(R.string.widget_no_activity_speech, aboutExerciseName) // val displayText = // context.getString(R.string.widget_no_activity_text) // // setTts(speechText, displayText) // } // } // // /** // * Instruct the widget manager to update the widget // */ // private fun updateWidget() { // appWidgetManager.updateAppWidget(appWidgetId, views) // } // // /** // * Create and observe the last exerciseType activity LiveData. // */ // /*private fun observeAndUpdateRequestedExercise() { // val activityData = repository.getLastActivities(1, exerciseType) // // activityData.observeOnce { activitiesStat -> // if (activitiesStat.isNotEmpty()) { // formatDataAndSetWidget(activitiesStat[0]) // updateWidget() // } else { // setNoActivityDataWidget() // updateWidget() // } // } // }*/ // // // /** // * Create and observe the last activity LiveData. // */ // /*private fun observeAndUpdateLastExercise() { // val activityData = repository.getLastActivities(1) // // activityData.observeOnce { activitiesStat -> // if (activitiesStat.isNotEmpty()) { // formatDataAndSetWidget(activitiesStat[0]) // updateWidget() // } else { // setNoActivityDataWidget() // updateWidget() // } // } // }*/ // //}
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/widget/BalanceWidgetProvider.kt
1794587834
package com.refridev.bankapp.widget import android.appwidget.AppWidgetManager import android.appwidget.AppWidgetProvider import android.content.Context import android.util.Log import android.widget.RemoteViews import com.refridev.bankapp.R import com.google.assistant.appactions.widgets.AppActionsWidgetExtension import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch class BalanceWidgetProvider : AppWidgetProvider() { override fun onUpdate( context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray ) { for (appWidgetId in appWidgetIds) { setTts("Berikut informasi saldo anda pada tanggal 19 January", appWidgetManager, appWidgetId) // Update the widget with the remote views defined in the XML layout appWidgetManager.updateAppWidget(appWidgetId, createRemoteViews(context)) } } private fun createRemoteViews(context: Context): RemoteViews { // Create RemoteViews for the widget using the XML layout return RemoteViews(context.packageName, R.layout.balance_widget) } private fun setTts( text: String, appWidgetManager: AppWidgetManager, appWidgetId: Int ) { val appActionsWidgetExtension: AppActionsWidgetExtension = AppActionsWidgetExtension.newBuilder(appWidgetManager) .setResponseSpeech(text) // TTS to be played back to the user .setResponseText(text) // Response text to be displayed in Assistant .build() // Update widget with TTS appActionsWidgetExtension.updateWidget(appWidgetId) } }
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/data/network/datasource/recipient/RecipientListDataSourceImpl.kt
4165980541
package com.refridev.bankapp.data.network.datasource.recipient import com.refridev.bankapp.data.model.response.RecipientListResponse import com.refridev.bankapp.data.network.service.ApiServices import javax.inject.Inject class RecipientListDataSourceImpl @Inject constructor(private val recipientApiServices : ApiServices?) : RecipientListDataSource { override suspend fun getRecipientList(): List<RecipientListResponse> { return listOf( RecipientListResponse("Aditya Putra (BRI)", "BRI 0892389207231"), RecipientListResponse("Aditya Putra (Mandiri)", "Mandiri 875957832929"), RecipientListResponse("Aditya Putra (BNI)", "BNI 84932043024"), ) // return recipientApiServices?.getRecipientList() ?: listOf() } }
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/data/network/datasource/recipient/RecipientListDataSource.kt
154256047
package com.refridev.bankapp.data.network.datasource.recipient import com.refridev.bankapp.data.model.response.RecipientListResponse interface RecipientListDataSource { suspend fun getRecipientList(): List<RecipientListResponse> }
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/data/network/service/ApiServices.kt
1127728747
package com.refridev.bankapp.data.network.service import com.refridev.bankapp.data.model.response.RecipientListResponse import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import retrofit2.http.GET import java.util.concurrent.TimeUnit interface ApiServices { @GET("recipient") suspend fun getRecipientList() : List<RecipientListResponse> companion object { @JvmStatic operator fun invoke(): ApiServices { val okHttpClient = OkHttpClient.Builder() .connectTimeout(120, TimeUnit.SECONDS) .readTimeout(120, TimeUnit.SECONDS) .build() val retrofit = Retrofit.Builder() .baseUrl("http://demo2968123.mockable.io/") .addConverterFactory(GsonConverterFactory.create()) .client(okHttpClient) .build() return retrofit.create(ApiServices::class.java) } } }
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/data/model/response/RecipientListResponse.kt
415713045
package com.refridev.bankapp.data.model.response import com.google.gson.annotations.SerializedName data class RecipientListResponse ( @SerializedName("name") var recipientName: String? = null, @SerializedName("account") var accountNumber: String? = null, )
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/base/BaseActivity.kt
922057959
package com.refridev.bankapp.base import android.graphics.Color import android.os.Bundle import android.view.LayoutInflater import android.view.Window import android.view.WindowManager import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.ViewModel import androidx.viewbinding.ViewBinding import javax.inject.Inject abstract class BaseActivity<B : ViewBinding, VM : ViewModel>( val bindingFactory: (LayoutInflater) -> B ) : AppCompatActivity(), BaseContract.BaseView { private lateinit var binding: B @Inject lateinit var viewModelInstance: VM fun getViewBinding(): B = binding fun getViewModel(): VM = viewModelInstance override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = bindingFactory(layoutInflater) setContentView(binding.root) initView() observeData() changeStatusBarColor("#3B82C9") } abstract fun initView() override fun observeData() {} private fun changeStatusBarColor(hexColor: String) { // Color must be in hexadecimal format val window: Window = window window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) window.statusBarColor = Color.parseColor(hexColor) } }
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/base/GenericViewModelFactory.kt
3856759387
package com.refridev.bankapp.base import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import java.lang.IllegalArgumentException class GenericViewModelFactory(private val viewModel: ViewModel) : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create(modelClass: Class<T>): T { if(modelClass.isAssignableFrom(viewModel::class.java)){ return viewModel as T } throw IllegalArgumentException("Unknown Class Name") } }
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/base/Resource.kt
1858715558
package com.refridev.bankapp.base sealed class Resource<T>( val data: T? = null, val message: String? = null ){ class Success<T>(data: T) : Resource<T>(data) class Loading<T>(data: T? = null) : Resource<T>(data) class Error<T>(message: String, data: T? = null) : Resource<T>(data, message) }
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/base/BaseContract.kt
2439870414
package com.refridev.bankapp.base interface BaseContract { interface BaseView { fun observeData() fun showContent(isVisible: Boolean) fun showLoading(isVisible: Boolean) fun showError(isErrorEnabled: Boolean, msg: String? = null) } interface BaseViewModel { fun logResponse(msg : String?) } interface BaseRepository { fun logResponse(msg : String?) } }
MileMarkerApp/app/src/androidTest/java/com/example/mc_assignment1/ExampleInstrumentedTest.kt
4072643928
package com.example.mc_assignment1 import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.mc_assignment1", appContext.packageName) } }
MileMarkerApp/app/src/test/java/com/example/mc_assignment1/ExampleUnitTest.kt
265007494
package com.example.mc_assignment1 import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
MileMarkerApp/app/src/main/java/com/example/mc_assignment1/ui/theme/Color.kt
2738632040
package com.example.mc_assignment1.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
MileMarkerApp/app/src/main/java/com/example/mc_assignment1/ui/theme/Theme.kt
945380840
package com.example.mc_assignment1.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun MC_Assignment1Theme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
MileMarkerApp/app/src/main/java/com/example/mc_assignment1/ui/theme/Type.kt
3709914749
package com.example.mc_assignment1.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
MileMarkerApp/app/src/main/java/com/example/mc_assignment1/MainActivity.kt
3572211539
package com.example.mc_assignment1 import android.content.Context import android.os.Bundle import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.* import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color.Companion.Green import androidx.compose.ui.graphics.Color.Companion.Red import androidx.compose.ui.graphics.Color.Companion.Yellow import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.unit.dp class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?){ super.onCreate(savedInstanceState) setContent{ MyApp(context = this) } } } //@Preview @Composable fun MyApp(context: Context) { var isKm by remember {mutableStateOf(true)} var csi by remember {mutableStateOf(0)} var userName by remember {mutableStateOf(TextFieldValue())} var alertMessage by remember {mutableStateOf("")} val stops=listOf( Stop("Delhi",0), Stop("Jaipur",300), Stop("Agra",450), Stop("Lucknow",120), Stop("Mumbai",1400), Stop("Ahmedabad",540), Stop("Kolkata",2300), Stop("Bangalore",1940), Stop("Hyderabad",790),Stop("Colombo",512), Stop("Dubai",3213), Stop("Chicago",11930) ) Column(modifier=Modifier.fillMaxSize()){ //enetr uname TextField( value=userName, onValueChange={newValue -> userName=newValue }, label={Text("Enter your name")}, modifier=Modifier .padding(16.dp) .fillMaxWidth() ) //alerttext box TextField( value=alertMessage, onValueChange={ newValue -> alertMessage=newValue }, label={Text("Alert Text")}, modifier=Modifier .padding(16.dp) .fillMaxWidth() ) Button( onClick={ isKm=!isKm } ) { if (isKm){ Text("Switch to Miles") } else{ Text("Switch to Kms") } } Spacer(modifier=Modifier.height(16.dp)) LazyColumn( modifier=Modifier.weight(1f), contentPadding=PaddingValues(horizontal=16.dp) ) { itemsIndexed(stops) {index,stop -> StopItem(stop,index,isKm,csi) } } Spacer(modifier=Modifier.height(16.dp)) //next stop button Button( onClick={ if (csi<(stops.size-1)){ csi++ } else{ if (userName.text.isNotBlank()){ showToast(context,alertMessage) } } } ) { Text("Next Stop!") } Spacer(modifier=Modifier.height(16.dp)) //journey info val cs=stops.getOrNull(csi) val td=stops.sumOf {it.distance} val cd=stops.subList(0,csi+1).sumOf {it.distance} val rd=td-cd cs?.let { Text("Dear ${userName.text}") Text("Current stop is: ${it.name}") Text("Distance covered to current Stop: ${formacsistance(it.distance,isKm)}") } Text("Total Distance Covered: ${formacsistance(cd,isKm)}") Text("Total Distance Remaining: ${formacsistance(rd,isKm)}") } } @Composable fun StopItem(stop: Stop,index: Int,isKm: Boolean,csi: Int){ val backgroundColor=when{ index < csi ->Green index == csi -> Yellow else -> Red } Box( modifier=Modifier .fillMaxWidth() .padding(vertical=4.dp) .background(color=backgroundColor) ) { Card( modifier=Modifier.fillMaxSize(), ) { Column(modifier=Modifier.padding(8.dp)){ Text("Stop ${index+1}: ${stop.name}") Text("Distance: ${formacsistance(stop.distance,isKm)}") } } } } data class Stop(val name: String, val distance: Int) fun formacsistance(distance: Int, isKm: Boolean): String { return if (isKm){ "$distance km" } else { "%.2f miles".format(distance * 0.621371) } } fun showToast(context: Context,mess: String) { Toast.makeText(context, mess,Toast.LENGTH_SHORT).show() }
SpringBoot-Kotlin-STYLiSH-Back-End/src/test/kotlin/com/example/backend/BackendApplicationTests.kt
1091136954
package com.example.backend import org.junit.jupiter.api.Test import org.springframework.boot.test.context.SpringBootTest @SpringBootTest class BackendApplicationTests { @Test fun contextLoads() {} }
SpringBoot-Kotlin-STYLiSH-Back-End/src/main/kotlin/com/example/backend/Product.kt
3623769899
package com.example.backend data class Product(val data: ArrayList<ProductData>) data class ProductData( val id: Long, val category: String, val title: String, val description: String, val price: Long, val texture: String, val wash: String, val place: String, val note: String, val story: String, val main_image: String, val images: ArrayList<String>, val variants: ArrayList<Variant>, val colors: ArrayList<Color>, val sizes: ArrayList<String> ) data class Variant(val color_code: String, val size: String, val stock: Long) data class Color(val code: String, val name: String)
SpringBoot-Kotlin-STYLiSH-Back-End/src/main/kotlin/com/example/backend/Carousel.kt
2482861703
package com.example.backend data class Carousel(val data: ArrayList<CarouselData>) data class CarouselData(val id: Long, val product_id: Long, val picture: String, val story: String)
SpringBoot-Kotlin-STYLiSH-Back-End/src/main/kotlin/com/example/backend/CorsConfig.kt
1544808764
package com.example.backend import org.springframework.context.annotation.Configuration import org.springframework.web.servlet.config.annotation.CorsRegistry import org.springframework.web.servlet.config.annotation.WebMvcConfigurer @Configuration class CorsConfig : WebMvcConfigurer { override fun addCorsMappings(registry: CorsRegistry) { registry .addMapping("/**") .allowedOrigins("*") .allowedMethods("GET", "POST", "PUT", "DELETE") .allowedHeaders("*") } }
SpringBoot-Kotlin-STYLiSH-Back-End/src/main/kotlin/com/example/backend/BackendApplication.kt
1798826775
package com.example.backend import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication @SpringBootApplication class BackendApplication fun main(args: Array<String>) { runApplication<BackendApplication>(*args) }
SpringBoot-Kotlin-STYLiSH-Back-End/src/main/kotlin/com/example/backend/RestControllers.kt
1939266244
package com.example.backend import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController @RestController @RequestMapping("api/1.0/marketing/campaigns") class CarouselController { private val carouselData = arrayListOf( CarouselData( 1, 201807242228, "https://api.appworks-school.tw/assets/201807242228/keyvisual.jpg", "於是\r\n我也想要給你\r\n一個那麼美好的自己。\r\n不朽《與自己和好如初》" ), CarouselData( 2, 201807242222, "https://api.appworks-school.tw/assets/201807242222/keyvisual.jpg", "永遠\r\n展現自信與專業\r\n無法抵擋的男人魅力。\r\n復古《再一次經典》" ), CarouselData( 3, 201807202140, "https://api.appworks-school.tw/assets/201807202140/keyvisual.jpg", "瞬間\r\n在城市的角落\r\n找到失落多時的記憶。\r\n印象《都會故事集》" ) ) private val carousel: Carousel = Carousel(carouselData) @GetMapping fun getCarousel() = carousel } @RestController @RequestMapping("api/1.0/products/{category}") class ProductController { private val productData: ArrayList<ProductData> = arrayListOf<ProductData>() private val products: Product = Product(productData) @GetMapping fun getProducts( @PathVariable category: String, @RequestParam paging: Int ): ResponseEntity<Product> = ResponseEntity.ok(products) } // // 在 RestControllers.kt 中新增一個新的 Controller // @RestController // @RequestMapping("api/v1/image") // class ImageController(private val imageService: ImageService) { // @GetMapping("/{id}") // fun getImage(@PathVariable id: Long): ResponseEntity<ByteArray> { // val imageData = imageService.getImageDataById(id) // return ResponseEntity.ok() // .contentType(MediaType.IMAGE_JPEG) // .body(imageData) // } // } // // 創建一個 ImageService 來處理從 MariaDB 中取得圖片的邏輯 // @Service // class ImageService(private val imageRepository: ImageRepository) { // fun getImageDataById(id: Long): ByteArray { // val image = imageRepository.findById(id) // // 在這裡實作從資料庫中取得圖片資料的邏輯 // // 返回圖片的 byte array // } // } // // 創建一個 ImageRepository 來處理與 MariaDB 互動的邏輯 // @Repository // interface ImageRepository : JpaRepository<Image, Long> { // // 在這裡可以定義取得圖片資料的方法 // }
JetpackAPIApp/app/src/androidTest/java/com/example/apiapp/ExampleInstrumentedTest.kt
3934170814
package com.example.apiapp import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.apiapp", appContext.packageName) } }
JetpackAPIApp/app/src/test/java/com/example/apiapp/ExampleUnitTest.kt
376762931
package com.example.apiapp import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
JetpackAPIApp/app/src/main/java/com/example/apiapp/ui/theme/Color.kt
1637509793
package com.example.apiapp.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260) val CardColor = Color(0xFF030F16) val Black500 = Color(0xff292d36)
JetpackAPIApp/app/src/main/java/com/example/apiapp/ui/theme/Theme.kt
1755313460
package com.example.apiapp.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme(primary = Color.LightGray, background = CardColor, secondary = PurpleGrey40) private val LightColorScheme = lightColorScheme(primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40) @Composable fun APIAppTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = false, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme WindowCompat.getInsetsController(window, view).isAppearanceLightNavigationBars = darkTheme WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme(colorScheme = colorScheme, typography = Typography, content = content) }
JetpackAPIApp/app/src/main/java/com/example/apiapp/ui/theme/Type.kt
3021780042
package com.example.apiapp.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp))
JetpackAPIApp/app/src/main/java/com/example/apiapp/MainActivity.kt
350675368
package com.example.apiapp import android.os.Bundle import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.viewModels import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues 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.shape.RoundedCornerShape import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import coil.compose.AsyncImagePainter import coil.compose.rememberAsyncImagePainter import coil.request.ImageRequest import coil.size.Size import com.example.apiapp.data.ProductsRepositoryImpl import com.example.apiapp.data.model.Product import com.example.apiapp.presentation.ProductsViewModel import com.example.apiapp.ui.theme.APIAppTheme import com.example.apiapp.ui.theme.Black500 import kotlinx.coroutines.flow.collectLatest @Suppress("UNCHECKED_CAST") class MainActivity : ComponentActivity() { private val viewModel by viewModels<ProductsViewModel> { object : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return ProductsViewModel(ProductsRepositoryImpl(RetrofitInstance.api)) as T } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { APIAppTheme { // A surface container using the 'background' color from the theme Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) { val productList = viewModel.products.collectAsState().value val context = LocalContext.current LaunchedEffect(key1 = viewModel.showErrorToastChannel) { viewModel.showErrorToastChannel.collectLatest { show -> if (show) { Toast.makeText(context, "Error", Toast.LENGTH_SHORT).show() } } } if (productList.isEmpty()) { Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { CircularProgressIndicator(color = Color.White) } } else { LazyColumn( modifier = Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, contentPadding = PaddingValues(8.dp) ) { items(productList.size) { index -> Product(productList[index]) Spacer(modifier = Modifier.height(16.dp)) } } } } } } } } @Composable fun Product(product: Product) { val imageState = rememberAsyncImagePainter( model = ImageRequest.Builder(LocalContext.current) .data(product.thumbnail) .size(Size.ORIGINAL) .build() ) .state Column( modifier = Modifier.clip(RoundedCornerShape(12.dp)).height(310.dp).fillMaxWidth().background(Black500) ) { if (imageState is AsyncImagePainter.State.Error) { Box(modifier = Modifier.fillMaxWidth().height(310.dp), contentAlignment = Alignment.Center) { CircularProgressIndicator(color = Color.White) } } if (imageState is AsyncImagePainter.State.Success) { Image( modifier = Modifier.fillMaxWidth().height(200.dp), painter = imageState.painter, contentDescription = product.title, contentScale = ContentScale.Crop ) } Spacer(modifier = Modifier.height(6.dp)) Text( modifier = Modifier.padding(horizontal = 16.dp), text = "${product.title} -- Price: ${product.price}$", fontSize = 18.sp, color = Color.White, fontWeight = FontWeight.SemiBold ) Spacer(modifier = Modifier.height(6.dp)) Text( modifier = Modifier.padding(horizontal = 16.dp), text = product.description, maxLines = 4, color = Color.Gray, fontSize = 16.sp, ) } }
JetpackAPIApp/app/src/main/java/com/example/apiapp/RetrofitInstance.kt
3294947248
package com.example.apiapp import com.example.apiapp.data.ProductAPI import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory object RetrofitInstance { private val interceptor: HttpLoggingInterceptor = HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY } private val client: OkHttpClient = OkHttpClient.Builder().addInterceptor(interceptor).build() val api: ProductAPI = Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create()) .baseUrl(ProductAPI.BASE_URL) .client(client) .build() .create(ProductAPI::class.java) }
JetpackAPIApp/app/src/main/java/com/example/apiapp/data/Result.kt
1975722318
package com.example.apiapp.data sealed class Result<T>(val data: T? = null, val message: String? = null) { class Success<T>(data: T?) : Result<T>(data) class Error<T>(data: T? = null, message: String?) : Result<T>(data, message) }
JetpackAPIApp/app/src/main/java/com/example/apiapp/data/ProductsRepository.kt
1630901177
package com.example.apiapp.data import com.example.apiapp.data.model.Product import kotlinx.coroutines.flow.Flow interface ProductsRepository { suspend fun getProductsList(): Flow<Result<List<Product>>> }