path
stringlengths
4
297
contentHash
stringlengths
1
10
content
stringlengths
0
13M
StopWatchBet/app/src/androidTest/java/com/example/stopwatchbet/ExampleInstrumentedTest.kt
1039136081
package com.example.stopwatchbet 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.stopwatchbet", appContext.packageName) } }
StopWatchBet/app/src/test/java/com/example/stopwatchbet/ExampleUnitTest.kt
4066267285
package com.example.stopwatchbet 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) } }
StopWatchBet/app/src/main/java/com/example/stopwatchbet/ui/theme/Color.kt
3076758102
package com.example.stopwatchbet.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)
StopWatchBet/app/src/main/java/com/example/stopwatchbet/ui/theme/Theme.kt
3274008718
package com.example.stopwatchbet.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 StopWatchBetTheme( 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 ) }
StopWatchBet/app/src/main/java/com/example/stopwatchbet/ui/theme/Type.kt
966674371
package com.example.stopwatchbet.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 ) */ )
StopWatchBet/app/src/main/java/com/example/stopwatchbet/MainActivity.kt
3733290737
package com.example.stopwatchbet import android.content.Context import android.graphics.fonts.FontStyle import android.os.Bundle import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement 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.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentWidth import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Button import androidx.compose.material3.Divider 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.MutableIntState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableLongStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.vectorResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.window.Dialog import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import com.example.stopwatchbet.ui.theme.StopWatchBetTheme import kotlinx.coroutines.delay import kotlin.random.Random class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { StopWatchBetTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { Whole() } } } } } @Composable fun Whole() { val context = LocalContext.current val navController = rememberNavController() val players = remember { mutableIntStateOf(2) } NavHost(navController = navController, startDestination = context.getString(R.string.nav_1)) { composable(context.getString(R.string.nav_1)){ Column( verticalArrangement = Arrangement.Center, modifier = Modifier.background(Color.White), horizontalAlignment = Alignment.CenterHorizontally) { StartScreen(players, context, navController) } } composable(context.getString(R.string.nav_2)) { Column(modifier = Modifier.background(Color.White),) { GameScreen(players, navController) } } } } @Composable fun StartScreen(players: MutableIntState, context: Context, navController: NavHostController) { Column(horizontalAlignment = Alignment.CenterHorizontally) { Text( text = stringResource(id = R.string.select_players_num), style = MaterialTheme.typography.bodyLarge.copy(textAlign = TextAlign.Center, color = Color.Black), modifier = Modifier.padding(bottom = 10.dp) ) Column( horizontalAlignment = Alignment.CenterHorizontally) { LazyColumn( horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .border(BorderStroke(1.dp, Color.LightGray)) .padding(horizontal = 20.dp, vertical = 10.dp) .height(48.dp) ) { (2..10).forEach { item { Text( text = it.toString(), style = if(players.intValue == it) MaterialTheme.typography.titleLarge.copy(Color.Black) else MaterialTheme.typography.bodyLarge.copy(Color.LightGray), modifier = Modifier.clickable { players.intValue = it } ) } } } Text(text = "${stringResource(id = R.string.players)} ${players.intValue}") } Spacer(modifier = Modifier.height(20.dp)) Box(modifier = Modifier.background(Color.LightGray)) { Image( imageVector = ImageVector.vectorResource(R.drawable.ic_arrow_right), contentDescription = null, modifier = Modifier .padding(horizontal = 20.dp, vertical = 10.dp) .clickable { navController.navigate(context.getString(R.string.nav_2)) } ) } } } @Composable fun GameScreen(players: MutableIntState, navController: NavHostController) { var isRunning by remember { mutableStateOf(false) } var elapsedTime by remember { mutableLongStateOf(0L) } var startTime by remember { mutableLongStateOf(0L) } var after by remember { mutableIntStateOf(0) } val record = remember { mutableMapOf<Int, MutableList<Int>>() } var order by remember { mutableIntStateOf(1) } val style = if (isRunning) MaterialTheme.typography.bodyLarge.copy( textAlign = TextAlign.Center, color = Color.White ) else MaterialTheme.typography.bodyLarge.copy(textAlign = TextAlign.Center, color = Color.Black) LaunchedEffect(isRunning) { while (isRunning) { val currentTime = System.currentTimeMillis() elapsedTime += currentTime - startTime startTime = currentTime delay(100) } } for (i in 1..players.intValue) { record.computeIfAbsent(i) { mutableListOf() } } Column(Modifier.padding(all = 10.dp)) { Column(modifier = Modifier .fillMaxWidth() .border(BorderStroke(1.dp, Color.DarkGray)) .weight(0.2f)) { Box(modifier = Modifier.background(if (!isRunning) Color.Green else Color.Red)) { Text( text = if (!isRunning) stringResource(id = R.string.start_timer) else stringResource(id = R.string.stop_timer), style = style, modifier = Modifier .padding(vertical = 4.dp) .fillMaxWidth() .clickable { if (!isRunning) { after++ startTime = System.currentTimeMillis() isRunning = true } else { isRunning = false } } ) if (after != 0 && !isRunning) { if (record[order]?.size == 2) { after = 0 ++order } record[order]?.add(formatTime(elapsedTime).last().digitToInt()) } } Text( text = formatTime(elapsedTime), style = MaterialTheme.typography.headlineLarge.copy( textAlign = TextAlign.Center, fontSize = 60.sp, color = Color.Black ), modifier = Modifier .fillMaxWidth() .padding(all = 10.dp) ) } Column(modifier = Modifier .verticalScroll(rememberScrollState()) .fillMaxWidth() .weight(0.8f)) { Spacer(modifier = Modifier.height(8.dp)) Column { record.forEach { (index, ints) -> Row(verticalAlignment = Alignment.CenterVertically) { Order(index, Modifier.padding(horizontal = 4.dp)) if (ints.isNotEmpty()) { RandomNum(ints[0], Modifier.weight(0.2f)) Spacer(modifier = Modifier.width(8.dp)) if (ints.size == 2) { RandomNum(ints[1], Modifier.weight(0.2f)) Text( text = "${ints[0] * ints[1]}", style = MaterialTheme.typography.bodyMedium.copy( fontWeight = FontWeight.Bold, fontSize = 20.sp, textAlign = TextAlign.Center, color = Color.Red ), modifier = Modifier.weight(0.2f) ) } } } Spacer(modifier = Modifier.height(10.dp)) } } if(order == players.intValue && record[order]?.size!! >= 2) { val sortedEntries = record.entries.sortedByDescending { it.value[0] * it.value[1] } Rank(sortedMap = sortedEntries) { navController.popBackStack() } } } } } @Composable fun Order(order: Int, modifier: Modifier) { Row(horizontalArrangement = Arrangement.Center) { Text( text = "${stringResource(id = R.string.player)} $order", style = MaterialTheme.typography.bodyMedium.copy(fontWeight = FontWeight.Normal, fontSize = 20.sp, textAlign = TextAlign.Center, color = Color.DarkGray), modifier = modifier ) } Spacer(modifier = Modifier.height(10.dp)) } @Composable fun RandomNum(num: Int, modifier: Modifier) { Row ( modifier = modifier, horizontalArrangement = Arrangement.Center){ Text( text = num.toString(), style = MaterialTheme.typography.bodyMedium.copy(fontWeight = FontWeight.Bold, fontSize = 20.sp,textAlign = TextAlign.Center, color = Color.Black), ) } } @Composable fun Rank(sortedMap: List<MutableMap.MutableEntry<Int, MutableList<Int>>>, onClickBack: () -> Unit) { Column(horizontalAlignment = Alignment.CenterHorizontally) { Divider() Text(text = stringResource(id = R.string.result)) sortedMap.forEachIndexed { index, mutableEntry -> val color = if(index == 0) Color.Blue else if(index == sortedMap.lastIndex) Color.Red else Color.DarkGray Row { Text( text = "${index+1} ${stringResource(id = R.string.rank)}", style = MaterialTheme.typography.labelLarge.copy(fontSize = 20.sp, color = color) ) Spacer(modifier = Modifier.width(10.dp)) Text( text = "${stringResource(id = R.string.player)} ${mutableEntry.key}", style = MaterialTheme.typography.labelLarge.copy(fontSize = 20.sp, color = color) ) } } Spacer(modifier = Modifier.height(20.dp)) Column(modifier = Modifier .background(Color.LightGray) .clickable { onClickBack() }) { Text( text = stringResource(id = R.string.retry), style = MaterialTheme.typography.bodyMedium.copy(fontSize = 16.sp, fontWeight = FontWeight.Normal, color = Color.Black), modifier = Modifier.padding(all = 8.dp) ) } } } @Composable fun formatTime(milliseconds: Long): String { val minutes = milliseconds / 60000 val seconds = milliseconds / 1000 % 60 val millis = milliseconds % 100 return String.format("%02d:%02d.%02d", minutes, seconds, millis) }
soochka/src/main/kotlin/App.kt
3213215066
package me.topilov import kotlinx.cli.* import me.topilov.context.JavaContext import me.topilov.context.PresetContext import me.topilov.dsl.preset import java.io.File import kotlin.script.experimental.api.* import kotlin.script.experimental.host.toScriptSource import kotlin.script.experimental.jvm.dependenciesFromCurrentContext import kotlin.script.experimental.jvm.jvm import kotlin.script.experimental.jvmhost.BasicJvmScriptingHost fun main(args: Array<String>) { val parser = ArgParser("soochka") val presetsDirPath by parser.option( ArgType.String, shortName = "c", description = "Path to soochka config scripts/directories" ).default("presets") val forestDirPath by parser.option( ArgType.String, shortName = "f", description = "Home directory for soochka" ).default(".") val realmDirPath by parser.option( ArgType.String, shortName = "r", description = "Directory to store realms data" ).default("realms") val dirPath by parser.option( ArgType.String, shortName = "d", description = "Add source root" ).multiple() val presetName by parser.option( ArgType.String, fullName = "preset", shortName = "p", description = "Specify preset name to use" ).required() val realmArg by parser.option( ArgType.String, fullName = "realm", description = "Specify realm address" ).required() parser.parse(args) val forestDir = File(forestDirPath) .also(File::mkdirs) val split = realmArg.split("-") if (split.size != 2) { println("Invalid realm address: $realmArg") return } val realmType = split[0] val realmId = split[1].toInt() val realmDir = when { realmDirPath.startsWith("/") -> File(realmDirPath) else -> File(forestDir, realmDirPath) }.also(File::mkdirs) val internalsDir = File(forestDir, ".soochka") .also(File::mkdirs) val presetsDir = File(presetsDirPath) .also(File::mkdirs) val presetFile = presetsDir .listFiles { file -> file.nameWithoutExtension == presetName } ?.firstOrNull() if (presetFile == null) { println("Unable to find preset: $presetName") return } val dir = dirPath.map(::File).onEach(File::mkdirs) preset.apply { this.realmId = realmId this.realmType = realmType this.assignedPort = 17700 } PresetContext.apply { this.realmDir = realmDir this.contentRoots = dir } when (val result = readPresetConfiguration(presetFile)) { is ResultWithDiagnostics.Success -> { val returnValue = result.value.returnValue if (returnValue !is ResultValue.Value) { println("Unable to parse preset: $presetName") return } val presetContent = returnValue.value as PresetContext presetContent.execute() } is ResultWithDiagnostics.Failure -> { println("Error ${result.reports.joinToString(" ")}") } } } fun readPresetConfiguration(file: File): ResultWithDiagnostics<EvaluationResult> { val scriptingHost = BasicJvmScriptingHost() val compilationConfiguration = ScriptCompilationConfiguration { jvm { dependenciesFromCurrentContext(wholeClasspath = true) } defaultImports(preset::class, PresetContext::class, JavaContext::class) } val sourceCode = file.readText().toScriptSource() return scriptingHost.eval(sourceCode, compilationConfiguration, null) }
soochka/src/main/kotlin/context/PresetContext.kt
1880955789
package me.topilov.context import me.topilov.dsl.PresetDslMarker import java.io.File import java.nio.file.Files import java.nio.file.StandardCopyOption import kotlin.system.exitProcess typealias Environment = MutableMap<String, Any> @PresetDslMarker class PresetContext( private var env: Environment = mutableMapOf(), private var java: JavaContext = JavaContext(), ) { companion object { lateinit var contentRoots: List<File> lateinit var realmDir: File } fun execute() { val command = java.getExecutionCommand() try { val builder = ProcessBuilder(command).directory(realmDir) env.forEach { (k, v) -> builder.environment()[k] = v.toString() } builder.inheritIO() val start = builder.start() start.waitFor() } catch (throwable: Throwable) { println("An error occurred while running command: ${command.joinToString(" ")}") throwable.printStackTrace() exitProcess(0) } } fun java(block: JavaContext.() -> Unit) { java.apply(block) } infix fun String.env(value: Any) { env[this] = value } fun resource(name: String): File { if (contentRoots.isEmpty()) throw IllegalStateException("No content roots specified!") contentRoots.forEach { contentRoot -> val file = File(contentRoot, name) if (file.exists()) return file.absoluteFile } throw RuntimeException("Unable to find resource '$name'!") } fun resourceCopy(source: String) { source resourceCopy "" } infix fun String.resourceCopy(destination: String) { val resource = resource(this) val destinationFile = File(realmDir, destination) copy(resource, destinationFile) } fun copy(sourceFile: File, destinationFile: File) { var destination = destinationFile if (sourceFile.isDirectory) { sourceFile.listFiles()?.forEach { file -> copy(file, File(destinationFile, file.name)) } return } if (destinationFile.isDirectory) { destination = File(destination, sourceFile.name) } destination.parentFile.mkdirs() Files.copy(sourceFile.toPath(), destination.toPath(), StandardCopyOption.REPLACE_EXISTING) } fun delete(obj: Any) { if (obj is File) { if (obj.isDirectory) { delete(*obj.listFiles() as Array<out Any>) } obj.delete() return } var path = "/${obj.toString().replace("\\", "/")}" if ("/../" in path) throw RuntimeException("Refusing to delete from suspicious path: $obj") while (path.startsWith("/")) path = path.substring(1) delete(File(realmDir, path)) } fun delete(vararg objects: Any) { objects.forEach(::delete) } }
soochka/src/main/kotlin/context/JavaContext.kt
2916806932
package me.topilov.context class JavaContext( private var javaPath: String = "java", private var mainClass: String? = null, private var jvmArgs: ArrayList<Any> = arrayListOf(), private var arguments: ArrayList<Any> = arrayListOf(), private var classpath: ArrayList<Any> = arrayListOf() ) { fun getExecutionCommand(): List<String> { val args = arrayListOf<String>() args.add(this.javaPath) if (mainClass == null) throw RuntimeException("Java: No main class specified") args.addAll(jvmArgs.map(Any::toString)) if (classpath.isNotEmpty()) { args.add("-cp") args.add(java.lang.String.join(":", classpath.map(Any::toString))) } mainClass ?.also(args::add) args.addAll(arguments.map(Any::toString)) return args } fun xmx(xmx: String) { jvmArgs.add("-Xmx$xmx") } fun xms(xms: String) { jvmArgs.add("-Xms$xms") } fun arguments(vararg arguments: Any) { this.arguments.addAll(arguments) } fun jvmArgs(vararg arguments: Any) { jvmArgs.addAll(arguments) } fun classpath(vararg arguments: Any) { classpath.addAll(arguments) } }
soochka/src/main/kotlin/dsl/annotations.kt
1938498993
package me.topilov.dsl @DslMarker annotation class PresetDslMarker
soochka/src/main/kotlin/dsl/dsl.kt
1241229360
package me.topilov.dsl import me.topilov.context.PresetContext object preset { lateinit var realmType: String var realmId: Int = 1 var assignedPort = 17770 operator fun invoke(init: PresetContext.() -> Unit): PresetContext { return PresetContext().also(init) } }
magame-android/core/src/test/java/com/dicoding/core/KoinModuleTest.kt
1356018174
package com.dicoding.core import android.content.Context import android.util.Log import androidx.room.Room import com.dicoding.core.data.collector.ResultBound import com.dicoding.core.data.source.local.DatabaseGame import com.dicoding.core.data.source.local.entity.favorite.FavoriteDao import com.dicoding.core.data.source.local.entity.game.GameDao import com.dicoding.core.data.source.local.entity.game.GameEntity import com.dicoding.core.data.source.local.source.GameLocalSource import com.dicoding.core.data.source.remote.network.ApiResponse import com.dicoding.core.data.source.remote.network.ApiService import com.dicoding.core.data.source.remote.response.DetailGameResponse import com.dicoding.core.data.source.remote.source.GameRemoteSource import com.dicoding.core.data.source.repository.GameRepository import com.dicoding.core.domain.models.Game import com.dicoding.core.domain.repository.IGameRepository import junit.framework.TestCase.assertNotNull import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.runBlocking import net.sqlcipher.database.SQLiteDatabase import net.sqlcipher.database.SupportFactory import okhttp3.OkHttpClient import org.junit.Before import org.junit.Test import org.koin.android.ext.koin.androidContext import org.koin.core.Koin import org.koin.core.context.startKoin import org.koin.dsl.koinApplication import org.koin.dsl.module import org.koin.test.AutoCloseKoinTest import org.koin.test.get import org.koin.test.inject import org.mockito.Mockito.mock import retrofit2.Retrofit import timber.log.Timber import kotlin.test.assertEquals @ExperimentalCoroutinesApi class KoinModuleTest : AutoCloseKoinTest() { //======= DATABASE ========== private val mockDatabaseGame: DatabaseGame = mock() private val gameDao: GameDao by inject() private val favoriteDao: FavoriteDao by inject() private val database: DatabaseGame by inject() //============================= //======= NETWORK ========== private val mockOkHttpClient: OkHttpClient = mock() private val mockRetrofit: Retrofit = mock() private val apiService: ApiService by inject() //============================= //======= Repository ========== private val mockLocalSource: GameLocalSource = mock() private val mockRemoteSource: GameRemoteSource = mock() private val mockRepository: GameRepository = mock() private val gameLocalSource: GameLocalSource by inject() private val gameRemoteSource: GameRemoteSource by inject() private val repository: GameRepository by inject() //============================= private val mockedContext: Context = mock(Context::class.java) private val moduleDatabase = module { single { mockDatabaseGame } factory { get<DatabaseGame>().gameDao() } factory { get<DatabaseGame>().favoriteDao() } single { Room.inMemoryDatabaseBuilder( androidContext(), DatabaseGame::class.java ).fallbackToDestructiveMigration() .build() } } private val moduleNetwork = module { single { mockOkHttpClient } single { mockRetrofit } single { mock<ApiService>() } } private val moduleRepository = module{ single { mockLocalSource } single { mockRemoteSource } single{ mockRepository } } @Test fun `test android context`() { startKoin { androidContext(mockedContext) modules( module { single { mockDatabaseGame } } ) } assertNotNull(mockDatabaseGame) } @Test fun `test database module dependencies`() { startKoin { androidContext(mockedContext) modules( moduleDatabase ) } assertNotNull(gameDao) assertNotNull(favoriteDao) assertNotNull(database) assert(database is DatabaseGame) } @Test fun `test network module dependencies`() { startKoin { modules( moduleNetwork ) } val injectedOkHttpClient: OkHttpClient by inject() val injectedRetrofit: Retrofit by inject() assertNotNull(injectedOkHttpClient) assertNotNull(injectedRetrofit) assert(apiService is ApiService) } @Test fun `test repository module dependencies`() { startKoin { androidContext(mockedContext) modules( moduleDatabase, moduleNetwork, moduleRepository ) } assertNotNull(gameLocalSource) assertNotNull(gameRemoteSource) assertNotNull(repository) assert(repository is GameRepository) } }
magame-android/core/src/main/java/com/dicoding/core/di/CoreModule.kt
136075994
package com.dicoding.core.di import androidx.room.Room import com.dicoding.core.BuildConfig import com.dicoding.core.data.source.local.DatabaseGame import com.dicoding.core.data.source.local.source.GameLocalSource import com.dicoding.core.data.source.remote.network.ApiService import com.dicoding.core.data.source.remote.source.GameRemoteSource import com.dicoding.core.data.source.repository.GameRepository import com.dicoding.core.domain.repository.IGameRepository import net.sqlcipher.database.SQLiteDatabase import net.sqlcipher.database.SupportFactory import okhttp3.CertificatePinner import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import org.koin.android.ext.koin.androidContext import org.koin.dsl.module import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit val databaseModule = module{ factory{ get<DatabaseGame>().gameDao() } factory{ get<DatabaseGame>().favoriteDao() } single { val passphrase: ByteArray = SQLiteDatabase.getBytes("magame".toCharArray()) val factory = SupportFactory(passphrase) Room.databaseBuilder( androidContext(), DatabaseGame::class.java, "Game.db" ).fallbackToDestructiveMigration() .openHelperFactory(factory) .build() } } val networkModule = module { single { val certificatePinner = CertificatePinner.Builder() .add(BuildConfig.HOST, BuildConfig.SHA_RAWG1) .add(BuildConfig.HOST, BuildConfig.SHA_RAWG2) .add(BuildConfig.HOST, BuildConfig.SHA_RAWG3) .build() OkHttpClient.Builder() .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)) .connectTimeout(120, TimeUnit.SECONDS) .readTimeout(120, TimeUnit.SECONDS) .certificatePinner(certificatePinner) .build() } single { val retrofit = Retrofit.Builder() .baseUrl(BuildConfig.BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .client(get()) .build() retrofit.create(ApiService::class.java) } } val repositoryModule = module{ single { GameLocalSource(get(),get()) } single { GameRemoteSource(get()) } single<IGameRepository> { GameRepository(androidContext(),get(),get()) } }
magame-android/core/src/main/java/com/dicoding/core/utils/DialogImage.kt
2786785964
package com.dicoding.core.utils import android.content.Context import android.view.LayoutInflater import android.view.View import android.widget.ImageView import androidx.appcompat.app.AlertDialog import androidx.swiperefreshlayout.widget.CircularProgressDrawable import com.bumptech.glide.Glide import com.dicoding.core.R class DialogImage (context: Context,inflater: LayoutInflater,urlImage: String){ private var dialog : AlertDialog init{ val builder: AlertDialog.Builder = AlertDialog.Builder(context) val circularProgressDrawable = CircularProgressDrawable(context) circularProgressDrawable.strokeWidth = 5f circularProgressDrawable.centerRadius = 30f circularProgressDrawable.start() val viewtemplelayout: View = inflater.inflate(R.layout.dialog_image, null) builder.setView(viewtemplelayout) dialog = builder.create() val image : ImageView = viewtemplelayout.findViewById(R.id.image) val btnClose : ImageView = viewtemplelayout.findViewById(R.id.btn_close) Glide.with(context).load(urlImage).placeholder(circularProgressDrawable).into(image) btnClose.setOnClickListener{ dialog.dismiss() } } fun show(){ dialog.show() } }
magame-android/core/src/main/java/com/dicoding/core/utils/Connectivity.kt
3176487196
package com.dicoding.core.utils import android.content.Context import android.net.ConnectivityManager import android.net.NetworkCapabilities import timber.log.Timber class Connectivity { companion object{ fun isOnline(context: Context): Boolean { val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager if (connectivityManager != null) { val capabilities = connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork) if (capabilities != null) { if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) { Timber.i("Internet", "NetworkCapabilities.TRANSPORT_CELLULAR") return true } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) { Timber.i("Internet", "NetworkCapabilities.TRANSPORT_WIFI") return true } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) { Timber.i("Internet", "NetworkCapabilities.TRANSPORT_ETHERNET") return true } } } return false } } }
magame-android/core/src/main/java/com/dicoding/core/data/source/repository/GameRepository.kt
93055601
package com.dicoding.core.data.source.repository import android.content.Context import com.dicoding.core.data.collector.DataBoundCollector import com.dicoding.core.data.collector.ResultBound import com.dicoding.core.data.source.local.source.GameLocalSource import com.dicoding.core.data.source.mapper.GameMapper import com.dicoding.core.data.source.remote.network.ApiResponse import com.dicoding.core.data.source.remote.response.DetailGameResponse import com.dicoding.core.data.source.remote.response.GameResponse import com.dicoding.core.data.source.remote.response.GameScreenshots import com.dicoding.core.data.source.remote.source.GameRemoteSource import com.dicoding.core.domain.models.Favorite import com.dicoding.core.domain.models.Game import com.dicoding.core.domain.repository.IGameRepository import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.map class GameRepository( private val context: Context, private val gameLocalSource: GameLocalSource, private val gameRemoteSource: GameRemoteSource ) : IGameRepository { override fun getAllGame(): Flow<ResultBound<List<Game>>> = object : DataBoundCollector<List<Game>, List<GameResponse>>(context) { override fun loadFromDB(): Flow<List<Game>> { return gameLocalSource.getAllData().map { GameMapper.mapEntitiesToDomain(it) } } override suspend fun createCall(): Flow<ApiResponse<List<GameResponse>>> = gameRemoteSource.getAllGame() override suspend fun saveCallResult(data: List<GameResponse>) { val gameList = GameMapper.mapResponsesToEntities(data) gameLocalSource.deleteData() gameLocalSource.insertData(gameList) } }.execute() override fun getAllGameBySearch(search: String): Flow<ResultBound<List<Game>>> = object : DataBoundCollector<List<Game>, List<GameResponse>>(context) { override fun loadFromDB(): Flow<List<Game>> { return gameLocalSource.getAllData().map { GameMapper.mapEntitiesToDomain(it) } } override suspend fun createCall(): Flow<ApiResponse<List<GameResponse>>> = gameRemoteSource.getAllGameBySearch(search) override suspend fun saveCallResult(data: List<GameResponse>) { val gameList = GameMapper.mapResponsesToEntities(data) gameLocalSource.deleteData() gameLocalSource.insertData(gameList) } }.execute() override fun getGameById(id: String): Flow<ApiResponse<DetailGameResponse>> = gameRemoteSource.getGameDetailById(id) override fun getGameScreenshotsById(id: String): Flow<ApiResponse<GameScreenshots>> = gameRemoteSource.getAllGameScreenshotsById(id) override fun getFavoriteByGame(game: Game): Flow<Favorite> = flow { emitAll(gameLocalSource.getFavoriteByGameId(game.id?: "").map { if(it == null){ Favorite() }else{ GameMapper.favEntityToFavDomain(it) } }) } override fun getAllFavorite(): Flow<List<Favorite>> = flow { emitAll(gameLocalSource.getAllDataFavorite().map { listFavoriteEntity -> listFavoriteEntity.map { GameMapper.favEntityToFavDomain(it) } }) } override suspend fun insertFavorite(game: Game) = gameLocalSource.insertFavorite( GameMapper.gameDomainToFavEntity(game) ) override suspend fun deleteFavorite(favorite: Favorite) = gameLocalSource.deleteFavorite( GameMapper.favDomainToFavEntity(favorite) ) }
magame-android/core/src/main/java/com/dicoding/core/data/source/mapper/GameMapper.kt
3175507594
package com.dicoding.core.data.source.mapper import com.dicoding.core.data.source.local.entity.favorite.FavoriteEntity import com.dicoding.core.data.source.local.entity.game.GameEntity import com.dicoding.core.data.source.remote.response.GameResponse import com.dicoding.core.domain.models.Favorite import com.dicoding.core.domain.models.Game object GameMapper { fun mapResponsesToEntities(input: List<GameResponse>): List<GameEntity> { val listGameEntity = ArrayList<GameEntity>() input.map {gameResponse -> val game = GameEntity( gameId = gameResponse.id.toString(), name = gameResponse.name ?: "", rating = (gameResponse.rating ?: 0 ).toFloat(), platform = gameResponse.platforms?.joinToString(",") { it?.platform?.name.toString() } ?: "" , image = gameResponse.backgroundImage ?: "", ratingsCount = gameResponse.ratingsCount ?: 0 ) listGameEntity.add(game) } return listGameEntity } fun mapEntitiesToDomain(input: List<GameEntity>): List<Game> = input.map { Game( name = it.name, rating = it.rating, platform = it.platform, ratingsCount = it.ratingsCount, image = it.image, id = it.gameId, ) } fun gameDomainToFavEntity(it: Game) : FavoriteEntity = FavoriteEntity( name = it.name ?: "", rating = (it.rating ?: 0).toFloat(), platform = it.platform ?: "", ratingsCount = it.ratingsCount ?: 0, image = it.image ?: "", gameId = it.id ?: "", ) fun favEntityToFavDomain(it: FavoriteEntity) : Favorite = Favorite( id = it.id, name = it.name, rating = it.rating, platform = it.platform, ratingsCount = it.ratingsCount, image = it.image, gameId = it.gameId, ) fun favDomainToFavEntity(it: Favorite) : FavoriteEntity = FavoriteEntity( id = it.id!!, name = it.name!!, rating = it.rating!!, platform = it.platform!!, ratingsCount = it.ratingsCount!!, image = it.image!!, gameId = it.gameId!!, ) fun favDomainToGame(it: Favorite) : Game = Game( id = it.gameId!!, name = it.name!!, rating = it.rating!!, platform = it.platform!!, ratingsCount = it.ratingsCount!!, image = it.image!!, ) }
magame-android/core/src/main/java/com/dicoding/core/data/source/local/entity/favorite/FavoriteEntity.kt
3567299620
package com.dicoding.core.data.source.local.entity.favorite import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "favorite") data class FavoriteEntity ( @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "id") var id: Int = 0, @ColumnInfo(name= "game_id") var gameId: String, @ColumnInfo(name= "name") var name: String, @ColumnInfo(name= "rating") var rating: Float, @ColumnInfo(name= "ratings_count") var ratingsCount: Int, @ColumnInfo(name= "platform") var platform: String, @ColumnInfo(name= "image") var image: String, )
magame-android/core/src/main/java/com/dicoding/core/data/source/local/entity/favorite/FavoriteDao.kt
2238829914
package com.dicoding.core.data.source.local.entity.favorite import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import kotlinx.coroutines.flow.Flow @Dao interface FavoriteDao { @Insert(onConflict = OnConflictStrategy.IGNORE) suspend fun insert(favorite: FavoriteEntity) @Delete suspend fun delete(favorite: FavoriteEntity) @Query("SELECT * from favorite ORDER BY id ASC") fun getAllData(): Flow<List<FavoriteEntity>> @Query("SELECT * from favorite where game_id = :gameId ORDER BY id ASC") fun getDataByGameId(gameId:String): Flow<FavoriteEntity> }
magame-android/core/src/main/java/com/dicoding/core/data/source/local/entity/game/GameDao.kt
4043161800
package com.dicoding.core.data.source.local.entity.game import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import kotlinx.coroutines.flow.Flow @Dao interface GameDao { @Insert(onConflict = OnConflictStrategy.IGNORE) suspend fun insert(game: List<GameEntity>) @Query("delete from game") suspend fun deleteAlldata() @Query("SELECT * from game ORDER BY id ASC") fun getAllData(): Flow<List<GameEntity>> }
magame-android/core/src/main/java/com/dicoding/core/data/source/local/entity/game/GameEntity.kt
1041811951
package com.dicoding.core.data.source.local.entity.game import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "game") data class GameEntity ( @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "id") var id: Int = 0, @ColumnInfo(name= "game_id") var gameId: String, @ColumnInfo(name= "name") var name: String, @ColumnInfo(name= "rating") var rating: Float, @ColumnInfo(name= "ratings_count") var ratingsCount: Int, @ColumnInfo(name= "platform") var platform: String, @ColumnInfo(name= "image") var image: String, )
magame-android/core/src/main/java/com/dicoding/core/data/source/local/entity/genre/GenreDao.kt
1274077254
package com.dicoding.core.data.source.local.entity.genre import androidx.room.Dao import androidx.lifecycle.LiveData import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.Update @Dao interface GenreDao { @Insert(onConflict = OnConflictStrategy.IGNORE) suspend fun insert(dao: GenreDao) @Update suspend fun update(dao: GenreDao) @Delete suspend fun delete(dao: GenreDao) @Query("SELECT * from genres ORDER BY id ASC") fun getAllData(): LiveData<List<GenreDao>> }
magame-android/core/src/main/java/com/dicoding/core/data/source/local/entity/genre/GenreEntity.kt
2390301251
package com.dicoding.core.data.source.local.entity.genre import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "genres") data class GenreEntity ( @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "id") var id: Int = 0, @ColumnInfo(name= "id_genre") var idGenre: String, @ColumnInfo(name= "name") var name: String )
magame-android/core/src/main/java/com/dicoding/core/data/source/local/source/GameLocalSource.kt
3067560250
package com.dicoding.core.data.source.local.source import com.dicoding.core.data.source.local.entity.favorite.FavoriteDao import com.dicoding.core.data.source.local.entity.favorite.FavoriteEntity import com.dicoding.core.data.source.local.entity.game.GameDao import com.dicoding.core.data.source.local.entity.game.GameEntity import kotlinx.coroutines.flow.Flow class GameLocalSource(private val gameDao: GameDao,private val favoriteDao: FavoriteDao) { fun getAllData() : Flow<List<GameEntity>> = gameDao.getAllData() suspend fun insertData(games: List<GameEntity>) = gameDao.insert(games) suspend fun deleteData() = gameDao.deleteAlldata() suspend fun insertFavorite(favoriteEntity: FavoriteEntity) = favoriteDao.insert(favoriteEntity) suspend fun deleteFavorite(favoriteEntity: FavoriteEntity) = favoriteDao.delete(favoriteEntity) fun getAllDataFavorite() : Flow<List<FavoriteEntity>> = favoriteDao.getAllData() fun getFavoriteByGameId(gameId: String) : Flow<FavoriteEntity> = favoriteDao.getDataByGameId(gameId) }
magame-android/core/src/main/java/com/dicoding/core/data/source/local/DatabaseGame.kt
2682672538
package com.dicoding.core.data.source.local import androidx.room.Database import androidx.room.RoomDatabase import com.dicoding.core.data.source.local.entity.favorite.FavoriteDao import com.dicoding.core.data.source.local.entity.favorite.FavoriteEntity import com.dicoding.core.data.source.local.entity.game.GameDao import com.dicoding.core.data.source.local.entity.game.GameEntity @Database(entities = [GameEntity::class,FavoriteEntity::class], version = 3, exportSchema = false) abstract class DatabaseGame : RoomDatabase() { abstract fun gameDao(): GameDao abstract fun favoriteDao(): FavoriteDao }
magame-android/core/src/main/java/com/dicoding/core/data/source/remote/response/GameResponse.kt
3076843311
package com.dicoding.core.data.source.remote.response import com.google.gson.annotations.SerializedName data class GameResponse( @field:SerializedName("added") val added: Int? = null, @field:SerializedName("rating") val rating: Float? = null, @field:SerializedName("metacritic") val metacritic: Int? = null, @field:SerializedName("playtime") val playtime: Int? = null, @field:SerializedName("short_screenshots") val shortScreenshots: List<ShortScreenshotsItem?>? = null, @field:SerializedName("platforms") val platforms: List<PlatformsItem?>? = null, @field:SerializedName("user_game") val userGame: Any? = null, @field:SerializedName("rating_top") val ratingTop: Int? = null, @field:SerializedName("reviews_text_count") val reviewsTextCount: Int? = null, @field:SerializedName("ratings") val ratings: List<RatingsItem?>? = null, @field:SerializedName("genres") val genres: List<GenresItem?>? = null, @field:SerializedName("saturated_color") val saturatedColor: String? = null, @field:SerializedName("id") val id: Int? = null, @field:SerializedName("added_by_status") val addedByStatus: AddedByStatus? = null, @field:SerializedName("parent_platforms") val parentPlatforms: List<ParentPlatformsItem?>? = null, @field:SerializedName("ratings_count") val ratingsCount: Int? = null, @field:SerializedName("slug") val slug: String? = null, @field:SerializedName("released") val released: String? = null, @field:SerializedName("suggestions_count") val suggestionsCount: Int? = null, @field:SerializedName("stores") val stores: List<StoresItem?>? = null, @field:SerializedName("tags") val tags: List<TagsItem?>? = null, @field:SerializedName("background_image") val backgroundImage: String? = null, @field:SerializedName("tba") val tba: Boolean? = null, @field:SerializedName("dominant_color") val dominantColor: String? = null, @field:SerializedName("esrb_rating") val esrbRating: EsrbRating? = null, @field:SerializedName("name") val name: String? = null, @field:SerializedName("updated") val updated: String? = null, @field:SerializedName("clip") val clip: Any? = null, @field:SerializedName("reviews_count") val reviewsCount: Int? = null )
magame-android/core/src/main/java/com/dicoding/core/data/source/remote/response/BaseGameResponse.kt
2999452475
package com.dicoding.core.data.source.remote.response import com.google.gson.annotations.SerializedName data class BaseGameResponse( @field:SerializedName("next") val next: String? = null, @field:SerializedName("nofollow") val nofollow: Boolean? = null, @field:SerializedName("noindex") val noindex: Boolean? = null, @field:SerializedName("nofollow_collections") val nofollowCollections: List<String?>? = null, @field:SerializedName("previous") val previous: Any? = null, @field:SerializedName("count") val count: Int? = null, @field:SerializedName("description") val description: String? = null, @field:SerializedName("seo_h1") val seoH1: String? = null, @field:SerializedName("filters") val filters: Filters? = null, @field:SerializedName("seo_title") val seoTitle: String? = null, @field:SerializedName("seo_description") val seoDescription: String? = null, @field:SerializedName("results") val results: List<GameResponse>, @field:SerializedName("seo_keywords") val seoKeywords: String? = null ) data class EsrbRating( @field:SerializedName("name") val name: String? = null, @field:SerializedName("id") val id: Int? = null, @field:SerializedName("slug") val slug: String? = null ) data class ShortScreenshotsItem( @field:SerializedName("image") val image: String? = null, @field:SerializedName("id") val id: Int? = null ) data class Platform( @field:SerializedName("image") val image: Any? = null, @field:SerializedName("games_count") val gamesCount: Int? = null, @field:SerializedName("year_end") val yearEnd: Any? = null, @field:SerializedName("year_start") val yearStart: Int? = null, @field:SerializedName("name") val name: String? = null, @field:SerializedName("id") val id: Int? = null, @field:SerializedName("image_background") val imageBackground: String? = null, @field:SerializedName("slug") val slug: String? = null ) data class TagsItem( @field:SerializedName("games_count") val gamesCount: Int? = null, @field:SerializedName("name") val name: String? = null, @field:SerializedName("language") val language: String? = null, @field:SerializedName("id") val id: Int? = null, @field:SerializedName("image_background") val imageBackground: String? = null, @field:SerializedName("slug") val slug: String? = null ) data class StoresItem( @field:SerializedName("id") val id: Int? = null, @field:SerializedName("store") val store: Store? = null ) data class PlatformsItem( @field:SerializedName("requirements_ru") val requirementsRu: Any? = null, @field:SerializedName("requirements_en") val requirementsEn: Any? = null, @field:SerializedName("released_at") val releasedAt: String? = null, @field:SerializedName("platform") val platform: Platform? = null ) data class RatingsItem( @field:SerializedName("count") val count: Int? = null, @field:SerializedName("id") val id: Int? = null, @field:SerializedName("title") val title: String? = null, @field:SerializedName("percent") val percent: Any? = null ) data class GenresItem( @field:SerializedName("games_count") val gamesCount: Int? = null, @field:SerializedName("name") val name: String? = null, @field:SerializedName("id") val id: Int? = null, @field:SerializedName("image_background") val imageBackground: String? = null, @field:SerializedName("slug") val slug: String? = null ) data class ParentPlatformsItem( @field:SerializedName("platform") val platform: Platform? = null ) data class Store( @field:SerializedName("games_count") val gamesCount: Int? = null, @field:SerializedName("domain") val domain: String? = null, @field:SerializedName("name") val name: String? = null, @field:SerializedName("id") val id: Int? = null, @field:SerializedName("image_background") val imageBackground: String? = null, @field:SerializedName("slug") val slug: String? = null ) data class YearsItem( @field:SerializedName("filter") val filter: String? = null, @field:SerializedName("nofollow") val nofollow: Boolean? = null, @field:SerializedName("decade") val decade: Int? = null, @field:SerializedName("count") val count: Int? = null, @field:SerializedName("from") val from: Int? = null, @field:SerializedName("to") val to: Int? = null, @field:SerializedName("years") val years: List<YearsItem?>? = null, @field:SerializedName("year") val year: Int? = null ) data class AddedByStatus( @field:SerializedName("owned") val owned: Int? = null, @field:SerializedName("beaten") val beaten: Int? = null, @field:SerializedName("dropped") val dropped: Int? = null, @field:SerializedName("yet") val yet: Int? = null, @field:SerializedName("playing") val playing: Int? = null, @field:SerializedName("toplay") val toplay: Int? = null ) data class Filters( @field:SerializedName("years") val years: List<YearsItem?>? = null )
magame-android/core/src/main/java/com/dicoding/core/data/source/remote/response/GameScreenshots.kt
2531655562
package com.dicoding.core.data.source.remote.response import com.google.gson.annotations.SerializedName data class GameScreenshots( @field:SerializedName("next") val next: Any? = null, @field:SerializedName("previous") val previous: Any? = null, @field:SerializedName("count") val count: Int? = null, @field:SerializedName("results") val results: List<ScreenshotItem>? = null ) data class ScreenshotItem( @field:SerializedName("image") val image: String? = null, @field:SerializedName("is_deleted") val isDeleted: Boolean? = null, @field:SerializedName("width") val width: Int? = null, @field:SerializedName("id") val id: Int? = null, @field:SerializedName("height") val height: Int? = null )
magame-android/core/src/main/java/com/dicoding/core/data/source/remote/response/DetailGameResponse.kt
1698346749
package com.dicoding.core.data.source.remote.response import com.google.gson.annotations.SerializedName data class DetailGameResponse( @field:SerializedName("added") val added: Int, @field:SerializedName("name_original") val nameOriginal: String, @field:SerializedName("rating") val rating: Any, @field:SerializedName("game_series_count") val gameSeriesCount: Int, @field:SerializedName("playtime") val playtime: Int, @field:SerializedName("platforms") val platforms: List<PlatformsItem>, @field:SerializedName("rating_top") val ratingTop: Int, @field:SerializedName("reviews_text_count") val reviewsTextCount: Int, @field:SerializedName("achievements_count") val achievementsCount: Int, @field:SerializedName("id") val id: Int, @field:SerializedName("parent_platforms") val parentPlatforms: List<ParentPlatformsItem>, @field:SerializedName("reddit_name") val redditName: String, @field:SerializedName("ratings_count") val ratingsCount: Int, @field:SerializedName("slug") val slug: String, @field:SerializedName("released") val released: String, @field:SerializedName("youtube_count") val youtubeCount: Int, @field:SerializedName("movies_count") val moviesCount: Int, @field:SerializedName("description_raw") val descriptionRaw: String, @field:SerializedName("tags") val tags: List<TagsItem>, @field:SerializedName("background_image") val backgroundImage: String, @field:SerializedName("tba") val tba: Boolean, @field:SerializedName("dominant_color") val dominantColor: String, @field:SerializedName("name") val name: String, @field:SerializedName("reddit_description") val redditDescription: String, @field:SerializedName("reddit_logo") val redditLogo: String, @field:SerializedName("updated") val updated: String, @field:SerializedName("reviews_count") val reviewsCount: Int, @field:SerializedName("metacritic") val metacritic: Int, @field:SerializedName("description") val description: String, @field:SerializedName("metacritic_url") val metacriticUrl: String, @field:SerializedName("alternative_names") val alternativeNames: List<String>, @field:SerializedName("parents_count") val parentsCount: Int, @field:SerializedName("user_game") val userGame: Any, @field:SerializedName("creators_count") val creatorsCount: Int, @field:SerializedName("ratings") val ratings: List<RatingsItem>, @field:SerializedName("genres") val genres: List<GenresItem>, @field:SerializedName("saturated_color") val saturatedColor: String, @field:SerializedName("added_by_status") val addedByStatus: AddedByStatus, @field:SerializedName("reddit_url") val redditUrl: String, @field:SerializedName("reddit_count") val redditCount: Int, @field:SerializedName("parent_achievements_count") val parentAchievementsCount: Int, @field:SerializedName("website") val website: String, @field:SerializedName("suggestions_count") val suggestionsCount: Int, @field:SerializedName("stores") val stores: List<StoresItem>, @field:SerializedName("additions_count") val additionsCount: Int, @field:SerializedName("twitch_count") val twitchCount: Int, @field:SerializedName("background_image_additional") val backgroundImageAdditional: String, @field:SerializedName("esrb_rating") val esrbRating: EsrbRating, @field:SerializedName("screenshots_count") val screenshotsCount: Int, @field:SerializedName("clip") val clip: Any )
magame-android/core/src/main/java/com/dicoding/core/data/source/remote/source/GameRemoteSource.kt
2629680870
package com.dicoding.core.data.source.remote.source import com.dicoding.core.data.source.remote.network.ApiResponse import com.dicoding.core.data.source.remote.network.ApiService import com.dicoding.core.data.source.remote.response.DetailGameResponse import com.dicoding.core.data.source.remote.response.GameResponse import com.dicoding.core.data.source.remote.response.GameScreenshots import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOn import timber.log.Timber class GameRemoteSource(private val apiService: ApiService) { fun getAllGame(): Flow<ApiResponse<List<GameResponse>>> { //get data from remote api return flow { try { val response = apiService.getList() val dataArray = response.results if (dataArray.isNotEmpty()){ emit(ApiResponse.Success(dataArray)) } else { emit(ApiResponse.Empty) } } catch (e : Exception){ emit(ApiResponse.Error(e.toString())) Timber.e("RemoteDataSource", e.toString()) } }.flowOn(Dispatchers.IO) } fun getAllGameBySearch(search:String): Flow<ApiResponse<List<GameResponse>>> { //get data from remote api return flow { try { val response = apiService.getListBySearch(search) val dataArray = response.results if (dataArray.isNotEmpty()){ emit(ApiResponse.Success(dataArray)) } else { emit(ApiResponse.Empty) } } catch (e : Exception){ emit(ApiResponse.Error(e.toString())) Timber.e("RemoteDataSource", e.toString()) } }.flowOn(Dispatchers.IO) } fun getGameDetailById(id:String): Flow<ApiResponse<DetailGameResponse>> { //get data from remote api return flow { emit(ApiResponse.Loading) try { val response = apiService.getGameById(id) if (response == null){ emit(ApiResponse.Empty) } else { emit(ApiResponse.Success(response)) } } catch (e : Exception){ emit(ApiResponse.Error(e.toString())) Timber.e("RemoteDataSource", e.toString()) } }.flowOn(Dispatchers.IO) } fun getAllGameScreenshotsById(id:String): Flow<ApiResponse<GameScreenshots>> { //get data from remote api return flow { try { val response = apiService.getScreenshotsGameById(id) if (response == null){ emit(ApiResponse.Empty) } else { emit(ApiResponse.Success(response)) } } catch (e : Exception){ emit(ApiResponse.Error(e.toString())) Timber.e("RemoteDataSource", e.toString()) } }.flowOn(Dispatchers.IO) } }
magame-android/core/src/main/java/com/dicoding/core/data/source/remote/network/ApiService.kt
3214588025
package com.dicoding.core.data.source.remote.network import com.dicoding.core.BuildConfig import com.dicoding.core.data.source.remote.response.BaseGameResponse import com.dicoding.core.data.source.remote.response.DetailGameResponse import com.dicoding.core.data.source.remote.response.GameScreenshots import retrofit2.http.GET import retrofit2.http.Path import retrofit2.http.Query interface ApiService { @GET("games?token&key=${BuildConfig.API_TOKEN}") suspend fun getList() : BaseGameResponse @GET("games?token&key=${BuildConfig.API_TOKEN}") suspend fun getListBySearch(@Query("search") search:String) : BaseGameResponse @GET("games/{id}?token&key=${BuildConfig.API_TOKEN}") suspend fun getGameById(@Path("id") id:String) : DetailGameResponse @GET("games/{id}/screenshots?token&key=${BuildConfig.API_TOKEN}") suspend fun getScreenshotsGameById(@Path("id") id:String) : GameScreenshots }
magame-android/core/src/main/java/com/dicoding/core/data/source/remote/network/ApiResponse.kt
438004254
package com.dicoding.core.data.source.remote.network sealed class ApiResponse<out R> { data class Success<out T>(val data: T) : ApiResponse<T>() data class Error(val errorMessage: String) : ApiResponse<Nothing>() data object Empty : ApiResponse<Nothing>() data object Loading : ApiResponse<Nothing>() }
magame-android/core/src/main/java/com/dicoding/core/data/collector/ResultBound.kt
1782828787
package com.dicoding.core.data.collector sealed class ResultBound<T>(val data: T? = null, val message: String? = null) { class Success<T>(data: T) : ResultBound<T>(data) class Loading<T>(data: T? = null) : ResultBound<T>(data) class Error<T>(message: String, data: T? = null) : ResultBound<T>(data, message) }
magame-android/core/src/main/java/com/dicoding/core/data/collector/DataBoundCollector.kt
907832910
package com.dicoding.core.data.collector import android.content.Context import com.dicoding.core.data.source.remote.network.ApiResponse import com.dicoding.core.utils.Connectivity import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.map abstract class DataBoundCollector<ResultType,RequestType>(context:Context) { private var context: Context init { this.context = context } fun execute() = flow<ResultBound<ResultType>>{ emit(ResultBound.Loading());val db = loadFromDB() if(Connectivity.isOnline(context)){ when (val apiResponse = createCall().first()) { is ApiResponse.Empty -> emitAll(db.map { ResultBound.Success(it) }) is ApiResponse.Success -> { saveCallResult(apiResponse.data) emitAll(db.map { ResultBound.Success(it) }) }is ApiResponse.Error -> { emit(ResultBound.Error(apiResponse.errorMessage)) }else -> emitAll(db.map { ResultBound.Success(it) })} }else{ emitAll(db.map { ResultBound.Success(it) }) } } protected abstract fun loadFromDB(): Flow<ResultType> protected abstract suspend fun createCall(): Flow<ApiResponse<RequestType>> protected abstract suspend fun saveCallResult(data: RequestType) }
magame-android/core/src/main/java/com/dicoding/core/domain/repository/IGameRepository.kt
3525895721
package com.dicoding.core.domain.repository import com.dicoding.core.data.collector.ResultBound import com.dicoding.core.data.source.remote.network.ApiResponse import com.dicoding.core.data.source.remote.response.DetailGameResponse import com.dicoding.core.data.source.remote.response.GameScreenshots import com.dicoding.core.domain.models.Favorite import com.dicoding.core.domain.models.Game import kotlinx.coroutines.flow.Flow interface IGameRepository { fun getAllGame(): Flow<ResultBound<List<Game>>> fun getAllGameBySearch(search: String): Flow<ResultBound<List<Game>>> fun getGameById(id:String): Flow<ApiResponse<DetailGameResponse>> fun getGameScreenshotsById(id:String): Flow<ApiResponse<GameScreenshots>> fun getFavoriteByGame(game: Game): Flow<Favorite> fun getAllFavorite(): Flow<List<Favorite>> suspend fun insertFavorite(game: Game) suspend fun deleteFavorite(favorite: Favorite) }
magame-android/core/src/main/java/com/dicoding/core/domain/models/Favorite.kt
3186050550
package com.dicoding.core.domain.models import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class Favorite ( val id: Int? = null, val gameId: String? = null, val name: String? = null, val rating: Float? = null, val ratingsCount: Int? = null, val platform: String? = null, val image: String? = null, ): Parcelable
magame-android/core/src/main/java/com/dicoding/core/domain/models/Game.kt
3657881856
package com.dicoding.core.domain.models import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class Game ( val id: String? = null, val name: String? = null, val rating: Float? = null, val ratingsCount: Int? = null, val platform: String? = null, val image: String? = null, ):Parcelable
magame-android/core/src/main/java/com/dicoding/core/domain/usecase/GameUseCase.kt
510197937
package com.dicoding.core.domain.usecase import com.dicoding.core.data.collector.ResultBound import com.dicoding.core.data.source.remote.network.ApiResponse import com.dicoding.core.data.source.remote.response.DetailGameResponse import com.dicoding.core.data.source.remote.response.GameScreenshots import com.dicoding.core.domain.models.Favorite import com.dicoding.core.domain.models.Game import kotlinx.coroutines.flow.Flow interface GameUseCase { fun getAllGame(): Flow<ResultBound<List<Game>>> fun getAllGameBySearch(search: String): Flow<ResultBound<List<Game>>> fun getGameById(id:String): Flow<ApiResponse<DetailGameResponse>> fun getGameScreenshotsById(id:String): Flow<ApiResponse<GameScreenshots>> suspend fun addFavorite(game: Game) suspend fun deleteFavorite(favorite: Favorite) fun getFavoriteByGame(game: Game): Flow<Favorite> fun getAllFavorite(): Flow<List<Favorite>> }
magame-android/core/src/main/java/com/dicoding/core/domain/usecase/GameInteractor.kt
4263783191
package com.dicoding.core.domain.usecase import com.dicoding.core.data.collector.ResultBound import com.dicoding.core.data.source.remote.network.ApiResponse import com.dicoding.core.data.source.remote.response.DetailGameResponse import com.dicoding.core.data.source.remote.response.GameScreenshots import com.dicoding.core.domain.models.Favorite import com.dicoding.core.domain.models.Game import com.dicoding.core.domain.repository.IGameRepository import kotlinx.coroutines.flow.Flow class GameInteractor(private val gameRepository: IGameRepository): GameUseCase { override fun getAllGame(): Flow<ResultBound<List<Game>>> = gameRepository.getAllGame() override fun getAllGameBySearch(search: String): Flow<ResultBound<List<Game>>> = gameRepository.getAllGameBySearch(search) override fun getGameById(id: String): Flow<ApiResponse<DetailGameResponse>> = gameRepository.getGameById(id) override fun getGameScreenshotsById(id: String): Flow<ApiResponse<GameScreenshots>> = gameRepository.getGameScreenshotsById(id) override fun getFavoriteByGame(game: Game) = gameRepository.getFavoriteByGame(game) override fun getAllFavorite(): Flow<List<Favorite>> = gameRepository.getAllFavorite() override suspend fun addFavorite(game: Game) = gameRepository.insertFavorite(game) override suspend fun deleteFavorite(favorite: Favorite) = gameRepository.deleteFavorite(favorite) }
magame-android/app/src/main/java/com/dicoding/magame/ui/game/detail/DetailGameFragment.kt
1416106499
package com.dicoding.magame.ui.game.detail import android.os.Build import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import com.bumptech.glide.Glide import com.dicoding.core.data.source.remote.network.ApiResponse import com.dicoding.core.data.source.remote.response.ScreenshotItem import com.dicoding.core.domain.models.Favorite import com.dicoding.core.domain.models.Game import com.dicoding.core.utils.DialogImage import com.dicoding.magame.R import com.dicoding.magame.databinding.FragmentDetailGameBinding import com.dicoding.magame.ui.game.detail.adapter.ScreenshootAdapter import com.dicoding.magame.ui.game.list.GameFragment.Companion.EXTRA_GAME import org.koin.androidx.viewmodel.ext.android.viewModel @Suppress("DEPRECATION") class DetailGameFragment : Fragment(),View.OnClickListener { private var _binding: FragmentDetailGameBinding? = null private val binding get() = _binding!! private var favorite: Favorite = Favorite() private lateinit var detailGameViewModel: DetailGameViewModel private lateinit var game: Game override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) var onScrollDown = false val cardParam = binding.detailGame.cardDetail.layoutParams as ViewGroup.MarginLayoutParams val topCardParam = cardParam.topMargin val detailGameViewModel: DetailGameViewModel by viewModel() this.detailGameViewModel = detailGameViewModel val game: Game? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { arguments?.getParcelable(EXTRA_GAME, Game::class.java) } else { arguments?.getParcelable(EXTRA_GAME) } this.game = game ?: Game() binding.detailGame.txtTitle.text = game?.name.toString() binding.detailGame.txtPlatform.text = getString(com.dicoding.core.R.string.platform_text,game?.platform) binding.detailGame.ratingBar.rating = (game?.rating ?: 0).toFloat() binding.detailGame.txtRating.text = getString(com.dicoding.core.R.string.rating_text,game?.rating ?: "" , game?.ratingsCount ?: "") Glide.with(requireActivity()).load(game?.image).into(binding.detailGame.imageGame) detailGameViewModel.detail(game?.id.toString()).observe(viewLifecycleOwner) { apiResponse -> when (apiResponse) { ApiResponse.Loading -> showLoading(true) ApiResponse.Empty -> { showLoading(false) Toast.makeText(requireActivity(), getString(R.string.detail_description_not_show),Toast.LENGTH_SHORT).show() } is ApiResponse.Error -> { showLoading(false) Toast.makeText(requireActivity(), getString(R.string.error_message),Toast.LENGTH_SHORT).show() } is ApiResponse.Success -> { showLoading(false) binding.detailGame.description.text = apiResponse.data.descriptionRaw Glide.with(requireActivity()).load(apiResponse.data.backgroundImageAdditional).into(binding.imageGameCover) } } } detailGameViewModel.screenshots(game?.id.toString()).observe(viewLifecycleOwner){apiResponse -> when (apiResponse) { ApiResponse.Loading -> showLoadingScreenshot(true) ApiResponse.Empty -> { showLoadingScreenshot(false) Toast.makeText(requireActivity(), getString(R.string.detail_screenshots_not_show),Toast.LENGTH_SHORT).show() } is ApiResponse.Error -> { showLoadingScreenshot(false) Toast.makeText(requireActivity(), getString(R.string.error_message),Toast.LENGTH_SHORT).show() } is ApiResponse.Success -> { showLoadingScreenshot(false) showRvScreenshot(apiResponse.data.results) } } } binding.detailGame.rvScreenshot.layoutManager = LinearLayoutManager(requireContext(),LinearLayoutManager.HORIZONTAL,false) binding.btnFavorite.setOnClickListener(this) binding.backButton.setOnClickListener(this) binding.appBarLayout.addOnOffsetChangedListener{ _, verticalOffset: Int -> if(verticalOffset <= -577 && !onScrollDown){ onScrollDown = true cardParam.setMargins(0,0,0,-30) binding.detailGame.cardDetail.layoutParams = cardParam }else if(verticalOffset >= -50 && onScrollDown){ onScrollDown = false cardParam.setMargins(0,topCardParam,0,-30) binding.detailGame.cardDetail.layoutParams = cardParam } } getFavorite() } private fun showRvScreenshot(list: List<ScreenshotItem>? = null){ if(list != null){ val adapter = ScreenshootAdapter(requireContext(),list) binding.detailGame.rvScreenshot.adapter = adapter adapter.setOnItemClickCallback(object : ScreenshootAdapter.OnItemClickCallback { override fun onItemClicked(data: ScreenshotItem) { DialogImage(requireContext(),layoutInflater,data.image.toString()).show() } }) } } private fun showLoading(loading: Boolean) { binding.progressBarCover.visibility = if (loading) View.VISIBLE else View.GONE binding.detailGame.progressBarDescription.visibility = if (loading) View.VISIBLE else View.GONE } private fun showLoadingScreenshot(loading: Boolean) { binding.detailGame.shimmerSs.progressBarScreenshot.visibility = if (loading) View.VISIBLE else View.GONE binding.detailGame.rvScreenshot.visibility = if (!loading) View.VISIBLE else View.GONE } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentDetailGameBinding.inflate(inflater, container, false) return binding.root } private fun getFavorite(){ binding.btnFavorite.speed = 2f detailGameViewModel.getFavoriteByGame(game).observe(viewLifecycleOwner){ if(it != Favorite()){ favorite = it binding.btnFavorite.playAnimation() } } } override fun onClick(v: View?) { if(v?.id == R.id.btn_favorite){ if(favorite == Favorite()){ binding.btnFavorite.playAnimation() detailGameViewModel.addFavorite(game) }else{ binding.btnFavorite.frame = 0 detailGameViewModel.deleteFavorite(favorite) favorite = Favorite() } } //back button if(v?.id == R.id.back_button){ activity?.onBackPressedDispatcher?.onBackPressed() // with this line } } }
magame-android/app/src/main/java/com/dicoding/magame/ui/game/detail/DetailGameViewModel.kt
1825083021
package com.dicoding.magame.ui.game.detail import androidx.lifecycle.ViewModel import androidx.lifecycle.asLiveData import androidx.lifecycle.viewModelScope import com.dicoding.core.domain.models.Favorite import com.dicoding.core.domain.models.Game import com.dicoding.core.domain.usecase.GameUseCase import kotlinx.coroutines.launch class DetailGameViewModel(private val gameUseCase: GameUseCase): ViewModel() { fun detail(id:String) = gameUseCase.getGameById(id).asLiveData() fun screenshots(id:String) = gameUseCase.getGameScreenshotsById(id).asLiveData() fun addFavorite(game: Game) = viewModelScope.launch { gameUseCase.addFavorite(game) } fun deleteFavorite(favorite: Favorite) = viewModelScope.launch { gameUseCase.deleteFavorite(favorite) } fun getFavoriteByGame(game: Game) = gameUseCase.getFavoriteByGame(game).asLiveData() }
magame-android/app/src/main/java/com/dicoding/magame/ui/game/detail/adapter/ScreenshootAdapter.kt
85321223
package com.dicoding.magame.ui.game.detail.adapter import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.dicoding.core.data.source.remote.response.ScreenshotItem import com.dicoding.magame.databinding.ItemScreenshotBinding class ScreenshootAdapter(private val context: Context,private val listScreenshoot: List<ScreenshotItem>) : RecyclerView.Adapter<ScreenshootAdapter.MyViewHolder>() { private lateinit var onItemClickCallback: OnItemClickCallback fun setOnItemClickCallback(onItemClickCallback: OnItemClickCallback) { this.onItemClickCallback = onItemClickCallback } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder { val binding = ItemScreenshotBinding.inflate(LayoutInflater.from(parent.context), parent, false) return MyViewHolder(binding) } override fun onBindViewHolder(holder: MyViewHolder, position: Int) { val data = listScreenshoot[position] holder.bind(data,context) holder.itemView.setOnClickListener { onItemClickCallback.onItemClicked(listScreenshoot[holder.adapterPosition]) } } override fun getItemCount(): Int = listScreenshoot.size class MyViewHolder(private val binding: ItemScreenshotBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(data: ScreenshotItem,context: Context) { Glide.with(context).load(data.image).into(binding.image) } } interface OnItemClickCallback { fun onItemClicked(data: ScreenshotItem) } }
magame-android/app/src/main/java/com/dicoding/magame/ui/game/list/GameViewModel.kt
4263425773
package com.dicoding.magame.ui.game.list import androidx.lifecycle.ViewModel import androidx.lifecycle.asLiveData import com.dicoding.core.domain.usecase.GameUseCase class GameViewModel(private val gameUseCase: GameUseCase): ViewModel() { fun games() = gameUseCase.getAllGame().asLiveData() fun gameSearch(search:String) = gameUseCase.getAllGameBySearch(search).asLiveData() }
magame-android/app/src/main/java/com/dicoding/magame/ui/game/list/adapter/GameAdapter.kt
2000776128
package com.dicoding.magame.ui.game.list.adapter import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.dicoding.core.R import com.dicoding.core.databinding.ItemGameBinding import com.dicoding.core.domain.models.Game class GameAdapter (private val context: Context,private val listGame: List<Game>) : RecyclerView.Adapter<GameAdapter.MyViewHolder>() { private lateinit var onItemClickCallback: OnItemClickCallback fun setOnItemClickCallback(onItemClickCallback: OnItemClickCallback) { this.onItemClickCallback = onItemClickCallback } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder { val binding = ItemGameBinding.inflate(LayoutInflater.from(parent.context), parent, false) return MyViewHolder(binding) } override fun onBindViewHolder(holder: MyViewHolder, position: Int) { val data = listGame[position] holder.bind(data,context) holder.itemView.setOnClickListener { onItemClickCallback.onItemClicked(listGame[holder.adapterPosition]) } } override fun getItemCount(): Int = listGame.size class MyViewHolder(private val binding: ItemGameBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(data: Game, context: Context) { binding.txtTitle.text = data.name binding.ratingBar.rating = (data.rating ?: 0).toFloat() binding.txtRating.text = context.getString(R.string.rating_text,data.rating ?: "" , data.ratingsCount ?: "") binding.txtPlatform.text = context.getString(R.string.platform_text,data.platform ?: "" ) Glide.with(context).load(data.image).into(binding.imageGame) } } interface OnItemClickCallback { fun onItemClicked(data: Game) } }
magame-android/app/src/main/java/com/dicoding/magame/ui/game/list/GameFragment.kt
3390494027
package com.dicoding.magame.ui.game.list import android.os.Bundle import android.view.LayoutInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.navigation.findNavController import androidx.recyclerview.widget.LinearLayoutManager import com.dicoding.core.data.collector.ResultBound import com.dicoding.core.domain.models.Game import com.dicoding.magame.ui.game.list.adapter.GameAdapter import com.dicoding.magame.R import com.dicoding.magame.databinding.FragmentGameBinding import com.google.android.material.snackbar.Snackbar import org.koin.androidx.viewmodel.ext.android.viewModel class GameFragment : Fragment(),MenuItem.OnMenuItemClickListener { private var _binding: FragmentGameBinding? = null private val binding get() = _binding!! private lateinit var gameViewModel: GameViewModel private var search: String = "" override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val gameViewModel: GameViewModel by viewModel() this.gameViewModel = gameViewModel binding.rvGame.layoutManager = LinearLayoutManager(requireContext()) if(search == ""){ showUserList() }else{ showUserListSearch(search) } with(binding) { searchView.setupWithSearchBar(searchBar) searchView.editText.setOnEditorActionListener{_,_,event -> searchBar.setText(searchView.text) search = searchView.text.toString() searchView.hide() binding.rvGame.visibility = View.GONE if(searchView.text.toString() == ""){ showUserList() }else{ showUserListSearch(searchView.text.toString()) } false } searchBar.menu.findItem(R.id.favorite_item).setOnMenuItemClickListener(this@GameFragment) } } private fun showUserListSearch(search:String){ binding.rvGame.visibility = View.GONE gameViewModel.gameSearch(search).observe(viewLifecycleOwner){games -> when (games) { is ResultBound.Error -> { showLoading(false) Snackbar.make(binding.root,games.message.toString(),Snackbar.LENGTH_SHORT).show() } is ResultBound.Loading -> showLoading(true) is ResultBound.Success -> { binding.rvGame.visibility = View.VISIBLE showLoading(false) showRecyclerList(games.data!!) } } } } private fun showUserList(){ gameViewModel.games().observe(viewLifecycleOwner) { games -> when (games) { is ResultBound.Error -> { showLoading(false) Snackbar.make(binding.root,games.message.toString(),Snackbar.LENGTH_SHORT).show() } is ResultBound.Loading -> showLoading(true) is ResultBound.Success -> { binding.rvGame.visibility = View.VISIBLE showLoading(false) showRecyclerList(games.data!!) } } } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentGameBinding.inflate(inflater,container,false) // Inflate the layout for this fragment return binding.root } private fun showLoading(loading: Boolean) { binding.progressBar.visibility = if (loading) View.VISIBLE else View.GONE } private fun showRecyclerList(list: List<Game>) { binding.rvGame.visibility = View.VISIBLE val listUserAdapter = GameAdapter(requireContext(), list) binding.rvGame.adapter = listUserAdapter listUserAdapter.setOnItemClickCallback(object : GameAdapter.OnItemClickCallback { override fun onItemClicked(data: Game) { val mBundle = Bundle() mBundle.putParcelable(EXTRA_GAME,data) binding.root.findNavController().navigate(R.id.action_gameFragment_to_detailGameFragment,mBundle) } }) } override fun onDestroyView() { super.onDestroyView() _binding = null } override fun onMenuItemClick(menu: MenuItem): Boolean { if(menu.itemId == R.id.favorite_item){ binding.root.findNavController().navigate(R.id.action_gameFragment_to_favoriteFragment) } return true } companion object { const val EXTRA_GAME = "extra_game" } }
magame-android/app/src/main/java/com/dicoding/magame/MyApplication.kt
29968191
package com.dicoding.magame import android.content.Context import com.dicoding.core.di.databaseModule import com.dicoding.core.di.networkModule import com.dicoding.core.di.repositoryModule import com.dicoding.magame.di.useCaseModule import com.dicoding.magame.di.viewModelModule import com.dicoding.magame.utils.ReleaseLogTree import com.google.android.play.core.splitcompat.SplitCompatApplication import org.koin.android.ext.koin.androidContext import org.koin.android.ext.koin.androidLogger import org.koin.core.KoinApplication import org.koin.core.context.startKoin import timber.log.Timber class MyApplication : SplitCompatApplication() { override fun onCreate() { super.onCreate() appContext = applicationContext if (BuildConfig.DEBUG) { Timber.plant(Timber.DebugTree()) }else{ Timber.plant(ReleaseLogTree()) } startKoin{ androidLogger() androidContext(this@MyApplication) modules( databaseModule, networkModule, repositoryModule, useCaseModule, viewModelModule) } } companion object { private lateinit var appContext: Context } }
magame-android/app/src/main/java/com/dicoding/magame/MainActivity.kt
4022676130
package com.dicoding.magame import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.dicoding.magame.ui.game.detail.DetailGameViewModel import org.koin.androidx.viewmodel.ext.android.viewModel class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val detailGameViewModel: DetailGameViewModel by viewModel() } }
magame-android/app/src/main/java/com/dicoding/magame/di/AppModule.kt
2804189389
package com.dicoding.magame.di import com.dicoding.core.domain.usecase.GameInteractor import com.dicoding.core.domain.usecase.GameUseCase import com.dicoding.magame.ui.game.detail.DetailGameViewModel import com.dicoding.magame.ui.game.list.GameViewModel import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.dsl.module val useCaseModule = module{ single<GameUseCase>{ GameInteractor( get() ) } } val viewModelModule = module{ viewModel { GameViewModel(get()) } viewModel { DetailGameViewModel(get()) } }
magame-android/app/src/main/java/com/dicoding/magame/utils/ReleaseLogTree.kt
2005185137
package com.dicoding.magame.utils import android.util.Log import com.google.firebase.crashlytics.FirebaseCrashlytics import timber.log.Timber class ReleaseLogTree : Timber.Tree() { override fun log(priority: Int, tag: String?, message: String, t: Throwable?) { if (priority == Log.ERROR || priority == Log.WARN) { if (t == null) { FirebaseCrashlytics.getInstance().log(message) } else { FirebaseCrashlytics.getInstance().recordException(t) } } } }
magame-android/app/src/main/java/com/dicoding/magame/SplashActivity.kt
3486180632
package com.dicoding.magame import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import com.dicoding.magame.databinding.ActivitySplashBinding class SplashActivity : AppCompatActivity(), View.OnClickListener { private var _binding : ActivitySplashBinding? = null private val binding get() = _binding!! override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) _binding = ActivitySplashBinding.inflate(layoutInflater) setContentView(binding.root) binding.btnGetStarted.setOnClickListener(this) } override fun onClick(v: View?) { if(v?.id == R.id.btn_get_started){ startActivity(Intent(applicationContext,MainActivity::class.java)) } } override fun onDestroy() { super.onDestroy() _binding = null } }
magame-android/favorite/src/main/java/com/dicoding/favorite/di/AppModule.kt
288412915
package com.dicoding.favorite.di import com.dicoding.favorite.FavoriteViewModel import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.dsl.module val favoriteViewModelModule = module{ viewModel { FavoriteViewModel(get()) } }
magame-android/favorite/src/main/java/com/dicoding/favorite/FavoriteViewModel.kt
560704009
package com.dicoding.favorite import androidx.lifecycle.ViewModel import androidx.lifecycle.asLiveData import com.dicoding.core.domain.usecase.GameUseCase class FavoriteViewModel(private val gameUseCase: GameUseCase): ViewModel() { fun favorite() = gameUseCase.getAllFavorite().asLiveData() }
magame-android/favorite/src/main/java/com/dicoding/favorite/adapter/FavoriteAdapter.kt
452353404
package com.dicoding.favorite.adapter import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.dicoding.core.databinding.ItemGameBinding import com.dicoding.core.domain.models.Favorite class FavoriteAdapter (private val context: Context,private val listFavorite: List<Favorite>) : RecyclerView.Adapter<FavoriteAdapter.MyViewHolder>() { private lateinit var onItemClickCallback: OnItemClickCallback fun setOnItemClickCallback(onItemClickCallback: OnItemClickCallback) { this.onItemClickCallback = onItemClickCallback } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder { val binding = ItemGameBinding.inflate(LayoutInflater.from(parent.context), parent, false) return MyViewHolder(binding) } override fun onBindViewHolder(holder: MyViewHolder, position: Int) { val data = listFavorite[position] holder.bind(data,context) holder.itemView.setOnClickListener { onItemClickCallback.onItemClicked(listFavorite[holder.adapterPosition]) } } override fun getItemCount(): Int = listFavorite.size class MyViewHolder(private val binding: ItemGameBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(data: Favorite,context: Context) { //set a item in here binding.txtTitle.text = data.name binding.txtRating.text = data.ratingsCount.toString() binding.ratingBar.rating = data.rating!!.toFloat() binding.txtPlatform.text = data.platform Glide.with(context).load(data.image).into(binding.imageGame) } } interface OnItemClickCallback { fun onItemClicked(data: Favorite) } }
magame-android/favorite/src/main/java/com/dicoding/favorite/FavoriteFragment.kt
3316965345
package com.dicoding.favorite import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.navigation.findNavController import androidx.recyclerview.widget.LinearLayoutManager import com.dicoding.core.data.source.mapper.GameMapper import com.dicoding.core.domain.models.Favorite import com.dicoding.favorite.adapter.FavoriteAdapter import com.dicoding.favorite.databinding.FragmentFavoriteBinding import com.dicoding.favorite.di.favoriteViewModelModule import com.dicoding.magame.ui.game.list.GameFragment import org.koin.androidx.viewmodel.ext.android.viewModel import org.koin.core.context.loadKoinModules class FavoriteFragment : Fragment() { private var _binding: FragmentFavoriteBinding? = null private val binding get() = _binding!! override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) loadKoinModules(favoriteViewModelModule) val vieModel : FavoriteViewModel by viewModel() binding.rvFavorite.layoutManager = LinearLayoutManager(requireContext()) vieModel.favorite().observe(viewLifecycleOwner){list -> if(list.isNotEmpty()){ binding.emptyInc.emptyView.visibility = View.GONE showRecyclerList(list) } } } private fun showRecyclerList(list: List<Favorite>) { binding.rvFavorite.visibility = View.VISIBLE val listUserAdapter = FavoriteAdapter(requireContext(), list) binding.rvFavorite.adapter = listUserAdapter listUserAdapter.setOnItemClickCallback(object : FavoriteAdapter.OnItemClickCallback { override fun onItemClicked(data: Favorite) { val mBundle = Bundle() val game = GameMapper.favDomainToGame(data) mBundle.putParcelable(GameFragment.EXTRA_GAME,game) binding.root.findNavController().navigate(com.dicoding.magame.R.id.action_favoriteFragment_to_detailGameFragment,mBundle) } }) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentFavoriteBinding.inflate(inflater,container,false) return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null } }
RPAutoMecanica/app/src/androidTest/java/com/example/rpautomecanica/ExampleInstrumentedTest.kt
4019894443
package com.example.rpautomecanica 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.rpautomecanica", appContext.packageName) } }
RPAutoMecanica/app/src/test/java/com/example/rpautomecanica/ExampleUnitTest.kt
4093914771
package com.example.rpautomecanica 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) } }
RPAutoMecanica/app/src/main/java/com/example/rpautomecanica/MainActivity.kt
1339537047
package com.example.rpautomecanica import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import com.example.rpautomecanica.databinding.ActivityMainBinding import android.content.Intent import android.graphics.Bitmap import android.net.Uri import android.os.Build import android.os.StrictMode import android.provider.MediaStore import android.widget.Button import androidx.core.content.FileProvider import java.io.File import java.io.FileOutputStream class MainActivity : AppCompatActivity(), View.OnClickListener { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) StrictMode.VmPolicy.Builder().build().also { StrictMode.setVmPolicy(it) } binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) binding.totalButton.setOnClickListener(this) val btnShare: Button = findViewById(R.id.botaoprint) btnShare.setOnClickListener { compartilharTela() } } private fun compartilharTela() { // Obtenha uma captura de tela val rootView: View = window.decorView.rootView rootView.isDrawingCacheEnabled = true val screenshot: Bitmap = Bitmap.createBitmap(rootView.drawingCache) rootView.isDrawingCacheEnabled = false // Salve a captura de tela em algum lugar temporário val screenshotFile = File(externalCacheDir, "screenshot.png") try { val fileOutputStream = FileOutputStream(screenshotFile) screenshot.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream) fileOutputStream.flush() fileOutputStream.close() // Obtenha a URI usando FileProvider val screenshotUri = FileProvider.getUriForFile( this, "seu.pacote.aqui.fileprovider", screenshotFile ) // Crie uma intenção de compartilhamento val shareIntent = Intent(Intent.ACTION_SEND) shareIntent.type = "image/png" shareIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri) // Garanta que outras aplicações possam ler o arquivo shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) // Inicie a atividade de compartilhamento startActivity(Intent.createChooser(shareIntent, "Compartilhar via")) } catch (e: Exception) { e.printStackTrace() } } override fun onClick(view: View?) { if (view != null) { if (view.id == R.id.total_button) { calculate() } } } private fun calculate() { var value1 = 0f if (binding.editValor1.text.toString() != "" && binding.editValor1.text.toString() != "." ) { value1 = binding.editValor1.text.toString().toFloat() } var value2 = 0f if (binding.editValor2.text.toString() != "" && binding.editValor2.text.toString() != "." ) { value2 = binding.editValor2.text.toString().toFloat() } var value3 = 0f if (binding.editValor3.text.toString() != "" && binding.editValor3.text.toString() != "." ) { value3 = binding.editValor3.text.toString().toFloat() } var value4 = 0f if (binding.editValor4.text.toString() != "" && binding.editValor4.text.toString() != "." ) { value4 = binding.editValor4.text.toString().toFloat() } var value5 = 0f if (binding.editValor5.text.toString() != "" && binding.editValor5.text.toString() != "." ) { value5 = binding.editValor5.text.toString().toFloat() } var value6 = 0f if (binding.editValor6.text.toString() != "" && binding.editValor6.text.toString() != "." ) { value6 = binding.editValor6.text.toString().toFloat() } var value7 = 0f if (binding.editValor7.text.toString() != "" && binding.editValor7.text.toString() != "." ) { value7 = binding.editValor7.text.toString().toFloat() } var value8 = 0f if (binding.editValor8.text.toString() != "" && binding.editValor8.text.toString() != "." ) { value8 = binding.editValor8.text.toString().toFloat() } var value9 = 0f if (binding.editValor9.text.toString() != "" && binding.editValor9.text.toString() != "." ) { value9 = binding.editValor9.text.toString().toFloat() } var value10 = 0f if (binding.editValor10.text.toString() != "" && binding.editValor10.text.toString() != "." ) { value10 = binding.editValor10.text.toString().toFloat() } val totalValue = (value1 + value2 + value3 + value4 + value5 + value6 + value7 + value8 + value9 + value10) binding.editValorTotal.text = "R$${"%.2f".format(totalValue)}" } }
appKmm/shared/src/iosMain/kotlin/com/example/appkmm/Platform.ios.kt
3464279270
package com.example.appkmm import platform.UIKit.UIDevice class IOSPlatform: Platform { override val model: String = UIDevice.currentDevice.systemName() + " " + UIDevice.currentDevice.systemVersion } actual fun getPlatform(): Platform = IOSPlatform()
appKmm/shared/src/iosMain/kotlin/com/example/appkmm/src/managers/WorkManager.kt
0
appKmm/shared/src/iosMain/kotlin/com/example/appkmm/src/managers/DataManager.ios.kt
1208986595
package com.example.appkmm.src.managers actual fun getDeviceInfo(): DeviceInfo { TODO("Not yet implemented") }
appKmm/shared/src/iosMain/kotlin/com/example/appkmm/src/utils/DeviceInfos.ios.kt
2088435396
package com.example.appkmm.src.utils actual class DeviceInfos(context : Any) { actual fun getOsDevice(): String { return "iOS" } actual fun getModel(): String { return "iphone" } }
appKmm/shared/src/iosMain/kotlin/com/example/appkmm/src/utils/Utils.ios.kt
1702816892
import platform.Foundation.* import kotlinx.cinterop.* import kotlin.native.concurrent.* actual class Utils actual constructor(context: Any?) { @OptIn(ExperimentalForeignApi::class) actual fun isConnected() : Boolean { val reachability = try { SCNetworkReachabilityCreateWithName(null, "www.apple.com") } catch (e: Throwable) { null } if (reachability == null) return false val flags = memScoped { val ptr = alloc<SCNetworkReachabilityFlagsVar>() if (!SCNetworkReachabilityGetFlags(reachability, ptr.ptr)) { return false } ptr.value } return flags.contains(kSCNetworkReachabilityFlagsReachable) && !flags.contains(kSCNetworkReachabilityFlagsConnectionRequired) } actual suspend fun stringToMD5(s: String): String { val data = s.dataUsingEncoding(NSUTF8StringEncoding) ?: return "" val hash = data.withUnsafeBytes { bytes -> val buffer = ByteArray(CC_MD5_DIGEST_LENGTH.toUInt()) CC_MD5(bytes, data.length.toUInt(), buffer.refTo(0)) buffer.joinToString("") { "%02x".format(it) } } println("***********************************$hash") return hash } }
appKmm/shared/src/iosMain/kotlin/com/example/appkmm/src/env/prod/Prod.kt
0
appKmm/shared/src/iosMain/kotlin/com/example/appkmm/src/env/staging/Staging.kt
0
appKmm/shared/src/iosMain/kotlin/com/example/appkmm/src/env/preprod/Preprod.kt
0
appKmm/shared/src/iosMain/kotlin/com/example/appkmm/src/data/local/manager/DataManager.ios.kt
1804379947
package com.example.appkmm.src.data.local.manager import com.example.appkmm.src.models.RequestData import platform.Foundation.NSUserDefaults import kotlinx.serialization.decodeFromString import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json actual class DataManager actual constructor(context : Any?) { actual suspend fun saveData(key: String, value: RequestData) { val serializedValue = Json.encodeToString(value) val defaults = NSUserDefaults.standardUserDefaults defaults.setObject(serializedValue, key) defaults.synchronize() } actual suspend fun readData(key: String): RequestData? { val defaults = NSUserDefaults.standardUserDefaults val serializedValue = defaults.objectForKey(key) as? String return serializedValue?.let { Json.decodeFromString(it) } } actual suspend fun saveCoreLibId(key: String, value: String) { val defaults = NSUserDefaults.standardUserDefaults defaults.setObject(value, key) defaults.synchronize() } actual suspend fun readCoreLibId(key: String): String? { val defaults = NSUserDefaults.standardUserDefaults return defaults.objectForKey(key) as? String } actual suspend fun saveBaseUrl(key: String, value: String) { val defaults = NSUserDefaults.standardUserDefaults defaults.setObject(value, key) defaults.synchronize() } actual suspend fun readBaseUrl(key: String): String? { val defaults = NSUserDefaults.standardUserDefaults return defaults.objectForKey(key) as? String } actual suspend fun saveMpDeviceIdentifier(key: String, value: String) { val defaults = NSUserDefaults.standardUserDefaults defaults.setObject(value, key) defaults.synchronize() } actual suspend fun readMpDeviceIdentifier(key: String): String? { val defaults = NSUserDefaults.standardUserDefaults return defaults.objectForKey(key) as? String } }
appKmm/shared/src/iosMain/kotlin/com/example/appkmm/src/data/remote/repository/Repository.ios.kt
4193357432
package com.example.appkmm.src.data.remote.repository import com.example.appkmm.src.data.local.manager.DataManager import com.example.appkmm.src.data.remote.api.CoreLibApi import com.example.appkmm.src.models.RequestData import com.mobelite.corelibkmm.src.models.ResponseData import com.mobelite.corelibkmm.src.models.ResponseWS import com.mobelite.corelibkmm.src.utils.Constants import io.ktor.client.HttpClient import io.ktor.client.plugins.ClientRequestException import io.ktor.client.request.forms.FormDataContent import io.ktor.client.request.post import io.ktor.client.statement.HttpResponse import io.ktor.client.statement.bodyAsText import io.ktor.http.ContentType import io.ktor.http.Parameters import io.ktor.http.contentType import io.ktor.util.InternalAPI import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import org.json.JSONObject actual class Repository actual constructor(private val context : Any?) : CoreLibApi { val client = HttpClient() lateinit var postDataRegistrartion: HttpResponse lateinit var postDataUpdate: HttpResponse lateinit var resultRegistrartion : ResponseWS lateinit var resultUpdate : ResponseWS /** * Posts user data to the server. * @return A ResponseWS object containing the response from the server. */ @OptIn(InternalAPI::class, DelicateCoroutinesApi::class) actual override suspend fun postUserData(data: RequestData): ResponseWS { val TAG = "Android Repository Register" runBlocking { val formData = mapOf( "action" to data.action, "device_identifier" to data.deviceIdentifier, "app_identifier" to data.appIdentifier, "app_version" to data.appVersion, "os_version" to data.osVersion, "os" to data.os, "device_model" to data.deviceModel, "device_manufacture" to data.deviceManufacture, "device_region" to data.deviceRegion, "device_timezone" to data.deviceTimezone, "screen_resolution" to data.screenResolution, "timestamp" to data.timestamp, //"check" to data.check, "check" to "944150675E23A25B1C6A4CDE5981EA22", "push_additional_params[${data.pushAdditionalParams.keys}]" to "${data.pushAdditionalParams.values}", "screen_dpi" to data.screenDpi ) val parameters = Parameters.build { formData.forEach { (key, value) -> append(key, value) } } try { postDataRegistrartion = client.post(Constants.BASE_URL) { body = FormDataContent(parameters) contentType(ContentType.Application.FormUrlEncoded) } } catch (e: ClientRequestException) { } finally { client.close() } val bodyResult = JSONObject(postDataRegistrartion.bodyAsText()) val responseDescriptionResult = bodyResult.getJSONObject("response_description") responseDescriptionResult.keys().forEach { key -> val value = responseDescriptionResult.getString(key) } // Extract response_code val responseCodeResult = bodyResult.getString("response_code") // Extract mpDeviceIdentifier from response_data val responseData = bodyResult.getJSONObject("response_data") val mpDeviceIdentifier = responseData.getString("mpDeviceIdentifier") val responseMessageResult = bodyResult.getJSONObject("response_message") val responseCode: String? = responseCodeResult val responseDescriptionMap = mutableMapOf<String, String>() responseDescriptionResult.keys().forEach { key -> val value = responseDescriptionResult.getString(key) responseDescriptionMap[key] = value } val responseDataObject = ResponseData(mpDeviceIdentifier) GlobalScope.launch { DataManager(context).saveMpDeviceIdentifier("mpDeviceIdentifier",mpDeviceIdentifier) } resultRegistrartion = ResponseWS( responseCode, responseDescriptionMap, responseMessageResult, responseDataObject ) } return resultRegistrartion } @OptIn(InternalAPI::class) actual override suspend fun getUpdateDeviceInfo( action: String?, mpDeviceIdentifier: String?, appVersion: String?, osVersion: String?, deviceRegion: String?, deviceTimezone: String?, deviceIdentifier: String?, timestamp: String?, check: String?, deviceInfo: Map<String?, String?>?, additionalParams: Map<String?, String?>? ): ResponseWS { val TAG = "Android Repository Update" runBlocking { val formData = mapOf( "action" to action, "mp_device_identifier" to deviceIdentifier, "app_version" to appVersion, "os_version" to osVersion, "device_region" to deviceRegion, "device_timezone" to deviceTimezone, "device_identifier" to deviceIdentifier, "timestamp" to timestamp, //"check" to "944150675E23A25B1C6A4CDE5981EA22", "check" to check, "device_info" to deviceInfo, "push_additional_params" to additionalParams ) val parameters = Parameters.build { formData.forEach { (key, value) -> (value as? String)?.let { append(key, it) } } } try { postDataUpdate = client.post(Constants.BASE_URL) { body = FormDataContent(parameters) contentType(ContentType.Application.FormUrlEncoded) } } catch (e: ClientRequestException) { println("Error: ${e.response.status.description}") } finally { client.close() } val bodyResult = JSONObject(postDataUpdate.bodyAsText()) val responseDescriptionResult = bodyResult.getJSONObject("response_description") responseDescriptionResult.keys().forEach { key -> val value = responseDescriptionResult.getString(key) } // Extract response_code val responseCodeResult = bodyResult.getString("response_code") // Extract mpDeviceIdentifier from response_data val responseData = bodyResult.getJSONObject("response_data") val mpDeviceIdentifier = responseData.getString("mpDeviceIdentifier") val responseMessageResult = bodyResult.getJSONObject("response_message") val responseCode: String? = responseCodeResult val responseDescriptionMap = mutableMapOf<String, String>() responseDescriptionResult.keys().forEach { key -> val value = responseDescriptionResult.getString(key) responseDescriptionMap[key] = value } val responseDataObject = ResponseData(null) resultUpdate = ResponseWS( responseCode, responseDescriptionMap, responseMessageResult, responseDataObject ) } return resultUpdate } }
appKmm/shared/src/commonMain/kotlin/com/example/appkmm/Platform.kt
200055992
package com.example.appkmm interface Platform { val model: String } expect fun getPlatform(): Platform
appKmm/shared/src/commonMain/kotlin/com/example/appkmm/Greeting.kt
1632804578
package com.example.appkmm import com.mobelite.corelibkmm.src.utils.Constants import io.ktor.client.HttpClient import io.ktor.client.plugins.ClientRequestException import io.ktor.client.request.post import io.ktor.client.request.setBody import io.ktor.client.statement.HttpResponse import io.ktor.client.statement.bodyAsText import io.ktor.http.ContentType import io.ktor.http.contentType import io.ktor.util.InternalAPI class Greeting { private lateinit var postData: HttpResponse suspend fun greeting(): String { val client = HttpClient() try { postData = client.post(Constants.BASE_URL) { contentType(ContentType.Application.Json) setBody("""{"value": "0"}""") // Send 1 as the value) } } catch (e: ClientRequestException) { println("Error: ${e.response.status.description}") } finally { client.close() } return postData.bodyAsText() } }
appKmm/shared/src/commonMain/kotlin/com/example/appkmm/src/repository/CoreLibEntryPoint.kt
2080535625
package com.example.appkmm.src.repository import com.example.appkmm.src.models.RequestData import com.mobelite.corelibkmm.src.models.ResponseWS import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.IO import kotlinx.coroutines.withContext object CoreLibEntryPoint { private fun initLibrary(context: Any?): UserRepository { return UserRepository(context) } suspend fun corelibInit (env : String, coreLibId : String, context : Any?) : ResponseWS { val baseUrl = if (env == "prod") { "https://ws.mobeliteplus.fr/" } else { "http://ws.staging.mobeliteplus.com/" } initLibrary(context).saveCoreLibId(coreLibId) initLibrary(context).saveBaseUrl(baseUrl) //postUserData(context) return postUserData(context) } suspend fun post(context: Any?) : ResponseWS { return initLibrary(context).postData() } suspend fun update(context: Any?) : ResponseWS { return initLibrary(context).updateData() } private suspend fun saveUserData(context : Any?) { return initLibrary(context).saveData() } private suspend fun readUserData(context: Any?): RequestData? { return initLibrary(context).readData() } suspend fun readCorelibId(context: Any?): String? { return initLibrary(context).readCoreLibId() } suspend fun postUserData(context: Any?): ResponseWS { return withContext(Dispatchers.IO) { val localData = initLibrary(context).readData() val newData = initLibrary(context).data() if (initLibrary(context).statusConnection()) { if (localData == null) { val response = initLibrary(context).postData() if (response.responseCode.equals("200")) { initLibrary(context).saveData() return@withContext ResponseWS(response.responseCode.toString(),response.responseDescription,response.responseMessage,response.responseData) } else { return@withContext ResponseWS("error", null, null, null) } } else if (localData.deviceIdentifier == newData.deviceIdentifier && localData.appIdentifier == newData.appIdentifier && localData.check == newData.check && localData.deviceModel == newData.deviceModel && localData.appVersion == newData.appVersion && localData.deviceManufacture== newData.deviceManufacture && localData.deviceRegion == newData.deviceRegion && localData.deviceTimezone == newData.deviceTimezone && localData.osVersion == newData.osVersion && localData.os == newData.os && localData.screenResolution == newData.screenResolution && localData.screenDpi == newData.screenDpi ) { initLibrary(context).saveData() return@withContext ResponseWS("200",null,"the data is stored successfully",null) } else { val update = initLibrary(context).updateData() return@withContext ResponseWS(update.responseCode.toString(),update.responseDescription,update.responseMessage,update.responseData) } } else { return@withContext ResponseWS("500", null, "please check your internet connection", null) } } } }
appKmm/shared/src/commonMain/kotlin/com/example/appkmm/src/repository/UserRepository.kt
3436530916
package com.example.appkmm.src.repository import Utils import com.example.appkmm.src.data.local.manager.DataManager import com.example.appkmm.src.data.remote.repository.Repository import com.example.appkmm.src.managers.DeviceInfo import com.example.appkmm.src.managers.getDeviceInfo import com.example.appkmm.src.models.RequestData import com.mobelite.corelibkmm.src.models.ResponseWS import com.mobelite.corelibkmm.src.utils.Constants class UserRepository(private val context: Any?) { private val deviceModel: DeviceInfo = getDeviceInfo() suspend fun getCheck() : String { return Utils(context).stringToMD5(deviceModel.deviceIdentifierForVendor + "||" + deviceModel.appIdentifier + "||" + deviceModel.timestamp + "||" + readCoreLibId()) } suspend fun data (): RequestData { return RequestData( action= Constants.ACTION_REGISTER, deviceIdentifier =deviceModel.deviceIdentifierForVendor, appIdentifier = deviceModel.appIdentifier, appVersion =deviceModel.appVersion, osVersion = deviceModel.osVersion, os= deviceModel.osName, deviceModel =deviceModel.deviceModel, deviceManufacture =deviceModel.deviceManufacturer, deviceRegion = deviceModel.deviceRegion, deviceTimezone = deviceModel.timeZone, screenResolution = "1242*2688", timestamp=deviceModel.timestamp.toString(), //check= "944150675E23A25B1C6A4CDE5981EA22", check = getCheck(), pushAdditionalParams = mapOf("GTUser" to "Not_Connected"), screenDpi = deviceModel.screenDpi ) } suspend fun postData(): ResponseWS { return Repository(context).postUserData(data()) } suspend fun updateData(): ResponseWS { return Repository(context).getUpdateDeviceInfo( action = Constants.ACTION_UPDATE, mpDeviceIdentifier = readMpDeviceIdentifier(), appVersion = deviceModel.appVersion, osVersion = deviceModel.osVersion, deviceRegion = deviceModel.deviceRegion, deviceTimezone = deviceModel.timeZone, deviceIdentifier = deviceModel.deviceIdentifierForVendor, timestamp = deviceModel.timestamp.toString(), check = getCheck(), deviceInfo = mapOf("param1" to "param2"), additionalParams = mapOf("GTUser" to "Not_Connected") ) } suspend fun saveData(){ return DataManager(context).saveData("Data",data()) } suspend fun readData(): RequestData? { return DataManager(context).readData("Data") } fun statusConnection() : Boolean { return Utils(context).isConnected() } suspend fun saveCoreLibId(coreLibId : String){ return DataManager(context).saveCoreLibId("CoreLibId",coreLibId) } suspend fun readCoreLibId(): String? { return DataManager(context).readCoreLibId("CoreLibId") } suspend fun saveBaseUrl(baseUrl : String){ return DataManager(context).saveBaseUrl("BaseUrl",baseUrl) } suspend fun readBaseUrl(): String? { return DataManager(context).readBaseUrl("BaseUrl") } suspend fun saveMpDeviceIdentifier(mpDeviceIdentifier : String){ return DataManager(context).saveMpDeviceIdentifier("MpDeviceIdentifier",mpDeviceIdentifier) } suspend fun readMpDeviceIdentifier(): String? { return DataManager(context).readMpDeviceIdentifier("MpDeviceIdentifier") } }
appKmm/shared/src/commonMain/kotlin/com/example/appkmm/src/repository/CorelibDelegate.kt
2598135986
package com.example.appkmm.src.repository object CorelibDelegate { fun initCoreLib(): CoreLibEntryPoint { return CoreLibEntryPoint } }
appKmm/shared/src/commonMain/kotlin/com/example/appkmm/src/managers/DataManager.kt
2611618649
package com.example.appkmm.src.managers interface DeviceInfo { val deviceModel: String val sysName: String val osVersion: String val deviceIdentifierForVendor: String val deviceRegion: String val timeZone: String val screenDpi: String val osName: String val timestamp: Long val appIdentifier: String val appVersion: String val deviceManufacturer: String } expect fun getDeviceInfo(): DeviceInfo
appKmm/shared/src/commonMain/kotlin/com/example/appkmm/src/utils/Utils.kt
1828354006
expect class Utils (context : Any?) { fun isConnected() : Boolean suspend fun stringToMD5(s: String): String }
appKmm/shared/src/commonMain/kotlin/com/example/appkmm/src/utils/DeviceInfos.kt
896516393
package com.example.appkmm.src.utils expect class DeviceInfos(context : Any) { fun getModel() : String fun getOsDevice() : String }
appKmm/shared/src/commonMain/kotlin/com/example/appkmm/src/utils/Constants.kt
2526730983
package com.mobelite.corelibkmm.src.utils object Constants { const val BASE_URL = "http://ws.mobeliteplus.fr/service.do" const val DATA_STORE_NAME = "CoreLib" const val ACTION_REGISTER = "mpRegisterDevice" const val ACTION_UPDATE = "mpUpdateDeviceInformation" }
appKmm/shared/src/commonMain/kotlin/com/example/appkmm/src/models/ResponseWS.kt
2117910886
package com.mobelite.corelibkmm.src.models import kotlinx.serialization.Contextual import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class ResponseWS( @SerialName("response_code") var responseCode: String?, @SerialName("response_description") var responseDescription: Map<String, String>?, @Contextual @SerialName("response_message") var responseMessage: Any?, @SerialName("response_data") var responseData: ResponseData? )
appKmm/shared/src/commonMain/kotlin/com/example/appkmm/src/models/RequestData.kt
851716709
package com.example.appkmm.src.models import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class RequestData( @SerialName("action") val action: String, @SerialName("device_identifier") val deviceIdentifier: String, @SerialName("app_identifier") val appIdentifier: String, @SerialName("app_version") val appVersion: String, @SerialName("os_version") val osVersion: String, @SerialName("os") val os: String, @SerialName("device_model") val deviceModel: String, @SerialName("device_manufacture") val deviceManufacture: String, @SerialName("device_region") val deviceRegion: String, @SerialName("device_timezone") val deviceTimezone: String, @SerialName("screen_resolution") val screenResolution: String, @SerialName("timestamp") val timestamp: String, @SerialName("check") val check: String, @SerialName("push_additional_params") val pushAdditionalParams: Map<String, String>, @SerialName("screen_dpi") val screenDpi: String )
appKmm/shared/src/commonMain/kotlin/com/example/appkmm/src/models/ResponseData.kt
2694213075
package com.mobelite.corelibkmm.src.models import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class ResponseData( @SerialName("mpDeviceIdentifier") var mpDeviceIdentifier: String?, @SerialName("has_update") var hasUpdate: String?, @SerialName("last_version") var lastVersion: String?, @SerialName("last_version_url") var lastVersionUrl: String?, @SerialName("last_version_will_block") var lastVersionWillBlock: String?, @SerialName("version_title") var versionTitle: String?, @SerialName("version_description") var versionDescription: String?, @SerialName("accept_btn_text") var acceptBtnText: String?, @SerialName("cancel_btn_text") var cancelBtnText: String?, @SerialName("display_evry") var displayEvry: String?, @SerialName("display_launch") var displayLaunch: String?, @SerialName("has_wm") var hasWm: String?, @SerialName("wm_title") var wmTitle: String?, @SerialName("wm_message") var wmMessage: String?, @SerialName("dismiss_btn_text") var dismissBtnText: String?, @SerialName("wm_display_every") var wmDisplayEvery: String?, @SerialName("wm_display_launch") var wmDisplayLaunch: String?, @SerialName("wm_id") var wmId: String?, @SerialName("notification_status_data") var notificationStatusData: Map<String?, String?>?, @SerialName("url") var url: String? ) { constructor(mpDeviceIdentifier: String?) : this(mpDeviceIdentifier, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null) }
appKmm/shared/src/commonMain/kotlin/com/example/appkmm/src/mappers/Mapper.kt
0
appKmm/shared/src/commonMain/kotlin/com/example/appkmm/src/data/local/manager/DataManager.kt
2559092563
package com.example.appkmm.src.data.local.manager import com.example.appkmm.src.models.RequestData // DataManager class acts as a bridge between the application's business logic and the local data storage. // It provides methods to save and read data using a DataStoreManager instance. expect class DataManager (context : Any?) { suspend fun saveData(key: String, value: RequestData) suspend fun readData(key: String): RequestData? suspend fun saveCoreLibId(key: String, value: String) suspend fun readCoreLibId(key: String): String? suspend fun saveBaseUrl(key: String, value: String) suspend fun readBaseUrl(key: String): String? suspend fun saveMpDeviceIdentifier(key: String, value: String) suspend fun readMpDeviceIdentifier(key: String): String? }
appKmm/shared/src/commonMain/kotlin/com/example/appkmm/src/data/remote/repository/Repository.kt
2562971574
package com.example.appkmm.src.data.remote.repository import com.example.appkmm.src.data.remote.api.CoreLibApi import com.example.appkmm.src.models.RequestData import com.mobelite.corelibkmm.src.models.ResponseWS expect class Repository(context : Any?) : CoreLibApi { /** * Sends user data to the server. * @return A ResponseWS response indicating the success or failure of the operation. */ override suspend fun postUserData(data : RequestData): ResponseWS override suspend fun getUpdateDeviceInfo( action: String?, mpDeviceIdentifier: String?, appVersion: String?, osVersion: String?, deviceRegion: String?, deviceTimezone: String?, deviceIdentifier: String?, timestamp: String?, check: String?, deviceInfo: Map<String?, String?>?, additionalParams: Map<String?, String?>? ): ResponseWS }
appKmm/shared/src/commonMain/kotlin/com/example/appkmm/src/data/remote/api/CoreLibApi.kt
1801113699
package com.example.appkmm.src.data.remote.api import com.example.appkmm.src.models.RequestData import com.mobelite.corelibkmm.src.models.ResponseWS interface CoreLibApi { /** * Sends user data to the server. * @return A ResponseWS response indicating the success or failure of the operation. */ suspend fun postUserData(data : RequestData) : ResponseWS suspend fun getUpdateDeviceInfo( action: String?, mpDeviceIdentifier: String?, appVersion: String?, osVersion: String?, deviceRegion: String?, deviceTimezone: String?, deviceIdentifier: String?, timestamp: String?, check: String?, deviceInfo: Map<String?, String?>?, additionalParams: Map<String?, String?>? ) : ResponseWS }
appKmm/shared/src/androidMain/kotlin/com/example/appkmm/Platform.android.kt
3654977477
package com.example.appkmm class AndroidPlatform : Platform { override val model: String = android.os.Build.MODEL } actual fun getPlatform(): Platform = AndroidPlatform()
appKmm/shared/src/androidMain/kotlin/com/example/appkmm/src/managers/WorkManager.kt
0
appKmm/shared/src/androidMain/kotlin/com/example/appkmm/src/managers/DataManager.android.kt
1573819960
package com.example.appkmm.src.managers import android.os.Build import java.util.TimeZone class AndroidDeviceInfo: DeviceInfo { override val deviceModel: String = Build.MODEL override val sysName: String = "Android" override val osVersion: String = Build.VERSION.RELEASE override val deviceIdentifierForVendor: String = "0DEA426A-C06E-42F9-A1B4-F12308089455" override val deviceRegion: String = "This should be changed" //context.resources.configuration.locale.country ?: "N/A" override val timeZone: String = TimeZone.getDefault().id override val screenDpi: String = "45454884" override val osName: String = "Android" override val timestamp: Long = 1709735813 //TODO change this override val appIdentifier: String = "com.elsevier-masson.gt11" override val appVersion: String = "1.3.1" override val deviceManufacturer: String = Build.MANUFACTURER } actual fun getDeviceInfo(): DeviceInfo = AndroidDeviceInfo()
appKmm/shared/src/androidMain/kotlin/com/example/appkmm/src/utils/Utils.android.kt
198490200
import android.content.Context import android.net.ConnectivityManager import android.net.NetworkCapabilities import java.security.MessageDigest import java.security.NoSuchAlgorithmException actual class Utils actual constructor(private val context: Any?) { val androidContext = context as? Context actual fun isConnected(): Boolean { val connectivityManager = androidContext?.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val network = connectivityManager.activeNetwork ?: return false val capabilities = connectivityManager.getNetworkCapabilities(network) ?: return false return capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) } actual suspend fun stringToMD5(s: String): String { try { val digest = MessageDigest.getInstance("MD5") digest.update(s.toByteArray()) val messageDigest = digest.digest() val hexString = StringBuilder() for (i in messageDigest.indices) { var h = Integer.toHexString(0xFF and messageDigest[i].toInt()) while (h.length < 2) { h = "0$h" } hexString.append(h) } println("***********************************${hexString.toString().toUpperCase()}") return hexString.toString().toUpperCase() } catch (e: NoSuchAlgorithmException) { e.printStackTrace() } return "" } }
appKmm/shared/src/androidMain/kotlin/com/example/appkmm/src/utils/DeviceInfos.android.kt
847718202
package com.example.appkmm.src.utils import android.content.Context import android.os.Build actual class DeviceInfos actual constructor(context : Any) { val androidContext = context as? Context actual fun getOsDevice(): String { return "android" } actual fun getModel(): String { return Build.MODEL } }
appKmm/shared/src/androidMain/kotlin/com/example/appkmm/src/env/prod/Prod.kt
0
appKmm/shared/src/androidMain/kotlin/com/example/appkmm/src/env/staging/Staging.kt
0
appKmm/shared/src/androidMain/kotlin/com/example/appkmm/src/env/preprod/Preprod.kt
0
appKmm/shared/src/androidMain/kotlin/com/example/appkmm/src/data/local/manager/DataManager.android.kt
2228446126
package com.example.appkmm.src.data.local.manager import android.content.Context import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.preferencesDataStore import com.example.appkmm.src.models.RequestData import kotlinx.coroutines.flow.firstOrNull import kotlinx.serialization.decodeFromString import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json actual class DataManager actual constructor(context: Any?) { companion object { private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "CoreLib") } private val androidContext = context as? Context actual suspend fun saveData(key: String, value: RequestData) { val serializedValue = Json.encodeToString(value) androidContext?.dataStore?.edit { preferences -> preferences[stringPreferencesKey(key)] = serializedValue } } actual suspend fun readData(key: String): RequestData? { val serializedValue = androidContext?.dataStore?.data?.firstOrNull()?.get(stringPreferencesKey(key)) return serializedValue?.let { Json.decodeFromString(it) } } actual suspend fun saveCoreLibId(key: String, value: String) { androidContext?.dataStore?.edit { preferences -> preferences[stringPreferencesKey(key)] = value } } actual suspend fun readCoreLibId(key: String): String? { return androidContext?.dataStore?.data?.firstOrNull()?.get(stringPreferencesKey(key)) } actual suspend fun saveBaseUrl(key: String, value: String) { androidContext?.dataStore?.edit { preferences -> preferences[stringPreferencesKey(key)] = value } } actual suspend fun readBaseUrl(key: String): String? { return androidContext?.dataStore?.data?.firstOrNull()?.get(stringPreferencesKey(key)) } actual suspend fun saveMpDeviceIdentifier(key: String, value: String) { androidContext?.dataStore?.edit { preferences -> preferences[stringPreferencesKey(key)] = value } } actual suspend fun readMpDeviceIdentifier(key: String): String? { return androidContext?.dataStore?.data?.firstOrNull()?.get(stringPreferencesKey(key)) } }
appKmm/shared/src/androidMain/kotlin/com/example/appkmm/src/data/remote/repository/Repository.android.kt
1499231714
package com.example.appkmm.src.data.remote.repository import android.annotation.SuppressLint import android.util.Log import com.example.appkmm.src.data.local.manager.DataManager import com.example.appkmm.src.data.remote.api.CoreLibApi import com.example.appkmm.src.models.RequestData import com.mobelite.corelibkmm.src.models.ResponseData import com.mobelite.corelibkmm.src.models.ResponseWS import com.mobelite.corelibkmm.src.utils.Constants import io.ktor.client.HttpClient import io.ktor.client.plugins.ClientRequestException import io.ktor.client.request.forms.FormDataContent import io.ktor.client.request.post import io.ktor.client.statement.HttpResponse import io.ktor.client.statement.bodyAsText import io.ktor.http.ContentType import io.ktor.http.Parameters import io.ktor.http.contentType import io.ktor.util.InternalAPI import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import org.json.JSONObject actual class Repository actual constructor(private val context : Any?) : CoreLibApi { val client = HttpClient() lateinit var postDataRegistrartion: HttpResponse lateinit var postDataUpdate: HttpResponse lateinit var resultRegistrartion : ResponseWS lateinit var resultUpdate : ResponseWS /** * Posts user data to the server. * @return A ResponseWS object containing the response from the server. */ @OptIn(InternalAPI::class, DelicateCoroutinesApi::class) actual override suspend fun postUserData(data: RequestData): ResponseWS { val TAG = "Android Repository Register" runBlocking { val formData = mapOf( "action" to data.action, "device_identifier" to data.deviceIdentifier, "app_identifier" to data.appIdentifier, "app_version" to data.appVersion, "os_version" to data.osVersion, "os" to data.os, "device_model" to data.deviceModel, "device_manufacture" to data.deviceManufacture, "device_region" to data.deviceRegion, "device_timezone" to data.deviceTimezone, "screen_resolution" to data.screenResolution, "timestamp" to data.timestamp, //"check" to data.check, "check" to "944150675E23A25B1C6A4CDE5981EA22", "push_additional_params[${data.pushAdditionalParams.keys}]" to "${data.pushAdditionalParams.values}", "screen_dpi" to data.screenDpi ) Log.w(TAG,"the data is :$formData" ) Log.w(TAG,"the check is :${formData.filter { it.key == "check" }}" ) val parameters = Parameters.build { formData.forEach { (key, value) -> append(key, value) } } try { postDataRegistrartion = client.post(Constants.BASE_URL) { body = FormDataContent(parameters) contentType(ContentType.Application.FormUrlEncoded) } } catch (e: ClientRequestException) { Log.w(TAG,"Error :${e.response.status.description}" ) } finally { client.close() } Log.w(TAG,"the result is :${postDataRegistrartion.bodyAsText()}" ) val test = JSONObject(postDataRegistrartion.bodyAsText()) val responseDescriptionResult = test.getJSONObject("response_description") responseDescriptionResult.keys().forEach { key -> val value = responseDescriptionResult.getString(key) Log.w(TAG,"the responseDescriptionResult is :${"$key: $value"}" ) } // Extract response_code val responseCodeResult = test.getString("response_code") Log.w(TAG,"the responseCodeResult is :${responseCodeResult}" ) // Extract mpDeviceIdentifier from response_data val responseData = test.getJSONObject("response_data") val mpDeviceIdentifier = responseData.getString("mpDeviceIdentifier") Log.w(TAG,"the mpDeviceIdentifier is :${mpDeviceIdentifier}" ) val responseMessageResult = test.getJSONObject("response_message") Log.w(TAG,"the responseMessageResult is :${responseMessageResult}" ) val responseCode: String? = responseCodeResult val responseDescriptionMap = mutableMapOf<String, String>() responseDescriptionResult.keys().forEach { key -> val value = responseDescriptionResult.getString(key) responseDescriptionMap[key] = value Log.w(TAG, "the responseDescriptionResult is: $key: $value") } val responseDataObject = ResponseData(mpDeviceIdentifier) GlobalScope.launch { DataManager(context).saveMpDeviceIdentifier("mpDeviceIdentifier",mpDeviceIdentifier) } resultRegistrartion = ResponseWS( responseCode, responseDescriptionMap, responseMessageResult, responseDataObject ) } return resultRegistrartion } @SuppressLint("SuspiciousIndentation") @OptIn(InternalAPI::class) actual override suspend fun getUpdateDeviceInfo( action: String?, mpDeviceIdentifier: String?, appVersion: String?, osVersion: String?, deviceRegion: String?, deviceTimezone: String?, deviceIdentifier: String?, timestamp: String?, check: String?, deviceInfo: Map<String?, String?>?, additionalParams: Map<String?, String?>? ): ResponseWS { val TAG = "Android Repository Update" runBlocking { val formData = mapOf( "action" to action, "mp_device_identifier" to deviceIdentifier, "app_version" to appVersion, "os_version" to osVersion, "device_region" to deviceRegion, "device_timezone" to deviceTimezone, "device_identifier" to deviceIdentifier, "timestamp" to timestamp, //"check" to "944150675E23A25B1C6A4CDE5981EA22", "check" to check, "device_info" to deviceInfo, "push_additional_params" to additionalParams ) Log.w(TAG,"the data is :$formData" ) val parameters = Parameters.build { formData.forEach { (key, value) -> (value as? String)?.let { append(key, it) } } } try { postDataUpdate = client.post(Constants.BASE_URL) { body = FormDataContent(parameters) contentType(ContentType.Application.FormUrlEncoded) } } catch (e: ClientRequestException) { println("Error: ${e.response.status.description}") } finally { client.close() } Log.w(TAG,"the result is :${postDataUpdate.bodyAsText()}" ) val test = JSONObject(postDataUpdate.bodyAsText()) val responseDescriptionResult = test.getJSONObject("response_description") responseDescriptionResult.keys().forEach { key -> val value = responseDescriptionResult.getString(key) Log.w(TAG,"the responseDescriptionResult is :${"$key: $value"}" ) } // Extract response_code val responseCodeResult = test.getString("response_code") Log.w(TAG,"the responseCodeResult is :${responseCodeResult}" ) // Extract mpDeviceIdentifier from response_data val responseData = test.getJSONObject("response_data") //val mpDeviceIdentifier = responseData.getString("mpDeviceIdentifier") Log.w(TAG,"the mpDeviceIdentifier is :${responseData}" ) val responseMessageResult = test.getJSONObject("response_message") Log.w(TAG,"the responseMessageResult is :${responseMessageResult}" ) val responseCode: String? = responseCodeResult val responseDescriptionMap = mutableMapOf<String, String>() responseDescriptionResult.keys().forEach { key -> val value = responseDescriptionResult.getString(key) responseDescriptionMap[key] = value Log.w(TAG, "the responseDescriptionResult is: $key: $value") } val responseDataObject = ResponseData(null) resultUpdate = ResponseWS( responseCode, responseDescriptionMap, responseMessageResult, responseDataObject ) } return resultUpdate } }
appKmm/androidApp/src/main/java/com/example/appkmm/android/MainActivity.kt
502931500
package com.example.appkmm.android import android.annotation.SuppressLint import android.os.Bundle import android.util.Log 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.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import com.example.appkmm.src.repository.CorelibDelegate class MainActivity : ComponentActivity() { val TAG = "MainAct" @SuppressLint("SuspiciousIndentation") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MyApplicationTheme { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { val env = listOf<String>("staging","prepord","prod") val coreLibId = "AK-84d4112081678b2d01bd3fe7de2d3fe7" val repository = CorelibDelegate.initCoreLib() val state = remember { mutableStateOf("Loading") } //val dataStoreManager = AndroidDataStoreManager(applicationContext) //val dataManager = DataManager(dataStoreManager) LaunchedEffect(true) { try { //val result = repository.corelibInit(env[2],coreLibId,applicationContext) val result = repository.update(applicationContext) state.value = result.responseCode.toString()+" "+result.responseMessage+" "+result.responseDescription+" "+result.responseData //repository.saveUserData(applicationContext) //Log.w(TAG,"the saved data is : ${repository.readUserData(applicationContext)}") } catch (e: Exception) { state.value } } GreetingView(state.value) Log.w(TAG,state.value) } } } } } @Composable fun GreetingView(text: String) { Text(text = text) } @Preview @Composable fun DefaultPreview() { MyApplicationTheme { GreetingView("Hello, Android!") } }
appKmm/androidApp/src/main/java/com/example/appkmm/android/MyApplicationTheme.kt
3405074421
package com.example.appkmm.android import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Shapes import androidx.compose.material3.Typography import androidx.compose.material3.darkColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color 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.dp import androidx.compose.ui.unit.sp @Composable fun MyApplicationTheme( darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit ) { val colors = if (darkTheme) { darkColorScheme( primary = Color(0xFFBB86FC), secondary = Color(0xFF03DAC5), tertiary = Color(0xFF3700B3) ) } else { lightColorScheme( primary = Color(0xFF6200EE), secondary = Color(0xFF03DAC5), tertiary = Color(0xFF3700B3) ) } val typography = Typography( bodyMedium = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp ) ) val shapes = Shapes( small = RoundedCornerShape(4.dp), medium = RoundedCornerShape(4.dp), large = RoundedCornerShape(0.dp) ) MaterialTheme( colorScheme = colors, typography = typography, shapes = shapes, content = content ) }
android_2/app/src/androidTest/kotlin/ru/netology/testing/uiautomator/ChangeTextTest.kt
3882065138
package ru.netology.testing.uiautomator import android.content.Context import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import androidx.test.uiautomator.By import androidx.test.uiautomator.UiDevice import androidx.test.uiautomator.UiSelector import androidx.test.uiautomator.Until import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test import org.junit.runner.RunWith const val SETTINGS_PACKAGE = "com.android.settings" const val MODEL_PACKAGE = "ru.netology.testing.uiautomator" const val TIMEOUT = 5000L @RunWith(AndroidJUnit4::class) class ChangeTextTest { private lateinit var device: UiDevice private val textToSet = "Netology" // @Test // fun testInternetSettings() { // // Press home // device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()) // device.pressHome() // // // Wait for launcher // val launcherPackage = device.launcherPackageName // device.wait(Until.hasObject(By.pkg(launcherPackage)), TIMEOUT) // waitForPackage(SETTINGS_PACKAGE) // // val context = ApplicationProvider.getApplicationContext<Context>() // val intent = context.packageManager.getLaunchIntentForPackage(SETTINGS_PACKAGE) // context.startActivity(intent) // device.wait(Until.hasObject(By.pkg(SETTINGS_PACKAGE)), TIMEOUT) // // device.findObject( // UiSelector().resourceId("android:id/title").instance(0) // ).click() // } // @Test // fun testChangeText() { // // Press home // device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()) // device.pressHome() // // // Wait for launcher // val launcherPackage = device.launcherPackageName // device.wait(Until.hasObject(By.pkg(launcherPackage)), TIMEOUT) // waitForPackage(SETTINGS_PACKAGE) // // val context = ApplicationProvider.getApplicationContext<Context>() // val packageName = context.packageName // val intent = context.packageManager.getLaunchIntentForPackage(packageName) // context.startActivity(intent) // device.wait(Until.hasObject(By.pkg(packageName)), TIMEOUT) // // // device.findObject(By.res(packageName, "userInput")).text = textToSet // device.findObject(By.res(packageName, "buttonChange")).click() // // val result = device.findObject(By.res(packageName, "textToBeChanged")).text // assertEquals(result, textToSet) // } private fun waitForPackage(packageName: String) { val context = ApplicationProvider.getApplicationContext<Context>() val intent = context.packageManager.getLaunchIntentForPackage(packageName) context.startActivity(intent) device.wait(Until.hasObject(By.pkg(packageName)), TIMEOUT) } @Before fun beforeEachTest() { // Press home device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()) device.pressHome() // Wait for launcher val launcherPackage = device.launcherPackageName device.wait(Until.hasObject(By.pkg(launcherPackage)), TIMEOUT) } @Test fun testInternetSettings() { waitForPackage(SETTINGS_PACKAGE) device.findObject( UiSelector().resourceId("android:id/title").instance(0) ).click() } @Test fun testChangeText() { val packageName = MODEL_PACKAGE waitForPackage(packageName) device.findObject(By.res(packageName, "userInput")).text = textToSet device.findObject(By.res(packageName, "buttonChange")).click() val result = device.findObject(By.res(packageName, "textToBeChanged")).text assertEquals(result, textToSet) } @Test fun testEmptyText() { val packageName = MODEL_PACKAGE waitForPackage(packageName) device.findObject(By.res(packageName, "userInput")).text = " " device.findObject(By.res(packageName, "buttonChange")).click() val result = device.findObject(By.res(packageName, "textToBeChanged")).text assertEquals(result, "Hello UiAutomator!") } @Test fun testNewActivity() { val packageName = MODEL_PACKAGE waitForPackage(packageName) device.findObject(By.res(packageName, "userInput")).text = "Hello World!" device.findObject(By.res(packageName, "buttonActivity")).click() waitForPackage(packageName) val result = device.findObject(By.res(packageName, "text")).text assertEquals(result, "Hello World!") } }
android_2/app/src/test/kotlin/ru/netology/testing/uiautomator/LocalTest.kt
1728585210
package ru.netology.testing.uiautomator import org.junit.Assert.assertEquals import org.junit.Test class LocalTest { @Test fun justTest() { assertEquals(true, true) } }
android_2/app/src/main/kotlin/ru/netology/testing/uiautomator/MainActivity.kt
3094248148
package ru.netology.testing.uiautomator import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import ru.netology.testing.uiautomator.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) with(binding) { buttonChange.setOnClickListener { val text = binding.userInput.text if (text.isNotBlank()) { textToBeChanged.text = text } } buttonActivity.setOnClickListener { val intent = ShowTextActivity.newStartIntent( this@MainActivity, binding.userInput.text.toString() ) startActivity(intent) } } } }
android_2/app/src/main/kotlin/ru/netology/testing/uiautomator/ShowTextActivity.kt
3434222029
package ru.netology.testing.uiautomator import android.content.Context import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import ru.netology.testing.uiautomator.databinding.ActivityShowTextBinding class ShowTextActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding = ActivityShowTextBinding.inflate(layoutInflater) setContentView(binding.root) binding.text.text = intent.getStringExtra(KEY_EXTRA_MESSAGE) ?: "" } companion object { const val KEY_EXTRA_MESSAGE = "testing_message" fun newStartIntent(context: Context, message: String): Intent { val newIntent = Intent(context, ShowTextActivity::class.java) newIntent.putExtra(KEY_EXTRA_MESSAGE, message) return newIntent } } }
ktGraphQL/src/test/kotlin/com/example/ktgraphql/KtGraphQlApplicationTests.kt
3898260106
package com.example.ktgraphql import org.junit.jupiter.api.Test import org.springframework.boot.test.context.SpringBootTest @SpringBootTest class KtGraphQlApplicationTests { @Test fun contextLoads() { } }