content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
package com.langdroid.summary import com.langdroid.core.ChatPrompt import com.langdroid.core.LangDroidModel import com.langdroid.core.models.openai.OpenAiModel import com.langdroid.core.models.request.config.GenerativeConfig import io.mockk.coEvery import io.mockk.every import io.mockk.mockk import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.take import kotlinx.coroutines.flow.toList internal object Mocks { private const val chunks = 3 private const val tokensTest = 1000 const val text1 = "Hello, can I help you?" const val text2 = "Hello, weather is good today" const val MOCK_TEXT = "Wow!" suspend fun createModelNormalWithList( text: String = text1, isStream: Boolean = true, isTestCompleteness: Boolean = false, isReduceText: Boolean = false ): Pair<LangDroidModel<*>, List<SummaryState>> { val model: LangDroidModel<*> = mockk() val openAiModel: OpenAiModel.Gpt3_5 = mockk() val config: GenerativeConfig<*> = mockk() every { openAiModel.tokenLimit } returns tokensTest * (if (isReduceText) 1 else 3) every { openAiModel.outputTokenLimit } returns tokensTest every { config.maxOutputTokens } returns tokensTest every { model.model } returns openAiModel every { model.config } returns config val flowGenerator = stringToStreamFlowGenerator(text, chunks) coEvery { model.generateText(any<String>()) } coAnswers { delay(DEFAULT_DELAY) Result.success(text) } coEvery { model.generateTextStream(any<String>()) } returns Result.success( flowGenerator(true) ) coEvery { model.generateText(any<List<ChatPrompt>>()) } coAnswers { delay(DEFAULT_DELAY) Result.success(text) } coEvery { model.generateTextStream(any<List<ChatPrompt>>()) } returns Result.success( flowGenerator(true) ) coEvery { model.sanityCheck() } returns true coEvery { model.calculateTokens(any<List<ChatPrompt>>()) } returns Result.success(42) return model to generateListForText( text, isStream, isReduceText, isTestCompleteness, flowGenerator ) } private suspend fun generateListForText( text: String, isStream: Boolean, isReduceText: Boolean, isTestCompleteness: Boolean, flowGenerator: (Boolean) -> Flow<String> ): List<SummaryState> { val outputItems = if (isStream) flowGenerator(false).take(count = chunks).toList() else listOf(text) return defaultStatesBefore(isStream, isReduceText) + outputItems .map { SummaryState.Output(it) } + defaultStatesAfter(isTestCompleteness) } private fun defaultStatesBefore(isStream: Boolean, isReduceText: Boolean): List<SummaryState> = if (isReduceText) { listOf(SummaryState.TextSplitting, SummaryState.Reduce(1, 1)) } else { listOf() } + if (!isStream) { listOf(SummaryState.Summarizing) } else { listOf() } private fun defaultStatesAfter(isTestCompleteness: Boolean): List<SummaryState> = if (isTestCompleteness) listOf() else listOf(SummaryState.Success) }
LangDroid/summary/src/commonTest/kotlin/com/langdroid/summary/Mocks.kt
1477413269
package com.langdroid.summary import app.cash.turbine.test import com.langdroid.core.LangDroidModel import com.langdroid.summary.Mocks.MOCK_TEXT import kotlinx.coroutines.flow.takeWhile import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.runTest import kotlin.test.Test import kotlin.test.assertEquals class TestSummaryChain { // Way to check if returned states are correct private fun runSummaryChainTest( description: String, isStream: Boolean, setup: suspend TestScope.() -> Pair<LangDroidModel<*>, List<SummaryState>> ) = runTest { val (model, expectedStates) = setup() val summaryChain = SummaryChain(model, isStream, coroutineScope = backgroundScope) val isCompletenessTest = checkIsCompletenessTest(description) val testFlow = if (isCompletenessTest) { summaryChain.invokeAndGetFlow(MOCK_TEXT).takeWhile { !it.isFinished() } } else summaryChain.invokeAndGetFlow(MOCK_TEXT) testFlow.test { for (state in expectedStates) { assertEquals(state, awaitItem()) } if (isCompletenessTest) awaitComplete() } } // Scenarios with isStream = false @Test fun testSummariesWithStreamFalse() { runSummaryChainTest("Normal", false) { Mocks.createModelNormalWithList(isStream = false) } } @Test fun testSummariesCompleteWithStreamFalse() { runSummaryChainTest("Completeness Test", false) { Mocks.createModelNormalWithList(isStream = false, isTestCompleteness = true) } } @Test fun testSummariesReduceWithStreamFalse() { runSummaryChainTest("Reduce Text Test", false) { Mocks.createModelNormalWithList(isStream = false, isReduceText = true) } } // Scenarios with isStream = true @Test fun testSummariesWithStreamTrue() { runSummaryChainTest("Normal", true) { Mocks.createModelNormalWithList(isStream = true) } } @Test fun testSummariesCompleteWithStreamTrue() { runSummaryChainTest("Completeness Test", true) { Mocks.createModelNormalWithList(isStream = true, isTestCompleteness = true) } } @Test fun testSummariesReduceWithStreamTrue() { runSummaryChainTest("Reduce Text Test", true) { Mocks.createModelNormalWithList(isStream = true, isReduceText = true) } } private fun checkIsCompletenessTest(description: String) = description.contains("complete", true) }
LangDroid/summary/src/commonTest/kotlin/com/langdroid/summary/TestSummaryChain.kt
3290272536
package com.langdroid.summary import androidx.lifecycle.LiveData import androidx.lifecycle.asLiveData public fun SummaryChain<*>.liveData(): LiveData<SummaryState> = processingState.asLiveData()
LangDroid/summary/src/androidMain/kotlin/com/langdroid/summary/extensions.kt
550408188
package com.example.briefbeat 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.briefbeat", appContext.packageName) } }
BriefBeat/app/src/androidTest/java/com/example/briefbeat/ExampleInstrumentedTest.kt
1279489379
package com.example.briefbeat 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) } }
BriefBeat/app/src/test/java/com/example/briefbeat/ExampleUnitTest.kt
607326668
package com.example.briefbeat class Articles( @JvmField var title: String, @JvmField var description: String, @JvmField var urlToImage: String, @JvmField var getUrlToImage: String, @JvmField var content: String )
BriefBeat/app/src/main/java/com/example/briefbeat/Articles.kt
1311483383
package com.example.briefbeat class NewsModal(var totalResults: Int, var status: String, var articles: ArrayList<Articles>)
BriefBeat/app/src/main/java/com/example/briefbeat/NewsModal.kt
3225005743
package com.example.briefbeat import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.ProgressBar import android.widget.Toast import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import retrofit2.Call import retrofit2.Callback import retrofit2.Response import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory class MainActivity : AppCompatActivity(),CategoryRVAdapter.CategoryClickInterface { private lateinit var newsRV: RecyclerView private lateinit var categoryRV: RecyclerView private lateinit var progressbar:ProgressBar private lateinit var articlesArrayList:ArrayList<Articles> private lateinit var categoryModalArrayList:ArrayList<CategoryModal> private lateinit var categoryRVAdapter: CategoryRVAdapter private lateinit var newsRVAdapter: NewsRVAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) //db223ddb2c07443686bfdc750ab4846a setContentView(R.layout.activity_main) newsRV=findViewById(R.id.vRV) categoryRV=findViewById(R.id.hRV) progressbar=findViewById(R.id.Pbar) articlesArrayList = ArrayList<Articles>() categoryModalArrayList=ArrayList<CategoryModal>() categoryRVAdapter = CategoryRVAdapter(categoryModalArrayList, this, this::onCategoryClick) newsRVAdapter= NewsRVAdapter(articlesArrayList,this) newsRV.layoutManager = LinearLayoutManager(this) newsRV.adapter=newsRVAdapter categoryRV.adapter=categoryRVAdapter getCategories() getNews("All") newsRVAdapter.notifyDataSetChanged() } fun getCategories(){ categoryModalArrayList.add(CategoryModal("All","https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT5_jbTu9KqPs28Pp-IYY1uskfhHTLbnqW0Ug&usqp=CAU")) categoryModalArrayList.add(CategoryModal("Science","https://assets.technologynetworks.com/production/dynamic/images/content/368887/science-is-becoming-less-disruptive-368887-960x540.jpg?cb=12105518")) categoryModalArrayList.add(CategoryModal("Technology","https://www.tofler.in/blog/wp-content/uploads/2023/08/technology.jpg")) categoryModalArrayList.add(CategoryModal("General","https://assets.weforum.org/global_future_council/image/FAdBujGNsB9kx8aa04DoOi3g5mnmf-OkZPy_0idrKMI.jpg")) categoryModalArrayList.add(CategoryModal("Sports","https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSKAkSRStDdnOJFFQBbhszGokRz5ADw4Btt4eNsXm-H393llFKh56mkpq9DHOp8vKrNqKY&usqp=CAU")) categoryModalArrayList.add(CategoryModal("Business","https://cloudinary.hbs.edu/hbsit/image/upload/s--EmT0lNtW--/f_auto,c_fill,h_375,w_750,/v20200101/6978C1C20B650473DD135E5352D37D55.jpg")) categoryModalArrayList.add(CategoryModal("Health","https://imageio.forbes.com/specials-images/imageserve/638ee3f77ab30981d50d997c/The-Top-5-Healthcare-Trends-In-2023/960x0.jpg?height=399&width=711&fit=bounds")) categoryModalArrayList.add(CategoryModal("Entertainment","https://etimg.etb2bimg.com/photo/75690061.cms")) categoryRVAdapter.notifyDataSetChanged() } private fun getNews(category: String) { progressbar.visibility= View.VISIBLE articlesArrayList.clear() val categoryURL = "https://newsapi.org/v2/top-headlines?country=in&category=$category&apikey=db223ddb2c07443686bfdc750ab4846a" val url="https://newsapi.org/v2/top-headlines?country=in&excludeDomains=stackoverflow.com&sortBy=publishedAt&language=en&apikey=db223ddb2c07443686bfdc750ab4846a" val Base_URL="https://newsapi.org/" val retrofit = Retrofit.Builder().baseUrl(Base_URL).addConverterFactory(GsonConverterFactory.create()).build() val retrofitAPI = retrofit.create(RetrofitAPI::class.java) val call: Call<NewsModal?>? = if (category == "All") { retrofitAPI.getAllNews(url) } else { retrofitAPI.getNewsByCategory(categoryURL) } call?.enqueue(object : Callback<NewsModal?> { override fun onResponse(call: Call<NewsModal?>, response: Response<NewsModal?>) { val newsModal = response.body() progressbar.visibility= View.GONE val articles: ArrayList<Articles> = newsModal!!.articles for (i in 0 until articles.size) { val article = articles[i] articlesArrayList.add(Articles(article.title, article.description, article.urlToImage,article.getUrlToImage,article.content)) } newsRVAdapter.notifyDataSetChanged() } override fun onFailure(call: Call<NewsModal?>, t: Throwable) { Toast.makeText(this@MainActivity, "Oops something went wrong!", Toast.LENGTH_SHORT).show() } }) } override fun onCategoryClick(position: Int) { val category = categoryModalArrayList[position].category getNews(category) } }
BriefBeat/app/src/main/java/com/example/briefbeat/MainActivity.kt
3425714526
package com.example.briefbeat import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Handler import android.text.PrecomputedText.Params import android.view.WindowManager import android.widget.ImageView class SplashScreenActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_splash_screen) // val icon=findViewById<ImageView>(R.id.splash_icon) // supportActionBar?.hide() // window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN) // Handler().postDelayed({ val icon=findViewById<ImageView>(R.id.splash_icon) icon.alpha=1f; icon.animate().setDuration(4000).alpha(1f).withEndAction{ val i= Intent(this,MainActivity::class.java) startActivity(i) finish() } // }, 2000) } }
BriefBeat/app/src/main/java/com/example/briefbeat/SplashScreenActivity.kt
1955042119
package com.example.briefbeat class CategoryModal(@JvmField var category: String, @JvmField var categoryImageURL: String)
BriefBeat/app/src/main/java/com/example/briefbeat/CategoryModal.kt
1045806630
package com.example.briefbeat import android.content.Intent import android.net.Uri import android.os.Bundle import android.widget.Button import android.widget.ImageView import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import com.squareup.picasso.Picasso class NewsDetailActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_news_detail) val title = intent.getStringExtra("title") val des = intent.getStringExtra("description") val content = intent.getStringExtra("content") val imageURL = intent.getStringExtra("image") val url = intent.getStringExtra("url") val titleTV = findViewById<TextView>(R.id.newsTitle) val subTitle = findViewById<TextView>(R.id.newsSubtitle) val desc = findViewById<TextView>(R.id.newsDes) val newsImg = findViewById<ImageView>(R.id.newsImg) val newsBtn = findViewById<Button>(R.id.newsButton) titleTV.text = title subTitle.text = des desc.text = content Picasso.get().load(imageURL).into(newsImg) newsBtn.setOnClickListener { val i = Intent(Intent.ACTION_VIEW) i.setData(Uri.parse(url)) startActivity(i) } } }
BriefBeat/app/src/main/java/com/example/briefbeat/NewsDetailActivity.kt
2683519397
package com.example.briefbeat import android.content.Context import android.content.Intent import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.squareup.picasso.Picasso class NewsRVAdapter( private val articlesArrayList: ArrayList<Articles>, private val context: Context ) : RecyclerView.Adapter<NewsRVAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.news, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val articles = articlesArrayList[position] holder.subtitleTV.text = articles.description holder.titleTV.text = articles.title Picasso.get().load(articles.urlToImage).into(holder.newsIV) holder.itemView.setOnClickListener { val intent = Intent(context, NewsDetailActivity::class.java) intent.putExtra("title", articles.title) intent.putExtra("content", articles.content) intent.putExtra("description", articles.description) intent.putExtra("image", articles.urlToImage) intent.putExtra("url", articles.getUrlToImage) context.startActivity(intent) } } override fun getItemCount(): Int { return articlesArrayList.size } inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val titleTV: TextView val subtitleTV: TextView val newsIV: ImageView init { titleTV = itemView.findViewById(R.id.newsText) subtitleTV = itemView.findViewById(R.id.newsDes) newsIV = itemView.findViewById(R.id.newsImage) } } }
BriefBeat/app/src/main/java/com/example/briefbeat/NewsRVAdapter.kt
1243490040
package com.example.briefbeat import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.squareup.picasso.Picasso class CategoryRVAdapter( private val categoryModal: List<CategoryModal>, private val categoryClickInterface: CategoryClickInterface, kFunction1: (Int) -> Unit ) : RecyclerView.Adapter<CategoryRVAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.categories, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val categoryModal1 = categoryModal[position] holder.categoryTV.text = categoryModal1.category Picasso.get().load(categoryModal1.categoryImageURL).into(holder.categoryIV) holder.itemView.setOnClickListener { categoryClickInterface.onCategoryClick(position) } } override fun getItemCount(): Int { return categoryModal.size } interface CategoryClickInterface { fun onCategoryClick(position: Int) } inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val categoryTV: TextView val categoryIV: ImageView init { categoryIV = itemView.findViewById(R.id.catImage) categoryTV = itemView.findViewById(R.id.catText) } } }
BriefBeat/app/src/main/java/com/example/briefbeat/CategoryRVAdapter.kt
955811412
package com.example.briefbeat import retrofit2.Call import retrofit2.http.GET import retrofit2.http.Url interface RetrofitAPI { @GET fun getAllNews(@Url url: String?): Call<NewsModal?>? @GET fun getNewsByCategory(@Url url: String?): Call<NewsModal?>? // Add a relative path for the base URL companion object { const val BASE_URL = "https://newsapi.org/" } }
BriefBeat/app/src/main/java/com/example/briefbeat/RetrofitAPI.kt
3720473567
package com.evicky.core 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.evicky.core.test", appContext.packageName) } }
FinLedgerPublic/core/src/androidTest/java/com/evicky/core/ExampleInstrumentedTest.kt
3364122584
package com.evicky.core 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) } }
FinLedgerPublic/core/src/test/java/com/evicky/core/ExampleUnitTest.kt
1965860362
package com.evicky.core.dataSource import com.evicky.utility.logger.Log import kotlinx.coroutines.suspendCancellableCoroutine import kotlin.coroutines.resume interface IDataSource { suspend fun writeData( documentPath: String, data: Any, logTag: String, writeSuccessLogMessage: String, writeFailureLogMessage: String ): Boolean suspend fun readData(logTag: String, documentPath: String): Map<String, Any>? suspend fun deleteData( documentPath: String, logTag: String, writeFailureLogMessage: String ): Boolean } class Firestore : IDataSource { // private val fireStore: FirebaseFirestore = FirebaseFirestore.getInstance() override suspend fun writeData( documentPath: String, data: Any, logTag: String, writeSuccessLogMessage: String, writeFailureLogMessage: String, ) = suspendCancellableCoroutine { continuation -> try { // fireStore.document(documentPath).set(data) // .addOnCompleteListener { task -> // if (task.isSuccessful) { // Log.i(logTag, "Data write success to firestore db $writeSuccessLogMessage: $documentPath") // if (continuation.isActive) continuation.resume(true) // } else { // Log.e(logTag, // "Data write failed to firestore db $writeFailureLogMessage: $documentPath. Error Message: ${task.exception?.message}", // task.exception) // if (continuation.isActive) continuation.resume(false) // } // } // sendSuccessResultIfOfflineForDocumentWrite(fireStore.document(documentPath), continuation) } catch (exception: Exception) { Log.e(logTag, "Exception from execution: Data write failed to firestore db. $writeFailureLogMessage: $documentPath. Error Message: ${exception.message}", exception) if (continuation.isActive) continuation.resume(false) } } override suspend fun readData(logTag: String, documentPath: String): Map<String, Any>? = // fireStore.document(documentPath).get().await().data null override suspend fun deleteData( documentPath: String, logTag: String, writeFailureLogMessage: String, ) = suspendCancellableCoroutine { continuation -> try { // fireStore.document(documentPath).delete() // .addOnCompleteListener { task -> // if (task.isSuccessful) { // Log.i(logTag, "Delete Success in firestore db: $documentPath") // if (continuation.isActive) continuation.resume(true) // } else { // Log.e(logTag, // "Delete Failure in firestore db: $writeFailureLogMessage: $documentPath. Error Message: ${task.exception?.message}", // task.exception) // if (continuation.isActive) continuation.resume(false) // } // // } } catch (exception: Exception) { Log.e(logTag, "Exception from execution: Delete Failure in firestore db: $writeFailureLogMessage: $documentPath. Error Message: ${exception.message}", exception) if (continuation.isActive) continuation.resume(false) } } } /** * While the device is in offline we won't get success or failure task result for writes to firestore. * So getting the meta data to send the result back to the caller if the data is from cache. */ //fun sendSuccessResultIfOfflineForDocumentWrite( // documentReference: DocumentReference, // continuation: CancellableContinuation<Boolean> //) { // documentReference.get().addOnSuccessListener { // if (it.metadata.isFromCache && continuation.isActive) continuation.resume(true) // } //} class DynamoDb : IDataSource { override suspend fun writeData( documentPath: String, data: Any, logTag: String, writeSuccessLogMessage: String, writeFailureLogMessage: String, ): Boolean { Log.i(logTag, "Data write success to dynamo db $writeSuccessLogMessage: $documentPath") return true } override suspend fun readData(logTag: String, documentPath: String): Map<String, Any>? { Log.i(logTag, "Data read success from dynamo db $documentPath") return null } override suspend fun deleteData( documentPath: String, logTag: String, writeFailureLogMessage: String, ): Boolean { Log.i(logTag, "Data delete success in dynamo db $documentPath") return true } }
FinLedgerPublic/core/src/main/java/com/evicky/core/dataSource/DataSource.kt
2787477708
package com.evicky.core.di import com.evicky.core.dataSource.DynamoDb import com.evicky.core.dataSource.Firestore import com.evicky.core.repo.ISignInRepo import com.evicky.core.repo.SignInRepo import com.evicky.core.usecase.SignInUseCase import com.evicky.utility.utils.CoroutineDispatcherProvider import com.evicky.utility.utils.ICoroutineDispatcherProvider import org.koin.core.module.dsl.bind import org.koin.core.module.dsl.factoryOf import org.koin.core.module.dsl.singleOf import org.koin.dsl.module val useCaseModule = module { factoryOf(::SignInUseCase) } val repoModule = module { factoryOf(::SignInRepo) { bind<ISignInRepo>() } } val dataSourceModule = module { singleOf(::Firestore) singleOf(::DynamoDb) } val coroutineDispatcherProviderModule = module { singleOf(::CoroutineDispatcherProvider) { bind<ICoroutineDispatcherProvider>()} }
FinLedgerPublic/core/src/main/java/com/evicky/core/di/DiKoin.kt
2635334684
package com.evicky.core.model.local data class SignInLocalData(val id: Long, val name: String)
FinLedgerPublic/core/src/main/java/com/evicky/core/model/local/SignInLocalData.kt
212399414
package com.evicky.core.model.remote import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class SignInRemoteData(val id: Long, val name: String, val address: String, val occupation: String): Parcelable
FinLedgerPublic/core/src/main/java/com/evicky/core/model/remote/SignInRemoteData.kt
1183121100
package com.evicky.core.usecase import com.evicky.core.model.local.SignInLocalData import com.evicky.core.model.remote.SignInRemoteData import com.evicky.core.repo.ISignInRepo import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json class SignInUseCase(private val signInRepo: ISignInRepo) { suspend fun writeData(data: SignInLocalData, logTag: String): Boolean { return signInRepo.writeData(documentPath = "Users/UserId", data = data, logTag = logTag) } suspend fun readData(path: String, logTag: String): SignInLocalData { val signInRemoteData = Json.decodeFromString<SignInRemoteData>(signInRepo.readData(logTag = logTag, path = path).toString()) return SignInLocalData(id = signInRemoteData.id, name = signInRemoteData.name) } }
FinLedgerPublic/core/src/main/java/com/evicky/core/usecase/SignInUseCase.kt
2256420234
package com.evicky.core.repo import com.evicky.core.dataSource.DynamoDb import com.evicky.core.dataSource.Firestore import com.evicky.core.dataSource.IDataSource import com.evicky.core.model.local.SignInLocalData interface ISignInRepo { suspend fun writeData(documentPath: String, data: SignInLocalData, logTag: String): Boolean suspend fun readData(logTag: String, path: String): Map<String, Any> } class SignInRepo(firestore: Firestore, dynamoDb: DynamoDb): ISignInRepo { private val isPremiumUser = false // This data may come from some other data source private val dataSource: IDataSource = if (isPremiumUser) dynamoDb else firestore override suspend fun writeData(documentPath: String, data: SignInLocalData, logTag: String): Boolean = dataSource.writeData( documentPath = documentPath, data = data, logTag = logTag, writeSuccessLogMessage = "Data written successfully", writeFailureLogMessage = "Data write failed") override suspend fun readData(logTag: String, path: String): Map<String, Any> = dataSource.readData(logTag, documentPath = path) ?: mapOf() }
FinLedgerPublic/core/src/main/java/com/evicky/core/repo/SignInRepo.kt
29047448
package com.evicky.financeledger 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.evicky.financeledger", appContext.packageName) } }
FinLedgerPublic/app/src/androidTest/java/com/evicky/financeledger/ExampleInstrumentedTest.kt
2565727763
package com.evicky.financeledger 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) } }
FinLedgerPublic/app/src/test/java/com/evicky/financeledger/ExampleUnitTest.kt
1859841968
package com.evicky.financeledger.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)
FinLedgerPublic/app/src/main/java/com/evicky/financeledger/ui/theme/Color.kt
4237046476
package com.evicky.financeledger.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 FinanceLedgerTheme( 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 ) }
FinLedgerPublic/app/src/main/java/com/evicky/financeledger/ui/theme/Theme.kt
3492488416
package com.evicky.financeledger.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 ) */ )
FinLedgerPublic/app/src/main/java/com/evicky/financeledger/ui/theme/Type.kt
2620877852
package com.evicky.financeledger import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import com.evicky.financeledger.root.RootHost import com.evicky.financeledger.ui.theme.FinanceLedgerTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { FinanceLedgerTheme { RootHost() } } } }
FinLedgerPublic/app/src/main/java/com/evicky/financeledger/MainActivity.kt
1610759643
package com.evicky.financeledger.root import androidx.compose.runtime.Composable import androidx.navigation.compose.NavHost import androidx.navigation.compose.rememberNavController import com.evicky.feature.signIn.signInNavGraph import com.evicky.feature.postlogin.navigateToPostLoginScreen import com.evicky.feature.postlogin.postLoginNavGraph import com.evicky.feature.util.SIGNIN_ROUTE @Composable internal fun RootHost() { val rootController = rememberNavController() NavHost( navController = rootController, startDestination = SIGNIN_ROUTE, ) { signInNavGraph( onSignInPress = { rootController.navigateToPostLoginScreen(it) } ) postLoginNavGraph() } }
FinLedgerPublic/app/src/main/java/com/evicky/financeledger/root/RootHost.kt
2205440914
package com.evicky.financeledger.application import android.app.Application import com.evicky.core.di.coroutineDispatcherProviderModule import com.evicky.core.di.dataSourceModule import com.evicky.core.di.repoModule import com.evicky.core.di.useCaseModule import com.evicky.feature.di.viewModelModule import org.koin.core.context.startKoin class FinanceLedgerApplication: Application() { override fun onCreate() { super.onCreate() // FirebaseApp.initializeApp(this) startKoin { modules( dataSourceModule, repoModule, useCaseModule, viewModelModule, coroutineDispatcherProviderModule ) } } }
FinLedgerPublic/app/src/main/java/com/evicky/financeledger/application/FinanceLedgerApplication.kt
3407825699
import org.gradle.api.Plugin import org.gradle.api.Project enum class ModuleType { Application, AndroidLibrary, JavaOrKotlinLibrary } class ApplicationGradlePlugin: Plugin<Project> { override fun apply(project: Project) { applyCommonPlugins(project) project.configureAndroidWithCompose(ModuleType.Application) } } class LibraryGradlePlugin: Plugin<Project> { override fun apply(project: Project) { applyCommonPlugins(project) project.configureAndroidWithCompose(ModuleType.AndroidLibrary) } } internal fun applyCommonPlugins(project: Project) { project.apply { plugin("kotlin-android") plugin("kotlin-kapt") } }
FinLedgerPublic/buildSrc/src/main/kotlin/CustomConventionGradlePlugin.kt
48529178
import com.android.build.api.dsl.ApplicationExtension import com.android.build.gradle.LibraryExtension import org.gradle.api.JavaVersion import org.gradle.api.Project private const val COMPILE_SDK_VERSION = 34 private const val MIN_SDK_VERSION = 24 private const val TARGET_SDK_VERSION = 34 private const val VERSION_CODE = 1 private const val VERSION_NAME = "1.0" const val KOTLIN_COMPILER_EXTENSION_VERSION = "1.5.6" private const val TEST_INSTRUMENTATION_RUNNER = "androidx.test.runner.AndroidJUnitRunner" internal fun Project.configureAndroidWithCompose(moduleType: ModuleType) { when (moduleType) { ModuleType.Application -> { project.extensions.getByType(ApplicationExtension::class.java).apply { compileSdk = COMPILE_SDK_VERSION defaultConfig { applicationId = "com.evicky.financeledger" minSdk = MIN_SDK_VERSION targetSdk = TARGET_SDK_VERSION versionCode = VERSION_CODE versionName = VERSION_NAME testInstrumentationRunner = TEST_INSTRUMENTATION_RUNNER vectorDrawables { useSupportLibrary = true } } compileOptions { sourceCompatibility = JavaVersion.VERSION_17 targetCompatibility = JavaVersion.VERSION_17 } buildFeatures { compose = true } composeOptions { kotlinCompilerExtensionVersion = KOTLIN_COMPILER_EXTENSION_VERSION } } } ModuleType.AndroidLibrary -> { project.extensions.getByType(LibraryExtension::class.java).apply { compileSdk = COMPILE_SDK_VERSION defaultConfig { minSdk = MIN_SDK_VERSION testInstrumentationRunner = TEST_INSTRUMENTATION_RUNNER consumerProguardFiles("consumer-rules.pro") } compileOptions { sourceCompatibility = JavaVersion.VERSION_17 targetCompatibility = JavaVersion.VERSION_17 } } // compose feature is enabled only for the library modules which requires it } ModuleType.JavaOrKotlinLibrary -> { // No-op } } }
FinLedgerPublic/buildSrc/src/main/kotlin/AndroidGradleConfig.kt
122905427
package com.evicky.feature 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.evicky.feature.test", appContext.packageName) } }
FinLedgerPublic/feature/src/androidTest/java/com/evicky/feature/ExampleInstrumentedTest.kt
470579217
package com.evicky.feature 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) } }
FinLedgerPublic/feature/src/test/java/com/evicky/feature/ExampleUnitTest.kt
3617261421
package com.evicky.feature.di import com.evicky.feature.signIn.SignInViewModel import org.koin.androidx.viewmodel.dsl.viewModelOf import org.koin.dsl.module val viewModelModule = module { viewModelOf(::SignInViewModel) }
FinLedgerPublic/feature/src/main/java/com/evicky/feature/di/DiKoin.kt
229539962
package com.evicky.feature.util const val SIGNIN_ROUTE = "login" const val POST_LOGIN_ROUTE = "postlogin"
FinLedgerPublic/feature/src/main/java/com/evicky/feature/util/Constants.kt
2643517000
package com.evicky.feature.signIn import androidx.compose.runtime.getValue import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavGraphBuilder import androidx.navigation.compose.composable import com.evicky.feature.util.SIGNIN_ROUTE import org.koin.androidx.compose.koinViewModel fun NavGraphBuilder.signInNavGraph( onSignInPress: (String) -> Unit ) { composable(route = SIGNIN_ROUTE) { val viewModel: SignInViewModel = koinViewModel() val loginUiState by viewModel.signInUiState.collectAsStateWithLifecycle() SignInScreen( signInUiState = loginUiState, onSignInPress = { if (loginUiState.errorMessage.isEmpty() && loginUiState.phoneNumber.isNotEmpty()) onSignInPress.invoke(it) }, onPhoneNumberChange = { updatedValue -> viewModel.onPhoneNumberChange(updatedValue) } ) } }
FinLedgerPublic/feature/src/main/java/com/evicky/feature/signIn/SignInGraph.kt
4274104900
package com.evicky.feature.signIn import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.evicky.core.model.local.SignInLocalData import com.evicky.core.usecase.SignInUseCase import com.evicky.utility.logger.Log import com.evicky.utility.utils.CoroutineDispatcherProvider import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.launch data class SignInUiState( val phoneNumber: String = "", val isLoginSuccess: Boolean = false, val errorMessage: String = "" ) private const val SIGNIN_VM_SAVED_STATE_HANDLE_KEY = "signInVMSavedStateHandleKey" private const val logTag = "SignInViewModel" class SignInViewModel(private val savedStateHandle: SavedStateHandle, private val signInUseCase: SignInUseCase, private val coroutineDispatcherProvider: CoroutineDispatcherProvider): ViewModel() { var signInUiState = MutableStateFlow(SignInUiState()) private set init { savedStateHandle.get<SignInUiState>(SIGNIN_VM_SAVED_STATE_HANDLE_KEY)?.let { signInUiState.value = it } } fun onPhoneNumberChange(phoneNumber: String) { signInUiState.value = signInUiState.value.copy(phoneNumber = phoneNumber) if (phoneNumber.length != 10) { setPhoneNumberFieldErrorMessage("Invalid mobile number.") } else { setPhoneNumberFieldErrorMessage("") } } private fun setPhoneNumberFieldErrorMessage(errorMessage: String) { signInUiState.value = signInUiState.value.copy(errorMessage = errorMessage) } fun writeDataToDataSource() { viewModelScope.launch(coroutineDispatcherProvider.io()) { val isWriteSuccess = signInUseCase.writeData(data = SignInLocalData(id = 1L, name = "eVicky"), logTag = "$logTag:writeDataToDataSource") Log.i("$logTag:writeDataToDataSource", "isWriteSuccess: $isWriteSuccess") } } fun readDataFromDataSource() { viewModelScope.launch(coroutineDispatcherProvider.io()) { val signInLocalData = signInUseCase.readData(path = "Users/UserId", logTag = logTag) Log.i("$logTag:readDataFromDataSource", "signInLocalData: $signInLocalData") } } override fun onCleared() { super.onCleared() //To not to lose data during android low memory kill savedStateHandle[SIGNIN_VM_SAVED_STATE_HANDLE_KEY] = signInUiState } }
FinLedgerPublic/feature/src/main/java/com/evicky/feature/signIn/SignInViewModel.kt
3801390457
package com.evicky.feature.signIn import android.content.res.Configuration import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column 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.shape.CircleShape import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Phone import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.evicky.feature.R @Composable internal fun SignInScreen( signInUiState: SignInUiState, onSignInPress: (String) -> Unit, onPhoneNumberChange: (String) -> Unit ) { Column( modifier = Modifier .fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, ) { Image( painter = painterResource(id = R.drawable.logo_finance_ledger), contentDescription = "logo", alignment = Alignment.Center, modifier = Modifier.height(250.dp).width(250.dp).clip(CircleShape) ) Spacer(modifier = Modifier.height(16.dp)) PhoneNumberField(signInUiState = signInUiState) { updatedValue -> onPhoneNumberChange(updatedValue) } OutlinedButton( onClick = { onSignInPress(signInUiState.phoneNumber) }, enabled = signInUiState.errorMessage.isEmpty() ) { Text(text = stringResource(R.string.sign_in)) } } } @Composable fun PhoneNumberField( modifier: Modifier = Modifier, signInUiState: SignInUiState, onPhoneNumberChange: (String) -> Unit, ) { OutlinedTextField( value = signInUiState.phoneNumber, onValueChange = { updatedValue -> onPhoneNumberChange(updatedValue) }, modifier = Modifier .fillMaxWidth() .then(modifier.padding(horizontal = 40.dp)), label = { Text(text = stringResource(R.string.mobile_number)) }, leadingIcon = { Icon(imageVector = Icons.Default.Phone, contentDescription = null) }, isError = signInUiState.errorMessage.isNotEmpty(), supportingText = { Text(text = signInUiState.errorMessage, style = MaterialTheme.typography.bodySmall, color = Color.Red) }, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number) ) } @Preview(showBackground = true, showSystemUi = false) @Composable private fun LoginScreenPreview() { MaterialTheme { SignInScreen( signInUiState = SignInUiState(), onSignInPress = { _ -> }, onPhoneNumberChange = { _ -> } ) } } @Preview(device = "id:Nexus 7", showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_NO or Configuration.UI_MODE_TYPE_NORMAL, showSystemUi = false ) @Composable private fun LoginScreenTabPreview() { MaterialTheme { SignInScreen( signInUiState = SignInUiState(), onSignInPress = { _ -> }, onPhoneNumberChange = { _ -> } ) } }
FinLedgerPublic/feature/src/main/java/com/evicky/feature/signIn/SignInScreen.kt
3157103840
package com.evicky.feature.postlogin import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.evicky.feature.R @Composable fun PostLoginScreen(phoneNumber: String) { Column(modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally) { Row( modifier = Modifier.fillMaxWidth().padding(50.dp), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically ) { OutlinedTextField(value = phoneNumber, onValueChange = {}, readOnly = true, label = { Text(text = stringResource(R.string.mobile_number)) }) } Text(text = "Login Success!", fontSize = 50.sp, fontFamily = FontFamily.Monospace, fontStyle = FontStyle.Italic) } } @Preview(showBackground = true) @Composable fun PostLoginScreenPreview() { MaterialTheme { PostLoginScreen("23232") } }
FinLedgerPublic/feature/src/main/java/com/evicky/feature/postlogin/PostLoginScreen.kt
484218302
package com.evicky.feature.postlogin import androidx.navigation.NavController import androidx.navigation.NavGraphBuilder import androidx.navigation.compose.composable import com.evicky.feature.util.POST_LOGIN_ROUTE fun NavController.navigateToPostLoginScreen(data: String) { navigate("$POST_LOGIN_ROUTE/$data") } private const val PHONE_NO_KEY = "phoneNumberKey" fun NavGraphBuilder.postLoginNavGraph() { composable(route = "$POST_LOGIN_ROUTE/{$PHONE_NO_KEY}") { val receivedPhoneNumber = it.arguments?.getString(PHONE_NO_KEY) ?: "" PostLoginScreen(phoneNumber = receivedPhoneNumber) } }
FinLedgerPublic/feature/src/main/java/com/evicky/feature/postlogin/PostLoginGraph.kt
1919015741
package com.evicky.utility 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.evicky.utility.test", appContext.packageName) } }
FinLedgerPublic/utility/src/androidTest/java/com/evicky/utility/ExampleInstrumentedTest.kt
2259566363
package com.evicky.utility 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) } }
FinLedgerPublic/utility/src/test/java/com/evicky/utility/ExampleUnitTest.kt
3278723020
package com.evicky.utility.logger import android.util.Log object Log { fun v(tag: String, msg: String?, throwable: Throwable? = null) = msg?.run { Log.v(tag, this, throwable) } fun d(tag: String, msg: String?, throwable: Throwable? = null) = msg?.run { Log.d(tag, this, throwable) } fun i(tag: String, msg: String?, throwable: Throwable? = null) = msg?.run { Log.i(tag, this, throwable) } fun w(tag: String, msg: String?, throwable: Throwable? = null) = msg?.run { Log.w(tag, this, throwable) } fun e(tag: String, msg: String?, throwable: Throwable? = null) = msg?.run { Log.e(tag, this, throwable) } }
FinLedgerPublic/utility/src/main/java/com/evicky/utility/logger/Log.kt
379615953
package com.evicky.utility.network import android.content.Context import android.net.ConnectivityManager import android.net.Network import android.net.NetworkCapabilities import android.net.NetworkRequest import android.os.Build import kotlinx.coroutines.CoroutineName import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.async import kotlinx.coroutines.channels.ProducerScope import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.launch import java.net.URL import javax.net.ssl.HttpsURLConnection private const val TAG = "InternetConnectionStatus" private const val PING_TIMEOUT = 5000 private const val NO_CONTENT_ERR_CODE = 204 private const val EXCEPTION_RETRY_DELAY = 2_000L private const val MAX_EXCEPTION_RETRY_COUNT = 10 private const val NO_CONTENT_REQUEST_URL = "https://clients3.google.com/generate_204" @OptIn(ExperimentalCoroutinesApi::class) class InternetConnectionStatus(context: Context) { private val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager private var connectExceptionRetryCount = 0 /** * Memoization variable to help exception retry recursion function. * If we get positive response for internet connectivity then this will be returned * insteadof negative values from recursion stack. This will be reset upon recursion completion * and on network lost callback. */ private var hasActiveInternet = false val networkStatus = callbackFlow { val networkStatusCallback = object : ConnectivityManager.NetworkCallback() { override fun onAvailable(network: Network) { val hasInternetCapability = hasInternetCapabilities(connectivityManager, network) if (hasInternetCapability.not()) { return } checkForInternetConnectivity("onAvailable", this@callbackFlow) } override fun onLost(network: Network) { trySend(false) hasActiveInternet = false } override fun onUnavailable() { checkForInternetConnectivity("onUnavailable", this@callbackFlow) } override fun onCapabilitiesChanged( network: Network, networkCapabilities: NetworkCapabilities ) { checkForInternetConnectivity("onCapabilitiesChanged", this@callbackFlow) } } val request = NetworkRequest.Builder() .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) .addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) .build() connectivityManager.registerNetworkCallback(request, networkStatusCallback) awaitClose { connectivityManager.unregisterNetworkCallback(networkStatusCallback) } }.distinctUntilChanged() fun checkForInternetConnectivity(source: String, producerScope: ProducerScope<Boolean>) { producerScope.launch(CoroutineName(this.javaClass.name) + Dispatchers.IO) { val hasInternet = pingGoogleToGetInternetConnectivityStatus() producerScope.trySend(hasInternet) hasActiveInternet = false } } @Suppress("DEPRECATION") fun hasInternetCapabilities(connectivityManager: ConnectivityManager, network: Network): Boolean = when { Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q -> connectivityManager.getNetworkCapabilities(network)?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) ?: false else -> connectivityManager.getNetworkInfo(network)?.let { networkInfo -> return@let networkInfo.isConnected } ?: false } suspend fun pingGoogleToGetInternetConnectivityStatus(): Boolean = coroutineScope { async(Dispatchers.IO) { try { val urlConnection: HttpsURLConnection = URL(NO_CONTENT_REQUEST_URL).openConnection() as HttpsURLConnection urlConnection.setRequestProperty("User-Agent", "Android") urlConnection.setRequestProperty("Connection", "close") urlConnection.connectTimeout = PING_TIMEOUT urlConnection.connect() hasActiveInternet = urlConnection.responseCode == NO_CONTENT_ERR_CODE && urlConnection.contentLength == 0 hasActiveInternet } catch (e: Exception) { delay(EXCEPTION_RETRY_DELAY) if (connectExceptionRetryCount < MAX_EXCEPTION_RETRY_COUNT) { connectExceptionRetryCount += 1 pingGoogleToGetInternetConnectivityStatus() } hasActiveInternet } }.await() } }
FinLedgerPublic/utility/src/main/java/com/evicky/utility/network/InternetConnectionStatus.kt
2934675006
package com.evicky.utility.utils import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers interface ICoroutineDispatcherProvider { fun main(): CoroutineDispatcher = Dispatchers.Main fun mainImmediate(): CoroutineDispatcher = Dispatchers.Main.immediate fun default(): CoroutineDispatcher = Dispatchers.Default fun io(): CoroutineDispatcher = Dispatchers.IO fun unconfined(): CoroutineDispatcher = Dispatchers.Unconfined } class CoroutineDispatcherProvider : ICoroutineDispatcherProvider class TestCoroutineDispatcherProvider : ICoroutineDispatcherProvider { // override fun main(): CoroutineDispatcher = UnconfinedTestDispatcher() // override fun default(): CoroutineDispatcher = UnconfinedTestDispatcher() // override fun io(): CoroutineDispatcher = UnconfinedTestDispatcher() // override fun unconfined(): CoroutineDispatcher = UnconfinedTestDispatcher() }
FinLedgerPublic/utility/src/main/java/com/evicky/utility/utils/CoroutineDispatcherProvider.kt
3739843480
package com.evicky.utility.utils
FinLedgerPublic/utility/src/main/java/com/evicky/utility/utils/Constants.kt
2539674331
package `in`.instea.customdialog 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("in.instea.customdialog", appContext.packageName) } }
custom_Dialog/app/src/androidTest/java/in/instea/customdialog/ExampleInstrumentedTest.kt
3265203503
package `in`.instea.customdialog 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) } }
custom_Dialog/app/src/test/java/in/instea/customdialog/ExampleUnitTest.kt
1589922886
package `in`.instea.customdialog import android.app.Dialog import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.Toast class MainActivity : AppCompatActivity() { lateinit var dialog: Dialog override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) var showBtn = findViewById<Button>(R.id.openDialog_button) showBtn.setOnClickListener { } dialog = Dialog(this) dialog.setContentView(R.layout.custom_dialog) // dialog.window?.setBackgroundDrawable(getDrawable(R.drawable.dialog_bg)) dialog.window?.setBackgroundDrawableResource(R.drawable.dialog_bg) val feedbackBtn = dialog.findViewById<Button>(R.id.btnFeedback) val goodBtn = dialog.findViewById<Button>(R.id.btnGood) showBtn.setOnClickListener { dialog.show() } feedbackBtn.setOnClickListener { Toast.makeText(this, "feedback sent...", Toast.LENGTH_SHORT).show() dialog.dismiss() } goodBtn.setOnClickListener { Toast.makeText(this, "Congratulations...", Toast.LENGTH_SHORT).show() dialog.dismiss() } } }
custom_Dialog/app/src/main/java/in/instea/customdialog/MainActivity.kt
4175291066
package com.example.practiceactivity 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.practiceactivity", appContext.packageName) } }
Retrofitwithloginandregistraion/app/src/androidTest/java/com/example/practiceactivity/ExampleInstrumentedTest.kt
284705448
package com.example.practiceactivity 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) } }
Retrofitwithloginandregistraion/app/src/test/java/com/example/practiceactivity/ExampleUnitTest.kt
3793318266
package com.example.practiceactivity import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Handler import android.os.Looper import android.widget.Toast import com.example.practiceactivity.databinding.ActivityMainBinding import com.google.firebase.auth.ktx.auth import com.google.firebase.ktx.Firebase class MainActivity : AppCompatActivity() { private lateinit var binding:ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { binding = ActivityMainBinding.inflate(layoutInflater) super.onCreate(savedInstanceState) setContentView(binding.root) binding.alreadyhaveaccount.setOnClickListener { startActivity(Intent(this@MainActivity,loginActivity::class.java)) finish() } binding.registerbtn.setOnClickListener { if (binding.emailet.text.toString() == "" || binding.passet.text.toString() == "") { Toast.makeText( this@MainActivity, "Please Enter All Info", Toast.LENGTH_SHORT ).show() } else { Firebase.auth.createUserWithEmailAndPassword( binding.emailet.text.toString(), binding.passet.text.toString() ) .addOnCompleteListener { if (it.isSuccessful) { startActivity(Intent(this@MainActivity,HomeActivity::class.java)) finish() } else { Toast.makeText( this@MainActivity, it.exception?.localizedMessage, Toast.LENGTH_SHORT ).show() } } } } } override fun onStart() { super.onStart() if(Firebase.auth.currentUser!=null){ startActivity(Intent(this@MainActivity,HomeActivity::class.java)) finish() } } }
Retrofitwithloginandregistraion/app/src/main/java/com/example/practiceactivity/MainActivity.kt
4040741987
package com.example.practiceactivity import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.Menu import android.view.MenuItem import com.example.practiceactivity.databinding.ActivityHomeBinding import com.google.firebase.auth.ktx.auth import com.google.firebase.ktx.Firebase class HomeActivity : AppCompatActivity() { private lateinit var binding:ActivityHomeBinding override fun onCreate(savedInstanceState: Bundle?) { binding = ActivityHomeBinding.inflate(layoutInflater) super.onCreate(savedInstanceState) setContentView(binding.root) /* binding.logoutbtn.setOnClickListener { Firebase.auth.signOut() startActivity(Intent(this@HomeActivity,MainActivity::class.java)) finish() }*/ } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu,menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId){ R.id.logout -> {Firebase.auth.signOut() startActivity(Intent(this@HomeActivity,MainActivity::class.java)) finish()} } return super.onOptionsItemSelected(item) } }
Retrofitwithloginandregistraion/app/src/main/java/com/example/practiceactivity/HomeActivity.kt
2590979542
package com.example.practiceactivity import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Handler import android.os.Looper class splashScreen : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_splash_screen) Handler(Looper.getMainLooper()).postDelayed({ startActivity(Intent(this@splashScreen,loginActivity::class.java)) finish() },3000) } }
Retrofitwithloginandregistraion/app/src/main/java/com/example/practiceactivity/splashScreen.kt
3252710784
package com.example.practiceactivity import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Toast import com.example.practiceactivity.databinding.ActivityLoginBinding import com.google.android.gms.auth.api.Auth import com.google.android.gms.auth.api.signin.GoogleSignInOptions import com.google.android.gms.common.api.GoogleApiClient import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.ktx.auth import com.google.firebase.ktx.Firebase class loginActivity : AppCompatActivity() { private lateinit var binding: ActivityLoginBinding private lateinit var mAuth: FirebaseAuth private lateinit var mGoogleApiClient: GoogleApiClient override fun onCreate(savedInstanceState: Bundle?) { binding = ActivityLoginBinding.inflate(layoutInflater) super.onCreate(savedInstanceState) setContentView(binding.root) binding.donthaveaccount.setOnClickListener { startActivity(Intent(this@loginActivity, MainActivity::class.java)) finish() } mAuth = FirebaseAuth.getInstance() val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.default_web_client_id)) .requestEmail() .build() mGoogleApiClient = GoogleApiClient.Builder(this) .enableAutoManage(this) { connectionResult -> Toast.makeText(this@loginActivity, "Google Service Error", Toast.LENGTH_SHORT) .show() } .addApi(Auth.GOOGLE_SIGN_IN_API, gso) .build() binding.loginbtn.setOnClickListener { val email = binding.emailetlogin.text.toString() val password = binding.passetlogin.text.toString() signInWithEmailAndPassword(email, password) } } private fun signInWithEmailAndPassword(email: String, password: String) { mAuth.signInWithEmailAndPassword(email, password) .addOnCompleteListener(this) { task -> if (task.isSuccessful) { startActivity(Intent(this@loginActivity, HomeActivity::class.java)) finish() } else { Toast.makeText(this@loginActivity, "Invalid Email or Password", Toast.LENGTH_SHORT).show() } } } override fun onStart() { super.onStart() if (Firebase.auth.currentUser != null) { startActivity(Intent(this@loginActivity, HomeActivity::class.java)) finish() } } }
Retrofitwithloginandregistraion/app/src/main/java/com/example/practiceactivity/loginActivity.kt
4147235757
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/androidTest/java/com/example/stopwatchbet/ExampleInstrumentedTest.kt
1039136081
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/test/java/com/example/stopwatchbet/ExampleUnitTest.kt
4066267285
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/Color.kt
3076758102
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/Theme.kt
3274008718
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/ui/theme/Type.kt
966674371
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) }
StopWatchBet/app/src/main/java/com/example/stopwatchbet/MainActivity.kt
3733290737
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/App.kt
3213215066
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/PresetContext.kt
1880955789
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/context/JavaContext.kt
2916806932
package me.topilov.dsl @DslMarker annotation class PresetDslMarker
soochka/src/main/kotlin/dsl/annotations.kt
1938498993
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) } }
soochka/src/main/kotlin/dsl/dsl.kt
1241229360
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/test/java/com/dicoding/core/KoinModuleTest.kt
1356018174
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/di/CoreModule.kt
136075994
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/DialogImage.kt
2786785964
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/utils/Connectivity.kt
3176487196
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/repository/GameRepository.kt
93055601
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/mapper/GameMapper.kt
3175507594
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/FavoriteEntity.kt
3567299620
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/favorite/FavoriteDao.kt
2238829914
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/GameDao.kt
4043161800
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/game/GameEntity.kt
1041811951
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/GenreDao.kt
1274077254
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/entity/genre/GenreEntity.kt
2390301251
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/source/GameLocalSource.kt
3067560250
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/local/DatabaseGame.kt
2682672538
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/GameResponse.kt
3076843311
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/BaseGameResponse.kt
2999452475
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/GameScreenshots.kt
2531655562
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/response/DetailGameResponse.kt
1698346749
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/source/GameRemoteSource.kt
2629680870
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/ApiService.kt
3214588025
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/source/remote/network/ApiResponse.kt
438004254
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/ResultBound.kt
1782828787
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/data/collector/DataBoundCollector.kt
907832910
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/repository/IGameRepository.kt
3525895721
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/Favorite.kt
3186050550
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/models/Game.kt
3657881856
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/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 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/core/src/main/java/com/dicoding/core/domain/usecase/GameInteractor.kt
4263783191
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/DetailGameFragment.kt
1416106499
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/DetailGameViewModel.kt
1825083021
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/detail/adapter/ScreenshootAdapter.kt
85321223
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/GameViewModel.kt
4263425773
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/adapter/GameAdapter.kt
2000776128