content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package com.example.appmarvels.presentation.favorites import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.lifecycle.Observer import com.example.appmarvels.MainCoroutineRule import com.example.appmarvels.framework.useCase.GetFavoritesUseCase import com.example.appmarvels.model.CharacterFactory import com.nhaarman.mockitokotlin2.any import com.nhaarman.mockitokotlin2.isA import com.nhaarman.mockitokotlin2.verify import com.nhaarman.mockitokotlin2.whenever import junit.framework.TestCase import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.test.runTest import org.junit.Assert.* import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.junit.MockitoJUnitRunner @ExperimentalCoroutinesApi @RunWith(MockitoJUnitRunner::class) class FavoritesViewModelTest { @get:Rule var instantExecutorRule = InstantTaskExecutorRule() @get:Rule var mainCoroutineRule = MainCoroutineRule() @Mock private lateinit var getFavoritesUseCase: GetFavoritesUseCase @Mock private lateinit var uiStateObserver: Observer<FavoritesViewModel.UiState> private val characters = listOf(CharacterFactory().create(CharacterFactory.Hero.ThreeDMan)) private lateinit var favoritesViewModel: FavoritesViewModel @Before fun setup() { favoritesViewModel = FavoritesViewModel( getFavoritesUseCase, mainCoroutineRule.testDispatcherProvider ).apply { state.observeForever(uiStateObserver) } } @Test fun `should notify uiState with not filled favorite list when get favorite returns empty`() = runTest { // Arrange whenever(getFavoritesUseCase.invoke(any())) .thenReturn( flowOf( emptyList() ) ) // Action favoritesViewModel.getAll() // Assert verify(uiStateObserver).onChanged( isA<FavoritesViewModel.UiState.ShowEmpty>() ) } @Test fun `should notify uiState with filled favorite list when get favorite returns`() = runTest { // Arrange whenever(getFavoritesUseCase.invoke(any())) .thenReturn(flowOf(characters)) // Action favoritesViewModel.getAll() // Assert TestCase.assertEquals(1, characters.size) } }
appMarvels/app/src/test/java/com/example/appmarvels/presentation/favorites/FavoritesViewModelTest.kt
899132318
package com.example.appmarvels.presentation.detail import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.lifecycle.Observer import com.example.appmarvels.MainCoroutineRule import com.example.appmarvels.framework.useCase.AddFavoritesUseCase import com.example.appmarvels.framework.useCase.CheckFavoriteUseCase import com.example.appmarvels.framework.useCase.GetCharacterCategoriesUseCase import com.example.appmarvels.framework.useCase.RemoveFavoritesUseCase import com.example.appmarvels.framework.useCase.base.ResultStatus import com.example.appmarvels.model.CharacterFactory import com.example.appmarvels.model.ComicFactory import com.example.appmarvels.model.EventFactory import com.example.appmarvels.R import com.example.appmarvels.framework.model.Comic import com.nhaarman.mockitokotlin2.any import com.nhaarman.mockitokotlin2.isA import com.nhaarman.mockitokotlin2.verify import com.nhaarman.mockitokotlin2.whenever import junit.framework.Assert import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.test.runTest import org.junit.Assert.* import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.junit.MockitoJUnitRunner @ExperimentalCoroutinesApi @RunWith(MockitoJUnitRunner::class) class DetailViewModelTest{ @get:Rule var instantExecutorRule = InstantTaskExecutorRule() @get:Rule var mainCoroutineRule = MainCoroutineRule() @Mock private lateinit var getCharacterCategoriesUseCase: GetCharacterCategoriesUseCase @Mock private lateinit var addFavoritesUseCase: AddFavoritesUseCase @Mock private lateinit var checkFavoriteUseCase: CheckFavoriteUseCase @Mock private lateinit var removeFavoritesUseCase: RemoveFavoritesUseCase @Mock private lateinit var uiStateObserver: Observer<UiActionStateLiveData.UiState> @Mock private lateinit var favoriteUiStateObserver: Observer<FavoriteUiActionStateLiveData.UiState> private val character = CharacterFactory().create(CharacterFactory.Hero.ThreeDMan) private val comics = listOf(ComicFactory().create(ComicFactory.FakeComic.FakeComic1)) private val events = listOf(EventFactory().create(EventFactory.FakeEvent.FakeEvent1)) private lateinit var detailViewModel: DetailViewModel @Before fun setup() { detailViewModel = DetailViewModel( getCharacterCategoriesUseCase, checkFavoriteUseCase, addFavoritesUseCase, removeFavoritesUseCase, mainCoroutineRule.testDispatcherProvider ).apply { categories.state.observeForever(uiStateObserver) favorite.state.observeForever(favoriteUiStateObserver) } } @Test fun `should notify uiState with Success from UiState when get character categories returns success`() = runTest { // Arrange whenever(getCharacterCategoriesUseCase.invoke(any())) .thenReturn( flowOf( ResultStatus.Success( comics to events ) ) ) // Act detailViewModel.categories.load(character.id) //Assert verify(uiStateObserver).onChanged(isA<UiActionStateLiveData.UiState.Success>()) val uiStateSuccess = detailViewModel.categories.state.value as UiActionStateLiveData.UiState.Success val categoriesParentList = uiStateSuccess.detailParentList Assert.assertEquals(2, categoriesParentList.size) assertEquals( R.string.details_comics_category, categoriesParentList[0].categoryStringResId ) assertEquals( R.string.details_events_category, categoriesParentList[1].categoryStringResId ) } @Test fun `should notify uiState with Success from UiState when get character categories returns only comics`() = runTest { // Arrange whenever(getCharacterCategoriesUseCase.invoke(any())) .thenReturn( flowOf( ResultStatus.Success( comics to emptyList() ) ) ) // Act detailViewModel.categories.load(character.id) //Assert verify(uiStateObserver).onChanged(isA<UiActionStateLiveData.UiState.Success>()) val uiStateSuccess = detailViewModel.categories.state.value as UiActionStateLiveData.UiState.Success val categoriesParentList = uiStateSuccess.detailParentList Assert.assertEquals(1, categoriesParentList.size) assertEquals( R.string.details_comics_category, categoriesParentList[0].categoryStringResId ) } @Test fun `should notify uiState with Success from UiState when get character categories returns only events`() = runTest { // Arrange whenever(getCharacterCategoriesUseCase.invoke(any())) .thenReturn( flowOf( ResultStatus.Success( emptyList<Comic>() to events ) ) ) // Act detailViewModel.categories.load(character.id) //Assert verify(uiStateObserver).onChanged(isA<UiActionStateLiveData.UiState.Success>()) val uiStateSuccess = detailViewModel.categories.state.value as UiActionStateLiveData.UiState.Success val categoriesParentList = uiStateSuccess.detailParentList Assert.assertEquals(1, categoriesParentList.size) assertEquals( R.string.details_events_category, categoriesParentList[0].categoryStringResId ) } @Test fun `should notify uiState with Empty from UiState when get character categories returns an empty result list`() = runTest { // Arrange whenever(getCharacterCategoriesUseCase.invoke(any())) .thenReturn( flowOf( ResultStatus.Success( emptyList<Comic>() to emptyList() ) ) ) // Act detailViewModel.categories.load(character.id) //Assert verify(uiStateObserver).onChanged(isA<UiActionStateLiveData.UiState.Empty>()) } @Test fun `should notify uiState with Error from UiState when get character categories returns an exception`() = runTest { // Arrange whenever(getCharacterCategoriesUseCase.invoke(any())) .thenReturn( flowOf( ResultStatus.Error( throwable = Throwable() ) ) ) // Act detailViewModel.categories.load(character.id) //Assert verify(uiStateObserver).onChanged(isA<UiActionStateLiveData.UiState.Error>()) } @Test fun `should notify favorite_uiState with filled favorite icon when check favorite returns true`() = runTest { // Arrange whenever(checkFavoriteUseCase.invoke(any())) .thenReturn( flowOf( ResultStatus.Success(true) ) ) // Action detailViewModel.favorite.checkFavorite(character.id) // Assert verify(favoriteUiStateObserver).onChanged( isA<FavoriteUiActionStateLiveData.UiState.Icon>() ) val uiState = detailViewModel.favorite.state.value as FavoriteUiActionStateLiveData.UiState.Icon assertEquals(R.drawable.ic_favorite_checked, uiState.icon) } @Test fun `should notify favorite_uiState with not filled favorite icon when check favorite returns false`() = runTest { // Arrange whenever(checkFavoriteUseCase.invoke(any())) .thenReturn( flowOf( ResultStatus.Success(false) ) ) // Action detailViewModel.favorite.checkFavorite(character.id) // Assert verify(favoriteUiStateObserver).onChanged( isA<FavoriteUiActionStateLiveData.UiState.Icon>() ) val uiState = detailViewModel.favorite.state.value as FavoriteUiActionStateLiveData.UiState.Icon assertEquals(R.drawable.ic_favorite_unchecked, uiState.icon) } @Test fun `should notify favorite_uiState with filled favorite icon when current icon is unchecked`() = runTest { // Arrange whenever(addFavoritesUseCase.invoke(any())) .thenReturn( flowOf( ResultStatus.Success(Unit) ) ) // Act detailViewModel.run { favorite.currentFavoriteIcon = R.drawable.ic_favorite_unchecked favorite.update( DetailViewArg(character.id, character.name, character.imageUrl) ) } // Assert verify(favoriteUiStateObserver).onChanged(isA<FavoriteUiActionStateLiveData.UiState.Icon>()) val uiState = detailViewModel.favorite.state.value as FavoriteUiActionStateLiveData.UiState.Icon assertEquals(R.drawable.ic_favorite_checked, uiState.icon) } @Test fun `should call remove and notify favorite_uiState with filled favorite icon when current icon is checked`() = runTest { // Arrange whenever(removeFavoritesUseCase.invoke(any())) .thenReturn( flowOf( ResultStatus.Success(Unit) ) ) // Act detailViewModel.run { favorite.currentFavoriteIcon = R.drawable.ic_favorite_checked favorite.update( DetailViewArg(character.id, character.name, character.imageUrl) ) } // Assert verify(favoriteUiStateObserver).onChanged(isA<FavoriteUiActionStateLiveData.UiState.Icon>()) val uiState = detailViewModel.favorite.state.value as FavoriteUiActionStateLiveData.UiState.Icon assertEquals(R.drawable.ic_favorite_unchecked, uiState.icon) } }
appMarvels/app/src/test/java/com/example/appmarvels/presentation/detail/DetailViewModelTest.kt
360939110
package com.example.appmarvels.presentation.characters import androidx.paging.PagingData import com.example.appmarvels.MainCoroutineRule import com.example.appmarvels.framework.useCase.GetCharactersUseCase import com.example.appmarvels.model.CharacterFactory import com.nhaarman.mockitokotlin2.any import com.nhaarman.mockitokotlin2.whenever import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.test.runTest import org.junit.Assert.* import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.junit.MockitoJUnitRunner @ExperimentalCoroutinesApi @RunWith(MockitoJUnitRunner::class) class CharactersViewModelTest { @get:Rule var mainCoroutineRule = MainCoroutineRule() @Mock lateinit var getCharactersUseCase: GetCharactersUseCase private lateinit var charactersViewModel: CharactersViewModel private val charactersFactory = CharacterFactory() private val pagingDataCharacters = PagingData.from( listOf( charactersFactory.create(CharacterFactory.Hero.ThreeDMan), charactersFactory.create(CharacterFactory.Hero.ABomb) ) ) @Before fun setUp() { charactersViewModel = CharactersViewModel(getCharactersUseCase) } @Test fun `should validate the paging data object values when calling charactersPagingData`() = runTest { whenever(getCharactersUseCase.invoke(any())).thenReturn( flowOf(pagingDataCharacters) ) val result = charactersViewModel.charactersPagingData("") assertNotNull(result.first()) } @Test(expected = RuntimeException::class) fun `should throw an exception when the calling to the use case returns an exception`() { runTest { whenever(getCharactersUseCase.invoke(any())).thenThrow(RuntimeException()) charactersViewModel.charactersPagingData("") } } }
appMarvels/app/src/test/java/com/example/appmarvels/presentation/characters/CharactersViewModelTest.kt
273196306
package com.example.appmarvels.util import android.view.View import com.example.appmarvels.framework.model.Character typealias OnCharacterItemClick = (character: Character, view: View) -> Unit
appMarvels/app/src/main/java/com/example/appmarvels/util/Alias.kt
2302402871
package com.example.appmarvels.framework.repository import com.example.appmarvels.framework.model.Character import kotlinx.coroutines.flow.Flow interface FavoritesLocalDataSource { fun getAll(): Flow<List<Character>> suspend fun isFavorite(characterId: Int): Boolean suspend fun save(character: Character) suspend fun delete(character: Character) }
appMarvels/app/src/main/java/com/example/appmarvels/framework/repository/FavoritesLocalDataSource.kt
1360994509
package com.example.appmarvels.framework.repository import com.example.appmarvels.framework.model.Character import kotlinx.coroutines.flow.Flow interface FavoritesRepository { fun getAll(): Flow<List<Character>> suspend fun isFavorite(characterId: Int): Boolean suspend fun saveFavorite(character: Character) suspend fun deleteFavorite(character: Character) }
appMarvels/app/src/main/java/com/example/appmarvels/framework/repository/FavoritesRepository.kt
232612079
package com.example.appmarvels.framework.repository import androidx.paging.PagingSource import com.example.appmarvels.framework.model.Character import com.example.appmarvels.framework.model.Comic import com.example.appmarvels.framework.model.Event interface CharacterRepository { fun getCharacters(query: String): PagingSource<Int, Character> suspend fun getComics(characterId: Int): List<Comic> suspend fun getEvents(characterId: Int): List<Event> }
appMarvels/app/src/main/java/com/example/appmarvels/framework/repository/CharacterRepository.kt
2463708350
package com.example.appmarvels.framework.repository import com.example.appmarvels.framework.model.CharacterPaging import com.example.appmarvels.framework.model.Comic import com.example.appmarvels.framework.model.Event interface CharactersRemoteDataSource { suspend fun fetchCharacters(queries: Map<String, String>): CharacterPaging suspend fun fetchComics(characterId: Int): List<Comic> suspend fun fetchEvents(characterId: Int): List<Event> }
appMarvels/app/src/main/java/com/example/appmarvels/framework/repository/CharactersRemoteDataSource.kt
3499039934
package com.example.appmarvels.framework.di import com.example.appmarvels.framework.imageLoader.GlideImageLoader import com.example.appmarvels.framework.imageLoader.ImageLoader import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.android.components.FragmentComponent @Module @InstallIn(FragmentComponent::class) interface AppModule { @Binds fun bindImageLoader(imageLoader: GlideImageLoader): ImageLoader }
appMarvels/app/src/main/java/com/example/appmarvels/framework/di/AppModule.kt
1045176093
package com.example.appmarvels.framework.di.qualifer import javax.inject.Qualifier @Qualifier @Retention(AnnotationRetention.BINARY) annotation class BaseUrl
appMarvels/app/src/main/java/com/example/appmarvels/framework/di/qualifer/BaseUrl.kt
4219028488
package com.example.appmarvels.framework.di import com.example.appmarvels.BuildConfig import com.example.appmarvels.framework.di.qualifer.BaseUrl import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent @Module @InstallIn(SingletonComponent::class) object BaseUrlModule { @BaseUrl @Provides fun provideBaseUrl(): String = BuildConfig.BASE_URL }
appMarvels/app/src/main/java/com/example/appmarvels/framework/di/BaseUrlModule.kt
2733276308
package com.example.appmarvels.framework.di import com.example.appmarvels.framework.useCase.base.AppCoroutinesDispatchers import com.example.appmarvels.framework.useCase.base.CoroutinesDispatchers import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent @Module @InstallIn(SingletonComponent::class) interface CoroutinesModule { @Binds fun bindDispatchers(dispatchers: AppCoroutinesDispatchers): CoroutinesDispatchers }
appMarvels/app/src/main/java/com/example/appmarvels/framework/di/CoroutinesModule.kt
3233781333
package com.example.appmarvels.framework.di import com.example.appmarvels.framework.di.qualifer.BaseUrl import com.example.appmarvels.framework.network.MarvelApi import com.example.appmarvels.framework.network.interceptor.AuthorizationInterceptor import com.example.appmarvels.BuildConfig import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.util.Calendar import java.util.TimeZone import java.util.concurrent.TimeUnit @Module @InstallIn(SingletonComponent::class) object NetworkModule { private const val TIMEOUT_SECONDS = 15L @Provides fun provideLoggingInterceptor(): HttpLoggingInterceptor { return HttpLoggingInterceptor().apply { setLevel( if (BuildConfig.DEBUG) { HttpLoggingInterceptor.Level.BODY } else HttpLoggingInterceptor.Level.NONE ) } } @Provides fun provideAuthorizationInterceptor(): AuthorizationInterceptor { return AuthorizationInterceptor( publicKey = BuildConfig.PUBLIC_KEY, privateKey = BuildConfig.PRIVATE_KEY, calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")) ) } @Provides fun provideOkHttpClient( loggingInterceptor: HttpLoggingInterceptor, authorizationInterceptor: AuthorizationInterceptor ): OkHttpClient { return OkHttpClient.Builder() .addInterceptor(loggingInterceptor) .addInterceptor(authorizationInterceptor) .readTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) .connectTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) .build() } @Provides fun provideGsonConverterFactory(): GsonConverterFactory { return GsonConverterFactory.create() } @Provides fun provideRetrofit( okHttpClient: OkHttpClient, converterFactory: GsonConverterFactory, @BaseUrl baseUrl: String ): MarvelApi { return Retrofit.Builder() .baseUrl(baseUrl) .client(okHttpClient) .addConverterFactory(converterFactory) .build() .create(MarvelApi::class.java) } }
appMarvels/app/src/main/java/com/example/appmarvels/framework/di/NetworkModule.kt
3501040871
package com.example.appmarvels.framework.di import com.example.appmarvels.framework.CharactersRepositoryImpl import com.example.appmarvels.framework.remote.RetrofitCharactersDataSource import com.example.appmarvels.framework.repository.CharacterRepository import com.example.appmarvels.framework.repository.CharactersRemoteDataSource import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent @Module @InstallIn(SingletonComponent::class) interface RepositoryModule { @Binds fun bindCharacterRepository(repository: CharactersRepositoryImpl): CharacterRepository @Binds fun bindRemoteDataSource( dataSource: RetrofitCharactersDataSource ): CharactersRemoteDataSource }
appMarvels/app/src/main/java/com/example/appmarvels/framework/di/RepositoryModule.kt
1522364656
package com.example.appmarvels.framework.di import com.example.appmarvels.framework.useCase.AddFavoritesUseCase import com.example.appmarvels.framework.useCase.AddFavoritesUseCaseImpl import com.example.appmarvels.framework.useCase.CheckFavoriteUseCase import com.example.appmarvels.framework.useCase.CheckFavoriteUseCaseImpl import com.example.appmarvels.framework.useCase.GetCharacterCategoriesUseCase import com.example.appmarvels.framework.useCase.GetCharacterCategoriesUseCaseImpl import com.example.appmarvels.framework.useCase.GetCharactersUseCase import com.example.appmarvels.framework.useCase.GetCharactersUseCaseImpl import com.example.appmarvels.framework.useCase.GetFavoritesUseCase import com.example.appmarvels.framework.useCase.GetFavoritesUseCaseImpl import com.example.appmarvels.framework.useCase.RemoveFavoritesUseCase import com.example.appmarvels.framework.useCase.RemoveFavoritesUseCaseImpl import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.android.components.ViewModelComponent @Module @InstallIn(ViewModelComponent::class) interface UseCaseModule { @Binds fun bindGetCharacterUseCase( useCase: GetCharactersUseCaseImpl) : GetCharactersUseCase @Binds fun bindGetComicUseCase( useCase: GetCharacterCategoriesUseCaseImpl ) : GetCharacterCategoriesUseCase @Binds fun bindCheckFavoriteUseCase(useCase: CheckFavoriteUseCaseImpl): CheckFavoriteUseCase @Binds fun bindAddFavoriteUseCase(useCase: AddFavoritesUseCaseImpl): AddFavoritesUseCase @Binds fun bindRemoveFavoriteUseCase(useCase: RemoveFavoritesUseCaseImpl): RemoveFavoritesUseCase @Binds fun bindGetFavoritesUseCase(useCase: GetFavoritesUseCaseImpl): GetFavoritesUseCase }
appMarvels/app/src/main/java/com/example/appmarvels/framework/di/UseCaseModule.kt
3356749802
package com.example.appmarvels.framework.di import android.content.Context import androidx.room.Room import com.example.appmarvels.framework.db.AppDatabase import com.example.appmarvels.framework.db.DbConstants import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent @Module @InstallIn(SingletonComponent::class) object DatabaseModule { @Provides fun provideAppDatabase( @ApplicationContext context: Context ): AppDatabase = Room.databaseBuilder( context, AppDatabase::class.java, DbConstants.APP_DATABASE_NAME ).build() @Provides fun provideFavoriteDao(appDatabase: AppDatabase) = appDatabase.favoriteDao() }
appMarvels/app/src/main/java/com/example/appmarvels/framework/di/DatabaseModule.kt
4096960560
package com.example.appmarvels.framework.di import com.example.appmarvels.framework.FavoritesRepositoryImpl import com.example.appmarvels.framework.local.RoomFavoritesDataSource import com.example.appmarvels.framework.repository.FavoritesLocalDataSource import com.example.appmarvels.framework.repository.FavoritesRepository import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent @Module @InstallIn(SingletonComponent::class) interface FavoritesRepositoryModule { @Binds fun bindFavoritesRepository(repository: FavoritesRepositoryImpl): FavoritesRepository @Binds fun bindLocalDataSource( dataSource: RoomFavoritesDataSource ): FavoritesLocalDataSource }
appMarvels/app/src/main/java/com/example/appmarvels/framework/di/FavoritesRepositoryModule.kt
1954402036
package com.example.appmarvels.framework import androidx.paging.PagingSource import com.example.appmarvels.framework.model.Comic import com.example.appmarvels.framework.model.Event import com.example.appmarvels.framework.paging.CharactersPagingSource import com.example.appmarvels.framework.repository.CharacterRepository import com.example.appmarvels.framework.repository.CharactersRemoteDataSource import com.example.appmarvels.framework.model.Character import javax.inject.Inject class CharactersRepositoryImpl @Inject constructor ( private val remoteDataSource: CharactersRemoteDataSource ) : CharacterRepository { override fun getCharacters(query: String): PagingSource<Int, Character> { return CharactersPagingSource(remoteDataSource, query) } override suspend fun getComics(characterId: Int): List<Comic> { return remoteDataSource.fetchComics(characterId) } override suspend fun getEvents(characterId: Int): List<Event> { return remoteDataSource.fetchEvents(characterId) } }
appMarvels/app/src/main/java/com/example/appmarvels/framework/CharactersRepositoryImpl.kt
512992026
package com.example.appmarvels.framework.network.response import com.google.gson.annotations.SerializedName data class DataContainerResponse<T>( @SerializedName("offset") val offset: Int, @SerializedName("total") val total: Int, @SerializedName("results") val results : List<T> )
appMarvels/app/src/main/java/com/example/appmarvels/framework/network/response/DataContainerResponse.kt
2095832154
package com.example.appmarvels.framework.network.response import com.example.appmarvels.framework.model.Character import com.google.gson.annotations.SerializedName data class CharacterResponse( @SerializedName("id") val id: Int, @SerializedName("name") val name: String, @SerializedName("thumbnail") val thumbnail: ThumbnailResponse ) fun CharacterResponse.toCharacterModel(): Character{ return Character ( id = this.id, name = this.name, imageUrl = this.thumbnail.getHttpsUrl() ) }
appMarvels/app/src/main/java/com/example/appmarvels/framework/network/response/CharacterResponse.kt
3046936606
package com.example.appmarvels.framework.network.response import com.example.appmarvels.framework.model.Comic import com.google.gson.annotations.SerializedName data class ComicsResponse( @SerializedName("id") val id: Int, @SerializedName("thumbnail") val thumbnail: ThumbnailResponse ) fun ComicsResponse.toComicModel(): Comic { return Comic ( id = this.id, imageUrl = this.thumbnail.getHttpsUrl() ) }
appMarvels/app/src/main/java/com/example/appmarvels/framework/network/response/ComicsResponse.kt
3318254649
package com.example.appmarvels.framework.network.response import com.google.gson.annotations.SerializedName data class DataWrapperResponse<T>( @SerializedName("copyright") val copyright: String, @SerializedName("data") val data: DataContainerResponse<T> )
appMarvels/app/src/main/java/com/example/appmarvels/framework/network/response/DataWrapperResponse.kt
1946150751
package com.example.appmarvels.framework.network.response import com.google.gson.annotations.SerializedName data class ThumbnailResponse( @SerializedName("path") val path: String, @SerializedName("extension") val extension: String ) fun ThumbnailResponse.getHttpsUrl () = "$path.$extension".replace("http", "https")
appMarvels/app/src/main/java/com/example/appmarvels/framework/network/response/ThumbnailResponse.kt
3105985103
package com.example.appmarvels.framework.network.response import com.example.appmarvels.framework.model.Event import com.google.gson.annotations.SerializedName data class EventResponse( @SerializedName("id") val id: Int, @SerializedName("thumbnail") val thumbnail: ThumbnailResponse ) fun EventResponse.toEventModel() : Event { return Event ( id = this.id, imageUrl = this.thumbnail.getHttpsUrl() ) }
appMarvels/app/src/main/java/com/example/appmarvels/framework/network/response/EventResponse.kt
136758453
package com.example.appmarvels.framework.network.interceptor import okhttp3.Interceptor import okhttp3.Response import java.math.BigInteger import java.security.MessageDigest import java.util.* class AuthorizationInterceptor( private val publicKey: String, private val privateKey: String, private val calendar: Calendar, ) : Interceptor { @Suppress("MagicNumber") override fun intercept(chain: Interceptor.Chain): Response { val request = chain.request() val requestUrl = request.url val ts = (calendar.timeInMillis / 1000L).toString() // TIME IN SECONDS val hash = "$ts$privateKey$publicKey".md5() val newUrl = requestUrl.newBuilder() .addQueryParameter(QUERY_PARAMETER_TS, ts) .addQueryParameter(QUERY_PARAMETER_API_KEY, publicKey) .addQueryParameter(QUERY_PARAMETER_HASH, hash) .build() return chain.proceed( request.newBuilder() .url(newUrl) .build() ) } @Suppress("MagicNumber") private fun String.md5(): String { val md = MessageDigest.getInstance("MD5") return BigInteger(1, md.digest(toByteArray())).toString(16).padStart(32, '0') } companion object { private const val QUERY_PARAMETER_TS = "ts" private const val QUERY_PARAMETER_API_KEY = "apikey" private const val QUERY_PARAMETER_HASH = "hash" } }
appMarvels/app/src/main/java/com/example/appmarvels/framework/network/interceptor/AuthorizationInterceptor.kt
932675246
package com.example.appmarvels.framework.network import com.example.appmarvels.framework.network.response.CharacterResponse import com.example.appmarvels.framework.network.response.ComicsResponse import com.example.appmarvels.framework.network.response.DataWrapperResponse import com.example.appmarvels.framework.network.response.EventResponse import retrofit2.http.GET import retrofit2.http.Path import retrofit2.http.QueryMap interface MarvelApi { @GET("characters") suspend fun getCharacters( @QueryMap queries: Map<String, String> ): DataWrapperResponse<CharacterResponse> @GET("characters/{characterId}/comics") suspend fun getComics( @Path("characterId") characterId: Int ): DataWrapperResponse<ComicsResponse> @GET("characters/{characterId}/events") suspend fun getEvents( @Path("characterId") characterId: Int ): DataWrapperResponse<EventResponse> }
appMarvels/app/src/main/java/com/example/appmarvels/framework/network/MarvelApi.kt
332108334
package com.example.appmarvels.framework import com.example.appmarvels.framework.repository.FavoritesLocalDataSource import com.example.appmarvels.framework.repository.FavoritesRepository import com.example.appmarvels.framework.model.Character import kotlinx.coroutines.flow.Flow import javax.inject.Inject class FavoritesRepositoryImpl @Inject constructor ( private val favoritesLocalDataSource: FavoritesLocalDataSource ) : FavoritesRepository { override fun getAll(): Flow<List<Character>> { return favoritesLocalDataSource.getAll() } override suspend fun isFavorite(characterId: Int): Boolean { return favoritesLocalDataSource.isFavorite(characterId) } override suspend fun saveFavorite(character: Character) { favoritesLocalDataSource.save(character) } override suspend fun deleteFavorite(character: Character) { favoritesLocalDataSource.delete(character) } }
appMarvels/app/src/main/java/com/example/appmarvels/framework/FavoritesRepositoryImpl.kt
1841067089
package com.example.appmarvels.framework.local import com.example.appmarvels.framework.db.dao.FavoriteDao import com.example.appmarvels.framework.db.entity.FavoriteEntity import com.example.appmarvels.framework.db.entity.toCharactersModel import com.example.appmarvels.framework.model.Character import com.example.appmarvels.framework.repository.FavoritesLocalDataSource import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import javax.inject.Inject class RoomFavoritesDataSource @Inject constructor( private val favoriteDao: FavoriteDao ) : FavoritesLocalDataSource { override fun getAll(): Flow<List<Character>> { return favoriteDao.loadFavorites().map { it.toCharactersModel() } } override suspend fun isFavorite(characterId: Int): Boolean { return favoriteDao.hasFavorite(characterId) != null } override suspend fun save(character: Character) { favoriteDao.insertFavorite(character.toFavoriteEntity()) } override suspend fun delete(character: Character) { favoriteDao.deleteFavorite(character.toFavoriteEntity()) } private fun Character.toFavoriteEntity() = FavoriteEntity(id, name, imageUrl) }
appMarvels/app/src/main/java/com/example/appmarvels/framework/local/RoomFavoritesDataSource.kt
648615281
package com.example.appmarvels.framework.paging import androidx.paging.PagingSource import androidx.paging.PagingState import com.example.appmarvels.framework.repository.CharactersRemoteDataSource import com.example.appmarvels.framework.model.Character class CharactersPagingSource( private val remoteDataSource: CharactersRemoteDataSource, private val query: String ) : PagingSource<Int, Character>() { @Suppress("TooGenericExceptionCaught") override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Character> { return try { val offset = params.key ?: 0 val queries = hashMapOf( "offset" to offset.toString() ) if (query.isNotEmpty()){ queries["nameStartsWith"] = query } val characterPaging = remoteDataSource.fetchCharacters(queries) val responseOffset = characterPaging.offset val totalCharacters = characterPaging.total LoadResult.Page( data = characterPaging.characters, prevKey = null, nextKey = if (responseOffset < totalCharacters) { responseOffset + LIMIT } else null ) } catch (exception: Exception) { LoadResult.Error(exception) } } override fun getRefreshKey(state: PagingState<Int, Character>): Int? { return state.anchorPosition?.let { anchorPosition -> val anchorPage = state.closestPageToPosition(anchorPosition) anchorPage?.prevKey?.plus(LIMIT) ?: anchorPage?.nextKey?.minus(LIMIT) } } companion object { private const val LIMIT = 20 } }
appMarvels/app/src/main/java/com/example/appmarvels/framework/paging/CharactersPagingSource.kt
1276639709
package com.example.appmarvels.framework.imageLoader import android.widget.ImageView import com.bumptech.glide.Glide import javax.inject.Inject class GlideImageLoader @Inject constructor() : ImageLoader { override fun load( imageView: ImageView, imageUrl: String, placeholder: Int, fallback: Int) { Glide.with(imageView.rootView) .load(imageUrl) .placeholder(placeholder) .fallback(fallback) .into(imageView) } }
appMarvels/app/src/main/java/com/example/appmarvels/framework/imageLoader/GlideImageLoader.kt
13106529
package com.example.appmarvels.framework.imageLoader import android.widget.ImageView import androidx.annotation.DrawableRes import com.example.appmarvels.R interface ImageLoader { fun load( imageView: ImageView, imageUrl: String, @DrawableRes placeholder: Int = R.drawable.ic_img_placeholder, @DrawableRes fallback: Int = R.drawable.ic_img_loading_error) }
appMarvels/app/src/main/java/com/example/appmarvels/framework/imageLoader/ImageLoader.kt
870411293
package com.example.appmarvels.framework.model data class Character( val id: Int, val name: String, val imageUrl: String )
appMarvels/app/src/main/java/com/example/appmarvels/framework/model/Character.kt
3769340468
package com.example.appmarvels.framework.model data class Comic( val id: Int, val imageUrl: String )
appMarvels/app/src/main/java/com/example/appmarvels/framework/model/Comic.kt
2085103308
package com.example.appmarvels.framework.model data class Event( val id: Int, val imageUrl: String )
appMarvels/app/src/main/java/com/example/appmarvels/framework/model/Event.kt
136773794
package com.example.appmarvels.framework.model data class CharacterPaging( val offset: Int, val total: Int, val characters: List<Character> )
appMarvels/app/src/main/java/com/example/appmarvels/framework/model/CharacterPaging.kt
2280388904
package com.example.appmarvels.framework.db.entity import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import com.example.appmarvels.framework.db.DbConstants import com.example.appmarvels.framework.model.Character @Entity(tableName = DbConstants.FAVORITES_TABLE_NAME) data class FavoriteEntity( @PrimaryKey @ColumnInfo(name = DbConstants.FAVORITES_COLUMN_INFO_ID) val id: Int, @ColumnInfo(name = DbConstants.FAVORITES_COLUMN_INFO_NAME) val name: String, @ColumnInfo(name = DbConstants.FAVORITES_COLUMN_INFO_IMAGE_URL) val imageUrl: String ) fun List<FavoriteEntity>.toCharactersModel() = map { Character(it.id, it.name, it.imageUrl) }
appMarvels/app/src/main/java/com/example/appmarvels/framework/db/entity/FavoriteEntity.kt
2866343773
package com.example.appmarvels.framework.db.dao import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import com.example.appmarvels.framework.db.DbConstants import com.example.appmarvels.framework.db.entity.FavoriteEntity import kotlinx.coroutines.flow.Flow @Dao interface FavoriteDao { @Query("SELECT * FROM ${DbConstants.FAVORITES_TABLE_NAME}") fun loadFavorites(): Flow<List<FavoriteEntity>> @Query("SELECT * FROM ${DbConstants.FAVORITES_TABLE_NAME} WHERE id = :characterId") suspend fun hasFavorite(characterId: Int): FavoriteEntity? @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertFavorite(favoriteEntity: FavoriteEntity) @Delete suspend fun deleteFavorite(favoriteEntity: FavoriteEntity) }
appMarvels/app/src/main/java/com/example/appmarvels/framework/db/dao/FavoriteDao.kt
884342645
package com.example.appmarvels.framework.db import androidx.room.Database import androidx.room.RoomDatabase import com.example.appmarvels.framework.db.dao.FavoriteDao import com.example.appmarvels.framework.db.entity.FavoriteEntity @Database(entities = [FavoriteEntity::class], version = 1, exportSchema = false) abstract class AppDatabase : RoomDatabase() { abstract fun favoriteDao(): FavoriteDao }
appMarvels/app/src/main/java/com/example/appmarvels/framework/db/AppDataBase.kt
2471206741
package com.example.appmarvels.framework.db object DbConstants { const val APP_DATABASE_NAME = "app_database" const val FAVORITES_TABLE_NAME = "favorites" const val FAVORITES_COLUMN_INFO_ID = "id" const val FAVORITES_COLUMN_INFO_NAME = "name" const val FAVORITES_COLUMN_INFO_IMAGE_URL = "image_url" }
appMarvels/app/src/main/java/com/example/appmarvels/framework/db/DbConstants.kt
3083792563
package com.example.appmarvels.framework.useCase import androidx.paging.Pager import androidx.paging.PagingConfig import androidx.paging.PagingData import com.example.appmarvels.framework.repository.CharacterRepository import com.example.appmarvels.framework.useCase.base.PagingUseCase import com.example.appmarvels.framework.model.Character import kotlinx.coroutines.flow.Flow import javax.inject.Inject interface GetCharactersUseCase { operator fun invoke(params: GetCharactersParams): Flow<PagingData<Character>> data class GetCharactersParams(val query: String, val pagingConfig: PagingConfig) } class GetCharactersUseCaseImpl @Inject constructor( private val charactersRepository: CharacterRepository ) : PagingUseCase<GetCharactersUseCase.GetCharactersParams, Character>(), GetCharactersUseCase { override fun createFlowObservable(params: GetCharactersUseCase.GetCharactersParams): Flow<PagingData<Character>> { val pagingSource = charactersRepository.getCharacters(params.query) return Pager(config = params.pagingConfig) { pagingSource }.flow } }
appMarvels/app/src/main/java/com/example/appmarvels/framework/useCase/GetCharactersUseCase.kt
3294901410
package com.example.appmarvels.framework.useCase import com.example.appmarvels.framework.repository.FavoritesRepository import com.example.appmarvels.framework.useCase.base.CoroutinesDispatchers import com.example.appmarvels.framework.useCase.base.ResultStatus import com.example.appmarvels.framework.useCase.base.UseCase import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.withContext import javax.inject.Inject interface CheckFavoriteUseCase{ operator fun invoke(params: Params): Flow<ResultStatus<Boolean>> data class Params(val characterId: Int) } class CheckFavoriteUseCaseImpl @Inject constructor( private val favoritesRepository: FavoritesRepository, private val dispatchers: CoroutinesDispatchers ): UseCase<CheckFavoriteUseCase.Params, Boolean>(), CheckFavoriteUseCase { override suspend fun doWork(params: CheckFavoriteUseCase.Params): ResultStatus<Boolean> { return withContext(dispatchers.io()){ val isFavorite = favoritesRepository.isFavorite(params.characterId) ResultStatus.Success(isFavorite) } } }
appMarvels/app/src/main/java/com/example/appmarvels/framework/useCase/CheckFavoriteUseCase.kt
2241304193
package com.example.appmarvels.framework.useCase import com.example.appmarvels.framework.model.Comic import com.example.appmarvels.framework.model.Event import com.example.appmarvels.framework.repository.CharacterRepository import com.example.appmarvels.framework.useCase.base.CoroutinesDispatchers import com.example.appmarvels.framework.useCase.base.ResultStatus import com.example.appmarvels.framework.useCase.base.UseCase import kotlinx.coroutines.async import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.withContext import javax.inject.Inject interface GetCharacterCategoriesUseCase { operator fun invoke(params: GetCategoriesParams): Flow<ResultStatus<Pair<List<Comic>, List<Event>>>> data class GetCategoriesParams(val characterId: Int) } class GetCharacterCategoriesUseCaseImpl @Inject constructor( private val repository: CharacterRepository, private val dispatchers: CoroutinesDispatchers ) : GetCharacterCategoriesUseCase, UseCase<GetCharacterCategoriesUseCase.GetCategoriesParams, Pair<List<Comic>, List<Event>>>() { override suspend fun doWork( params: GetCharacterCategoriesUseCase.GetCategoriesParams ): ResultStatus<Pair<List<Comic>, List<Event>>> { return withContext(dispatchers.io()) { val comicsDeferred = async { repository.getComics(params.characterId) } val eventsDeferred = async { repository.getEvents(params.characterId) } val comics = comicsDeferred.await() val events = eventsDeferred.await() ResultStatus.Success(comics to events) } } }
appMarvels/app/src/main/java/com/example/appmarvels/framework/useCase/GetCharacterCategoriesUseCase.kt
2126252542
package com.example.appmarvels.framework.useCase import com.example.appmarvels.framework.repository.FavoritesRepository import com.example.appmarvels.framework.useCase.base.CoroutinesDispatchers import com.example.appmarvels.framework.useCase.base.ResultStatus import com.example.appmarvels.framework.useCase.base.UseCase import com.example.appmarvels.framework.model.Character import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.withContext import javax.inject.Inject interface AddFavoritesUseCase { operator fun invoke(params: Params): Flow<ResultStatus<Unit>> data class Params(val characterId: Int, val name: String, val imageUrl: String) } class AddFavoritesUseCaseImpl @Inject constructor( private val favoritesRepository: FavoritesRepository, private val dispatchers: CoroutinesDispatchers ) : UseCase<AddFavoritesUseCase.Params, Unit>(), AddFavoritesUseCase { override suspend fun doWork(params: AddFavoritesUseCase.Params): ResultStatus<Unit> { return withContext(dispatchers.io()) { favoritesRepository.saveFavorite( Character(params.characterId, params.name, params.imageUrl) ) ResultStatus.Success(Unit) } } }
appMarvels/app/src/main/java/com/example/appmarvels/framework/useCase/AddFavoritesUseCase.kt
1209532999
package com.example.appmarvels.framework.useCase import com.example.appmarvels.framework.repository.FavoritesRepository import com.example.appmarvels.framework.useCase.base.CoroutinesDispatchers import com.example.appmarvels.framework.model.Character import com.example.appmarvels.framework.useCase.base.FlowUseCase import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.withContext import javax.inject.Inject interface GetFavoritesUseCase { suspend operator fun invoke(params: Unit = Unit): Flow<List<Character>> } class GetFavoritesUseCaseImpl @Inject constructor( private val favoritesRepository: FavoritesRepository, private val dispatchers: CoroutinesDispatchers ) : FlowUseCase<Unit, List<Character>>(), GetFavoritesUseCase { override suspend fun createFlowObservable(params: Unit): Flow<List<Character>> { return withContext(dispatchers.io()) { favoritesRepository.getAll() } } }
appMarvels/app/src/main/java/com/example/appmarvels/framework/useCase/GetFavoritesUseCase.kt
3378088880
package com.example.appmarvels.framework.useCase.base import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import javax.inject.Inject interface CoroutinesDispatchers { fun main(): CoroutineDispatcher = Dispatchers.Main fun default(): CoroutineDispatcher = Dispatchers.Default fun io(): CoroutineDispatcher = Dispatchers.IO fun unconfined(): CoroutineDispatcher = Dispatchers.Unconfined } class AppCoroutinesDispatchers @Inject constructor(): CoroutinesDispatchers
appMarvels/app/src/main/java/com/example/appmarvels/framework/useCase/base/AppCoroutinesDispatchers.kt
3121142325
package com.example.appmarvels.framework.useCase.base sealed class ResultStatus <out T> { object Loading : ResultStatus<Nothing>() data class Success<out T>(val data: T) : ResultStatus<T>() data class Error(val throwable: Throwable) : ResultStatus<Nothing>() override fun toString(): String { return when (this) { Loading -> "Loading" is Success<*> -> "Success[data=$data]" is Error -> "Error[throwable=$throwable]" } } }
appMarvels/app/src/main/java/com/example/appmarvels/framework/useCase/base/ResultStatus.kt
1906446635
package com.example.appmarvels.framework.useCase.base import androidx.paging.PagingData import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.flow abstract class UseCase<in P, R> { operator fun invoke(params: P): Flow<ResultStatus<R>> = flow { emit(ResultStatus.Loading) emit(doWork(params)) }.catch { throwable -> emit(ResultStatus.Error(throwable)) } protected abstract suspend fun doWork(params: P): ResultStatus<R> } abstract class PagingUseCase<in P, R : Any> { operator fun invoke(params: P): Flow<PagingData<R>> = createFlowObservable(params) protected abstract fun createFlowObservable(params: P): Flow<PagingData<R>> } abstract class FlowUseCase<in P, R : Any> { suspend operator fun invoke(params: P): Flow<R> = createFlowObservable(params) protected abstract suspend fun createFlowObservable(params: P): Flow<R> }
appMarvels/app/src/main/java/com/example/appmarvels/framework/useCase/base/UseCase.kt
4194463499
package com.example.appmarvels.framework.useCase import com.example.appmarvels.framework.repository.FavoritesRepository import com.example.appmarvels.framework.useCase.base.CoroutinesDispatchers import com.example.appmarvels.framework.useCase.base.ResultStatus import com.example.appmarvels.framework.useCase.base.UseCase import com.example.appmarvels.framework.model.Character import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.withContext import javax.inject.Inject interface RemoveFavoritesUseCase { operator fun invoke(params: Params): Flow<ResultStatus<Unit>> data class Params(val characterId: Int, val name: String, val imageUrl: String) } class RemoveFavoritesUseCaseImpl @Inject constructor( private val favoritesRepository: FavoritesRepository, private val dispatchers: CoroutinesDispatchers ) : UseCase<RemoveFavoritesUseCase.Params, Unit>(), RemoveFavoritesUseCase { override suspend fun doWork(params: RemoveFavoritesUseCase.Params): ResultStatus<Unit> { return withContext(dispatchers.io()) { favoritesRepository.deleteFavorite( Character(params.characterId, params.name, params.imageUrl) ) ResultStatus.Success(Unit) } } }
appMarvels/app/src/main/java/com/example/appmarvels/framework/useCase/RemoveFavoritesUseCase.kt
2105546625
package com.example.appmarvels.framework.remote import com.example.appmarvels.framework.model.CharacterPaging import com.example.appmarvels.framework.model.Comic import com.example.appmarvels.framework.model.Event import com.example.appmarvels.framework.network.MarvelApi import com.example.appmarvels.framework.network.response.toCharacterModel import com.example.appmarvels.framework.network.response.toComicModel import com.example.appmarvels.framework.network.response.toEventModel import com.example.appmarvels.framework.repository.CharactersRemoteDataSource import javax.inject.Inject class RetrofitCharactersDataSource @Inject constructor( private val marvelApi: MarvelApi ) : CharactersRemoteDataSource { override suspend fun fetchCharacters(queries: Map<String, String>): CharacterPaging { val data = marvelApi.getCharacters(queries).data val characters = data.results.map { it.toCharacterModel() } return CharacterPaging( data.offset, data.total, characters ) } override suspend fun fetchComics(characterId: Int): List<Comic> { return marvelApi.getComics(characterId).data.results.map { it.toComicModel() } } override suspend fun fetchEvents(characterId: Int): List<Event> { return marvelApi.getEvents(characterId).data.results.map { it.toEventModel() } } }
appMarvels/app/src/main/java/com/example/appmarvels/framework/remote/RetrofitCharactersDataSource.kt
2944042170
package com.example.appmarvels import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class MarvelApp : Application()
appMarvels/app/src/main/java/com/example/appmarvels/MarvelApp.kt
2324944700
package com.example.appmarvels.presentation import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.navigation.NavController import androidx.navigation.fragment.NavHostFragment import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.setupWithNavController import com.example.appmarvels.R import com.example.appmarvels.databinding.ActivityMainBinding import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : AppCompatActivity() { private lateinit var navController: NavController private lateinit var appBarConfiguration: AppBarConfiguration override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_container) as NavHostFragment navController = navHostFragment.navController binding.bottomNavMain.setupWithNavController(navController) appBarConfiguration = AppBarConfiguration( setOf(R.id.charactersFragment, R.id.favoritesFragment, R.id.aboutFragment) ) binding.toolbarApp.setupWithNavController(navController, appBarConfiguration) navController.addOnDestinationChangedListener {_, destination, _ -> val isTopLevelDestination = appBarConfiguration.topLevelDestinations.contains(destination.id) if (!isTopLevelDestination){ binding.toolbarApp.setNavigationIcon(R.drawable.ic_back) } } } }
appMarvels/app/src/main/java/com/example/appmarvels/presentation/MainActivity.kt
1120337602
package com.example.appmarvels.presentation.extension import android.widget.Toast import androidx.annotation.StringRes import androidx.fragment.app.Fragment fun Fragment.showShortToast(@StringRes textResId: Int) = Toast.makeText(requireContext(), textResId, Toast.LENGTH_SHORT).show()
appMarvels/app/src/main/java/com/example/appmarvels/presentation/extension/FragmentExtension.kt
1995285100
package com.example.appmarvels.presentation.extension import com.example.appmarvels.framework.useCase.base.ResultStatus import kotlinx.coroutines.flow.Flow suspend fun<T> Flow<ResultStatus<T>>.watchStatus( loading: suspend () -> Unit = {}, success: suspend (data: T) -> Unit, error: suspend (throwable: Throwable) -> Unit ) { collect{ status -> when(status) { ResultStatus.Loading -> loading.invoke() is ResultStatus.Success -> success.invoke(status.data) is ResultStatus.Error -> error.invoke(status.throwable) } } }
appMarvels/app/src/main/java/com/example/appmarvels/presentation/extension/FlowExtension.kt
1136513723
package com.example.appmarvels.presentation.favorites import com.example.appmarvels.presentation.common.ListItem data class FavoriteItem( val id: Int, val name: String, val imageUrl: String, override val key: Long = id.toLong() ): ListItem
appMarvels/app/src/main/java/com/example/appmarvels/presentation/favorites/FavoriteItem.kt
3688620153
package com.example.appmarvels.presentation.favorites import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import com.example.appmarvels.databinding.FragmentFavoritesBinding import com.example.appmarvels.framework.imageLoader.ImageLoader import com.example.appmarvels.presentation.common.getGenericAdapterOf import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject @AndroidEntryPoint class FavoritesFragment : Fragment() { private var _binding: FragmentFavoritesBinding? = null private val binding: FragmentFavoritesBinding get() = _binding!! private val viewModel: FavoritesViewModel by viewModels() @Inject lateinit var imageLoader: ImageLoader private val favoritesAdapter by lazy { getGenericAdapterOf { FavoritesViewHolder.create(it, imageLoader) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ) = FragmentFavoritesBinding.inflate( inflater, container, false ).apply { _binding = this }.root override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initFavoritesAdapter() viewModel.state.observe(viewLifecycleOwner) { uiState -> binding.flipperFavorites.displayedChild = when (uiState) { is FavoritesViewModel.UiState.ShowFavorites -> { favoritesAdapter.submitList(uiState.favorites.sortedBy { it.name }) FLIPPER_CHILD_CHARACTERS } FavoritesViewModel.UiState.ShowEmpty -> { favoritesAdapter.submitList(emptyList()) FLIPPER_CHILD_EMPTY } } } viewModel.getAll() } private fun initFavoritesAdapter() { binding.recyclerFavorites.run { setHasFixedSize(true) adapter = favoritesAdapter } } override fun onDestroyView() { _binding = null super.onDestroyView() } companion object { private const val FLIPPER_CHILD_CHARACTERS = 0 private const val FLIPPER_CHILD_EMPTY = 1 } }
appMarvels/app/src/main/java/com/example/appmarvels/presentation/favorites/FavoritesFragment.kt
2418454661
package com.example.appmarvels.presentation.favorites import android.view.LayoutInflater import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import com.example.appmarvels.databinding.ItemCharacterBinding import com.example.appmarvels.framework.imageLoader.ImageLoader import com.example.appmarvels.presentation.common.GenericViewHolder class FavoritesViewHolder( itemBinding: ItemCharacterBinding, private val imageLoader: ImageLoader ) : GenericViewHolder<FavoriteItem>(itemBinding) { private val textName: TextView = itemBinding.textName private val imageCharacter: ImageView = itemBinding.imageCharacter override fun bind(data: FavoriteItem) { textName.text = data.name imageLoader.load(imageCharacter, data.imageUrl) } companion object { fun create(parent: ViewGroup, imageLoader: ImageLoader): FavoritesViewHolder { val itemBinding = ItemCharacterBinding .inflate(LayoutInflater.from(parent.context), parent, false) return FavoritesViewHolder(itemBinding, imageLoader) } } }
appMarvels/app/src/main/java/com/example/appmarvels/presentation/favorites/FavoritesViewHolder.kt
3172501806
package com.example.appmarvels.presentation.favorites import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.liveData import androidx.lifecycle.switchMap import com.example.appmarvels.framework.useCase.GetFavoritesUseCase import com.example.appmarvels.framework.useCase.base.CoroutinesDispatchers import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.catch import javax.inject.Inject @HiltViewModel class FavoritesViewModel @Inject constructor( private val getFavoritesUseCase: GetFavoritesUseCase, private val coroutinesDispatchers: CoroutinesDispatchers ) : ViewModel() { private val action = MutableLiveData<Action>() val state: LiveData<UiState> = action.switchMap { action -> liveData(coroutinesDispatchers.main()) { when (action) { is Action.GetAll -> { getFavoritesUseCase.invoke() .catch { UiState.ShowEmpty } .collect { val items = it.map { character -> FavoriteItem(character.id, character.name, character.imageUrl) } val uiState = if (items.isEmpty()) { UiState.ShowEmpty } else UiState.ShowFavorites(items) emit(uiState) } } } } } fun getAll() { action.value = Action.GetAll } sealed class UiState { data class ShowFavorites(val favorites: List<FavoriteItem>) : UiState() object ShowEmpty : UiState() } sealed class Action { object GetAll : Action() } }
appMarvels/app/src/main/java/com/example/appmarvels/presentation/favorites/FavoritesViewModel.kt
2532941419
package com.example.appmarvels.presentation.about import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.example.appmarvels.R class AboutFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_about, container, false) } }
appMarvels/app/src/main/java/com/example/appmarvels/presentation/about/AboutFragment.kt
145589708
package com.example.appmarvels.presentation.common import androidx.recyclerview.widget.RecyclerView import androidx.viewbinding.ViewBinding abstract class GenericViewHolder<T>( itemBinding: ViewBinding ) : RecyclerView.ViewHolder(itemBinding.root) { abstract fun bind(data: T) }
appMarvels/app/src/main/java/com/example/appmarvels/presentation/common/GenericViewHolder.kt
2905431289
package com.example.appmarvels.presentation.common import android.view.ViewGroup import androidx.recyclerview.widget.ListAdapter inline fun <T: ListItem, VH: GenericViewHolder<T>> getGenericAdapterOf( crossinline createViewHolder: (ViewGroup) -> VH ): ListAdapter<T, VH> { val diff = GenericDiffCallback<T>() return object : ListAdapter<T, VH>(diff){ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH { return createViewHolder(parent) } override fun onBindViewHolder(holder: VH, position: Int) { holder.bind(getItem(position)) } } }
appMarvels/app/src/main/java/com/example/appmarvels/presentation/common/GenericAdapter.kt
3699283308
package com.example.appmarvels.presentation.common interface ListItem { val key: Long fun areItemsTheSame(other: ListItem) = this.key == other.key fun areContentsTheSame(other: ListItem) = this == other }
appMarvels/app/src/main/java/com/example/appmarvels/presentation/common/ListItem.kt
3251959309
package com.example.appmarvels.presentation.common import androidx.recyclerview.widget.DiffUtil class GenericDiffCallback<T : ListItem> : DiffUtil.ItemCallback<T>() { override fun areItemsTheSame(oldItem: T, newItem: T): Boolean { return oldItem.areItemsTheSame(newItem) } override fun areContentsTheSame(oldItem: T, newItem: T): Boolean { return oldItem.areContentsTheSame(newItem) } }
appMarvels/app/src/main/java/com/example/appmarvels/presentation/common/GenericDiffCallback.kt
1434731842
package com.example.appmarvels.presentation.detail import android.os.Parcelable import androidx.annotation.Keep import kotlinx.parcelize.Parcelize @Keep @Parcelize data class DetailViewArg( val characterId: Int, val name: String, val imageUrl: String ) : Parcelable
appMarvels/app/src/main/java/com/example/appmarvels/presentation/detail/DetailViewArg.kt
1617287835
package com.example.appmarvels.presentation.detail import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.liveData import androidx.lifecycle.switchMap import com.example.appmarvels.R import com.example.appmarvels.framework.useCase.GetCharacterCategoriesUseCase import com.example.appmarvels.presentation.extension.watchStatus import kotlin.coroutines.CoroutineContext class UiActionStateLiveData( private val coroutineContext: CoroutineContext, private val getCharacterCategoriesUseCase: GetCharacterCategoriesUseCase ) { private val action = MutableLiveData<Action>() val state: LiveData<UiState> = action.switchMap { liveData(coroutineContext) { when(it) { is Action.Load -> { getCharacterCategoriesUseCase.invoke( GetCharacterCategoriesUseCase.GetCategoriesParams(it.characterId) ).watchStatus( loading = { emit(UiState.Loading) }, success = { data -> val detailParentList = mutableListOf<DetailParentVE>() val comics = data.first if (comics.isNotEmpty()) { comics.map { comic -> DetailChildVE(comic.id, comic.imageUrl) }.also { detailParentList.add( DetailParentVE(R.string.details_comics_category, it) ) } } val events = data.second if (events.isNotEmpty()) { events.map { event -> DetailChildVE(event.id, event.imageUrl) }.also { detailParentList.add( DetailParentVE(R.string.details_events_category, it) ) } } if (detailParentList.isNotEmpty()) emit(UiState.Success(detailParentList)) else emit(UiState.Empty) }, error = { emit(UiState.Error) } ) } } } } fun load(characterId: Int) { action.value = Action.Load(characterId) } sealed class UiState { object Loading : UiState() data class Success(val detailParentList: List<DetailParentVE>) : UiState() object Error : UiState() object Empty : UiState() } sealed class Action { data class Load(val characterId: Int): Action() } }
appMarvels/app/src/main/java/com/example/appmarvels/presentation/detail/UiActionStateLiveData.kt
211617204
package com.example.appmarvels.presentation.detail import android.view.LayoutInflater import android.view.ViewGroup import android.widget.ImageView import androidx.recyclerview.widget.RecyclerView import com.example.appmarvels.databinding.ItemChildDetailBinding import com.example.appmarvels.framework.imageLoader.ImageLoader class DetailChildAdapter( private val detailChildList: List<DetailChildVE>, private val imageLoader: ImageLoader ) : RecyclerView.Adapter<DetailChildAdapter.DetailChildViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DetailChildViewHolder { return DetailChildViewHolder.create(parent, imageLoader) } override fun onBindViewHolder(holder: DetailChildViewHolder, position: Int) { holder.bind(detailChildList[position]) } override fun getItemCount() = detailChildList.size class DetailChildViewHolder( itemBinding: ItemChildDetailBinding, private val imageLoader: ImageLoader ) : RecyclerView.ViewHolder(itemBinding.root) { private val imageCategory: ImageView = itemBinding.imageItemCategory fun bind(detailChildVE: DetailChildVE){ imageLoader.load(imageCategory, detailChildVE.imageUrl) } companion object { fun create( parent: ViewGroup, imageLoader: ImageLoader ): DetailChildViewHolder { val itemBinding = ItemChildDetailBinding .inflate(LayoutInflater.from(parent.context), parent, false) return DetailChildViewHolder(itemBinding, imageLoader) } } } }
appMarvels/app/src/main/java/com/example/appmarvels/presentation/detail/DetailChildAdapter.kt
1153528361
package com.example.appmarvels.presentation.detail import androidx.annotation.DrawableRes import androidx.annotation.StringRes import androidx.annotation.VisibleForTesting import androidx.lifecycle.LiveData import androidx.lifecycle.LiveDataScope import androidx.lifecycle.MutableLiveData import androidx.lifecycle.liveData import androidx.lifecycle.switchMap import com.example.appmarvels.R import com.example.appmarvels.framework.useCase.AddFavoritesUseCase import com.example.appmarvels.framework.useCase.CheckFavoriteUseCase import com.example.appmarvels.framework.useCase.RemoveFavoritesUseCase import com.example.appmarvels.presentation.extension.watchStatus import kotlin.coroutines.CoroutineContext class FavoriteUiActionStateLiveData( private val coroutineContext: CoroutineContext, checkFavoriteUseCase: CheckFavoriteUseCase, private val addFavoritesUseCase: AddFavoritesUseCase, private val removeFavoritesUseCase: RemoveFavoritesUseCase ) { @set:VisibleForTesting var currentFavoriteIcon = R.drawable.ic_favorite_unchecked private val action = MutableLiveData<Action>() val state: LiveData<UiState> = action.switchMap { liveData(coroutineContext) { when (it) { is Action.CheckFavorite -> { checkFavoriteUseCase.invoke(CheckFavoriteUseCase.Params(it.characterId)) .watchStatus( success = { isFavorite -> if (isFavorite) currentFavoriteIcon = R.drawable.ic_favorite_checked emitFavoriteIcon() }, error = {} ) } is Action.AddFavorite -> { it.detailViewArg.run { addFavoritesUseCase.invoke( AddFavoritesUseCase.Params(characterId, name, imageUrl) ).watchStatus( loading = { emit(UiState.Loading) }, success = { currentFavoriteIcon = R.drawable.ic_favorite_checked emitFavoriteIcon() }, error = { emit(UiState.Error(R.string.error_add_favorite)) } ) } } is Action.RemoveFavorite -> { it.detailViewArg.run { removeFavoritesUseCase.invoke( RemoveFavoritesUseCase.Params(characterId, name, imageUrl) ).watchStatus( loading = { emit(UiState.Loading) }, success = { currentFavoriteIcon = R.drawable.ic_favorite_unchecked emitFavoriteIcon() }, error = { emit(UiState.Error(R.string.error_remove_favorite)) } ) } } } } } private suspend fun LiveDataScope<UiState>.emitFavoriteIcon() { emit(UiState.Icon(currentFavoriteIcon)) } fun checkFavorite(characterId: Int) { action.value = Action.CheckFavorite(characterId) } fun update(detailViewArg: DetailViewArg) { action.value = if (currentFavoriteIcon == R.drawable.ic_favorite_unchecked) Action.AddFavorite(detailViewArg) else Action.RemoveFavorite(detailViewArg) } sealed class UiState { object Loading : UiState() data class Icon(@DrawableRes val icon: Int) : UiState() data class Error(@StringRes val messageResId: Int) : UiState() } sealed class Action { data class CheckFavorite(val characterId: Int) : Action() data class AddFavorite(val detailViewArg: DetailViewArg) : Action() data class RemoveFavorite(val detailViewArg: DetailViewArg) : Action() } }
appMarvels/app/src/main/java/com/example/appmarvels/presentation/detail/FavoriteUiActionStateLiveData.kt
988163918
package com.example.appmarvels.presentation.detail import androidx.annotation.StringRes data class DetailChildVE( val id: Int, val imageUrl: String ) data class DetailParentVE( @StringRes val categoryStringResId: Int, val detailChildList: List<DetailChildVE> = listOf() )
appMarvels/app/src/main/java/com/example/appmarvels/presentation/detail/DetailEntities.kt
2538483287
package com.example.appmarvels.presentation.detail import android.view.LayoutInflater import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.example.appmarvels.databinding.ItemParentDetailBinding import com.example.appmarvels.framework.imageLoader.ImageLoader class DetailParentAdapter ( private val detailParentList: List<DetailParentVE>, private val imageLoader: ImageLoader ) : RecyclerView.Adapter<DetailParentAdapter.DetailParentViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DetailParentViewHolder { return DetailParentViewHolder.create(parent, imageLoader) } override fun onBindViewHolder(holder: DetailParentViewHolder, position: Int) { holder.bind(detailParentList[position]) } override fun getItemCount() = detailParentList.size class DetailParentViewHolder( itemBinding: ItemParentDetailBinding, private val imageLoader: ImageLoader ) : RecyclerView.ViewHolder(itemBinding.root) { private val textItemCategory: TextView = itemBinding.textItemCategory private val recyclerChildDetail: RecyclerView = itemBinding.recyclerChildDetail fun bind(detailParentVE: DetailParentVE){ textItemCategory.text = itemView.context.getString(detailParentVE.categoryStringResId) recyclerChildDetail.run { setHasFixedSize(true) adapter = DetailChildAdapter(detailParentVE.detailChildList, imageLoader) } } companion object { fun create( parent: ViewGroup, imageLoader: ImageLoader ): DetailParentViewHolder { val itemBinding = ItemParentDetailBinding .inflate(LayoutInflater.from(parent.context), parent, false) return DetailParentViewHolder(itemBinding, imageLoader) } } } }
appMarvels/app/src/main/java/com/example/appmarvels/presentation/detail/DetailParentAdapter.kt
3312481621
package com.example.appmarvels.presentation.detail import androidx.lifecycle.ViewModel import com.example.appmarvels.framework.useCase.AddFavoritesUseCase import com.example.appmarvels.framework.useCase.CheckFavoriteUseCase import com.example.appmarvels.framework.useCase.GetCharacterCategoriesUseCase import com.example.appmarvels.framework.useCase.RemoveFavoritesUseCase import com.example.appmarvels.framework.useCase.base.CoroutinesDispatchers import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject @HiltViewModel class DetailViewModel @Inject constructor( getCharacterCategoriesUseCase: GetCharacterCategoriesUseCase, checkFavoriteUseCase: CheckFavoriteUseCase, addFavoritesUseCase: AddFavoritesUseCase, removeFavoritesUseCase: RemoveFavoritesUseCase, coroutinesDispatchers: CoroutinesDispatchers ) : ViewModel() { val categories = UiActionStateLiveData( coroutinesDispatchers.main(), getCharacterCategoriesUseCase ) val favorite = FavoriteUiActionStateLiveData( coroutinesDispatchers.main(), checkFavoriteUseCase, addFavoritesUseCase, removeFavoritesUseCase ) }
appMarvels/app/src/main/java/com/example/appmarvels/presentation/detail/CharacterDetailViewModel.kt
2114795255
package com.example.appmarvels.presentation.detail import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.fragment.navArgs import androidx.transition.TransitionInflater import com.example.appmarvels.databinding.FragmentCharacterDetailBinding import com.example.appmarvels.framework.imageLoader.ImageLoader import com.example.appmarvels.presentation.extension.showShortToast import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject @AndroidEntryPoint class CharacterDetailFragment : Fragment() { private var _binding: FragmentCharacterDetailBinding? = null private val binding: FragmentCharacterDetailBinding get() = _binding!! private val viewModel: DetailViewModel by viewModels() private val args by navArgs<CharacterDetailFragmentArgs>() @Inject lateinit var imageLoader: ImageLoader override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ) = FragmentCharacterDetailBinding.inflate( inflater, container, false ).apply { _binding = this }.root @Suppress("MagicNumber") override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val detailViewArg = args.detailViewArg binding.imageCharacter.run { transitionName = detailViewArg.name imageLoader.load(this, detailViewArg.imageUrl) } setSharedElementTransitionOnEnter() loadCategoriesAndObserveUiState(detailViewArg) setAndObserveFavoriteUiState(detailViewArg) } private fun loadCategoriesAndObserveUiState(detailViewArg: DetailViewArg) { viewModel.categories.load(detailViewArg.characterId) viewModel.categories.state.observe(viewLifecycleOwner) { uiState -> binding.flipperDetail.displayedChild = when (uiState) { UiActionStateLiveData.UiState.Loading -> FLIPPER_CHILD_POSITION_LOADING is UiActionStateLiveData.UiState.Success -> { binding.recyclerParentDetail.run { setHasFixedSize(true) adapter = DetailParentAdapter(uiState.detailParentList, imageLoader) } FLIPPER_CHILD_POSITION_SUCCESS } UiActionStateLiveData.UiState.Error -> { binding.includeErrorView.buttonRetry.setOnClickListener { viewModel.categories.load(detailViewArg.characterId) } FLIPPER_CHILD_POSITION_ERROR } UiActionStateLiveData.UiState.Empty -> FLIPPER_CHILD_POSITION_EMPTY } } } private fun setAndObserveFavoriteUiState(detailViewArg: DetailViewArg) { viewModel.favorite.run { checkFavorite(detailViewArg.characterId) binding.imageFavoriteIcon.setOnClickListener { update(detailViewArg) } state.observe(viewLifecycleOwner) { uiState -> binding.flipperFavorite.displayedChild = when (uiState) { FavoriteUiActionStateLiveData.UiState.Loading -> FLIPPER_FAVORITE_CHILD_POSITION_LOADING is FavoriteUiActionStateLiveData.UiState.Icon -> { binding.imageFavoriteIcon.setImageResource(uiState.icon) FLIPPER_FAVORITE_CHILD_POSITION_IMAGE } is FavoriteUiActionStateLiveData.UiState.Error -> { showShortToast(uiState.messageResId) FLIPPER_FAVORITE_CHILD_POSITION_IMAGE } } } } } // Define a animação da transição como "move" private fun setSharedElementTransitionOnEnter() { TransitionInflater.from(requireContext()) .inflateTransition(android.R.transition.move).apply { sharedElementEnterTransition = this } } override fun onDestroyView() { super.onDestroyView() _binding = null } companion object { private const val FLIPPER_CHILD_POSITION_LOADING = 0 private const val FLIPPER_CHILD_POSITION_SUCCESS = 1 private const val FLIPPER_CHILD_POSITION_ERROR = 2 private const val FLIPPER_CHILD_POSITION_EMPTY = 3 private const val FLIPPER_FAVORITE_CHILD_POSITION_IMAGE = 0 private const val FLIPPER_FAVORITE_CHILD_POSITION_LOADING = 1 } }
appMarvels/app/src/main/java/com/example/appmarvels/presentation/detail/CharacterDetailFragment.kt
116297243
package com.example.appmarvels.presentation.characters import android.view.LayoutInflater import android.view.ViewGroup import androidx.core.view.isVisible import androidx.paging.LoadState import androidx.recyclerview.widget.RecyclerView import com.example.appmarvels.databinding.ItemCharacterLoadMoreStateBinding class CharactersLoadMoreStateViewHolder( itemBinding: ItemCharacterLoadMoreStateBinding, retry: () -> Unit ): RecyclerView.ViewHolder(itemBinding.root) { private val binding = ItemCharacterLoadMoreStateBinding.bind(itemView) private val progressBarLoadingMore = binding.progressLoadingMore private val textTryAgainMessage = binding.textTryAgain.also { it.setOnClickListener { retry() } } fun bind(loadState: LoadState) { progressBarLoadingMore.isVisible = loadState is LoadState.Loading textTryAgainMessage.isVisible = loadState is LoadState.Error } companion object { fun create(parent: ViewGroup, retry: () -> Unit): CharactersLoadMoreStateViewHolder { val itemBinding = ItemCharacterLoadMoreStateBinding .inflate(LayoutInflater.from(parent.context), parent, false) return CharactersLoadMoreStateViewHolder(itemBinding, retry) } } }
appMarvels/app/src/main/java/com/example/appmarvels/presentation/characters/CharactersLoadMoreStateViewHolder.kt
804872651
package com.example.appmarvels.presentation.characters import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.example.appmarvels.databinding.ItemCharacterBinding import com.example.appmarvels.framework.model.Character import com.example.appmarvels.framework.imageLoader.ImageLoader import com.example.appmarvels.util.OnCharacterItemClick class CharactersViewHolder( itemCharacterBinding: ItemCharacterBinding, private val imageLoader: ImageLoader, private val onItemClick: OnCharacterItemClick ): RecyclerView.ViewHolder(itemCharacterBinding.root) { private val textName = itemCharacterBinding.textName private val imageCharacter = itemCharacterBinding.imageCharacter fun bind(character: Character) { textName.text = character.name imageCharacter.transitionName = character.name imageLoader.load(imageCharacter, character.imageUrl) itemView.setOnClickListener { onItemClick.invoke(character, imageCharacter) } } companion object { fun create( parent: ViewGroup, imageLoader: ImageLoader, onItemClick: OnCharacterItemClick ) : CharactersViewHolder { val inflater = LayoutInflater.from(parent.context) val itemBinding = ItemCharacterBinding.inflate(inflater, parent, false) return CharactersViewHolder(itemBinding, imageLoader, onItemClick) } } }
appMarvels/app/src/main/java/com/example/appmarvels/presentation/characters/CharactersViewHolder.kt
2498207606
package com.example.appmarvels.presentation.characters import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.navigation.fragment.FragmentNavigatorExtras import androidx.navigation.fragment.findNavController import androidx.paging.LoadState import com.example.appmarvels.databinding.FragmentCharactersBinding import com.example.appmarvels.framework.imageLoader.ImageLoader import com.example.appmarvels.presentation.detail.DetailViewArg import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch import javax.inject.Inject @AndroidEntryPoint class CharactersFragment : Fragment() { private var _binding: FragmentCharactersBinding? = null private val binding: FragmentCharactersBinding get() = _binding!! private val viewModel: CharactersViewModel by viewModels() private lateinit var charactersAdapter: CharactersAdapter @Inject lateinit var imageLoader: ImageLoader override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ) = FragmentCharactersBinding.inflate( inflater, container, false ).apply { _binding = this }.root override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initCharacterAdapter() observeInitialLoadState() lifecycleScope.launch { viewLifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { viewModel.charactersPagingData("").collectLatest { pagingData -> charactersAdapter.submitData(pagingData) } } } } private fun initCharacterAdapter() { charactersAdapter = CharactersAdapter(imageLoader) { character, view -> val extras = FragmentNavigatorExtras( view to character.name ) val directions = CharactersFragmentDirections .actionCharactersFragmentToCharacterDetailFragment( character.name, DetailViewArg(character.id, character.name, character.imageUrl) ) findNavController().navigate(directions, extras) } with(binding.recyclerCharacters) { scrollToPosition(0) setHasFixedSize(true) adapter = charactersAdapter.withLoadStateFooter( footer = CharactersLoadStateAdapter( charactersAdapter::retry ) ) } } private fun observeInitialLoadState() { lifecycleScope.launch { charactersAdapter.loadStateFlow.collectLatest { loadState -> binding.flipperCharacters.displayedChild = when (loadState.refresh) { is LoadState.Loading -> { setShimmerVisibility(true) FLIPPER_CHILD_LOADING } is LoadState.NotLoading -> { setShimmerVisibility(false) FLIPPER_CHILD_CHARACTERS } is LoadState.Error -> { setShimmerVisibility(false) binding.includeViewCharactersErrorState.buttonRetry.setOnClickListener { charactersAdapter.retry() } FLIPPER_CHILD_ERROR } } } } } private fun setShimmerVisibility(visibiity: Boolean) { binding.includeViewCharactersLoadingState.shimmerCharacters.run { isVisible = visibiity if (visibiity) { startShimmer() } else stopShimmer() } } override fun onDestroyView() { super.onDestroyView() _binding = null } companion object { private const val FLIPPER_CHILD_LOADING = 0 private const val FLIPPER_CHILD_CHARACTERS = 1 private const val FLIPPER_CHILD_ERROR = 2 } }
appMarvels/app/src/main/java/com/example/appmarvels/presentation/characters/CharactersFragment.kt
2557410606
package com.example.appmarvels.presentation.characters import android.view.ViewGroup import androidx.paging.LoadState import androidx.paging.LoadStateAdapter class CharactersLoadStateAdapter( private val retry: () -> Unit ) : LoadStateAdapter<CharactersLoadMoreStateViewHolder>() { override fun onCreateViewHolder( parent: ViewGroup, loadState: LoadState ) = CharactersLoadMoreStateViewHolder.create(parent, retry) override fun onBindViewHolder( holder: CharactersLoadMoreStateViewHolder, loadState: LoadState ) = holder.bind(loadState) }
appMarvels/app/src/main/java/com/example/appmarvels/presentation/characters/CharactersLoadStateAdapter.kt
1089216458
package com.example.appmarvels.presentation.characters import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.paging.PagingConfig import androidx.paging.PagingData import androidx.paging.cachedIn import com.example.appmarvels.framework.model.Character import com.example.appmarvels.framework.useCase.GetCharactersUseCase import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.Flow import javax.inject.Inject @HiltViewModel class CharactersViewModel @Inject constructor ( private val getCharactersUseCase: GetCharactersUseCase ) : ViewModel() { fun charactersPagingData(query: String): Flow<PagingData<Character>> { return getCharactersUseCase( GetCharactersUseCase.GetCharactersParams(query, getPagingConfig()) ).cachedIn(viewModelScope) } private fun getPagingConfig() = PagingConfig( pageSize = 20 ) }
appMarvels/app/src/main/java/com/example/appmarvels/presentation/characters/CharactersViewModel.kt
3124476786
package com.example.appmarvels.presentation.characters import android.view.ViewGroup import androidx.paging.PagingDataAdapter import androidx.recyclerview.widget.DiffUtil import com.example.appmarvels.framework.imageLoader.ImageLoader import com.example.appmarvels.util.OnCharacterItemClick import com.example.appmarvels.framework.model.Character import javax.inject.Inject class CharactersAdapter @Inject constructor ( private val imageLoader: ImageLoader, private val onItemClick: OnCharacterItemClick ) : PagingDataAdapter<Character, CharactersViewHolder>(diffCallback) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CharactersViewHolder { return CharactersViewHolder.create(parent, imageLoader, onItemClick) } override fun onBindViewHolder(holder: CharactersViewHolder, position: Int) { getItem(position)?.let { holder.bind(it) } } companion object { private val diffCallback = object : DiffUtil.ItemCallback<Character>() { override fun areItemsTheSame(oldItem: Character, newItem: Character): Boolean { return oldItem.name == newItem.name } override fun areContentsTheSame(oldItem: Character, newItem: Character): Boolean { return oldItem == newItem } } } }
appMarvels/app/src/main/java/com/example/appmarvels/presentation/characters/CharactersAdapter.kt
3152043070
package com.jetpackcompose.sample 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.jetpackcompose.sample", appContext.packageName) } }
JetPackCompose_Sample/app/src/androidTest/java/com/jetpackcompose/sample/ExampleInstrumentedTest.kt
1973190847
package com.jetpackcompose.sample 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) } }
JetPackCompose_Sample/app/src/test/java/com/jetpackcompose/sample/ExampleUnitTest.kt
2515465650
package com.jetpackcompose.sample.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)
JetPackCompose_Sample/app/src/main/java/com/jetpackcompose/sample/ui/theme/Color.kt
2437028500
package com.jetpackcompose.sample.ui.theme.components import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Card 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.draw.shadow import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.jetpackcompose.sample.R @Preview(heightDp = 300) @Composable fun previewItem() { LazyColumn(content = { items(getCategoryList()){ BlogCategory(img = it.img, title = it.title , subtitle =it.subtitle ) } }) } @Composable fun BlogCategory(img: Int, title: String, subtitle: String) { Card( modifier = Modifier .shadow(8.dp, RoundedCornerShape(5.dp)) .padding(10.dp) ) { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(8.dp) ) { Image( painter = painterResource(id = img), contentDescription = "testing", modifier = Modifier .size(48.dp) .padding(8.dp) .clip(CircleShape) .weight(2f) ) itemDescription(title, subtitle, Modifier.weight(8f)) } } } @Composable public fun itemDescription(title: String, subtitle: String, modifier: Modifier) { Column(modifier = modifier) { Text( text = title, fontWeight = FontWeight.Bold, fontSize = 10.sp ) Text( text = subtitle, fontWeight = FontWeight.Bold, fontSize = 8.sp ) } } data class Category(val img : Int, val title: String, val subtitle: String ) fun getCategoryList():MutableList<Category>{ val list = mutableListOf<Category>() list.add(Category(R.drawable.ic_launcher_background, "tititle", "subtitle")) list.add(Category(R.drawable.ic_launcher_background, "tititle", "subtitle")) list.add(Category(R.drawable.ic_launcher_background, "tititle", "subtitle")) list.add(Category(R.drawable.ic_launcher_background, "tititle", "subtitle")) list.add(Category(R.drawable.ic_launcher_background, "tititle", "subtitle")) list.add(Category(R.drawable.ic_launcher_background, "tititle", "subtitle")) list.add(Category(R.drawable.ic_launcher_background, "tititle", "subtitle")) list.add(Category(R.drawable.ic_launcher_background, "tititle", "subtitle")) list.add(Category(R.drawable.ic_launcher_background, "tititle", "subtitle")) list.add(Category(R.drawable.ic_launcher_background, "tititle", "subtitle")) list.add(Category(R.drawable.ic_launcher_background, "tititle", "subtitle")) list.add(Category(R.drawable.ic_launcher_background, "tititle", "subtitle")) list.add(Category(R.drawable.ic_launcher_background, "tititle", "subtitle")) list.add(Category(R.drawable.ic_launcher_background, "tititle", "subtitle")) list.add(Category(R.drawable.ic_launcher_background, "tititle", "subtitle")) list.add(Category(R.drawable.ic_launcher_background, "tititle", "subtitle")) list.add(Category(R.drawable.ic_launcher_background, "tititle", "subtitle")) list.add(Category(R.drawable.ic_launcher_background, "tititle", "subtitle")) list.add(Category(R.drawable.ic_launcher_background, "tititle", "subtitle")) list.add(Category(R.drawable.ic_launcher_background, "tititle", "subtitle")) list.add(Category(R.drawable.ic_launcher_background, "tititle", "subtitle")) list.add(Category(R.drawable.ic_launcher_background, "tititle", "subtitle")) list.add(Category(R.drawable.ic_launcher_background, "tititle", "subtitle")) list.add(Category(R.drawable.ic_launcher_background, "tititle", "subtitle")) list.add(Category(R.drawable.ic_launcher_background, "tititle", "subtitle")) return list }
JetPackCompose_Sample/app/src/main/java/com/jetpackcompose/sample/ui/theme/components/LazyColoumn.kt
1094472207
package com.jetpackcompose.sample.ui.theme.components import android.util.Log import androidx.compose.foundation.Image 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.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.Favorite import androidx.compose.material3.Button import androidx.compose.material3.Card import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.shadow import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp @Preview @Composable fun NotificationScreen() { var count: MutableState<Int> = rememberSaveable { mutableStateOf(0) } Column( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.fillMaxSize(1f) ) { NotificationCounter(count.value) { count.value++ } MessageBar(count.value) } } @Composable fun MessageBar(value: Int) { Card(modifier = Modifier .shadow(elevation = 4.dp)) { Row(Modifier.padding(8.dp), verticalAlignment = Alignment.CenterVertically) { Image(imageVector = Icons.Outlined.Favorite, contentDescription = "", Modifier.padding(4.dp)) Text(text = "Message sent so far $value") } } } @Composable fun NotificationCounter(value: Int, increement: () -> Int) { Column(verticalArrangement = Arrangement.Center) { Text(text = "You have sent ${value} notification") Button(onClick = { // count.value++ increement() Log.d("CODERSTAG", "Button CLicked") }) { Text(text = "Send Notification") } } }
JetPackCompose_Sample/app/src/main/java/com/jetpackcompose/sample/ui/theme/components/StateExample.kt
3917448397
package com.jetpackcompose.sample.ui.theme.components import android.util.Log import androidx.compose.material3.Button import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.tooling.preview.Preview @Preview @Composable fun Recomposable(){ val state= remember { mutableStateOf(0.00) } Log.d("TAGGED","Initial recomposition state") Button(onClick = { state.value= Math.random() }) { Log.d("TAGGED"," Logged during both composition and recomposition") Text(text = state.value.toString()) } }
JetPackCompose_Sample/app/src/main/java/com/jetpackcompose/sample/ui/theme/components/RecompositionState.kt
3763977179
package com.jetpackcompose.sample.ui.theme.components import android.os.Bundle import android.util.Log import androidx.activity.ComponentActivity import androidx.activity.compose.setContent 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.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.Button import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.jetpackcompose.sample.R import com.jetpackcompose.sample.ui.theme.JetPackComposeSampleTheme class SplashActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { JetPackComposeSampleTheme { Surface( ) { // Recomposable() // previewItem() NotificationScreen() } } } } } @Composable fun SplashUI() { Text(text = "", modifier = Modifier .clickable { } .background(Color.Green) .size(200.dp) .border(4.dp, Color.Blue) .clip(CircleShape) .background(Color.Yellow) .size(200.dp)) } @Preview(showBackground = true) @Composable fun CircularImage(){ Image(painter = painterResource(id = R.drawable.ic_launcher_background) , contentScale = ContentScale.Crop, modifier = Modifier .size(80.dp) .clip(CircleShape) .border(2.dp, Color.Magenta, CircleShape), contentDescription = "testing" ) } //@Preview(showBackground = true) @Composable fun splashPreview() { JetPackComposeSampleTheme { SplashUI() } }
JetPackCompose_Sample/app/src/main/java/com/jetpackcompose/sample/ui/theme/components/SplashActivity.kt
422481427
package com.jetpackcompose.sample.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 JetPackComposeSampleTheme( 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 ) }
JetPackCompose_Sample/app/src/main/java/com/jetpackcompose/sample/ui/theme/Theme.kt
2843464843
package com.jetpackcompose.sample.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 ) */ )
JetPackCompose_Sample/app/src/main/java/com/jetpackcompose/sample/ui/theme/Type.kt
3075119550
package com.jetpackcompose.sample import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import com.jetpackcompose.sample.ui.theme.JetPackComposeSampleTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { JetPackComposeSampleTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { Greeting("Android") } } } } } @Composable fun Greeting(name: String, modifier: Modifier = Modifier) { Text( text = "Hello $name!", modifier = modifier ) } @Preview(showBackground = true) @Composable fun GreetingPreview() { JetPackComposeSampleTheme { Greeting("Andrjjjjjoid") } }
JetPackCompose_Sample/app/src/main/java/com/jetpackcompose/sample/MainActivity.kt
35306163
package instaU.ayush.com import instaU.ayush.com.plugins.* import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.http.* import io.ktor.server.testing.* import kotlin.test.* class ApplicationTest { @Test fun testRoot() = testApplication { application { configureRouting() } client.get("/").apply { assertEquals(HttpStatusCode.OK, status) assertEquals("Hello World!", bodyAsText()) } } }
InstaU---Backend-Server/src/test/kotlin/instaU/ayush/com/ApplicationTest.kt
2653022427
package instaU.ayush.com.repository.auth import instaU.ayush.com.dao.user.UserDao import instaU.ayush.com.model.AuthResponse import instaU.ayush.com.model.AuthResponseData import instaU.ayush.com.model.SignInParams import instaU.ayush.com.model.SignUpParams import instaU.ayush.com.plugins.generateToken import instaU.ayush.com.security.hashPassword import instaU.ayush.com.util.Response import io.ktor.http.* class AuthRepositoryImpl( private val userDao: UserDao ) : AuthRepository { override suspend fun signUp(params: SignUpParams): Response<AuthResponse> { return if (userAlreadyExist(params.email)) { Response.Error( code = HttpStatusCode.Conflict, data = AuthResponse( errorMessage = "A user with this email already exists!" ) ) } else { val insertedUser = userDao.insert(params) if (insertedUser == null) { Response.Error( code = HttpStatusCode.InternalServerError, data = AuthResponse( errorMessage = "Oops, sorry we could not register the user, try later!" ) ) } else { Response.Success( data = AuthResponse( data = AuthResponseData( id = insertedUser.id, name = insertedUser.name, bio = insertedUser.bio, token = generateToken(params.email) ) ) ) } } } override suspend fun signIn(params: SignInParams): Response<AuthResponse> { val user = userDao.findByEmail(params.email) return if (user == null) { Response.Error( code = HttpStatusCode.NotFound, data = AuthResponse( errorMessage = "Invalid credentials, no user with this email!" ) ) } else { val hashedPassword = hashPassword(params.password) if (user.password == hashedPassword) { Response.Success( data = AuthResponse( data = AuthResponseData( id = user.id, name = user.name, bio = user.bio, token = generateToken(params.email), followingCount = user.followingCount, followersCount = user.followersCount ) ) ) } else { Response.Error( code = HttpStatusCode.Forbidden, data = AuthResponse( errorMessage = "Invalid credentials, wrong password!" ) ) } } } private suspend fun userAlreadyExist(email: String): Boolean { return userDao.findByEmail(email) != null } }
InstaU---Backend-Server/src/main/kotlin/instaU/ayush/com/repository/auth/AuthRepositoryImpl.kt
60991478
package instaU.ayush.com.repository.auth import instaU.ayush.com.model.AuthResponse import instaU.ayush.com.model.SignInParams import instaU.ayush.com.model.SignUpParams import instaU.ayush.com.util.Response interface AuthRepository { suspend fun signUp(params: SignUpParams): Response<AuthResponse> suspend fun signIn(params: SignInParams): Response<AuthResponse> }
InstaU---Backend-Server/src/main/kotlin/instaU/ayush/com/repository/auth/AuthRepository.kt
1965411433
package instaU.ayush.com.di import instaU.ayush.com.dao.user.UserDao import instaU.ayush.com.dao.user.UserDaoImpl import instaU.ayush.com.repository.auth.AuthRepository import instaU.ayush.com.repository.auth.AuthRepositoryImpl import org.koin.dsl.module val appModule = module { single<AuthRepository> { AuthRepositoryImpl(get()) } single<UserDao> { UserDaoImpl() } }
InstaU---Backend-Server/src/main/kotlin/instaU/ayush/com/di/AppModule.kt
1430199203
package instaU.ayush.com.di import io.ktor.server.application.* import org.koin.ktor.plugin.Koin fun Application.configureDI(){ install(Koin){ modules(appModule) } }
InstaU---Backend-Server/src/main/kotlin/instaU/ayush/com/di/Koin.kt
3671136750
package instaU.ayush.com import instaU.ayush.com.dao.DatabaseFactory import instaU.ayush.com.di.configureDI import instaU.ayush.com.plugins.* import io.ktor.server.application.* import io.ktor.server.engine.* import io.ktor.server.netty.* val jwtIssuer = System.getenv("jwt.domain") fun main() { embeddedServer(Netty, port = 8081, host = "0.0.0.0", module = Application::module) .start(wait = true) fun ayush() { println(jwtIssuer) } ayush() } fun Application.module() { DatabaseFactory.init() configureSerialization() configureDI() configureSecurity() configureRouting() }
InstaU---Backend-Server/src/main/kotlin/instaU/ayush/com/Application.kt
2198647616
package instaU.ayush.com.route import instaU.ayush.com.model.AuthResponse import instaU.ayush.com.model.SignInParams import instaU.ayush.com.model.SignUpParams import instaU.ayush.com.repository.auth.AuthRepository import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.request.* import io.ktor.server.response.* import io.ktor.server.routing.* import org.koin.ktor.ext.inject fun Routing.authRouting(){ val repository by inject<AuthRepository>() route(path = "/signup"){ post { val params = call.receiveNullable<SignUpParams>() if (params == null){ call.respond( status = HttpStatusCode.BadRequest, message = AuthResponse( errorMessage = "Invalid credentials!" ) ) return@post } val result = repository.signUp(params = params) call.respond( status = result.code, message = result.data ) } } route(path = "/login"){ post { val params = call.receiveNullable<SignInParams>() if (params == null){ call.respond( status = HttpStatusCode.BadRequest, message = AuthResponse( errorMessage = "Invalid credentials!" ) ) return@post } val result = repository.signIn(params = params) call.respond( status = result.code, message = result.data ) } } }
InstaU---Backend-Server/src/main/kotlin/instaU/ayush/com/route/AuthRoute.kt
1879174205
package instaU.ayush.com.util import de.mkammerer.snowflakeid.SnowflakeIdGenerator //private val generatorId = System.getenv("id.generator") private val generatorId = "1" object IdGenerator { fun generateId(): Long{ return SnowflakeIdGenerator.createDefault(generatorId.toInt()).next() } }
InstaU---Backend-Server/src/main/kotlin/instaU/ayush/com/util/IdGenerator.kt
1703975870
package instaU.ayush.com.util import io.ktor.http.content.* import java.io.File import java.util.UUID fun PartData.FileItem.saveFile(folderPath: String): String{ val fileName = "${UUID.randomUUID()}.${File(originalFileName as String).extension}" val fileBytes = streamProvider().readBytes() val folder = File(folderPath) folder.mkdirs() File("$folder/$fileName").writeBytes(fileBytes) return fileName }
InstaU---Backend-Server/src/main/kotlin/instaU/ayush/com/util/FileExt.kt
2319504625
package instaU.ayush.com.util import io.ktor.http.* // Generic class to handle response // from the repository sealed class Response<T>( val code: HttpStatusCode = HttpStatusCode.OK, val data: T ){ class Success<T>(data: T): Response<T>(data = data) class Error<T>( code: HttpStatusCode, data: T ): Response<T>( code, data ) }
InstaU---Backend-Server/src/main/kotlin/instaU/ayush/com/util/Response.kt
292188461
package instaU.ayush.com.util import instaU.ayush.com.model.PostResponse import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.plugins.* import io.ktor.server.response.* suspend fun ApplicationCall.getLongParameter(name: String, isQueryParameter: Boolean = false): Long{ val parameter = if (isQueryParameter){ request.queryParameters[name]?.toLongOrNull() }else{ parameters[name]?.toLongOrNull() } ?: kotlin.run { respond( status = HttpStatusCode.BadRequest, message = PostResponse( success = false, message = "Parameter $name is missing or invalid" ) ) throw BadRequestException("Parameter $name is missing or invalid") } return parameter }
InstaU---Backend-Server/src/main/kotlin/instaU/ayush/com/util/CallExt.kt
974217196
package instaU.ayush.com.util object Constants { const val BASE_URL = "http://0.0.0.0:8080/" const val POST_IMAGES_FOLDER = "post_images/" const val POST_IMAGES_FOLDER_PATH = "build/resources/main/static/$POST_IMAGES_FOLDER" const val PROFILE_IMAGES_FOLDER = "profile_images/" const val PROFILE_IMAGES_FOLDER_PATH = "build/resources/main/static/$PROFILE_IMAGES_FOLDER" }
InstaU---Backend-Server/src/main/kotlin/instaU/ayush/com/util/Constants.kt
775760829
package instaU.ayush.com.security import io.ktor.util.* import javax.crypto.Mac import javax.crypto.spec.SecretKeySpec //private val ALGORITHM = System.getenv("hash.algorithm") //private val HASH_KEY = System.getenv("hash.secret").toByteArray() private val ALGORITHM = "HmacSHA256" private val HASH_KEY = "ayushrai".toByteArray() private val hMacKey = SecretKeySpec(HASH_KEY, ALGORITHM) fun hashPassword(password: String): String{ val hMac = Mac.getInstance(ALGORITHM) hMac.init(hMacKey) return hex(hMac.doFinal(password.toByteArray())) }
InstaU---Backend-Server/src/main/kotlin/instaU/ayush/com/security/HashingService.kt
1089894229
package instaU.ayush.com.plugins import instaU.ayush.com.route.* import io.ktor.server.application.* import io.ktor.server.http.content.* import io.ktor.server.response.* import io.ktor.server.routing.* fun Application.configureRouting() { routing { authRouting() static { resources("static") } route("/") { get { call.respondText("Hello Users this is Ayush!") } } } }
InstaU---Backend-Server/src/main/kotlin/instaU/ayush/com/plugins/Routing.kt
2765154766